Programs & Examples On #Hbox

CSS3 100vh not constant in mobile browser

As I am new, I can't comment on other answers.

If someone is looking for an answer to make this work (and can use javascript - as it seems to be required to make this work at the moment) this approach has worked pretty well for me and it accounts for mobile orientation change as well. I use Jquery for the example code but should be doable with vanillaJS.

-First, I use a script to detect if the device is touch or hover. Bare-bones example:

if ("ontouchstart" in document.documentElement) {
    document.body.classList.add('touch-device');

} else {
    document.body.classList.add('hover-device');
}

This adds class to the body element according to the device type (hover or touch) that can be used later for the height script.

-Next use this code to set height of the device on load and on orientation change:

if (jQuery('body').hasClass("touch-device")) {
//Loading height on touch-device
    function calcFullHeight() {
        jQuery('.hero-section').css("height", $(window).height());
    }

    (function($) {
        calcFullHeight();

        jQuery(window).on('orientationchange', function() {
            // 500ms timeout for getting the correct height after orientation change
            setTimeout(function() {
                calcFullHeight();
            }, 500);

        });
    })(jQuery);

} else {
    jQuery('.hero-section').css("height", "100vh");


}

-Timeout is set so that the device would calculate the new height correctly on orientation change. If there is no timeout, in my experience the height will not be correct. 500ms might be an overdo but has worked for me.

-100vh on hover-devices is a fallback if the browser overrides the CSS 100vh.

Cannot get a text value from a numeric cell “Poi”

As explained in the Apache POI Javadocs, you should not use cell.setCellType(Cell.CELL_TYPE_STRING) to get the string value of a numeric cell, as you'll loose all the formatting

Instead, as the javadocs explain, you should use DataFormatter

What DataFormatter does is take the floating point value representing the cell is stored in the file, along with the formatting rules applied to it, and returns you a string that look like it the cell does in Excel.

So, if you're after a String of the cell, looking much as you had it looking in Excel, just do:

 // Create a formatter, do this once
 DataFormatter formatter = new DataFormatter(Locale.US);

 .....

 for (int i=1; i <= sheet.getLastRowNum(); i++) {
        Row r = sheet.getRow(i);
        if (r == null) { 
           // empty row, skip
        } else {
           String j_username = formatter.formatCellValue(row.getCell(0));
           String j_password =  formatter.formatCellValue(row.getCell(1));

           // Use these
        }
 }

The formatter will return String cells as-is, and for Numeric cells will apply the formatting rules on the style to the number of the cell

Perform debounce in React.js

I was searching for a solution to the same problem and came across this thread as well as some others but they had the same problem: if you are trying to do a handleOnChange function and you need the value from an event target, you will get cannot read property value of null or some such error. In my case, I also needed to preserve the context of this inside the debounced function since I'm executing a fluxible action. Here's my solution, it works well for my use case so I'm leaving it here in case anyone comes across this thread:

// at top of file:
var myAction = require('../actions/someAction');

// inside React.createClass({...});

handleOnChange: function (event) {
    var value = event.target.value;
    var doAction = _.curry(this.context.executeAction, 2);

    // only one parameter gets passed into the curried function,
    // so the function passed as the first parameter to _.curry()
    // will not be executed until the second parameter is passed
    // which happens in the next function that is wrapped in _.debounce()
    debouncedOnChange(doAction(myAction), value);
},

debouncedOnChange: _.debounce(function(action, value) {
    action(value);
}, 300)

CSS how to make scrollable list

As per your question vertical listing have a scrollbar effect.

CSS / HTML :

_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8">_x000D_
        <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <header>header area</header>_x000D_
        <nav>_x000D_
            <ul>_x000D_
                <li>Link 1</li>_x000D_
                <li>Link 2</li>_x000D_
                <li>Link 3</li>_x000D_
                <li>Link 4</li>_x000D_
                <li>Link 5</li>_x000D_
                <li>Link 6</li> _x000D_
                <li>Link 7</li> _x000D_
                <li>Link 8</li>_x000D_
                <li>Link 9</li>_x000D_
                <li>Link 10</li>_x000D_
                <li>Link 11</li>_x000D_
                <li>Link 13</li>_x000D_
                <li>Link 13</li>_x000D_
_x000D_
            </ul>_x000D_
        </nav>_x000D_
        _x000D_
        <footer>footer area</footer>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JavaFX "Location is required." even though it is in the same package

instead of

Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));

put

Parent root = FXMLLoader.load(getClass().getResource("/main.fxml"));

Difference is of " / " .

Reason :

1st one : getResource will try to find the resource relative to the package

2nd one : getResource will treat it as an absolute path and simply call the classloader .

How to refresh Gridview after pressed a button in asp.net

I was totally lost on why my Gridview.Databind() would not refresh.

My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:

gvServerConfiguration.Databind()
uppServerConfiguration.Update()

uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.

Hope this helps someone.

Uncaught TypeError: Cannot set property 'value' of null

In case anyone landed on this page for a similar issue, I found that this error can happen if your JavaScript is running in the HEAD before your form is ready. Moving your JavaScript to the bottom of the page fixed it for my situation.

How do I add a Font Awesome icon to input field?

simple way for new font awesome

  <div class="input-group">
                    <input type="text" class="form-control" placeholder="Search" name="txtSearch"  >
                    <div class="input-group-btn">
                        <button class="btn btn-default" type="submit"><i class="fas fa-search"></i></button>
                    </div>
                </div>

Install sbt on ubuntu

No command sbt found

It's saying that sbt is not on your path. Try to run ./sbt from ~/bin/sbt/bin or wherever the sbt executable is to verify that it runs correctly. Also check that you have execute permissions on the sbt executable. If this works , then add ~/bin/sbt/bin to your path and sbt should run from anywhere.

See this question about adding a directory to your path.

To verify the path is set correctly use the which command on LINUX. The output will look something like this:

$ which sbt
/usr/bin/sbt

Lastly, to verify sbt is working try running sbt -help or likewise. The output with -help will look something like this:

$ sbt -help
Usage: sbt [options]

  -h | -help         print this message
  ...

Getting CheckBoxList Item values

You can try this:-

string values = "";
foreach(ListItem item in myCBL.Items){
if(item.Selected)
{
values += item.Value.ToString() + ",";  
}
}
values = values.TrimEnd(',');  //To eliminate comma in last.

restrict edittext to single line

android:maxLines="1"
android:inputType="text"

Add the above code to have a single line in EditText tag in your layout.

android:singleLine="true" is deprecated

This constant was deprecated in API level 3.

This attribute is deprecated. Use maxLines instead to change the layout of a static text, and use the textMultiLine flag in the inputType attribute instead for editable text views (if both singleLine and inputType are supplied, the inputType flags will override the value of singleLine).

Trigger an event on `click` and `enter`

$('#usersSearch').keyup(function() { // handle keyup event on search input field

    var key = e.which || e.keyCode;  // store browser agnostic keycode

    if(key == 13) 
        $(this).closest('form').submit(); // submit parent form
}

How to limit google autocomplete results to City and Country only

I found a solution for myself

var acService = new google.maps.places.AutocompleteService();
var autocompleteItems = [];

acService.getPlacePredictions({
    types: ['(regions)']
}, function(predictions) {
    predictions.forEach(function(prediction) {
        if (prediction.types.some(function(x) {
                return x === "country" || x === "administrative_area1" || x === "locality";
            })) {
            if (prediction.terms.length < 3) {
                autocompleteItems.push(prediction);
            }
        }
    });
});

this solution only show city and country..

How do I get LaTeX to hyphenate a word that contains a dash?

multi-disciplinary will not be hyphenated, as explained by kennytm. But multi-\-disciplinary has the same hyphenation opportunities that multidisciplinary has.

I admit that I don't know why this works. It is different from the behaviour described here (emphasis mine):

The command \- inserts a discretionary hyphen into a word. This also becomes the only point where hyphenation is allowed in this word.

Drop shadow on a div container?

This works for me on all my browsers:

.shadow {
-moz-box-shadow: 0 0 30px 5px #999;
-webkit-box-shadow: 0 0 30px 5px #999;
}

then just give any div the shadow class, no jQuery required.

jQuery Event Keypress: Which key was pressed?

Actually this is better:

 var code = e.keyCode || e.which;
 if(code == 13) { //Enter keycode
   //Do something
 }

How do I get the last inserted ID of a MySQL table in PHP?

To get last inserted id in codeigniter After executing insert query just use one function called insert_id() on database, it will return last inserted id

Ex:

$this->db->insert('mytable',$data);
echo $this->db->insert_id(); //returns last inserted id

in one line

echo $this->db->insert('mytable',$data)->insert_id();

Simulate low network connectivity for Android

There's a simple way of testing low speeds on a real device that seems to have been overlooked. It does require a Mac and an ethernet (or other wired) network connection.

Turn on Wifi sharing on the Mac, turning your computer into a Wifi hotspot, connect your device to this. Use Netlimiter/Charles Proxy or Network Link Conditioner (which you may have already installed) to control the speeds.

For more details and to understand what sort of speeds you should test on check out: http://opensignal.com/blog/2016/02/05/go-slow-how-why-to-test-apps-on-poor-connections/

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

It seems that there is a typo, since 1104*1104*50=60940800 and you are trying to reshape to dimensions 50,1104,104. So it seems that you need to change 104 to 1104.

T-SQL Cast versus Convert

CONVERT is SQL Server specific, CAST is ANSI.

CONVERT is more flexible in that you can format dates etc. Other than that, they are pretty much the same. If you don't care about the extended features, use CAST.

EDIT:

As noted by @beruic and @C-F in the comments below, there is possible loss of precision when an implicit conversion is used (that is one where you use neither CAST nor CONVERT). For further information, see CAST and CONVERT and in particular this graphic: SQL Server Data Type Conversion Chart. With this extra information, the original advice still remains the same. Use CAST where possible.

Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it

This happens when you somehow confused java itself. You are trying to run a java 6 VM where it found a JRE 7. It might show this problem even if you type in the command line just java or java -version in a misconfigured environment. The JAR is not the problem, except in the very unlikely case where the code in JAR is looking in the Windows Registry for that (which probably is not your case).

In my case, I had the java.exe, javaw.exe and javaws.exe from Java 6 in the Windows/System32 folder (don't know how it got to be there). The rest of the JDK and JRE where found in the PATH inside C:\Java\jdk_1.7.0\bin. Oops!

Android Respond To URL in Intent

You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

Note that path prefix is optional.

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />

            <data android:host="www.docs.google.com" />
            <data android:host="docs.google.com" />

            <data android:pathPrefix="/forms" />
        </intent-filter>

Node package ( Grunt ) installed but not available

Other solution is to remove the ubuntu bundler in my case i used:

sudo apt-get remove ruby-bundler 

That worked for me.

How do I query between two dates using MySQL?

You can do it manually, by comparing with greater than or equal and less than or equal.

 select * from table_name where created_at_column  >=   lower_date  and  created_at_column <= upper_date;

In our example, we need to retrieve data from a particular day to day. We will compare from the beginning of the day to the latest second in another day.

  select * from table_name where created_at_column  >=   '2018-09-01 00:00:00'  and  created_at_column <= '2018-09-05 23:59:59';

JSON forEach get Key and Value

I would do it this way. Assuming I have a JSON of movies ...

movies.forEach((obj) => {
  Object.entries(obj).forEach(([key, value]) => {
    console.log(`${key} ${value}`);
  });
});

How open PowerShell as administrator from the run window

The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":

[Windows 10/Windows 8 Power User menu with "Windows Powershell (Admin)

Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:

[Taskbar and Start Menu Properties: "Replace Command Prompt With Windows Powershell"

Convert a Pandas DataFrame to a dictionary

The to_dict() method sets the column names as dictionary keys so you'll need to reshape your DataFrame slightly. Setting the 'ID' column as the index and then transposing the DataFrame is one way to achieve this.

to_dict() also accepts an 'orient' argument which you'll need in order to output a list of values for each column. Otherwise, a dictionary of the form {index: value} will be returned for each column.

These steps can be done with the following line:

>>> df.set_index('ID').T.to_dict('list')
{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

In case a different dictionary format is needed, here are examples of the possible orient arguments. Consider the following simple DataFrame:

>>> df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
>>> df
        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125

Then the options are as follows.

dict - the default: column names are keys, values are dictionaries of index:data pairs

>>> df.to_dict('dict')
{'a': {0: 'red', 1: 'yellow', 2: 'blue'}, 
 'b': {0: 0.5, 1: 0.25, 2: 0.125}}

list - keys are column names, values are lists of column data

>>> df.to_dict('list')
{'a': ['red', 'yellow', 'blue'], 
 'b': [0.5, 0.25, 0.125]}

series - like 'list', but values are Series

>>> df.to_dict('series')
{'a': 0       red
      1    yellow
      2      blue
      Name: a, dtype: object, 

 'b': 0    0.500
      1    0.250
      2    0.125
      Name: b, dtype: float64}

split - splits columns/data/index as keys with values being column names, data values by row and index labels respectively

>>> df.to_dict('split')
{'columns': ['a', 'b'],
 'data': [['red', 0.5], ['yellow', 0.25], ['blue', 0.125]],
 'index': [0, 1, 2]}

records - each row becomes a dictionary where key is column name and value is the data in the cell

>>> df.to_dict('records')
[{'a': 'red', 'b': 0.5}, 
 {'a': 'yellow', 'b': 0.25}, 
 {'a': 'blue', 'b': 0.125}]

index - like 'records', but a dictionary of dictionaries with keys as index labels (rather than a list)

>>> df.to_dict('index')
{0: {'a': 'red', 'b': 0.5},
 1: {'a': 'yellow', 'b': 0.25},
 2: {'a': 'blue', 'b': 0.125}}

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

OS_ACTIVITY_MODE = disable

This will also disable the ability to debug in real devices (no console output from real devices from then on).

PHP - remove <img> tag from string

Sean it works fine i've just used this code

$content = preg_replace("/<img[^>]+\>/i", " ", $content); 
echo $content;

//the result it's only the plain text. It works!!!

How to implement a read only property

C# 6.0 adds readonly auto properties

public object MyProperty { get; }

So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.


Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.

Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.

Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.

Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.

Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.

But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.

How to expand a list to function arguments in Python

You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

def foo(x,y,z):
   return "%d, %d, %d" % (x,y,z)

values = [1,2,3]

# the solution.
foo(*values)

JAVA_HOME does not point to the JDK

Execute:

$ export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-3.b16.el6_9.x86_64

and set operating system environment:

vi /etc/environment

Then follow these steps:

  1. Press i
  2. Paste

    JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-3.b16.el6_9.x86_64
    
  3. Press esc

  4. Press :wq

CALL command vs. START with /WAIT option

This is an old thread, but I have just encountered this situation and discovered a neat way around it. I was trying to run a setup.exe, but the focus was returning to the next line of the script without waiting for the setup.exe to finish. I tried the above solutions with no luck.

In the end, piping the command through more did the trick.

setup.exe {arguments} | more

Converting an int into a 4 byte char array (C)

Do you want to address the individual bytes of a 32-bit int? One possible method is a union:

union
{
    unsigned int integer;
    unsigned char byte[4];
} foo;

int main()
{
    foo.integer = 123456789;
    printf("%u %u %u %u\n", foo.byte[3], foo.byte[2], foo.byte[1], foo.byte[0]);
}

Note: corrected the printf to reflect unsigned values.

Jmeter - get current date and time

Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}

Which will give you: 2018-01-16T08:32:28.75Z

MySQL Workbench - Connect to a Localhost

Its Worked for me on Windows

First i installed and started XAMPP Control Panel enter image description here

Clicked for Start under Actions for MySQL. And below is my Configuration for MySQL (MySQL Workbench 8.0 CE) Connections enter image description here And it got connected with Test DataBase

Can't perform a React state update on an unmounted component

Based on @ford04 answer, here is the same encapsulated in a method :

import React, { FC, useState, useEffect, DependencyList } from 'react';

export function useEffectAsync( effectAsyncFun : ( isMounted: () => boolean ) => unknown, deps?: DependencyList ) {
    useEffect( () => {
        let isMounted = true;
        const _unused = effectAsyncFun( () => isMounted );
        return () => { isMounted = false; };
    }, deps );
} 

Usage:

const MyComponent : FC<{}> = (props) => {
    const [ asyncProp , setAsyncProp ] = useState( '' ) ;
    useEffectAsync( async ( isMounted ) =>
    {
        const someAsyncProp = await ... ;
        if ( isMounted() )
             setAsyncProp( someAsyncProp ) ;
    });
    return <div> ... ;
} ;

What is the MySQL VARCHAR max size?

Before Mysql version 5.0.3 Varchar datatype can store 255 character, but from 5.0.3 it can be store 65,535 characters.

BUT it has a limitation of maximum row size of 65,535 bytes. It means including all columns it must not be more than 65,535 bytes.

In your case it may possible that when you are trying to set more than 10000 it is exceeding more than 65,535 and mysql will gives the error.

For more information: https://dev.mysql.com/doc/refman/5.0/en/column-count-limit.html

blog with example: http://goo.gl/Hli6G3

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

MySQL Query - Records between Today and Last 30 Days

You can also write this in mysql -

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date < DATE_ADD(NOW(), INTERVAL -1 MONTH);

FIXED

Make javascript alert Yes/No Instead of Ok/Cancel

You cannot do that with the native confirm() as it is the browser’s method.

You have to create a plugin for a confirm box (or try one created by someone else). And they often look better, too.

Additional Tip: Change your English sentence to something like

Really, Delete this Thing?

Using .otf fonts on web browsers

From the Google Font Directory examples:

@font-face {
  font-family: 'Tangerine';
  font-style: normal;
  font-weight: normal;
  src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
  font-family: 'Tangerine', serif;
  font-size: 48px;
}

This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf

Here are some good sites:

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

MongoDB has a simple web based administrative port at 28017 by default.

There is no HTTP access at the default port of 27017 (which is what the error message is trying to suggest). The default port is used for native driver access, not HTTP traffic.

To access MongoDB, you'll need to use a driver like the MongoDB native driver for NodeJS. You won't "POST" to MongoDB directly (but you might create a RESTful API using express which uses the native drivers). Instead, you'll use a wrapper library that makes accessing MongoDB convenient. You might also consider using Mongoose (which uses the native driver) which adds an ORM-like model for MongoDB in NodeJS.

If you can't get to the web interface, it may be disabled. Normally, I wouldn't expect that you'd need it for doing development unless you're checking logs and such.

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/ directory, or Scripts\ on Windows).

The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.

/exclude in xcopy just for a file type

The /EXCLUDE: argument expects a file containing a list of excluded files.

So create a file called excludedfileslist.txt containing:

.cs\

Then a command like this:

xcopy /r /d /i /s /y /exclude:excludedfileslist.txt C:\dev\apan C:\web\apan

Alternatively you could use Robocopy, but would require installing / copying a robocopy.exe to the machines.

Update

An anonymous comment edit which simply stated "This Solution exclude also css file!"

This is true creating a excludedfileslist.txt file contain just:

.cs

(note no backslash on the end)

Will also exclude all of the following:

  • file1.cs
  • file2.css
  • dir1.cs\file3.txt
  • dir2\anyfile.cs.something.txt

Sometimes people don't read or understand the XCOPY command's help, here is an item I would like to highlight:

Using /exclude

  • List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

As the example states it excludes "all files with the .obj extension" but it doesn't state that it also excludes files or directories named file1.obj.tmp or dir.obj.output\example2.txt.

There is a way around .css files being excluded also, change the excludedfileslist.txt file to contain just:

.cs\

(note the backslash on the end).

Here is a complete test sequence for your reference:

C:\test1>ver

Microsoft Windows [Version 6.1.7601]

C:\test1>md src
C:\test1>md dst
C:\test1>md src\dir1
C:\test1>md src\dir2.cs
C:\test1>echo "file contents" > src\file1.cs
C:\test1>echo "file contents" > src\file2.css
C:\test1>echo "file contents" > src\dir1\file3.txt
C:\test1>echo "file contents" > src\dir1\file4.cs.txt
C:\test1>echo "file contents" > src\dir2.cs\file5.txt

C:\test1>xcopy /r /i /s /y .\src .\dst
.\src\file1.cs
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
.\src\dir2.cs\file5.txt
5 File(s) copied

C:\test1>echo .cs > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\dir1\file3.txt
1 File(s) copied

C:\test1>echo .cs\ > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
3 File(s) copied

This test was completed on a Windows 7 command line and retested on Windows 10 "10.0.14393".

Note that the last example does exclude .\src\dir2.cs\file5.txt which may or may not be unexpected for you.

Set database from SINGLE USER mode to MULTI USER

I have just fixed using following steps, It may help you.

Step: 1

right click on single user database


Step: 2

take offline


Step: 3

Drop connection and take offline


Step: 4

Take online


Step: 5

Then run following query.

ALTER DATABASE YourDBName
SET MULTI_USER
WITH ROLLBACK IMMEDIATE
GO

Enjoy...!

What is the difference between JavaScript and ECMAScript?

Technically ECMAScript is the language that everyone is using and implementing -- it is the specification created many years ago when Netscape and Microsoft sat down and attempted to standardise the scripting between JavaScript (Netscape's scripting language) and JScript (Microsoft's).

Subsequently all these engines are ostensibly implementing ECMAScript, however JavaScript (the name) now hangs around for both traditional naming reasons, and as a marketing term by Mozilla for their various non-standard extensions (which they want to be able to actually "version")

How to listen to route changes in react router v4?

With the useEffect hook it's possible to detect route changes without adding a listener.

import React, { useEffect }           from 'react';
import { Switch, Route, withRouter }  from 'react-router-dom';
import Main                           from './Main';
import Blog                           from './Blog';


const App  = ({history}) => {

    useEffect( () => {

        // When route changes, history.location.pathname changes as well
        // And the code will execute after this line

    }, [history.location.pathname]);

    return (<Switch>
              <Route exact path = '/'     component = {Main}/>
              <Route exact path = '/blog' component = {Blog}/>
            </Switch>);

}

export default withRouter(App);

How to refresh activity after changing language (Locale) inside application

After changing language newly created activities display with changed new language, but current activity and previously created activities which are in pause state are not updated.How to update activities ?

Pre API 11 (Honeycomb), the simplest way to make the existing activities to be displayed in new language is to restart it. In this way you don't bother to reload each resources by yourself.

private void restartActivity() {
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

Register an OnSharedPreferenceChangeListener, in its onShredPreferenceChanged(), invoke restartActivity() if language preference was changed. In my example, only the PreferenceActivity is restarted, but you should be able to restart other activities on activity resume by setting a flag.

Update (thanks @stackunderflow): As of API 11 (Honeycomb) you should use recreate() instead of restartActivity().

public class PreferenceActivity extends android.preference.PreferenceActivity implements
        OnSharedPreferenceChangeListener {

    // ...

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("pref_language")) {
            ((Application) getApplication()).setLocale();
            restartActivity();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }
}

I have a blog post on this topic with more detail, but it's in Chinese. The full source code is on github: PreferenceActivity.java

Resize command prompt through commands

Actually, there's a much simpler way to do this. If you just open the batch file, click on the window, and then click "properties", and then to "layout", and scroll down to "Window Size", you can edit it from there. It will also stay that way every time you open that specific batch file, so it's pretty handy.

How to set editable true/false EditText in Android programmatically?

editText.setFocusable(false);
editText.setClickable(false);

Check if int is between two numbers

You are human, and therefore you understand what the term "10 < x < 20" suppose to mean. The computer doesn't have this intuition, so it reads it as: "(10 < x) < 20".

For example, if x = 15, it will calculate:

(10 < x) => TRUE

"TRUE < 20" => ???

In C programming, it will be worse, since there are no True\False values. If x = 5, the calculation will be:

10 < x => 0 (the value of False)

0 < 20 => non-0 number (True)

and therefore "10 < 5 < 20" will return True! :S

Angular expression if array contains

You can accomplish this with a slightly different syntax:

ng-class="{'approved': selectedForApproval.indexOf(jobSet) === -1}"

Plnkr

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

The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences...

+----------------+-----------------+----------------+----------------+
|    Command     | Displays Output | Can Get Output | Gets Exit Code |
+----------------+-----------------+----------------+----------------+
| system()       | Yes (as text)   | Last line only | Yes            |
| passthru()     | Yes (raw)       | No             | Yes            |
| exec()         | No              | Yes (array)    | Yes            |
| shell_exec()   | No              | Yes (string)   | No             |
| backticks (``) | No              | Yes (string)   | No             |
+----------------+-----------------+----------------+----------------+
  • "Displays Output" means it streams the output to the browser (or command line output if running from a command line).
  • "Can Get Output" means you can get the output of the command and assign it to a PHP variable.
  • The "exit code" is a special value returned by the command (also called the "return status"). Zero usually means it was successful, other values are usually error codes.

Other misc things to be aware of:

  • The shell_exec() and the backticks operator do the same thing.
  • There are also proc_open() and popen() which allow you to interactively read/write streams with an executing command.
  • Add "2>&1" to the command string if you also want to capture/display error messages.
  • Use escapeshellcmd() to escape command arguments that may contain problem characters.
  • If passing an $output variable to exec() to store the output, if $output isn't empty, it will append the new output to it. So you may need to unset($output) first.

IN vs ANY operator in PostgreSQL

(Neither IN nor ANY is an "operator". A "construct" or "syntax element".)

Logically, quoting the manual:

IN is equivalent to = ANY.

But there are two syntax variants of IN and two variants of ANY. Details:

IN taking a set is equivalent to = ANY taking a set, as demonstrated here:

But the second variant of each is not equivalent to the other. The second variant of the ANY construct takes an array (must be an actual array type), while the second variant of IN takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:

ANY is more versatile

The ANY construct is far more versatile, as it can be combined with various operators, not just =. Example:

SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');

For a big number of values, providing a set scales better for each:

Related:

Inversion / opposite / exclusion

"Find rows where id is in the given array":

SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);

Inversion: "Find rows where id is not in the array":

SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}');  -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));

All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[].

Rows with id IS NULL do not pass either of these expressions. To include NULL values additionally:

SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;

Best way to format multiple 'or' conditions in an if statement (Java)

Do you want to switch to this??

switch(x) {
    case 12:
    case 16:
    case 19: 
        //Do something
        break;
    default:
        //Do nothing or something else..
        break;
}

Warn user before leaving web page with unsaved changes

Tested Eli Grey's universal solution, only worked after I simplified the code to

  'use strict';
  (() => {
    const modified_inputs = new Set();
    const defaultValue = 'defaultValue';
    // store default values
    addEventListener('beforeinput', evt => {
      const target = evt.target;
      if (!(defaultValue in target.dataset)) {
        target.dataset[defaultValue] = ('' + (target.value || target.textContent)).trim();
      }
    });

    // detect input modifications
    addEventListener('input', evt => {
      const target = evt.target;
      let original = target.dataset[defaultValue];

      let current = ('' + (target.value || target.textContent)).trim();

      if (original !== current) {
        if (!modified_inputs.has(target)) {
          modified_inputs.add(target);
        }
      } else if (modified_inputs.has(target)) {
        modified_inputs.delete(target);
      }
    });

    addEventListener(
      'saved',
      function(e) {
        modified_inputs.clear()
      },
      false
    );

    addEventListener('beforeunload', evt => {
      if (modified_inputs.size) {
        const unsaved_changes_warning = 'Changes you made may not be saved.';
        evt.returnValue = unsaved_changes_warning;
        return unsaved_changes_warning;
      }
    });

  })();

The modifications to his is deleted the usage of target[defaultValue] and only use target.dataset[defaultValue] to store the real default value.

And I added a 'saved' event listener where the 'saved' event will be triggered by yourself on your saving action succeeded.

But this 'universal' solution only works in browsers, not works in app's webview, for example, wechat browsers.

To make it work in wechat browsers(partially) also, another improvements again:

  'use strict';
  (() => {
    const modified_inputs = new Set();
    const defaultValue = 'defaultValue';
    // store default values
    addEventListener('beforeinput', evt => {
      const target = evt.target;
      if (!(defaultValue in target.dataset)) {
        target.dataset[defaultValue] = ('' + (target.value || target.textContent)).trim();
      }
    });

    // detect input modifications
    addEventListener('input', evt => {
      const target = evt.target;
      let original = target.dataset[defaultValue];

      let current = ('' + (target.value || target.textContent)).trim();

      if (original !== current) {
        if (!modified_inputs.has(target)) {
          modified_inputs.add(target);
        }
      } else if (modified_inputs.has(target)) {
        modified_inputs.delete(target);
      }

      if(modified_inputs.size){
        const event = new Event('needSave')
        window.dispatchEvent(event);
      }
    });

    addEventListener(
      'saved',
      function(e) {
        modified_inputs.clear()
      },
      false
    );

    addEventListener('beforeunload', evt => {
      if (modified_inputs.size) {
        const unsaved_changes_warning = 'Changes you made may not be saved.';
        evt.returnValue = unsaved_changes_warning;
        return unsaved_changes_warning;
      }
    });

    const ua = navigator.userAgent.toLowerCase();

    if(/MicroMessenger/i.test(ua)) {
      let pushed = false

      addEventListener('needSave', evt => {
        if(!pushed) {
          pushHistory();

          window.addEventListener("popstate", function(e) {
            if(modified_inputs.size) {
              var cfi = confirm('???????????' + JSON.stringify(e));
              if (cfi) {
                modified_inputs.clear()
                history.go(-1)
              }else{
                e.preventDefault();
                e.stopPropagation();
              }
            }
          }, false);
        }

        pushed = true
      });
    }

    function pushHistory() {
      var state = {
        title: document.title,
        url: "#flag"
      };
      window.history.pushState(state, document.title, "#flag");
    }
  })();

Nginx subdomain configuration

You could move the common parts to another configuration file and include from both server contexts. This should work:

server {
  listen 80;
  server_name server1.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

server {
  listen 80;
  server_name another-one.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled (normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org's configuration file is /etc/nginx/sites-enabled and it looks like this:

server {
  listen   80 default_server;
  listen   [2a01:4f8:120:3105::101:1]:80 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-80;
}

server {
  listen   443 default_server;
  listen   [2a01:4f8:120:3105::101:1]:443 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/ssl-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-443;
}

As an example here's the /etc/nginx/include.d/all-common file that's included from both server contexts:

index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;

location ~ /\.ht {
  deny all;
}

location = /favicon.ico {
  log_not_found off;
  access_log off;
}

location ~ /(README|ChangeLog)$ {
  types { }
  default_type text/plain;
}

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

nodejs send html file to client

you can render the page in express more easily


 var app   = require('express')();    
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
 
    app.get('/signup',function(req,res){      
    res.sendFile(path.join(__dirname,'/signup.html'));
    });

so if u request like http://127.0.0.1:8080/signup that it will render signup.html page under views folder.

Tomcat request timeout

You can set the default time out in the server.xml

<Connector URIEncoding="UTF-8" 
    acceptCount="100" 
    connectionTimeout="20000" 
    disableUploadTimeout="true" 
    enableLookups="false" 
    maxHttpHeaderSize="8192" 
    maxSpareThreads="75" 
    maxThreads="150" 
    minSpareThreads="25" 
    port="7777" 
    redirectPort="8443"/>

How to open the terminal in Atom?

First, you should install "platformio-ide-terminal": Open "Preferences ?," >> Click "+ Install" >> In "Search packages" type "platformio-ide-terminal" >> Click "Install".

And answering exactly the question. If you have previously installed, just use:

  • Shortcut: ctrl-` or Option+Command+T (??T)
  • by Menu: Go to Packages > platformio-ide-terminal [or other] > New terminal

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You can also add android:noHistory="true" to your Activity tag in AndroidManifest.xml.

<activity
            ...
            android:noHistory="true">
</activity>

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Smart way to truncate long strings

All modern browsers now support a simple CSS solution for automatically adding an ellipsis if a line of text exceeds the available width:

p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

(Note that this requires the width of the element to be limited in some way in order to have any effect.)

Based on https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/.

It should be noted that this approach does not limit based on the number of characters. It also does not work if you need to allow multiple lines of text.

How to check if all elements of a list matches a condition?

You could use itertools's takewhile like this, it will stop once a condition is met that fails your statement. The opposite method would be dropwhile

for x in itertools.takewhile(lambda x: x[2] == 0, list)
    print x

Validate email address textbox using JavaScript

If you wish to allow accent (see RFC 5322) and allow new domain extension like .quebec. use this expression:

/\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/
  • The '\u00C0-\u017F' part is for alowing accent. We use the unicode range for that.
  • The '{2,}' simply say a minimum of 2 char for the domain extension. You can replace this by '{2,63}' if you dont like the infinitive range.

Based on this article

JsFidler

_x000D_
_x000D_
$(document).ready(function() {_x000D_
var input = $('.input_field');_x000D_
var result = $('.test_result');_x000D_
        var regExpression = /\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/;_x000D_
    _x000D_
   $('.btnTest').click(function(){_x000D_
          var isValid = regExpression.test(input.val());_x000D_
          if (isValid)_x000D_
              result.html('<span style="color:green;">This email is valid</span>');_x000D_
           else_x000D_
              result.html('<span style="color:red;">This email is not valid</span>');_x000D_
_x000D_
   });_x000D_
_x000D_
});
_x000D_
body {_x000D_
    padding: 40px;_x000D_
}_x000D_
_x000D_
label {_x000D_
    font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type=text] {_x000D_
    width: 20em_x000D_
}_x000D_
.test_result {_x000D_
  font-size:4em;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label for="search_field">Input</label>_x000D_
<input type='text' class='input_field' />_x000D_
<button type="button" class="btnTest">_x000D_
Test_x000D_
</button>_x000D_
<br/>_x000D_
<div class="test_result">_x000D_
Not Tested_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to trigger an event in input text after I stop typing/writing?

cleaned solution :

$.fn.donetyping = function(callback, delay){
  delay || (delay = 1000);
  var timeoutReference;
  var doneTyping = function(elt){
    if (!timeoutReference) return;
    timeoutReference = null;
    callback(elt);
  };

  this.each(function(){
    var self = $(this);
    self.on('keyup',function(){
      if(timeoutReference) clearTimeout(timeoutReference);
      timeoutReference = setTimeout(function(){
        doneTyping(self);
      }, delay);
    }).on('blur',function(){
      doneTyping(self);
    });
  });

  return this;
};

Add inline style using Javascript

Using jQuery :

$(nFilter).attr("style","whatever");

Otherwise :

nFilter.setAttribute("style", "whatever");

should work

Basic Ajax send/receive with node.js

Express makes this kind of stuff really intuitive. The syntax looks like below :

var app = require('express').createServer();
app.get("/string", function(req, res) {
    var strings = ["rad", "bla", "ska"]
    var n = Math.floor(Math.random() * strings.length)
    res.send(strings[n])
})
app.listen(8001)

https://expressjs.com

If you're using jQuery on the client side you can do something like this:

$.get("/string", function(string) {
    alert(string)
})

download file using an ajax request

Update April 27, 2015

Up and coming to the HTML5 scene is the download attribute. It's supported in Firefox and Chrome, and soon to come to IE11. Depending on your needs, you could use it instead of an AJAX request (or using window.location) so long as the file you want to download is on the same origin as your site.

You could always make the AJAX request/window.location a fallback by using some JavaScript to test if download is supported and if not, switching it to call window.location.

Original answer

You can't have an AJAX request open the download prompt since you physically have to navigate to the file to prompt for download. Instead, you could use a success function to navigate to download.php. This will open the download prompt but won't change the current page.

$.ajax({
    url: 'download.php',
    type: 'POST',
    success: function() {
        window.location = 'download.php';
    }
});

Even though this answers the question, it's better to just use window.location and avoid the AJAX request entirely.

What is "Advanced" SQL?

I would expect:

  • stored procedure creation and usage
  • joins (inner and outer) and how to correctly use GROUP BY
  • performance evaluation/tuning
  • knowledge of efficient (and inefficient) ways of doing things in queries (understanding how certain things can affect performance, e.g. using functions in WHERE clauses)
  • dynamic SQL and knowledge of cursors (and IMO the few times they should be used)
  • understanding of schema design, indexing, and referential integrity

Error: Java: invalid target release: 11 - IntelliJ IDEA

Got this same error after updating my Idea and I resolved it as follows:

File >> Project Structure... >> Project

“Project language level:” was set to “11 - Local variable syntax for lambda parameters” so I changed it to “SDK default (8 - Lambdas, type annotations etc.)” then applied the change and the error was resolved.

MYSQL query between two timestamps

Try this one. It works for me.

SELECT * FROM eventList
WHERE DATE(date) 
  BETWEEN 
    '2013-03-26' 
  AND 
    '2013-03-27'

How can I get the content of CKEditor using JQuery?

var value = CKEDITOR.instances['YourInstanceName'].getData()
 alert( value);

Replace YourInstanceName with the name of your instance and you will get the desired results.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

This might help to format if you are using ES6.
Below code snippet will ignore the seconds. If you want to consider seconds you can add that as the first parameter.

   const formatFrom24Hrsto12Hrs = (time, ignoreZero = true) => {
      let [hours, minutes] = time.split(':')
      let modifier = +hours < 12 ? 'am' : 'pm'
      hours = +hours % 12 || 12
      minutes = ignoreZero && +minutes === 0 ? '' : `:${minutes}`
      return hours + minutes + modifier
    }

How can I dynamically add items to a Java array?

keep a count of where you are in the primitive array

class recordStuff extends Thread
{
    double[] aListOfDoubles;
    int i = 0;

    void run()
    {
        double newData;
        newData = getNewData(); // gets data from somewhere

        aListofDoubles[i] = newData; // adds it to the primitive array of doubles
        i++ // increments the counter for the next pass

        System.out.println("mode: " + doStuff());
    }

    void doStuff()
    {
        // Calculate the mode of the double[] array

        for (int i = 0; i < aListOfDoubles.length; i++) 
        {
            int count = 0;
            for (int j = 0; j < aListOfDoubles.length; j++)
            {
                if (a[j] == a[i]) count++;
            }
            if (count > maxCount) 
            {
                maxCount = count;
                maxValue = aListOfDoubles[i];
            }
        }
        return maxValue;
    }
}

AngularJS: How to clear query parameters in the URL?

Need to make it work when html5mode = false?

All of the other answers work only when Angular's html5mode is true. If you're working outside of html5mode, then $location refers only to the "fake" location that lives in your hash -- and so $location.search can't see/edit/fix the actual page's search params.

Here's a workaround, to be inserted in the HTML of the page before angular loads:

<script>
  if (window.location.search.match("code=")){
    var newHash = "/after-auth" + window.location.search;
    if (window.history.replaceState){
      window.history.replaceState( {}, "", window.location.toString().replace(window.location.search, ""));
    }
    window.location.hash = newHash;
  }
</script>

Select elements by attribute

$("input[attr]").length might be a better option.

React eslint error missing in props validation

the problem is in flow annotation in handleClick, i removed this and works fine thanks @alik

How do you reinstall an app's dependencies using npm?

Delete node_module and re-install again by command

rm -rf node_modules && npm i

Squash the first two commits in Git?

Update July 2012 (git 1.7.12+)

You now can rebase all commits up to root, and select the second commit Y to be squashed with the first X.

git rebase -i --root master

pick sha1 X
squash sha1 Y
pick sha1 Z
git rebase [-i] --root $tip

This command can now be used to rewrite all the history leading from "$tip" down to the root commit.

See commit df5df20c1308f936ea542c86df1e9c6974168472 on GitHub from Chris Webb (arachsys).


Original answer (February 2009)

I believe you will find different recipes for that in the SO question "How do I combine the first two commits of a git repository?"

Charles Bailey provided there the most detailed answer, reminding us that a commit is a full tree (not just diffs from a previous states).
And here the old commit (the "initial commit") and the new commit (result of the squashing) will have no common ancestor.
That mean you can not "commit --amend" the initial commit into new one, and then rebase onto the new initial commit the history of the previous initial commit (lots of conflicts)

(That last sentence is no longer true with git rebase -i --root <aBranch>)

Rather (with A the original "initial commit", and B a subsequent commit needed to be squashed into the initial one):

  1. Go back to the last commit that we want to form the initial commit (detach HEAD):

    git checkout <sha1_for_B>
    
  2. Reset the branch pointer to the initial commit, but leaving the index and working tree intact:

    git reset --soft <sha1_for_A>
    
  3. Amend the initial tree using the tree from 'B':

    git commit --amend
    
  4. Temporarily tag this new initial commit (or you could remember the new commit sha1 manually):

    git tag tmp
    
  5. Go back to the original branch (assume master for this example):

    git checkout master
    
  6. Replay all the commits after B onto the new initial commit:

    git rebase --onto tmp <sha1_for_B>
    
  7. Remove the temporary tag:

    git tag -d tmp
    

That way, the "rebase --onto" does not introduce conflicts during the merge, since it rebases history made after the last commit (B) to be squashed into the initial one (which was A) to tmp (representing the squashed new initial commit): trivial fast-forward merges only.

That works for "A-B", but also "A-...-...-...-B" (any number of commits can be squashed into the initial one this way)

Why is my Button text forced to ALL CAPS on Lollipop?

By default, Button in android provides all caps keyword. If you want button text to be in lower case or mixed case you can disable textAllCaps flag using android:textAllCaps="false"

PowerShell - Start-Process and Cmdline Switches

I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)

cmd /C "$msbuild $args" >> $outputfile

How to get ° character in a string in python?

Above answers assume that UTF8 encoding can safely be used - this one is specifically targetted for Windows.

The Windows console normaly uses CP850 encoding and not utf-8, so if you try to use a source file utf8-encoded, you get those 2 (incorrect) characters instead of a degree °.

Demonstration (using python 2.7 in a windows console):

deg = u'\xb0`  # utf code for degree
print deg.encode('utf8')

effectively outputs .

Fix: just force the correct encoding (or better use unicode):

local_encoding = 'cp850'    # adapt for other encodings
deg = u'\xb0'.encode(local_encoding)
print deg

or if you use a source file that explicitely defines an encoding:

# -*- coding: utf-8 -*-
local_encoding = 'cp850'  # adapt for other encodings
print " The current temperature in the country/city you've entered is " + temp_in_county_or_city + "°C.".decode('utf8').encode(local_encoding)

Cast object to T

Actually, the responses bring up an interesting question, which is what you want your function to do in the case of error.

Maybe it would make more sense to construct it in the form of a TryParse method that attempts to read into T, but returns false if it can't be done?

    private static bool ReadData<T>(XmlReader reader, string value, out T data)
    {
        bool result = false;
        try
        {
            reader.MoveToAttribute(value);
            object readData = reader.ReadContentAsObject();
            data = readData as T;
            if (data == null)
            {
                // see if we can convert to the requested type
                data = (T)Convert.ChangeType(readData, typeof(T));
            }
            result = (data != null);
        }
        catch (InvalidCastException) { }
        catch (Exception ex)
        {
            // add in any other exception handling here, invalid xml or whatnot
        }
        // make sure data is set to a default value
        data = (result) ? data : default(T);
        return result;
    }

edit: now that I think about it, do I really need to do the convert.changetype test? doesn't the as line already try to do that? I'm not sure that doing that additional changetype call actually accomplishes anything. Actually, it might just increase the processing overhead by generating exception. If anyone knows of a difference that makes it worth doing, please post!

How can I generate random alphanumeric strings?

UPDATED based on comments. The original implementation generated a-h ~1.95% of the time and the remaining characters ~1.56% of the time. The update generates all characters ~1.61% of the time.

FRAMEWORK SUPPORT - .NET Core 3 (and future platforms that support .NET Standard 2.1 or above) provides a cryptographically sound method RandomNumberGenerator.GetInt32() to generate a random integer within a desired range.

Unlike some of the alternatives presented, this one is cryptographically sound.

using System;
using System.Security.Cryptography;
using System.Text;

namespace UniqueKey
{
    public class KeyGenerator
    {
        internal static readonly char[] chars =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); 

        public static string GetUniqueKey(int size)
        {            
            byte[] data = new byte[4*size];
            using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetBytes(data);
            }
            StringBuilder result = new StringBuilder(size);
            for (int i = 0; i < size; i++)
            {
                var rnd = BitConverter.ToUInt32(data, i * 4);
                var idx = rnd % chars.Length;

                result.Append(chars[idx]);
            }

            return result.ToString();
        }

        public static string GetUniqueKeyOriginal_BIASED(int size)
        {
            char[] chars =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            byte[] data = new byte[size];
            using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetBytes(data);
            }
            StringBuilder result = new StringBuilder(size);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }
    }
}

Based on a discussion of alternatives here and updated/modified based on the comments below.

Here's a small test harness that demonstrates the distribution of characters in the old and updated output. For a deep discussion of the analysis of randomness, check out random.org.

using System;
using System.Collections.Generic;
using System.Linq;
using UniqueKey;

namespace CryptoRNGDemo
{
    class Program
    {

        const int REPETITIONS = 1000000;
        const int KEY_SIZE = 32;

        static void Main(string[] args)
        {
            Console.WriteLine("Original BIASED implementation");
            PerformTest(REPETITIONS, KEY_SIZE, KeyGenerator.GetUniqueKeyOriginal_BIASED);

            Console.WriteLine("Updated implementation");
            PerformTest(REPETITIONS, KEY_SIZE, KeyGenerator.GetUniqueKey);
            Console.ReadKey();
        }

        static void PerformTest(int repetitions, int keySize, Func<int, string> generator)
        {
            Dictionary<char, int> counts = new Dictionary<char, int>();
            foreach (var ch in UniqueKey.KeyGenerator.chars) counts.Add(ch, 0);

            for (int i = 0; i < REPETITIONS; i++)
            {
                var key = generator(KEY_SIZE); 
                foreach (var ch in key) counts[ch]++;
            }

            int totalChars = counts.Values.Sum();
            foreach (var ch in UniqueKey.KeyGenerator.chars)
            {
                Console.WriteLine($"{ch}: {(100.0 * counts[ch] / totalChars).ToString("#.000")}%");
            }
        }
    }
}

Check if application is installed - Android

@Override 
protected void onResume() {
    super.onResume();
    boolean installed = false;

    while (!installed) {
        installed = appInstalledOrNot (APPPACKAGE);
        if (installed) {
            Toast.makeText(this, "App installed", Toast.LENGTH_SHORT).show ();
        }
    }
} 

private boolean appInstalledOrNot (String uri) {
    PackageManager pm = getPackageManager();
    boolean app_installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        app_installed = false;
    }
    return app_installed;
}

How to generate sample XML documents from their DTD or XSD?

Microsoft has published a "document generator" tool as a sample. This is an article that describes the architecture and operation of the sample app in some detail.

If you just want to run the sample generation tool, click here and install the MSI.

It's free. The source is available. Requires the .NET Framework to run. Works only with XSDs. (not Relax NG or DTD).

Delete rows with foreign key in PostgreSQL

It means that in table kontakty you have a row referencing the row in osoby you want to delete. You have do delete that row first or set a cascade delete on the relation between tables.

Powodzenia!

Angular2: custom pipe could not be found

I take no issue with the accepted answer as it certainly helped me. However, after implementing it, I still got the same error.

Turns out this was because I was calling the pipes incorrectly in my component as well:

My custom-pipe.ts file:

@Pipe({ name: 'doSomething' })
export class doSomethingPipe implements PipeTransform {
    transform(input: string): string {
        // Do something
    }
}

So far, so good, but in my component.html file I was calling the pipes as follows:

{{ myData | doSomethingPipe }}

This will again throw the error that the pipe is not found. This is because Angular looks up the pipes by the name defined in the Pipe decorator. So in my example, the pipe should instead be called like this:

{{ myData | doSomething }}

Silly mistake, but it cost me a fair amount of time. Hope this helps!

Should I use past or present tense in git commit messages?

Stick with the present tense imperative because

  • it's good to have a standard
  • it matches tickets in the bug tracker which naturally have the form "implement something", "fix something", or "test something."

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:

cv2.cv.CV_CAP_PROP_POS_FRAMES

to

cv2.CAP_PROP_POS_FRAMES

and same applies to cv2.CAP_PROP_POS_FRAME_COUNT.

Hope it helps.

What is the difference between compileSdkVersion and targetSdkVersion?

As a oneliner guide:

minSdkVersion <= targetSdkVersion <= compileSdkVersion

Ideally:

minSdkVersion (lowest possible) <= targetSdkVersion == compileSdkVersion (latest SDK)

Read more from this great post by Ian Lake

PHP 5 disable strict standards error

Do you want to disable error reporting, or just prevent the user from seeing it? It’s usually a good idea to log errors, even on a production site.

# in your PHP code:
ini_set('display_errors', '0');     # don't show any errors...
error_reporting(E_ALL | E_STRICT);  # ...but do log them

They will be logged to your standard system log, or use the error_log directive to specify exactly where you want errors to go.

How to use Elasticsearch with MongoDB?

Here how to do this on mongodb 3.0. I used this nice blog

  1. Install mongodb.
  2. Create data directories:
$ mkdir RANDOM_PATH/node1
$ mkdir RANDOM_PATH/node2> 
$ mkdir RANDOM_PATH/node3
  1. Start Mongod instances
$ mongod --replSet test --port 27021 --dbpath node1
$ mongod --replSet test --port 27022 --dbpath node2
$ mongod --replSet test --port 27023 --dbpath node3
  1. Configure the Replica Set:
$ mongo
config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]};    
rs.initiate(config);
  1. Installing Elasticsearch:
a. Download and unzip the [latest Elasticsearch][2] distribution

b. Run bin/elasticsearch to start the es server.

c. Run curl -XGET http://localhost:9200/ to confirm it is working.
  1. Installing and configuring the MongoDB River:

$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb

$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments

  1. Create the “River” and the Index:

curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'

  1. Test on browser:

    http://localhost:9200/_search?q=home

PHP - If variable is not empty, echo some html code

i hope this will work too, try using"is_null"

<?php 
$web = the_field('website');
if (!is_null($web)) {
?>

....html code here

<?php
} else { 
    echo "Niente";
}
?>

http://php.net/manual/en/function.is-null.php

hope that suits you..

Oracle: how to set user password unexpire?

While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE

Let check the parameter value.
If in Case it is :

SQL> show parameter resource_limit
NAME                                 TYPE        VALUE
------------------------------------ ----------- ---------
resource_limit                       boolean     FALSE
Its mean resource limit is off,we ist have to enable it. 

Use the ALTER SYSTEM statement to turn on resource limits. 

SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.

Switch statement multiple cases in JavaScript

For me this is the simplest way:

switch (["afshin","saeed","larry"].includes(varName) ? 1 : 2) {
   case 1:
       alert('Hey');
       break;

   default:
       alert('Default case');
       break;
}

How to dismiss ViewController in Swift?

From Apple documentations:

The presenting view controller is responsible for dismissing the view controller it presented

Thus, it is a bad practise to just invoke the dismiss method from it self.

What you should do if you're presenting it modal is:

presentingViewController?.dismiss(animated: true, completion: nil)

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

Answers by ‘smartnut007’, ‘Bill Karwin’, and ‘sqlvogel’ are excellent. Yet let me put an interesting perspective to it.

Well, we have prime and non-prime keys.

When we focus on how non-primes depend on primes, we see two cases:

Non-primes can be dependent or not.

  • When dependent: we see they must depend on a full candidate key. This is 2NF.
  • When not dependent: there can be no-dependency or transitive dependency

    • Not even transitive dependency: Not sure what normalization theory addresses this.
    • When transitively dependent: It is deemed undesirable. This is 3NF.

What about dependencies among primes?

Now you see, we’re not addressing the dependency relationship among primes by either 2nd or 3rd NF. Further such dependency, if any, is not desirable and thus we’ve a single rule to address that. This is BCNF.

Referring to the example from Bill Karwin's post here, you’ll notice that both ‘Topping’, and ‘Topping Type’ are prime keys and have a dependency. Had they been non-primes with dependency, then 3NF would have kicked in.

Note:

The definition of BCNF is very generic and without differentiating attributes between prime and non-prime. Yet, the above way of thinking helps to understand how some anomaly is percolated even after 2nd and 3rd NF.

Advanced Topic: Mapping generic BCNF to 2NF & 3NF

Now that we know BCNF provides a generic definition without reference to any prime/non-prime attribues, let's see how BCNF and 2/3 NF's are related.

First, BCNF requires (other than the trivial case) that for each functional dependency X -> Y (FD), X should be super-key. If you just consider any FD, then we've three cases - (1) Both X and Y non-prime, (2) Both prime and (3) X prime and Y non-prime, discarding the (nonsensical) case X non-prime and Y prime.

For case (1), 3NF takes care of.

For case (3), 2NF takes care of.

For case (2), we find the use of BCNF

Is putting a div inside an anchor ever correct?

No it won't validate, but yes it generally will work in modern browsers. That being said, use a span inside your anchor, and set display: block on it as well, that will definitely work everywhere, and it will validate!

How to scale a BufferedImage

AffineTransformOp offers the additional flexibility of choosing the interpolation type.

BufferedImage before = getBufferedImage(encoded);
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0);
AffineTransformOp scaleOp = 
   new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);

The fragment shown illustrates resampling, not cropping; this related answer addresses the issue; some related examples are examined here.

How to rename a table column in Oracle 10g

suppose supply_master is a table, and

SQL>desc supply_master;


SQL>Name
 SUPPLIER_NO    
 SUPPLIER_NAME
 ADDRESS1       
 ADDRESS2       
 CITY           
 STATE          
 PINCODE  


SQL>alter table Supply_master rename column ADDRESS1 TO ADDR;
Table altered



SQL> desc Supply_master;
 Name                   
 -----------------------
 SUPPLIER_NO            
 SUPPLIER_NAME          
 ADDR   ///////////this has been renamed........//////////////                
 ADDRESS2               
 CITY                   
 STATE                  
 PINCODE                  

Google Maps V3 marker with label

If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..

<script type="text/javascript">
    var point = { lat: 22.5667, lng: 88.3667 };
    var markerSize = { x: 22, y: 40 };


    google.maps.Marker.prototype.setLabel = function(label){
        this.label = new MarkerLabel({
          map: this.map,
          marker: this,
          text: label
        });
        this.label.bindTo('position', this, 'position');
    };

    var MarkerLabel = function(options) {
        this.setValues(options);
        this.span = document.createElement('span');
        this.span.className = 'map-marker-label';
    };

    MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
        onAdd: function() {
            this.getPanes().overlayImage.appendChild(this.span);
            var self = this;
            this.listeners = [
            google.maps.event.addListener(this, 'position_changed', function() { self.draw();    })];
        },
        draw: function() {
            var text = String(this.get('text'));
            var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
            this.span.innerHTML = text;
            this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
            this.span.style.top = (position.y - markerSize.y + 40) + 'px';
        }
    });
    function initialize(){
        var myLatLng = new google.maps.LatLng(point.lat, point.lng);
        var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var myMarker = new google.maps.Marker({
            map: gmap,
            position: myLatLng,
            label: 'Hello World!',
            draggable: true
        });
    }
</script>
<style>
    .map-marker-label{
        position: absolute;
    color: blue;
    font-size: 16px;
    font-weight: bold;
    }
</style>

This will work.

How to access environment variable values?

A performance-driven approach - calling environ is expensive, so it's better to call it once and save it to a dictionary. Full example:

from os import environ


# Slower
print(environ["USER"], environ["NAME"])

# Faster
env_dict = dict(environ)
print(env_dict["USER"], env_dict["NAME"])

P.S- if you worry about exposing private environment variables, then sanitize env_dict after the assignment.

Change the current directory from a Bash script

Putting the above together, you can make an alias

alias your_cmd=". your_cmd"

if you don't want to write the leading "." each time you want to source your script to the shell environment, or if you simply don't want to remember that must be done for the script to work correctly.

How to clear an ImageView in Android?

This works for me.

emoji.setBackground(null);

This crashes in runtime.

viewToUse.setImageResource(android.R.color.transparent);  

How to print all information from an HTTP request to the screen, in PHP

A simple way would be:

<?php
print_r($_SERVER);
print_r($_POST);
print_r($_GET);
print_r($_FILES);
?>

A bit of massaging would be required to get everything in the order you want, and to exclude the variables you are not interested in, but should give you a start.

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Join 'methods' are available in Arrays and the classes that extend AbstractCollections but doesn't override toString() method (like virtually all collections in java.util).

For instance:

String s= java.util.Arrays.toString(collectionOfStrings.toArray());
s = s.substing(1, s.length()-1);// [] are guaranteed to be there

That's quite weird way since it works only for numbers alike data SQL wise.

Make error: missing separator

I had the missing separator file in Makefiles generated by qmake. I was porting Qt code to a different platform. I didn't have QMAKESPEC nor MAKE set. Here's the link I found the answer:

https://forum.qt.io/topic/3783/missing-separator-error-in-makefile/5

External resource not being loaded by AngularJs

I had this error in tests, the directive templateUrl wasn't trusted, but only for the spec, so I added the template directory:

beforeEach(angular.mock.module('app.templates'));

My main directory is app.

How to search a list of tuples in Python

Hmm... well, the simple way that comes to mind is to convert it to a dict

d = dict(thelist)

and access d[53].

EDIT: Oops, misread your question the first time. It sounds like you actually want to get the index where a given number is stored. In that case, try

dict((t[0], i) for i, t in enumerate(thelist))

instead of a plain old dict conversion. Then d[53] would be 2.

How can I debug my JavaScript code?

  • Internet Explorer 8 (Developer Tools - F12). Anything else is second rate in Internet Explorer land
  • Firefox and Firebug. Hit F12 to display.
  • Safari (Show Menu Bar, Preferences -> Advanced -> Show Develop menu bar)
  • Google Chrome JavaScript Console (F12 or (Ctrl + Shift + J)). Mostly the same browser as Safari, but Safari is better IMHO.
  • Opera (Tools -> Advanced -> Developer Tools)

How to make a progress bar

Basically its this: You have three files: Your long running PHP script, a progress bar controlled by Javascript (@SapphireSun gives an option), and a progress script. The hard part is the Progress Script; your long script must be able to report its progress without direct communication to your progress script. This can be in the form of session id's mapped to progress meters, a database, or check of whats not finished.

The process is simple:

  1. Execute your script and zero out progress bar
  2. Using AJAX, query your progress script
  3. Progress script must somehow check on progress
  4. Change the progress bar to reflect the value
  5. Clean up when finished

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

If you're using react-native then please try the below commands first before running your project:

  1. npm install --save-dev jetifier
  2. npx jetify

Now run your project again. Hope this will work.

Dynamic variable names in Bash

Example below returns value of $name_of_var

var=name_of_var
echo $(eval echo "\$$var")

String Resource new line /n not possible?

If you put "\n" in a string in the xml file, it's taken as "\\n"

So , I did :

text = text.Replace("\\\n", "\n");   ( text is taken from resX file) 

And then I get a line jump on the screen

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

I had the same issue trying to install jquery-rails. The fix was

sudo apt-get install zlibc zlib1g zlib1g-dev

How Do I Make Glyphicons Bigger? (Change Size?)

Fontawesome has a perfect solution to this.

I implemented the same. just on your main .css file add this

.gi-2x{font-size: 2em;}
.gi-3x{font-size: 3em;}
.gi-4x{font-size: 4em;}
.gi-5x{font-size: 5em;}

In your example you just have to do this.

<div class = "jumbotron">
    <span class="glyphicon glyphicon-globe gi-5x"></span>
</div>  

Limit the height of a responsive image with css

The trick is to add both max-height: 100%; and max-width: 100%; to .container img. Example CSS:

.container {
  width: 300px;
  border: dashed blue 1px;
}

.container img {
  max-height: 100%;
  max-width: 100%;
}

In this way, you can vary the specified width of .container in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)

Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/

SELECT list is not in GROUP BY clause and contains nonaggregated column

country.code is not in your group by statement, and is not an aggregate (wrapped in an aggregate function).

https://www.w3schools.com/sql/sql_ref_sqlserver.asp

Convert java.util.Date to java.time.LocalDate

Date input = new Date();
LocalDateTime  conv=LocalDateTime.ofInstant(input.toInstant(), ZoneId.systemDefault());
LocalDate convDate=conv.toLocalDate();

The Date instance does contain time too along with the date while LocalDate doesn't. So you can firstly convert it into LocalDateTime using its method ofInstant() then if you want it without time then convert the instance into LocalDate.

How to export settings?

I'm preferred my own way to synchronize all Visual Studio Code extensions between laptops, using .dotfiles and small script to perform updates automatically. This way helps me every time when I want to install all extensions I have without any single mouse activity in Visual Studio Code after installing (via Homebrew).

So I just write each new added extension to .txt file stored at my .dotfiles folder. After that I pull master branch on another laptop to get up-to-date file with all extensions.

Using the script, which Big Rich had written before, with one more change, I can totally synchronise all extensions almost automatically.

Script

cat dart-extensions.txt | xargs -L 1 code --install-extension

And also there is one more way to automate that process. Here you can add a script which looks up a Visual Studio Code extension in realtime and each time when you take a diff between the code --list-extensions command and your .txt file in .dotfiles, you can easily update your file and push it to your remote repository.

SQL Server : export query as a .txt file

You can use windows Powershell to execute a query and output it to a text file

Invoke-Sqlcmd -Query "Select * from database" -ServerInstance "Servername\SQL2008" -Database "DbName" > c:\Users\outputFileName.txt

Maven Run Project

See the exec maven plugin. You can run Java classes using:

mvn exec:java -Dexec.mainClass="com.example.Main" [-Dexec.args="argument1"] ...

The invocation can be as simple as mvn exec:java if the plugin configuration is in your pom.xml. The plugin site on Mojohaus has a more detailed example.

<project>
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>com.example.Main</mainClass>
                    <arguments>
                        <argument>argument1</argument>
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Finding the index of an item in a list

A variant on the answer from FMc and user7177 will give a dict that can return all indices for any entry:

>>> a = ['foo','bar','baz','bar','any', 'foo', 'much']
>>> l = dict(zip(set(a), map(lambda y: [i for i,z in enumerate(a) if z is y ], set(a))))
>>> l['foo']
[0, 5]
>>> l ['much']
[6]
>>> l
{'baz': [2], 'foo': [0, 5], 'bar': [1, 3], 'any': [4], 'much': [6]}
>>> 

You could also use this as a one liner to get all indices for a single entry. There are no guarantees for efficiency, though I did use set(a) to reduce the number of times the lambda is called.

Counting unique values in a column in pandas dataframe like in Qlik?

you can use unique property by using len function

len(df['hID'].unique()) 5

Undefined reference to 'vtable for xxx'

Missing implementation of a function in class

The reason I faced this issue was because I had deleted the function's implementation from the cpp file, but forgotten to delete the declaration from the .h file.

My answer doesn't specifically answer your question, but lets people who come to this thread looking for answer know that this can also one cause.

Bootstrap 4 File Input

As of Bootstrap 4.3 you can change placeholder and button text inside the label tag:

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="custom-file">_x000D_
  <input type="file" class="custom-file-input" id="exampleInputFile">_x000D_
  <label class="custom-file-label" for="exampleInputFile" data-browse="{Your button text}">{Your placeholder text}</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

here-document gives 'unexpected end of file' error

Note one can also get this error if you do this;

while read line; do
  echo $line
done << somefile

Because << somefile should read < somefile in this case.

Loaded nib but the 'view' outlet was not set

Just spent more than hour trying to find out why my view property is not set in my view controller upon initiating it from nib. Remember to call "[super initWithNibName...]" inside your view controller's initWithNibName.

Does the join order matter in SQL?

If you try joining C on a field from B before joining B, i.e.:

SELECT A.x, 
       A.y, 
       A.z 
FROM A 
   INNER JOIN C
       on B.x = C.x
   INNER JOIN B
       on A.x = B.x

your query will fail, so in this case the order matters.

How to test if a DataSet is empty?

If (ds != null)

Should do the work for you!

How to encode URL parameters?

With urlsearchparams:

const params = new URLSearchParams()
params.append('imageurl', http://www.image.com/?username=unknown&password=unknown)
return `http://www.foobar.com/foo?${params.toString()}`

How do I remove a CLOSE_WAIT socket connection

It is also worth noting that if your program spawns a new process, that process may inherit all your opened handles. Even after your own program closs, those inherited handles can still be alive via the orphaned child process. And they don't necessarily show up quite the same in netstat. But all the same, the socket will hang around in CLOSE_WAIT while this child process is alive.

I had a case where I was running ADB. ADB itself spawns a server process if its not already running. This inherited all my handles initially, but did not show up as owning any of them when I was investigating (the same was true for both macOS and Windows - not sure about Linux).

WebAPI to Return XML

You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.

If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.

Accept: application/xml

You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1

EDIT: based on your edited question with code:

Simple return list of string, instead of converting it to XML. try it using Fiddler.

public List<string> Get(int tenantID, string dataType, string ActionName)
    {
       List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
       return SQLResult;
     }

For example if your list is like:

List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;

and you specify Accept: application/xml the output will be:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>Test1</string>
  <string>Test2</string>
  <string>Test3</string>
</ArrayOfstring>

and if you specify 'Accept: application/json' in the request then the output will be:

[
  "Test1",
  "Test2",
  "Test3"
]

So let the client request the content type, instead of you sending the customized xml.

Detecting a mobile browser

I advise you check out http://wurfl.io/

In a nutshell, if you import a tiny JS file:

<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>

you will be left with a JSON object that looks like:

{
 "complete_device_name":"Google Nexus 7",
 "is_mobile":true,
 "form_factor":"Tablet"
}

(that's assuming you are using a Nexus 7, of course) and you will be able to do things like:

if(WURFL.form_factor == "Tablet"){
    //dostuff();
}

This is what you are looking for.

Disclaimer: I work for the company that offers this free service. Thanks.

How to make an Android device vibrate? with different frequency?

Vibrate without using permission

If you want to simply vibrate the device once to provide a feedback on a user action. You can use performHapticFeedback() function of a View. This doesn't need the VIBRATE permission to be declared in the manifest.

Use the following function as a top level function in some common class like Utils.kt of your project:

/**
 * Vibrates the device. Used for providing feedback when the user performs an action.
 */
fun vibrate(view: View) {
    view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}

And then use it anywhere in your Fragment or Activity as following:

vibrate(requireView())

Simple as that!

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

Bart Kiers, your regex has a couple issues. The best way to do that is this:

(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits

In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

It took us a day to resolve this problem. The solution is forcing your webservice to use version 11.0.0 in your web.config file.

<runtime>      
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
  </dependentAssembly>
</assemblyBinding>

Skipping Iterations in Python

I think you're looking for continue

Makefile ifeq logical or

As found on the mailing list archive,

one can use the filter function.

For example

ifeq ($(GCC_MINOR),$(filter $(GCC_MINOR),4 5))

filter X, A B will return those of A,B that are equal to X. Note, while this is not relevant in the above example, this is a XOR operation. I.e. if you instead have something like:

ifeq (4, $(filter 4, $(VAR1) $(VAR2)))

And then do e.g. make VAR1=4 VAR2=4, the filter will return 4 4, which is not equal to 4.

A variation that performs an OR operation instead is:

ifneq (,$(filter $(GCC_MINOR),4 5))

where a negative comparison against an empty string is used instead (filter will return en empty string if GCC_MINOR doesn't match the arguments). Using the VAR1/VAR2 example it would look like this:

ifneq (, $(filter 4, $(VAR1) $(VAR2)))

The downside to those methods is that you have to be sure that these arguments will always be single words. For example, if VAR1 is 4 foo, the filter result is still 4, and the ifneq expression is still true. If VAR1 is 4 5, the filter result is 4 5 and the ifneq expression is true.

One easy alternative is to just put the same operation in both the ifeq and else ifeq branch, e.g. like this:

ifeq ($(GCC_MINOR),4)
    @echo Supported version
else ifeq ($(GCC_MINOR),5)
    @echo Supported version
else
    @echo Unsupported version
endif

How to install maven on redhat linux

I made the following script:

#!/bin/bash

# Target installation location
MAVEN_HOME="/your/path/here"

# Link to binary tar.gz archive
# See https://maven.apache.org/download.cgi?html_a_name#Files
MAVEN_BINARY_TAR_GZ_ARCHIVE="http://www.trieuvan.com/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"

# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See https://maven.apache.org/configure.html
MAVEN_OPTS="" # Optional (not needed)

if [[ ! -d $MAVEN_HOME ]]; then
  # Create nonexistent subdirectories recursively
  mkdir -p $MAVEN_HOME

  # Curl location of tar.gz archive & extract without first directory
  curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1

  # Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
  ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn

  # Permanently set environmental variable (if not null)
  if [[ -n $MAVEN_OPTS ]]; then
    echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc
  fi

  # Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
  # is your $PATH environment.
  # See http://stackoverflow.com/questions/26609922/maven-home-mvn-home-or-m2-home
  echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
else
  # Do nothing if target installation directory already exists
  echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."
fi

How to count the number of rows in excel with data?

Dim RowNumber As Integer
RowNumber = ActiveSheet.Range("A65536").End(xlUp).Row

In your case it should return #9

How do I set the timeout for a JAX-WS webservice client?

In case your appserver is WebLogic (for me it was 10.3.6) then properties responsible for timeouts are:

com.sun.xml.ws.connect.timeout 
com.sun.xml.ws.request.timeout

good postgresql client for windows?

I like Postgresql Maestro. I also use their version for MySql. I'm pretty statisfied with their product. Or you can use the free tool PgAdmin.

How to change the pop-up position of the jQuery DatePicker control

This puts the functionality into a method named function, allowing for your code to encapsulate it or for the method to be made a jquery extension. Just used on my code, works perfectly

var nOffsetTop  = /* whatever value, set from wherever */;
var nOffsetLeft = /* whatever value, set from wherever */;

$(input).datepicker
(
   beforeShow : function(oInput, oInst) 
   { 
      AlterPostion(oInput, oInst, nOffsetTop, nOffsetLeft); 
   }
);

/* can be converted to extension, or whatever*/
var AlterPosition = function(oInput, oItst, nOffsetTop, nOffsetLeft)
{
   var divContainer = oInst.dpDiv;
   var oElem        = $(this);
       oInput       = $(oInput);

   setTimeout(function() 
   { 
      divContainer.css
      ({ 
         top  : (nOffsetTop >= 0 ? "+=" + nOffsetTop : "-=" + (nOffsetTop * -1)), 
         left : (nOffsetTop >= 0 ? "+=" + nOffsetLeft : "-=" + (nOffsetLeft * -1))
      }); 
   }, 10);
}

How do I pull my project from github?

First, you'll need to tell git about yourself. Get your username and token together from your settings page.

Then run:

git config --global github.user YOUR_USERNAME
git config --global github.token YOURTOKEN

You will need to generate a new key if you don't have a back-up of your key.

Then you should be able to run:

git clone [email protected]:YOUR_USERNAME/YOUR_PROJECT.git

Page Redirect after X seconds wait using JavaScript

$(document).ready(function() {
    window.setTimeout(function(){window.location.href = "https://www.google.co.in"},5000);
});

Case objects vs Enumerations in Scala

If you are serious about maintaining interoperability with other JVM languages (e.g. Java) then the best option is to write Java enums. Those work transparently from both Scala and Java code, which is more than can be said for scala.Enumeration or case objects. Let's not have a new enumerations library for every new hobby project on GitHub, if it can be avoided!

Recommended way to get hostname in Java

InetAddress.getLocalHost().getHostName() is the best way out of the two as this is the best abstraction at the developer level.

How can JavaScript save to a local file?

So, your real question is: "How can JavaScript save to a local file?"

Take a look at http://www.tiddlywiki.com/

They save their HTML page locally after you have "changed" it internally.

[ UPDATE 2016.01.31 ]

TiddlyWiki original version saved directly. It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename.

TiddlyWiki current version just downloads it as any file download. You need to do your own backup management. :(

[ END OF UPDATE

The trick is, you have to open the page as file:// not as http:// to be able to save locally.

The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial.

-Jesse

Disable submit button when form invalid with AngularJS

You need to use the name of your form, as well as ng-disabled: Here's a demo on Plunker

<form name="myForm">
    <input name="myText" type="text" ng-model="mytext" required />
    <button ng-disabled="myForm.$invalid">Save</button>
</form>

Remove #N/A in vlookup result

If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.

=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))

or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.

=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")

in earlier versions you need to repeat the VLOOKUP, e.g.

=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

How to vertically center a container in Bootstrap?

add Bootstrap.css then add this to your css

_x000D_
_x000D_
   _x000D_
html, body{height:100%; margin:0;padding:0}_x000D_
 _x000D_
.container-fluid{_x000D_
  height:100%;_x000D_
  display:table;_x000D_
  width: 100%;_x000D_
  padding: 0;_x000D_
}_x000D_
 _x000D_
.row-fluid {height: 100%; display:table-cell; vertical-align: middle;}_x000D_
 _x000D_
 _x000D_
_x000D_
.centering {_x000D_
  float:none;_x000D_
  margin:0 auto;_x000D_
}
_x000D_
Now call in your page _x000D_
_x000D_
<div class="container-fluid">_x000D_
    <div class="row-fluid">_x000D_
        <div class="centering text-center">_x000D_
           Am in the Center Now :-)_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I concatenate a boolean to a string in Python?

The recommended way is to let str.format handle the casting (docs). Methods with %s substitution may be deprecated eventually (see PEP3101).

>>> answer = True
>>> myvar = "the answer is {}".format(answer)
>>> print(myvar)
the answer is True

In Python 3.6+ you may use literal string interpolation:

 >>> print(f"the answer is {answer}")
the answer is True

PIL image to array (numpy array to array) - Python

Based on zenpoy's answer:

import Image
import numpy

def image2pixelarray(filepath):
    """
    Parameters
    ----------
    filepath : str
        Path to an image file

    Returns
    -------
    list
        A list of lists which make it simple to access the greyscale value by
        im[y][x]
    """
    im = Image.open(filepath).convert('L')
    (width, height) = im.size
    greyscale_map = list(im.getdata())
    greyscale_map = numpy.array(greyscale_map)
    greyscale_map = greyscale_map.reshape((height, width))
    return greyscale_map

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

On Salesforce platform this error is caused by /, the solution is to escape these as //.

How to list all files in a directory and its subdirectories in hadoop hdfs

If you are using hadoop 2.* API there are more elegant solutions:

    Configuration conf = getConf();
    Job job = Job.getInstance(conf);
    FileSystem fs = FileSystem.get(conf);

    //the second boolean parameter here sets the recursion to true
    RemoteIterator<LocatedFileStatus> fileStatusListIterator = fs.listFiles(
            new Path("path/to/lib"), true);
    while(fileStatusListIterator.hasNext()){
        LocatedFileStatus fileStatus = fileStatusListIterator.next();
        //do stuff with the file like ...
        job.addFileToClassPath(fileStatus.getPath());
    }

Does MS SQL Server's "between" include the range boundaries?

BETWEEN (Transact-SQL)

Specifies a(n) (inclusive) range to test.

test_expression [ NOT ] BETWEEN begin_expression AND end_expression

Arguments

test_expression

Is the expression to test for in the range defined by begin_expression and end_expression. test_expression must be the same data type as both begin_expression and end_expression.

NOT

Specifies that the result of the predicate be negated.

begin_expression

Is any valid expression. begin_expression must be the same data type as both test_expression and end_expression.

end_expression

Is any valid expression. end_expression must be the same data type as both test_expression and begin_expression.

AND

Acts as a placeholder that indicates test_expression should be within the range indicated by begin_expression and end_expression.

Remarks

To specify an exclusive range, use the greater than (>) and less than operators (<). If any input to the BETWEEN or NOT BETWEEN predicate is NULL, the result is UNKNOWN.

Result Value

BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

NOT BETWEEN returns TRUE if the value of test_expression is less than the value of begin_expression or greater than the value of end_expression.

JPA OneToMany not deleting child

You can try this:

@OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true).

Replace all spaces in a string with '+'

Use a regular expression with the g modifier:

var replaced = str.replace(/ /g, '+');

From Using Regular Expressions with JavaScript and ActionScript:

/g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.

Getting multiple keys of specified value of a generic Dictionary?

Then layman's solution

A function similar to the one below could be written to make such a dictionary:

    public Dictionary<TValue, TKey> Invert(Dictionary<TKey, TValue> dict) {
    Dictionary<TValue, TKey> ret = new Dictionary<TValue, TKey>();
    foreach (var kvp in dict) {ret[kvp.value] = kvp.key;} return ret; }

Remove all constraints affecting a UIView

Details

  • Xcode 10.2.1 (10E1001), Swift 5

Solution

import UIKit

extension UIView {

    func removeConstraints() { removeConstraints(constraints) }
    func deactivateAllConstraints() { NSLayoutConstraint.deactivate(getAllConstraints()) }
    func getAllSubviews() -> [UIView] { return UIView.getAllSubviews(view: self) }

    func getAllConstraints() -> [NSLayoutConstraint] {
        var subviewsConstraints = getAllSubviews().flatMap { $0.constraints }
        if let superview = self.superview {
            subviewsConstraints += superview.constraints.compactMap { (constraint) -> NSLayoutConstraint? in
                if let view = constraint.firstItem as? UIView, view == self { return constraint }
                return nil
            }
        }
        return subviewsConstraints + constraints
    }

    class func getAllSubviews(view: UIView) -> [UIView] {
        return view.subviews.flatMap { [$0] + getAllSubviews(view: $0) }
    }
}

Usage

print("constraints: \(view.getAllConstraints().count), subviews: \(view.getAllSubviews().count)")
view.deactivateAllConstraints()

Spring RestTemplate GET with parameters

If your url is http://localhost:8080/context path?msisdn={msisdn}&email={email}

then

Map<String,Object> queryParams=new HashMap<>();
queryParams.put("msisdn",your value)
queryParams.put("email",your value)

works for resttemplate exchange method as described by you

add new element in laravel collection object

I have solved this if you are using array called for 2 tables. Example you have, $tableA['yellow'] and $tableA['blue'] . You are getting these 2 values and you want to add another element inside them to separate them by their type.

foreach ($tableA['yellow'] as $value) {
    $value->type = 'YELLOW';  //you are adding new element named 'type'
}

foreach ($tableA['blue'] as $value) {
    $value->type = 'BLUE';  //you are adding new element named 'type'
}

So, both of the tables value will have new element called type.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

Why am I getting "IndentationError: expected an indented block"?

As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.

Is it possible to append Series to rows of DataFrame without making a list first?

Maybe an easier way would be to add the pandas.Series into the pandas.DataFrame with ignore_index=True argument to DataFrame.append(). Example -

DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value)
    DF = DF.append(SR_row,ignore_index=True)

Demo -

In [1]: import pandas as pd

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

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

In [5]: s = pd.Series([5,6],index=['A','B'])

In [6]: s
Out[6]:
A    5
B    6
dtype: int64

In [36]: df.append(s,ignore_index=True)
Out[36]:
   A  B
0  1  2
1  3  4
2  5  6

Another issue in your code is that DataFrame.append() is not in-place, it returns the appended dataframe, you would need to assign it back to your original dataframe for it to work. Example -

DF = DF.append(SR_row,ignore_index=True)

To preserve the labels, you can use your solution to include name for the series along with assigning the appended DataFrame back to DF. Example -

DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value,name=sample)
    DF = DF.append(SR_row)
DF.head()

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s

On a server using a logon script, tell the logon to run the batch file. Jason

How to copy selected files from Android with adb pull

As to the short script, the following runs on my Linux host

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION="\.jpg"

while read MYFILE ; do
    adb pull "$DEVICE_DIR/$MYFILE" "$HOST_DIR/$MYFILE"
done < $(adb shell ls -1 "$DEVICE_DIR" | grep "$EXTENSION")

"ls minus one" lets "ls" show one file per line, and the quotation marks allow spaces in the filename.

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

You should probably stop using launch images in iOS 8 and use a storyboard or nib/xib.

  • In Xcode 6, open the File menu and choose New ? File... ? iOS ? User Interface ? Launch Screen.

  • Then open the settings for your project by clicking on it.

  • In the General tab, in the section called App Icons and Launch Images, set the Launch Screen File to the files you just created (this will set UILaunchStoryboardName in info.plist).

Note that for the time being the simulator will only show a black screen, so you need to test on a real device.

Adding a Launch Screen xib file to your project:

Adding a new Launch Screen xib file

Configuring your project to use the Launch Screen xib file instead of the Asset Catalog:

Configure project to use Launch Screen xob

jQuery set radio button

Why do you need 'input:radio[name=cols]'. Don't know your html, but assuming that ids are unique, you can simply do this.

$('#'+newcol).prop('checked', true);

Send inline image in email

Try this

 string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:filename\"></body></html>";
 AlternateView avHtml = AlternateView.CreateAlternateViewFromString
    (htmlBody, null, MediaTypeNames.Text.Html);

 LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg);
 inline.ContentId = Guid.NewGuid().ToString();
 avHtml.LinkedResources.Add(inline);

 MailMessage mail = new MailMessage();
 mail.AlternateViews.Add(avHtml);

 Attachment att = new Attachment(filePath);
 att.ContentDisposition.Inline = true;

 mail.From = from_email;
 mail.To.Add(data.email);
 mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot";
 mail.Body = String.Format(
            "<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +
            @"<img src=""cid:{0}"" />", att.ContentId);

 mail.IsBodyHtml = true;
 mail.Attachments.Add(att);

Test if something is not undefined in JavaScript

In some of these answers there is a fundamental misunderstanding about how to use typeof.

Incorrect

if (typeof myVar === undefined) {

Correct

if (typeof myVar === 'undefined') {

The reason is that typeof returns a string. Therefore, you should be checking that it returned the string "undefined" rather than undefined (not enclosed in quotation marks), which is itself one of JavaScript's primitive types. The typeof operator will never return a value of type undefined.


Addendum

Your code might technically work if you use the incorrect comparison, but probably not for the reason you think. There is no preexisting undefined variable in JavaScript - it's not some sort of magic keyword you can compare things to. You can actually create a variable called undefined and give it any value you like.

let undefined = 42;

And here is an example of how you can use this to prove the first method is incorrect:

https://jsfiddle.net/p6zha5dm/

Anaconda / Python: Change Anaconda Prompt User Path

If you want to access folder you specified using Anaconda Prompt, try typing

cd C:\Users\u354590

Mac OS X and multiple Java versions

Uninstall jdk8, install jdk7, then reinstall jdk8.

My approach to switching between them (in .profile) :

export JAVA_7_HOME=$(/usr/libexec/java_home -v1.7)
export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_9_HOME=$(/usr/libexec/java_home -v9)

alias java7='export JAVA_HOME=$JAVA_7_HOME'
alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java9='export JAVA_HOME=$JAVA_9_HOME'

#default java8
export JAVA_HOME=$JAVA_8_HOME

Then you can simply type java7 or java8 in a terminal to switch versions.

(edit: updated to add Dylans improvement for Java 9)

Access denied for root user in MySQL command-line

Are you logging into MySQL as root? You have to explicitly grant privileges to your "regular" MySQL user account while logged in as MySQL root.

First set up a root account for your MySQL database.

In the terminal type:

mysqladmin -u root password 'password'

To log into MySQL, use this:

mysql -u root -p

To set the privileges manually start the server with the skip-grant-tables option, open mysql client and manually update the mysql.user table and/or the mysql.db tables. This can be a tedious task though so if what you need is an account with all privs I would do the following.

Start the server with the skip-grant-tables option

Start mysql client (without a username/password)

Issue the command

flush privileges;

which forces the grant tables to be loaded.

Create a new account with the GRANT command something like this (but replacing username and password with whatever you want to use.

GRANT ALL on *.* to 'username'@'localhost' identified by 'password';

Restart the server in normal mode (without skip-grant-tables) and log in with your newly created account.

Refer this MySQL docs.

maven compilation failure

Inside in yours classses on which is complain maven is some dependecy which belongs to some jar's try right these jars re-build with maven command, i use this command mvn clean install -DskipTests=true should be work in this case when some symbols from classes is missing

Masking password input from the console : Java

You would use the Console class

char[] password = console.readPassword("Enter password");  
Arrays.fill(password, ' ');

By executing readPassword echoing is disabled. Also after the password is validated it is best to overwrite any values in the array.

If you run this from an ide it will fail, please see this explanation for a thorough answer: Explained

Linq filter List<string> where it contains a string value from another List<string>

Try the following:

var filteredFileSet = fileList.Where(item => filterList.Contains(item));

When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.

As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

$this->db->count_all_results is part of an Active Record query (preparing the query, to only return the number, not the actual results).

$query->num_rows() is performed on a resultset object (after returning results from the DB).

Input type number "only numeric value" validation

You need to use regular expressions in your custom validator. For example, here's the code that allows only 9 digits in the input fields:

function ssnValidator(control: FormControl): {[key: string]: any} {
  const value: string = control.value || '';
  const valid = value.match(/^\d{9}$/);
  return valid ? null : {ssn: true};
}

Take a look at a sample app here:

https://github.com/Farata/angular2typescript/tree/master/Angular4/form-samples/src/app/reactive-validator

How to get a jqGrid cell value when editing

As you stated, according to the jqGrid documentation for getCell and getRowData:

Do not use this method when you editing the row or cell. This will return the cell content and not the actual value of the input element

Since neither of these methods will return your data directly, you would have to use them to return the cell content itself and then parse it, perhaps using jQuery. It would be nice if a future version of jqGrid could provide a means to do some of this parsing itself, and/or provide an API to make it more straightforward. But on the other hand is this really a use case that comes up that often?

Alternatively, if you can explain your original problem in more detail there may be other options.

html vertical align the text inside input type button

I've given up trying to align my text on buttons! Now, if I need it, I'm using <a> tags, like so:

<a href="javascript:void();" style="display:block;font-size:1em;padding:5px;cursor:default;" onclick="document.getElementById('form').submit();">Submit</a>

So, if the document's font size is 12px, my "button" will have 22px height. And the text will be vertically align. That in theory, because, in some casses, an unequal padding of "6px 5px 4px 5px" will do the job done.

Although, is a hack, this technique is pretty good for solving compatibility issues in older browsers too, like IE6!

pip install: Please check the permissions and owner of that directory

If you altered your $PATH variable that could also cause the problem. If you think that might be the issue, check your ~/.bash_profile or ~/.bashrc

How do I concatenate two text files in PowerShell?

If you need to order the files by specific parameter (e.g. date time):

gci *.log | sort LastWriteTime | % {$(Get-Content $_)} | Set-Content result.log

List of IP Space used by Facebook

Updated list as of 6/11/2013

204.15.20.0/22
69.63.176.0/20

66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20

How to declare an array of objects in C#

I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

You need to initialize each member of the array separatedly.

houses[0] = new GameObject(..);

Only then can you access the object without compilation errors.

So you can explicitly initalize the array:

for (int i = 0; i < houses.Length; i++)
{
    houses[i] = new GameObject();
}

or you can change GameObject to value type.

Difference between attr_accessor and attr_accessible

attr_accessor is a Ruby method that gives you setter and getter methods to an instance variable of the same name. So it is equivalent to

class MyModel
  def my_variable
    @my_variable
  end
  def my_variable=(value)
    @my_variable = value
  end
end

attr_accessible is a Rails method that determines what variables can be set in a mass assignment.

When you submit a form, and you have something like MyModel.new params[:my_model] then you want to have a little bit more control, so that people can't submit things that you don't want them to.

You might do attr_accessible :email so that when someone updates their account, they can change their email address. But you wouldn't do attr_accessible :email, :salary because then a person could set their salary through a form submission. In other words, they could hack their way to a raise.

That kind of information needs to be explicitly handled. Just removing it from the form isn't enough. Someone could go in with firebug and add the element into the form to submit a salary field. They could use the built in curl to submit a new salary to the controller update method, they could create a script that submits a post with that information.

So attr_accessor is about creating methods to store variables, and attr_accessible is about the security of mass assignments.

How to get tf.exe (TFS command line client)?

You can also try TFS CLI for Node.js which is a cross-platform CLI for Microsoft Team Foundation Server and Visual Studio Team Services.

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

If Sheets("Sheet1").OLEObjects("CheckBox1").Object.Value = True Then

I believe Tim is right. You have a Form Control. For that you have to use this

If ActiveSheet.Shapes("Check Box 1").ControlFormat.Value = 1 Then

removing html element styles via javascript

Remove removeProperty

_x000D_
_x000D_
var el=document.getElementById("id");


el.style.removeProperty('display')

console.log("display removed"+el.style["display"])

console.log("color "+el.style["color"])
_x000D_
<div id="id" style="display:block;color:red">s</div>
_x000D_
_x000D_
_x000D_

Distinct in Linq based on only one field of the table

data.Select(x=>x.Name).Distinct().Select(x => new SelectListItem { Text = x });

Excel VBA App stops spontaneously with message "Code execution has been halted"

One solution is here:

The solution for this problem is to add the line of code “Application.EnableCancelKey = xlDisabled” in the first line of your macro.. This will fix the problem and you will be able to execute the macro successfully without getting the error message “Code execution has been interrupted”.

But, after I inserted this line of code, I was not able to use Ctrl+Break any more. So it works but not greatly.

How do you read scanf until EOF in C?

I guess best way to do this is ...

int main()
{
    char str[100];
    scanf("[^EOF]",str);
    printf("%s",str);
    return 0;     
}

Git error on commit after merge - fatal: cannot do a partial commit during a merge

I got this when I forgot the -m in my git commit when resolving a git merge conflict.

git commit "commit message"

should be

git commit -m "commit message"

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

I had this error with Visual Studion 2019, my project was NopCommerce 4.30 which is an ASP.Net Core 3.1 project. I added page "gouden-munten-buitenland" to be the starting page and I only got the error when going to that page. Turned out that Visual Studio generated an invalid applicationHost.config :

<applicationPools>
    ....
    <add name="gouden-munten-buitenland AppPool" autoStart="true" />
    <add name="gouden-munten-buitenland AppPool 2" autoStart="true" /> <!-- WRONG -->
    <add name="Nop.Web AppPool" managedRuntimeVersion="" />
    <applicationPoolDefaults managedRuntimeVersion="v4.0">
    <processModel loadUserProfile="true" setProfileEnvironment="false" />
    </applicationPoolDefaults>
</applicationPools>

and

<sites>
    ....
    <site name="Nop.Web" id="2">
    ...
    <application path="/gouden-munten-buitenland/gouden-munten-buitenland" applicationPool="gouden-munten-buitenland AppPool">
        <virtualDirectory path="/" physicalPath="C:\Usr\Stephan\Wrk\Kevelam\kNop.430\Presentation\Nop.Web" />
    </application>
    <application path="/gouden-munten-buitenland" applicationPool="gouden-munten-buitenland AppPool 2">
        <virtualDirectory path="/" physicalPath="C:\Usr\Stephan\Wrk\Kevelam\kNop.430\Presentation\Nop.Web" />
    </application> <!-- WRONG -->
    ....
    </site>
    ...
</sites>

I removed the nodes identified as 'WRONG' and then it worked.

Table row and column number in jQuery

Get COLUMN INDEX on click:

$(this).closest("td").index();

Get ROW INDEX on click:

$(this).closest("tr").index();

how to get the host url using javascript from the current page

// will return the host name and port
var host = window.location.host; 

or possibly

var host = window.location.protocol + "//" + window.location.host;

or if you like concatenation

var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);

// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);

// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;

If you have or expect custom ports use window.location.host instead of window.location.hostname

Regular expression to match numbers with or without commas and decimals in text

Some days ago, I worked on the problem of removing trailing zeros from the string of a number.

In the continuity of that problem, I find this one interesting because it widens the problem to numbers comprising commas.

I have taken the regex's pattern I had writen in that previous problem I worked on and I improved it in order that it can treat the numbers with commas as an answer for this problem.

I've been carried away with my enthusiasm and my liking of regexes. I don't know if the result fits exactly to the need expressed by Michael Prescott. I would be interested to know the points that are in excess or in lack in my regex, and to correct it to make it more suitable for you.

Now, after a long session of work on this regex, I have a sort of weight in the brain, so I'm not fresh enough to give a lot of explanation. If points are obscure, and if anybody may come to be interested enough, please, ask me.

The regex is built in order that it can detect the numbers expressed in scientific notation 2E10 or even 5,22,454.12E-00.0478 , removing unnecessary zeros in the two parts of such numbers too. If an exponent is equal to zero , the number is modified so that there is no more exponent.

I put some verification in the pattern so that some particular cases will not match, for exemple '12..57' won't match. But in ',111' the string '111' matches because the preceding comma is considered a comma not being in a number but a comma of sentence.

I think that the managing of commas should be improved, because it seems to me that there are only 2 digits between commas in Indian numbering. It won't be dificult to correct, I presume

Here after is a code demonstrating how my regex works. There are two functions, according if one wants the numbers '.1245' to be transformed in '0.1245' or not. I wouldn't be surprised if errors or unwanted matchings or unmatchings will remain for certain cases of number strings; then I'd like to know these cases to understand and correct the deficiency.

I apologize for this code written in Python, but regexes are trans-langage and I think everybody will be capable of undertsanding the reex's pattern

import re

regx = re.compile('(?<![\d.])(?!\.\.)(?<![\d.][eE][+-])(?<![\d.][eE])(?<!\d[.,])'
                  '' #---------------------------------
                  '([+-]?)'
                  '(?![\d,]*?\.[\d,]*?\.[\d,]*?)'
                  '(?:0|,(?=0)|(?<!\d),)*'
                  '(?:'
                  '((?:\d(?!\.[1-9])|,(?=\d))+)[.,]?'
                  '|\.(0)'
                  '|((?<!\.)\.\d+?)'
                  '|([\d,]+\.\d+?))'
                  '0*'
                  '' #---------------------------------
                  '(?:'
                  '([eE][+-]?)(?:0|,(?=0))*'
                  '(?:'
                  '(?!0+(?=\D|\Z))((?:\d(?!\.[1-9])|,(?=\d))+)[.,]?'
                  '|((?<!\.)\.(?!0+(?=\D|\Z))\d+?)'
                  '|([\d,]+\.(?!0+(?=\D|\Z))\d+?))'
                  '0*'
                  ')?'
                  '' #---------------------------------
                  '(?![.,]?\d)')


def dzs_numbs(x,regx = regx): # ds = detect and zeros-shave
    if not regx.findall(x):
        yield ('No match,', 'No catched string,', 'No groups.')
    for mat in regx.finditer(x):
        yield (mat.group(), ''.join(mat.groups('')), mat.groups(''))

def dzs_numbs2(x,regx = regx): # ds = detect and zeros-shave
    if not regx.findall(x):
        yield ('No match,', 'No catched string,', 'No groups.')
    for mat in regx.finditer(x):
        yield (mat.group(),
               ''.join(('0' if n.startswith('.') else '')+n for n in mat.groups('')),
               mat.groups(''))

NS = ['  23456000and23456000. or23456000.000  00023456000 s000023456000.  000023456000.000 ',
      'arf 10000 sea10000.+10000.000  00010000-00010000. kant00010000.000 ',
      '  24:  24,  24.   24.000  24.000,   00024r 00024. blue 00024.000  ',
      '  8zoom8.  8.000  0008  0008. and0008.000  ',
      '  0   00000M0. = 000.  0.0  0.000    000.0   000.000   .000000   .0   ',
      '  .0000023456    .0000023456000   '
      '  .0005872    .0005872000   .00503   .00503000   ',
      '  .068    .0680000   .8   .8000  .123456123456    .123456123456000    ',
      '  .657   .657000   .45    .4500000   .7    .70000  0.0000023230000   000.0000023230000   ',
      '  0.0081000    0000.0081000  0.059000   0000.059000     ',
      '  0.78987400000 snow  00000.78987400000  0.4400000   00000.4400000   ',
      '  -0.5000  -0000.5000   0.90   000.90   0.7   000.7   ',
      '  2.6    00002.6   00002.60000  4.71   0004.71    0004.7100   ',
      '  23.49   00023.49   00023.490000  103.45   0000103.45   0000103.45000    ',
      '  10003.45067   000010003.45067   000010003.4506700 ',
      '  +15000.0012   +000015000.0012   +000015000.0012000    ',
      '  78000.89   000078000.89   000078000.89000    ',
      '  .0457e10   .0457000e10   00000.0457000e10  ',
      '   258e8   2580000e4   0000000002580000e4   ',
      '  0.782e10   0000.782e10   0000.7820000e10  ',
      '  1.23E2   0001.23E2  0001.2300000E2   ',
      '  432e-102  0000432e-102   004320000e-106   ',
      '  1.46e10and0001.46e10  0001.4600000e10   ',
      '  1.077e-300  0001.077e-300  0001.077000e-300   ',
      '  1.069e10   0001.069e10   0001.069000e10   ',
      '  105040.03e10  000105040.03e10  105040.0300e10    ',
      '  +286E000024.487900  -78.4500e.14500   .0140E789.  ',
      '  081,12.40E07,95.0120     0045,78,123.03500e-0.00  ',
      '  0096,78,473.0380e-0.    0008,78,373.066000E0.    0004512300.E0000  ',
      '  ..18000  25..00 36...77   2..8  ',
      '  3.8..9    .12500.     12.51.400  ',
      '  00099,111.8713000   -0012,45,83,987.26+0.000,099,88,44.or00,00,00.00must',
      '  00099,44,and   0000,099,88,44.bom',
      '00,000,00.587000  77,98,23,45.,  this,that ',
      '  ,111  145.20  +9,9,9  0012800  .,,.  1  100,000 ',
      '1,1,1.111  000,001.111   -999.  0.  111.110000  1.1.1.111  9.909,888']


for ch in NS:
    print 'string: '+repr(ch)
    for strmatch, modified, the_groups in dzs_numbs2(ch):
        print strmatch.rjust(20),'',modified,'',the_groups
    print

result

string: '  23456000and23456000. or23456000.000  00023456000 s000023456000.  000023456000.000 '
            23456000  23456000  ('', '23456000', '', '', '', '', '', '', '')
           23456000.  23456000  ('', '23456000', '', '', '', '', '', '', '')
        23456000.000  23456000  ('', '23456000', '', '', '', '', '', '', '')
         00023456000  23456000  ('', '23456000', '', '', '', '', '', '', '')
       000023456000.  23456000  ('', '23456000', '', '', '', '', '', '', '')
    000023456000.000  23456000  ('', '23456000', '', '', '', '', '', '', '')

string: 'arf 10000 sea10000.+10000.000  00010000-00010000. kant00010000.000 '
               10000  10000  ('', '10000', '', '', '', '', '', '', '')
              10000.  10000  ('', '10000', '', '', '', '', '', '', '')
           10000.000  10000  ('', '10000', '', '', '', '', '', '', '')
            00010000  10000  ('', '10000', '', '', '', '', '', '', '')
           00010000.  10000  ('', '10000', '', '', '', '', '', '', '')
        00010000.000  10000  ('', '10000', '', '', '', '', '', '', '')

string: '  24:  24,  24.   24.000  24.000,   00024r 00024. blue 00024.000  '
                  24  24  ('', '24', '', '', '', '', '', '', '')
                 24,  24  ('', '24', '', '', '', '', '', '', '')
                 24.  24  ('', '24', '', '', '', '', '', '', '')
              24.000  24  ('', '24', '', '', '', '', '', '', '')
              24.000  24  ('', '24', '', '', '', '', '', '', '')
               00024  24  ('', '24', '', '', '', '', '', '', '')
              00024.  24  ('', '24', '', '', '', '', '', '', '')
           00024.000  24  ('', '24', '', '', '', '', '', '', '')

string: '  8zoom8.  8.000  0008  0008. and0008.000  '
                   8  8  ('', '8', '', '', '', '', '', '', '')
                  8.  8  ('', '8', '', '', '', '', '', '', '')
               8.000  8  ('', '8', '', '', '', '', '', '', '')
                0008  8  ('', '8', '', '', '', '', '', '', '')
               0008.  8  ('', '8', '', '', '', '', '', '', '')
            0008.000  8  ('', '8', '', '', '', '', '', '', '')

string: '  0   00000M0. = 000.  0.0  0.000    000.0   000.000   .000000   .0   '
                   0  0  ('', '0', '', '', '', '', '', '', '')
               00000  0  ('', '0', '', '', '', '', '', '', '')
                  0.  0  ('', '0', '', '', '', '', '', '', '')
                000.  0  ('', '0', '', '', '', '', '', '', '')
                 0.0  0  ('', '', '0', '', '', '', '', '', '')
               0.000  0  ('', '', '0', '', '', '', '', '', '')
               000.0  0  ('', '', '0', '', '', '', '', '', '')
             000.000  0  ('', '', '0', '', '', '', '', '', '')
             .000000  0  ('', '', '0', '', '', '', '', '', '')
                  .0  0  ('', '', '0', '', '', '', '', '', '')

string: '  .0000023456    .0000023456000     .0005872    .0005872000   .00503   .00503000   '
         .0000023456  0.0000023456  ('', '', '', '.0000023456', '', '', '', '', '')
      .0000023456000  0.0000023456  ('', '', '', '.0000023456', '', '', '', '', '')
            .0005872  0.0005872  ('', '', '', '.0005872', '', '', '', '', '')
         .0005872000  0.0005872  ('', '', '', '.0005872', '', '', '', '', '')
              .00503  0.00503  ('', '', '', '.00503', '', '', '', '', '')
           .00503000  0.00503  ('', '', '', '.00503', '', '', '', '', '')

string: '  .068    .0680000   .8   .8000  .123456123456    .123456123456000    '
                .068  0.068  ('', '', '', '.068', '', '', '', '', '')
            .0680000  0.068  ('', '', '', '.068', '', '', '', '', '')
                  .8  0.8  ('', '', '', '.8', '', '', '', '', '')
               .8000  0.8  ('', '', '', '.8', '', '', '', '', '')
       .123456123456  0.123456123456  ('', '', '', '.123456123456', '', '', '', '', '')
    .123456123456000  0.123456123456  ('', '', '', '.123456123456', '', '', '', '', '')

string: '  .657   .657000   .45    .4500000   .7    .70000  0.0000023230000   000.0000023230000   '
                .657  0.657  ('', '', '', '.657', '', '', '', '', '')
             .657000  0.657  ('', '', '', '.657', '', '', '', '', '')
                 .45  0.45  ('', '', '', '.45', '', '', '', '', '')
            .4500000  0.45  ('', '', '', '.45', '', '', '', '', '')
                  .7  0.7  ('', '', '', '.7', '', '', '', '', '')
              .70000  0.7  ('', '', '', '.7', '', '', '', '', '')
     0.0000023230000  0.000002323  ('', '', '', '.000002323', '', '', '', '', '')
   000.0000023230000  0.000002323  ('', '', '', '.000002323', '', '', '', '', '')

string: '  0.0081000    0000.0081000  0.059000   0000.059000     '
           0.0081000  0.0081  ('', '', '', '.0081', '', '', '', '', '')
        0000.0081000  0.0081  ('', '', '', '.0081', '', '', '', '', '')
            0.059000  0.059  ('', '', '', '.059', '', '', '', '', '')
         0000.059000  0.059  ('', '', '', '.059', '', '', '', '', '')

string: '  0.78987400000 snow  00000.78987400000  0.4400000   00000.4400000   '
       0.78987400000  0.789874  ('', '', '', '.789874', '', '', '', '', '')
   00000.78987400000  0.789874  ('', '', '', '.789874', '', '', '', '', '')
           0.4400000  0.44  ('', '', '', '.44', '', '', '', '', '')
       00000.4400000  0.44  ('', '', '', '.44', '', '', '', '', '')

string: '  -0.5000  -0000.5000   0.90   000.90   0.7   000.7   '
             -0.5000  -0.5  ('-', '', '', '.5', '', '', '', '', '')
          -0000.5000  -0.5  ('-', '', '', '.5', '', '', '', '', '')
                0.90  0.9  ('', '', '', '.9', '', '', '', '', '')
              000.90  0.9  ('', '', '', '.9', '', '', '', '', '')
                 0.7  0.7  ('', '', '', '.7', '', '', '', '', '')
               000.7  0.7  ('', '', '', '.7', '', '', '', '', '')

string: '  2.6    00002.6   00002.60000  4.71   0004.71    0004.7100   '
                 2.6  2.6  ('', '', '', '', '2.6', '', '', '', '')
             00002.6  2.6  ('', '', '', '', '2.6', '', '', '', '')
         00002.60000  2.6  ('', '', '', '', '2.6', '', '', '', '')
                4.71  4.71  ('', '', '', '', '4.71', '', '', '', '')
             0004.71  4.71  ('', '', '', '', '4.71', '', '', '', '')
           0004.7100  4.71  ('', '', '', '', '4.71', '', '', '', '')

string: '  23.49   00023.49   00023.490000  103.45   0000103.45   0000103.45000    '
               23.49  23.49  ('', '', '', '', '23.49', '', '', '', '')
            00023.49  23.49  ('', '', '', '', '23.49', '', '', '', '')
        00023.490000  23.49  ('', '', '', '', '23.49', '', '', '', '')
              103.45  103.45  ('', '', '', '', '103.45', '', '', '', '')
          0000103.45  103.45  ('', '', '', '', '103.45', '', '', '', '')
       0000103.45000  103.45  ('', '', '', '', '103.45', '', '', '', '')

string: '  10003.45067   000010003.45067   000010003.4506700 '
         10003.45067  10003.45067  ('', '', '', '', '10003.45067', '', '', '', '')
     000010003.45067  10003.45067  ('', '', '', '', '10003.45067', '', '', '', '')
   000010003.4506700  10003.45067  ('', '', '', '', '10003.45067', '', '', '', '')

string: '  +15000.0012   +000015000.0012   +000015000.0012000    '
         +15000.0012  +15000.0012  ('+', '', '', '', '15000.0012', '', '', '', '')
     +000015000.0012  +15000.0012  ('+', '', '', '', '15000.0012', '', '', '', '')
  +000015000.0012000  +15000.0012  ('+', '', '', '', '15000.0012', '', '', '', '')

string: '  78000.89   000078000.89   000078000.89000    '
            78000.89  78000.89  ('', '', '', '', '78000.89', '', '', '', '')
        000078000.89  78000.89  ('', '', '', '', '78000.89', '', '', '', '')
     000078000.89000  78000.89  ('', '', '', '', '78000.89', '', '', '', '')

string: '  .0457e10   .0457000e10   00000.0457000e10  '
            .0457e10  0.0457e10  ('', '', '', '.0457', '', 'e', '10', '', '')
         .0457000e10  0.0457e10  ('', '', '', '.0457', '', 'e', '10', '', '')
    00000.0457000e10  0.0457e10  ('', '', '', '.0457', '', 'e', '10', '', '')

string: '   258e8   2580000e4   0000000002580000e4   '
               258e8  258e8  ('', '258', '', '', '', 'e', '8', '', '')
           2580000e4  2580000e4  ('', '2580000', '', '', '', 'e', '4', '', '')
  0000000002580000e4  2580000e4  ('', '2580000', '', '', '', 'e', '4', '', '')

string: '  0.782e10   0000.782e10   0000.7820000e10  '
            0.782e10  0.782e10  ('', '', '', '.782', '', 'e', '10', '', '')
         0000.782e10  0.782e10  ('', '', '', '.782', '', 'e', '10', '', '')
     0000.7820000e10  0.782e10  ('', '', '', '.782', '', 'e', '10', '', '')

string: '  1.23E2   0001.23E2  0001.2300000E2   '
              1.23E2  1.23E2  ('', '', '', '', '1.23', 'E', '2', '', '')
           0001.23E2  1.23E2  ('', '', '', '', '1.23', 'E', '2', '', '')
      0001.2300000E2  1.23E2  ('', '', '', '', '1.23', 'E', '2', '', '')

string: '  432e-102  0000432e-102   004320000e-106   '
            432e-102  432e-102  ('', '432', '', '', '', 'e-', '102', '', '')
        0000432e-102  432e-102  ('', '432', '', '', '', 'e-', '102', '', '')
      004320000e-106  4320000e-106  ('', '4320000', '', '', '', 'e-', '106', '', '')

string: '  1.46e10and0001.46e10  0001.4600000e10   '
             1.46e10  1.46e10  ('', '', '', '', '1.46', 'e', '10', '', '')
          0001.46e10  1.46e10  ('', '', '', '', '1.46', 'e', '10', '', '')
     0001.4600000e10  1.46e10  ('', '', '', '', '1.46', 'e', '10', '', '')

string: '  1.077e-300  0001.077e-300  0001.077000e-300   '
          1.077e-300  1.077e-300  ('', '', '', '', '1.077', 'e-', '300', '', '')
       0001.077e-300  1.077e-300  ('', '', '', '', '1.077', 'e-', '300', '', '')
    0001.077000e-300  1.077e-300  ('', '', '', '', '1.077', 'e-', '300', '', '')

string: '  1.069e10   0001.069e10   0001.069000e10   '
            1.069e10  1.069e10  ('', '', '', '', '1.069', 'e', '10', '', '')
         0001.069e10  1.069e10  ('', '', '', '', '1.069', 'e', '10', '', '')
      0001.069000e10  1.069e10  ('', '', '', '', '1.069', 'e', '10', '', '')

string: '  105040.03e10  000105040.03e10  105040.0300e10    '
        105040.03e10  105040.03e10  ('', '', '', '', '105040.03', 'e', '10', '', '')
     000105040.03e10  105040.03e10  ('', '', '', '', '105040.03', 'e', '10', '', '')
      105040.0300e10  105040.03e10  ('', '', '', '', '105040.03', 'e', '10', '', '')

string: '  +286E000024.487900  -78.4500e.14500   .0140E789.  '
  +286E000024.487900  +286E24.4879  ('+', '286', '', '', '', 'E', '', '', '24.4879')
     -78.4500e.14500  -78.45e0.145  ('-', '', '', '', '78.45', 'e', '', '.145', '')
          .0140E789.  0.014E789  ('', '', '', '.014', '', 'E', '789', '', '')

string: '  081,12.40E07,95.0120     0045,78,123.03500e-0.00  '
081,12.40E07,95.0120  81,12.4E7,95.012  ('', '', '', '', '81,12.4', 'E', '', '', '7,95.012')
   0045,78,123.03500  45,78,123.035  ('', '', '', '', '45,78,123.035', '', '', '', '')

string: '  0096,78,473.0380e-0.    0008,78,373.066000E0.    0004512300.E0000  '
    0096,78,473.0380  96,78,473.038  ('', '', '', '', '96,78,473.038', '', '', '', '')
  0008,78,373.066000  8,78,373.066  ('', '', '', '', '8,78,373.066', '', '', '', '')
         0004512300.  4512300  ('', '4512300', '', '', '', '', '', '', '')

string: '  ..18000  25..00 36...77   2..8  '
           No match,  No catched string,  No groups.

string: '  3.8..9    .12500.     12.51.400  '
           No match,  No catched string,  No groups.

string: '  00099,111.8713000   -0012,45,83,987.26+0.000,099,88,44.or00,00,00.00must'
   00099,111.8713000  99,111.8713  ('', '', '', '', '99,111.8713', '', '', '', '')
  -0012,45,83,987.26  -12,45,83,987.26  ('-', '', '', '', '12,45,83,987.26', '', '', '', '')
         00,00,00.00  0  ('', '', '0', '', '', '', '', '', '')

string: '  00099,44,and   0000,099,88,44.bom'
           00099,44,  99,44  ('', '99,44', '', '', '', '', '', '', '')
     0000,099,88,44.  99,88,44  ('', '99,88,44', '', '', '', '', '', '', '')

string: '00,000,00.587000  77,98,23,45.,  this,that '
    00,000,00.587000  0.587  ('', '', '', '.587', '', '', '', '', '')
        77,98,23,45.  77,98,23,45  ('', '77,98,23,45', '', '', '', '', '', '', '')

string: '  ,111  145.20  +9,9,9  0012800  .,,.  1  100,000 '
                ,111  111  ('', '111', '', '', '', '', '', '', '')
              145.20  145.2  ('', '', '', '', '145.2', '', '', '', '')
              +9,9,9  +9,9,9  ('+', '9,9,9', '', '', '', '', '', '', '')
             0012800  12800  ('', '12800', '', '', '', '', '', '', '')
                   1  1  ('', '1', '', '', '', '', '', '', '')
             100,000  100,000  ('', '100,000', '', '', '', '', '', '', '')

string: '1,1,1.111  000,001.111   -999.  0.  111.110000  1.1.1.111  9.909,888'
           1,1,1.111  1,1,1.111  ('', '', '', '', '1,1,1.111', '', '', '', '')
         000,001.111  1.111  ('', '', '', '', '1.111', '', '', '', '')
               -999.  -999  ('-', '999', '', '', '', '', '', '', '')
                  0.  0  ('', '0', '', '', '', '', '', '', '')
          111.110000  111.11  ('', '', '', '', '111.11', '', '', '', '')

Chmod recursively

Adding executable permissions, recursively, to all files (not folders) within the current folder with sh extension:

find . -name '*.sh' -type f | xargs chmod +x

* Notice the pipe (|)

Why and when to use angular.copy? (Deep Copy)

In that case, you don't need to use angular.copy()

Explanation :

  • = represents a reference whereas angular.copy() creates a new object as a deep copy.

  • Using = would mean that changing a property of response.data would change the corresponding property of $scope.example or vice versa.

  • Using angular.copy() the two objects would remain seperate and changes would not reflect on each other.

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

If you have content with height unknown but you know the height the of container. The following solution works extremely well.

HTML

<div class="center-test">
    <span></span><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. 
    Nesciunt obcaecati maiores nulla praesentium amet explicabo ex iste asperiores 
    nisi porro sequi eaque rerum necessitatibus molestias architecto eum velit 
    recusandae ratione.</p>
</div>

CSS

.center-test { 
   width: 300px; 
   height: 300px; 
   text-align: 
   center; 
   background-color: #333; 
}
.center-test span { 
   height: 300px; 
   display: inline-block; 
   zoom: 1; 
   *display: inline; 
   vertical-align: middle; 
 }
.center-test p { 
   display: inline-block; 
   zoom: 1; 
   *display: inline; 
   vertical-align: middle; 
   color: #fff; 
 }

EXAMPLE http://jsfiddle.net/thenewconfection/eYtVN/

One gotcha for newby's to display: inline-block; [span] and [p] have no html white space so that the span then doesn't take up any space. Also I've added in the CSS hack for display inline-block for IE. Hope this helps someone!

Android ListView Divider

I had the same issue. However making the view 1px didn't seem to work on my original Nexus 7. I noticed that the screen density was 213 which is less than the 240 used in xhdpi. So it was thinking the device was an mdpi density.

My solution was to make it so the dimens folder had a dividerHeight parameter. I set it to 2dp in the values-mdpi folder but 1dp in the values-hdpi etc folders.

How to go up a level in the src path of a URL in HTML?

Use ../:

background-image: url('../images/bg.png');

You can use that as often as you want, e.g. ../../images/ or even at different positions, e.g. ../images/../images/../images/ (same as ../images/ of course)

HTML: How to make a submit button with text + image in it?

<input type="button" id="btnTexWrapped" style="background: url('http://i0006.photobucket.com/albums/0006/findstuff22/Backgrounds/bokeh2backgrounds.jpg');background-size:30px;width:50px;height:3em;" />

Change input style elements as you want to get the button you need.

I hope it was helpful.

What is the use of <<<EOD in PHP?

there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD') and heredoc(<<<EOD) strings

you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.

nowdoc strings will not expand variables just like single quotes.

ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Swift - Remove " character from string

Let's say you have a string:

var string = "potatoes + carrots"

And you want to replace the word "potatoes" in that string with "tomatoes"

string = string.replacingOccurrences(of: "potatoes", with: "tomatoes", options: NSString.CompareOptions.literal, range: nil)

If you print your string, it will now be: "tomatoes + carrots"

If you want to remove the word potatoes from the sting altogether, you can use:

string = string.replacingOccurrences(of: "potatoes", with: "", options: NSString.CompareOptions.literal, range: nil)

If you want to use some other characters in your sting, use:

  • Null Character (\0)
  • Backslash (\)
  • Horizontal Tab (\t)
  • Line Feed (\n)
  • Carriage Return (\r)
  • Double Quote (\")
  • Single Quote (\')

Example:

string = string.replacingOccurrences(of: "potatoes", with: "dog\'s toys", options: NSString.CompareOptions.literal, range: nil)

Output: "dog's toys + carrots"