Programs & Examples On #Png transparency

Git commit in terminal opens VIM, but can't get back to terminal

To save your work and exit press Esc and then :wq (w for write and q for quit).

Alternatively, you could both save and exit by pressing Esc and then :x

To set another editor run export EDITOR=myFavoriteEdioron your terminal, where myFavoriteEdior can be vi, gedit, subl(for sublime) etc.

The equivalent of wrap_content and match_parent in flutter?

Use FractionallySizedBox widget.

FractionallySizedBox(
  widthFactor: 1.0, // width w.r.t to parent
  heightFactor: 1.0,  // height w.r.t to parent
  child: *Your Child Here*
}

This widget is also very useful when you want to size your child at a fractional of its parent's size.

Example:

If you want the child to occupy 50% width of its parent, provide widthFactor as 0.5

How do I reset the setInterval timer?

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

function myFn() {console.log('idle');}

var myTimer = setInterval(myFn, 4000);

// Then, later at some future time, 
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

You could also use a little timer object that offers a reset feature:

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new or original interval, stop current interval
    this.reset = function(newT = t) {
        t = newT;
        return this.stop().start();
    }
}

Usage:

var timer = new Timer(function() {
    // your function here
}, 5000);


// switch interval to 10 seconds
timer.reset(10000);

// stop the timer
timer.stop();

// start the timer
timer.start();

Working demo: https://jsfiddle.net/jfriend00/t17vz506/

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

SEVERE: Error listenerStart

This boils down to that a ServletContextListener which is registered by either @WebListener annotation on the class, or by a <listener> declaration in web.xml, has thrown an unhandled exception inside the contextInitialized() method. This is usually caused by a developer's mistake (a bug) and needs to be fixed. For example, a NullPointerException.

The full exception should be visible in webapp-specific startup log as well as the IDE console, before the particular line which you've copypasted. If there is none and you still can't figure the cause of the exception by just looking at the code, put the entire contextInitialized() code in a try-catch wherein you log the exception to a reliable output and then interpret and fix it accordingly.

Setting the correct PATH for Eclipse

Go to System Properties > Advanced > Enviroment Variables and look under System variables

First, create/set your JAVA_HOME variable

Even though Eclipse doesn't consult the JAVA_HOME variable, it's still a good idea to set it. See How do I run Eclipse? for more information.

If you have not created and/or do not see JAVA_HOME under the list of System variables, do the following:

  1. Click New... at the very bottom
  2. For Variable name, type JAVA_HOME exactly
  3. For Variable value, this could be different depending on what bits your computer and java are.
    • If both your computer and java are 64-bit, type C:\Program Files\Java\jdk1.8.0_60
    • If both your computer and java are 32-bit, type C:\Program Files\Java\jdk1.8.0_60
    • If your computer is 64-bit, but your java is 32-bit, type C:\Program Files (x86)\Java\jdk1.8.0_60

If you have created and/or do see JAVA_HOME, do the following:

  1. Click on the row under System variables that you see JAVA_HOME in
  2. Click Edit... at the very bottom
  3. For Variable value, change it to what was stated in #3 above based on java's and your computer's bits. To repeat:
    • If both your computer and java are 64-bit, change it to C:\Program Files\Java\jdk1.8.0_60
    • If both your computer and java are 32-bit, change it to C:\Program Files\Java\jdk1.8.0_60
    • If your computer is 64-bit, but your java is 32-bit, change it to C:\Program Files (x86)\Java\jdk1.8.0_60

Next, add to your PATH variable

  1. Click on the row under System variables with PATH in it
  2. Click Edit... at the very bottom
  3. If you have a newer version of windows:
    • Click New
    • Type in C:\Program Files (x86)\Java\jdk1.8.0_60 OR C:\Program Files\Java\jdk1.8.0_60 depending on the bits of your computer and java (see above ^).
    • Press Enter and Click New again.
    • Type in C:\Program Files (x86)\Java\jdk1.8.0_60\jre OR C:\Program Files\Java\jdk1.8.0_60\jre depending on the bits of your computer and java (see above again ^).
    • Press Enter and press OK on all of the related windows
  4. If you have an older version of windows
    • In the Variable value textbox (or something similar) drag the cursor all the way to the very end
    • Add a semicolon (;) if there isn't one already
    • C:\Program Files (x86)\Java\jdk1.8.0_60 OR C:\Program Files\Java\jdk1.8.0_60
    • Add another semicolon (;)
    • C:\Program Files (x86)\Java\jdk1.8.0_60\jre OR C:\Program Files\Java\jdk1.8.0_60\jre

Changing eclipse.ini

  1. Find your eclipse.ini file and copy-paste it in the same directory (should be named eclipse(1).ini)
  2. Rename eclipse.ini to eclipse.ini.old just in case something goes wrong
  3. Rename eclipse(1).ini to eclipse.ini
  4. Open your newly-renamed eclipse.ini and replace all of it with this:

    -startup
    plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
    --launcher.library
    plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
    -product
    org.eclipse.epp.package.java.product
    --launcher.defaultAction
    openFile
    --launcher.XXMaxPermSize
    256M
    -showsplash
    org.eclipse.platform
    --launcher.XXMaxPermSize
    256m
    --launcher.defaultAction
    openFile
    -vm
    C:\Program Files\Java\jdk1.8.0_60\bin\javaw.exe
    -vmargs
    -Dosgi.requiredJavaVersion=1.5
    -Xms40m
    -Xmx1024m
    

XXMaxPermSize may be deprecated, so it might not work. If eclipse still does not launch, do the following:

  1. Delete the newer eclipse.ini
  2. Rename eclipse.ini.old to eclipse.ini
  3. Open command prompt
  4. type in eclipse -vm C:\Program Files (x86)\Java\jdk1.8.0_60\bin\javaw.exe

If the problem remains

Try updating your eclipse and java to the latest version. 8u60 (1.8.0_60) is not the latest version of java. Sometimes, the latest version of java doesn't work with older versions of eclipse and vice versa. Otherwise, leave a comment if you're still having problems. You could also try a fresh reinstallation of Java.

Display Parameter(Multi-value) in Report

Hopefully someone else finds this useful:

Using the Join is the best way to use a multi-value parameter. But what if you want to have an efficient 'Select All'? If there are 100s+ then the query will be very inefficient.

To solve this instead of using a SQL Query as is, change it to using an expression (click the Fx button top right) then build your query something like this (speech marks are necessary):

= "Select * from tProducts Where 1 = 1 " 
IIF(Parameters!ProductID.Value(0)=-1,Nothing," And ProductID In (" & Join(Parameters!ProductID.Value,"','") & ")")

In your Parameter do the following:

    SELECT -1 As ProductID, 'All' as ProductName Union All
    Select  
    tProducts.ProductID,tProducts.ProductName
    FROM
    tProducts

By building the query as an expression means you can make the SQL Statement more efficient but also handle the difficulty SQL Server has with handling values in an 'In' statement.

How do I programmatically click a link with javascript?

You could just redirect them to another page. Actually making it literally click a link and travel to it seems unnessacary, but I don't know the whole story.

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

Add the jstl-1.2.jar into the tomcat/lib folder.

With this, your dependency error will be fixed again.

Jquery Ajax Loading image

Description

You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

  1. Create a div with your image
  2. Make it visible in jQuery.ajaxStart
  3. Hide it in jQuery.ajaxStop

Sample

<div id="loading" style="display:none">Your Image</div>

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
    $(function () {
        var loading = $("#loading");
        $(document).ajaxStart(function () {
            loading.show();
        });

        $(document).ajaxStop(function () {
            loading.hide();
        });

        $("#startAjaxRequest").click(function () {
            $.ajax({
                url: "http://www.google.com",
                // ... 
            });
        });
    });
</script>

<button id="startAjaxRequest">Start</button>

More Information

Why do we need to use flatMap?

When I started to have a look at Rxjs I also stumbled on that stone. What helped me is the following:

  • documentation from reactivex.io . For instance, for flatMap: http://reactivex.io/documentation/operators/flatmap.html
  • documentation from rxmarbles : http://rxmarbles.com/. You will not find flatMap there, you must look at mergeMap instead (another name).
  • the introduction to Rx that you have been missing: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754. It addresses a very similar example. In particular it addresses the fact that a promise is akin to an observable emitting only one value.
  • finally looking at the type information from RxJava. Javascript not being typed does not help here. Basically if Observable<T> denotes an observable object which pushes values of type T, then flatMap takes a function of type T' -> Observable<T> as its argument, and returns Observable<T>. map takes a function of type T' -> T and returns Observable<T>.

    Going back to your example, you have a function which produces promises from an url string. So T' : string, and T : promise. And from what we said before promise : Observable<T''>, so T : Observable<T''>, with T'' : html. If you put that promise producing function in map, you get Observable<Observable<T''>> when what you want is Observable<T''>: you want the observable to emit the html values. flatMap is called like that because it flattens (removes an observable layer) the result from map. Depending on your background, this might be chinese to you, but everything became crystal clear to me with typing info and the drawing from here: http://reactivex.io/documentation/operators/flatmap.html.

Installing MySQL-python

Reread the error message. It says:

sh: mysql_config: not found

If you are on Ubuntu Natty, mysql_config belongs to package libmysqlclient-dev

How to change default timezone for Active Record in Rails?

adding following to application.rb works

 config.time_zone = 'Eastern Time (US & Canada)'
 config.active_record.default_timezone = :local # Or :utc

Python's equivalent of && (logical-and) in an if-statement

A single & (not double &&) is enough or as the top answer suggests you can use 'and'. I also found this in pandas

cities['Is wide and has saint name'] = (cities['Population'] > 1000000) 
& cities['City name'].apply(lambda name: name.startswith('San'))

if we replace the "&" with "and", it won't work.

Creating multiple objects with different names in a loop to store in an array list

ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
    //get a customerName
    //get an amount
    custArr.add(new Customer(customerName, amount);
}

For this to work... you'll have to fix your constructor...


Assuming your Customer class has variables called name and sale, your constructor should look like this:

public Customer(String customerName, double amount) {
    name = customerName;
    sale = amount;
}

Change your Store class to something more like this:

public class Store {

    private ArrayList<Customer> custArr;

    public new Store() {
        custArr = new ArrayList<Customer>();
    }

    public void addSale(String customerName, double amount) {
        custArr.add(new Customer(customerName, amount));
    }

    public Customer getSaleAtIndex(int index) {
        return custArr.get(index);
    }

    //or if you want the entire ArrayList:
    public ArrayList getCustArr() {
        return custArr;
    }
}

How to get HQ youtube thumbnails?

Are you referring to the full resolution one?:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

I don't believe you can get 'multiple' images of HQ because the one you have is the one.

Check the following answer out for more information on the URLs: How do I get a YouTube video thumbnail from the YouTube API?

For live videos use https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault_live.jpg

- cornips

How to implement a SQL like 'LIKE' operator in java?

Ok this is a bit of a weird solution, but I thought it should still be mentioned.

Instead of recreating the like mechanism we can utilize the existing implementation already available in any database!

(Only requirement is, your application must have access to any database).

Just run a very simple query each time,that returns true or false depending on the result of the like's comparison. Then execute the query, and read the answer directly from the database!

For Oracle db:

SELECT
CASE 
     WHEN 'StringToSearch' LIKE 'LikeSequence' THEN 'true'
     ELSE 'false'
 END test
FROM dual 

For MS SQL Server

SELECT
CASE 
     WHEN 'StringToSearch' LIKE 'LikeSequence' THEN 'true'
     ELSE 'false'
END test

All you have to do is replace "StringToSearch" and "LikeSequence" with bind parameters and set the values you want to check.

How do I add an "Add to Favorites" button or link on my website?

I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:

jQuery('.bookmarkMeLink').click(function() {
    if (window.sidebar && window.sidebar.addPanel) { 
        // Mozilla Firefox Bookmark
        window.sidebar.addPanel(document.title,window.location.href,'');
    }
    else if(window.sidebar && jQuery.browser.mozilla){
        //for other version of FF add rel="sidebar" to link like this:
        //<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
        jQuery(this).attr('rel', 'sidebar');
    }
    else if(window.external && ('AddFavorite' in window.external)) { 
        // IE Favorite
        window.external.AddFavorite(location.href,document.title); 
    } else if(window.opera && window.print) { 
        // Opera Hotlist
        this.title=document.title;
        return true;
    } else { 
        // webkit - safari/chrome
        alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');

    }
});

strcpy() error in Visual studio 2012

There's an explanation and solution for this on MSDN:

The function strcpy is considered unsafe due to the fact that there is no bounds checking and can lead to buffer overflow.

Consequently, as it suggests in the error description, you can use strcpy_s instead of strcpy:

strcpy_s( char *strDestination, size_t numberOfElements,
const char *strSource );

and:

To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

http://social.msdn.microsoft.com/Forums/da-DK/vcgeneral/thread/c7489eef-b391-4faa-bf77-b824e9e8f7d2

wait until all threads finish their work in java

Use this in your main thread: while(!executor.isTerminated()); Put this line of code after starting all the threads from executor service. This will only start the main thread after all the threads started by executors are finished. Make sure to call executor.shutdown(); before the above loop.

PHP not displaying errors even though display_errors = On

For me I solved it by deleting the file of php_errors.txt in the relative folder. Then the file is created automatically again when the code runs next time, and with the errors printed this time.

How can I rebuild indexes and update stats in MySQL innoDB?

You can also use the provided CLI tool mysqlcheck to run the optimizations. It's got a ton of switches but at its most basic you just pass in the database, username, and password.

Adding this to cron or the Windows Scheduler can make this an automated process. (MariaDB but basically the same thing.)

jQuery load more data on scroll

I suggest using more Math.ceil for avoid error on some screen.
Because on a few different screens it's not absolutely accurate
I realized that when I console.log.

console.log($(window).scrollTop()); //5659.20123123890  

And

console.log$(document).height() - $(window).height()); // 5660

So I think we should edit your code to

$(window).scroll(function() {
    if(Math.ceil($(window).scrollTop()) 
       == Math.ceil(($(document).height() - $(window).height()))) {
           // ajax call get data from server and append to the div
    }
});

Or Allow load data from server before scroll until bottom.

if ($(window).scrollTop() >= ($(document).height() - $(window).height() - 200)) {
 // Load data
}

Archive the artifacts in Jenkins

Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.

A common convention is to put the result of a build into a build, target or bin directory.

The Jenkins archiver can use globs (target/*.jar) to easily pick up the right file even if you have a unique name per build.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

Try to do this. It worked for me.

Debug=>Options=>General => Remove the check mark for "Enable Just My Code"

How to remove indentation from an unordered list item?

Set the list style and left padding to nothing.

ul {
    list-style: none;
    padding-left: 0;
}?

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
  padding-left: 0;_x000D_
}
_x000D_
<ul>_x000D_
  <li>a</li>_x000D_
  <li>b</li>_x000D_
  <li>c</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

To maintain the bullets you can replace the list-style: none with list-style-position: inside or the shorthand list-style: inside:

ul {
  list-style-position: inside;
  padding-left: 0;
}

_x000D_
_x000D_
ul {_x000D_
  list-style-position: inside;_x000D_
  padding-left: 0;_x000D_
}
_x000D_
<ul>_x000D_
  <li>a</li>_x000D_
  <li>b</li>_x000D_
  <li>c</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Thymeleaf using path variables to th:href

try this one is a very easy method if you are in list of model foreach (var item in Modal) loop

<th:href="/category/edit/@item.idCategory>View</a>"

or

<th:href="/category/edit/@item.idCategory">View</a>

Opening a folder in explorer and selecting a file

Using Process.Start on explorer.exe with the /select argument oddly only works for paths less than 120 characters long.

I had to use a native windows method to get it to work in all cases:

[DllImport("shell32.dll", SetLastError = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);

[DllImport("shell32.dll", SetLastError = true)]
public static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);

public static void OpenFolderAndSelectItem(string folderPath, string file)
{
    IntPtr nativeFolder;
    uint psfgaoOut;
    SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);

    if (nativeFolder == IntPtr.Zero)
    {
        // Log error, can't find folder
        return;
    }

    IntPtr nativeFile;
    SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);

    IntPtr[] fileArray;
    if (nativeFile == IntPtr.Zero)
    {
        // Open the folder without the file selected if we can't find the file
        fileArray = new IntPtr[0];
    }
    else
    {
        fileArray = new IntPtr[] { nativeFile };
    }

    SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);

    Marshal.FreeCoTaskMem(nativeFolder);
    if (nativeFile != IntPtr.Zero)
    {
        Marshal.FreeCoTaskMem(nativeFile);
    }
}

What is the difference between gravity and layout_gravity in Android?

The android:gravity sets the gravity (position) of the children whereas the android:layout_gravity sets the position of the view itself. Hope it helps

MongoDb query condition on comparing 2 fields

If your query consists only of the $where operator, you can pass in just the JavaScript expression:

db.T.find("this.Grade1 > this.Grade2");

For greater performance, run an aggregate operation that has a $redact pipeline to filter the documents which satisfy the given condition.

The $redact pipeline incorporates the functionality of $project and $match to implement field level redaction where it will return all documents matching the condition using $$KEEP and removes from the pipeline results those that don't match using the $$PRUNE variable.


Running the following aggregate operation filter the documents more efficiently than using $where for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where, which can slow down the query:

db.T.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$gt": [ "$Grade1", "$Grade2" ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

which is a more simplified version of incorporating the two pipelines $project and $match:

db.T.aggregate([
    {
        "$project": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
            "Grade1": 1,
            "Grade2": 1,
            "OtherFields": 1,
            ...
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

With MongoDB 3.4 and newer:

db.T.aggregate([
    {
        "$addFields": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

Android: Storing username and password?

The info at http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html is a fairly pragmatic, but "uses-hidden-android-apis" based approach. It's something to consider when you really can't get around storing credentials/passwords locally on the device.

I've also created a cleaned up gist of that idea at https://gist.github.com/kbsriram/5503519 which might be helpful.

CSS Child vs Descendant selectors

CSS selection and applying style to a particular element can be done through traversing through the dom element [Example

Example

.a .b .c .d{
    background: #bdbdbd;
}
div>div>div>div:last-child{
    background: red;
}
<div class='a'>The first paragraph.
 <div class='b'>The second paragraph.
  <div class='c'>The third paragraph.
   <div class='d'>The fourth paragraph.</div>
   <div class='e'>The fourth paragraph.</div>
  </div>
 </div>
</div>

target input by type and name (selector)

You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

or

$("input:checkbox[name='ProductCode']").each(function(){ ...

It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName method which will be used to select elements and be much faster than selecting by the name attribute

How to center a checkbox in a table cell?

Make sure that your <td> is not display: block;

Floating will do this, but much easier to just: display: inline;

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

As @borayeris said,

yum install glibc.i686

But if you cannot find glibc.i686 or libstdc++ package, try -

sudo yum search glibc
sudo yum search libstd

and then,

sudo yum install {package}

android - listview get item view by position

Preferred way to change the appearance/whatever of row views once the ListView is drawn is to change something in the data ListView draws from (the array of objects that is passed into your Adapter) and make sure to account for that in your getView() function, then redraw the ListView by calling

notifyDataSetChanged();

EDIT: while there is a way to do this, if you need to do this chances are doing something wrong. While are few edge cases I can think about, generally using notifyDataSetChanged() and other built in mechanisms is a way to go.

EDIT 2: One of the common mistakes people make is trying to come up with their own way to respond to user clicking/selecting a row in the ListView, as in one of the comments to this post. There is an existing way to do this. Here's how:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    /* Parameters
    parent:     The AdapterView where the click happened.
    view:       The view within the AdapterView that was clicked (this will be a view provided by the adapter)
    position:   The position of the view in the adapter.
    id:         The row id of the item that was clicked. */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //your code here
    }
});

ListView has a lot of build-in functionality and there is no need to reinvent the wheel for simpler cases. Since ListView extends AdapterView, you can set the same Listeners, such as OnItemClickListener as in the example above.

sys.stdin.readline() reads without prompt, returning 'nothing in between'

Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.

But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.

There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.

First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty(). That part is cross-platform.

For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin. In Python 3, this just means sys.stdin.buffer.raw.read(1) and sys.stdin.buffer.raw.readline(). However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding) on the results; you can wrap that all up in a function.

For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1), you do msvcrt.getwch().

For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1), etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw function. If you want to return to line-discipline mode later, you'll need to use the termios module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno()) before calling setraw, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash), you don't have to learn what all those fiddly bits mean.

On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw. You could always replace readline by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.

How do I set cell value to Date and apply default Excel date format?

To set to default Excel type Date (defaulted to OS level locale /-> i.e. xlsx will look different when opened by a German or British person/ and flagged with an asterisk if you choose it in Excel's cell format chooser) you should:

    CellStyle cellStyle = xssfWorkbook.createCellStyle();
    cellStyle.setDataFormat((short)14);
    cell.setCellStyle(cellStyle);

I did it with xlsx and it worked fine.

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

How to call an async method from a getter or setter?

I think my example below may follow @Stephen-Cleary 's approach but I wanted to give a coded example. This is for use in a data binding context for example Xamarin.

The constructor of the class - or indeed the setter of another property on which it is dependent - may call an async void that will populate the property on completion of the task without the need for an await or block. When it finally gets a value it will update your UI via the NotifyPropertyChanged mechanism.

I'm not certain about any side effects of calling a aysnc void from a constructor. Perhaps a commenter will elaborate on error handling etc.

class MainPageViewModel : INotifyPropertyChanged
{
    IEnumerable myList;

    public event PropertyChangedEventHandler PropertyChanged;

    public MainPageViewModel()
    {

        MyAsyncMethod()

    }

    public IEnumerable MyList
    {
        set
        {
            if (myList != value)
            {
                myList = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("MyList"));
                }
            }
        }
        get
        {
            return myList;
        }
    }

    async void MyAsyncMethod()
    {
        MyList = await DoSomethingAsync();
    }


}

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

Using jq to parse and display multiple fields in a json serially

You can use addition to concatenate strings.

Strings are added by being joined into a larger string.

jq '.users[] | .first + " " + .last'

The above works when both first and last are string. If you are extracting different datatypes(number and string), then we need to convert to equivalent types. Referring to solution on this question. For example.

jq '.users[] | .first + " " + (.number|tostring)'

TypeError: Cannot read property "0" from undefined

Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.

Ammend your while statement to this...

for(var iIndex = 1; iIndex <= data.length; iIndex++){
    if (data[iIndex][0] === name){
         break;
    };
    Logger.log(data[i][0]);
 };

Should URL be case sensitive?

Old question but I stumbled here so why not take a shot at it since the question is seeking various perspective and not a definitive answer.

w3c may have its recommendations - which I care a lot - but want to rethink since the question is here.

Why does w3c consider domain names be case insensitive and leaves anything afterwards case insensitive ?

I am thinking that the rationale is that the domain part of the URL is hand typed by a user. Everything after being hyper text will be resolved by the machine (browser and server in the back).

Machines can handle case insensitivity better than humans (not the technical kind:)).

But the question is just because the machines CAN handle that should it be done that way ?

I mean what are the benefits of naming and accessing a resource sitting at hereIsTheResource vs hereistheresource ?

The lateral is very unreadable than the camel case one which is more readable. Readable to Humans (including the technical kind.)

So here are my points:-

Resource Path falls in the somewhere in the middle of programming structure and being close to an end user behind the browser sometimes.

Your URL (excluding the domain name) should be case insensitive if your users are expected to touch it or type it etc. You should develop your application to AVOID having users type the path as much as possible.

Your URL (excluding the domain name) should be case sensitive if your users would never type it by hand.

Conclusion

Path should be case sensitive. My points are weighing towards the case sensitive paths.

Converting Milliseconds to Minutes and Seconds?

After converting millis to seconds (by dividing by 1000), you can use / 60 to get the minutes value, and % 60 (remainder) to get the "seconds in minute" value.

long millis = .....;  // obtained from StopWatch
long minutes = (millis / 1000)  / 60;
int seconds = (int)((millis / 1000) % 60);

Free space in a CMD shell

I make a variation to generate this out from script:

volume C: - 49 GB total space / 29512314880 byte(s) free

I use diskpart to get this information.

@echo off
setlocal enableextensions enabledelayedexpansion
set chkfile=drivechk.tmp
if "%1" == "" goto :usage
set drive=%1
set drive=%drive:\=%
set drive=%drive::=%
dir %drive%:>nul 2>%chkfile%
for %%? in (%chkfile%) do (
  set chksize=%%~z?
)
if %chksize% neq 0 (
  more %chkfile%
  del %chkfile%
  goto :eof
)
del %chkfile%
echo list volume | diskpart | find /I " %drive% " >%chkfile%
for /f "tokens=6" %%a in ('type %chkfile%' ) do (
    set dsksz=%%a
)
for /f "tokens=7" %%a in ('type %chkfile%' ) do (
    set dskunit=%%a
)
del %chkfile%
for /f "tokens=3" %%a in ('dir %drive%:\') do (
  set bytesfree=%%a
)
set bytesfree=%bytesfree:,=%
echo volume %drive%: - %dsksz% %dskunit% total space / %bytesfree% byte(s) free
endlocal

goto :eof
:usage
  echo.
  echo   usage: freedisk ^<driveletter^> (eg.: freedisk c)

What is the difference between properties and attributes in HTML?

When writing HTML source code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.

For instance, this HTML element:

<input type="text" value="Name:">

has 2 attributes (type and value).

Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.

For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes property of that object.

When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it's not a one-to-one relationship. For instance, for this HTML element:

<input id="the-input" type="text" value="Name:">

the corresponding DOM node will have id,type, and value properties (among others):

  • The id property is a reflected property for the id attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. id is a pure reflected property, it doesn't modify or limit the value.

  • The type property is a reflected property for the type attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. type isn't a pure reflected property because it's limited to known values (e.g., the valid types of an input). If you had <input type="foo">, then theInput.getAttribute("type") gives you "foo" but theInput.type gives you "text".

  • In contrast, the value property doesn't reflect the value attribute. Instead, it's the current value of the input. When the user manually changes the value of the input box, the value property will reflect this change. So if the user inputs "John" into the input box, then:

    theInput.value // returns "John"
    

    whereas:

    theInput.getAttribute('value') // returns "Name:"
    

    The value property reflects the current text-content inside the input box, whereas the value attribute contains the initial text-content of the value attribute from the HTML source code.

    So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute. Or you can use the defaultValue property, which is a pure reflection of the value attribute:

    theInput.value                 // returns "John"
    theInput.getAttribute('value') // returns "Name:"
    theInput.defaultValue          // returns "Name:"
    

There are several properties that directly reflect their attribute (rel, id), some are direct reflections with slightly-different names (htmlFor reflects the for attribute, className reflects the class attribute), many that reflect their attribute but with restrictions/modifications (src, href, disabled, multiple), and so on. The spec covers the various kinds of reflection.

dereferencing pointer to incomplete type

Another possible reason is indirect reference. If a code references to a struct that not included in current c file, the compiler will complain.

a->b->c //error if b not included in current c file

Sql Server string to date conversion

SQL Server (2005, 2000, 7.0) does not have any flexible, or even non-flexible, way of taking an arbitrarily structured datetime in string format and converting it to the datetime data type.

By "arbitrarily", I mean "a form that the person who wrote it, though perhaps not you or I or someone on the other side of the planet, would consider to be intuitive and completely obvious." Frankly, I'm not sure there is any such algorithm.

How to execute an SSIS package from .NET?

So there is another way you can actually fire it from any language. The best way I think, you can just create a batch file which will call your .dtsx package.

Next you call the batch file from any language. As in windows platform, you can run batch file from anywhere, I think this will be the most generic approach for your purpose. No code dependencies.

Below is a blog for more details..

https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/

Happy coding.. :)

Thanks, Ayan

Int division: Why is the result of 1/3 == 0?

The conversion in JAVA is quite simple but need some understanding. As explain in the JLS for integer operations:

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

And an example is always the best way to translate the JLS ;)

int + long -> long
int(1) + long(2) + int(3) -> long(1+2) + long(3)

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

short + int -> int + int -> int

A small example using Eclipse to show that even an addition of two shorts will not be that easy :

short s = 1;
s = s + s; <- Compiling error

//possible loss of precision
//  required: short
//  found:    int

This will required a casting with a possible loss of precision.

The same is true for the floating point operators

If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).

So the promotion is done on the float into double.

And the mix of both integer and floating value result in floating values as said

If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

This is true for binary operators but not for "Assignment Operators" like +=

A simple working example is enough to prove this

int i = 1;
i += 1.5f;

The reason is that there is an implicit cast done here, this will be execute like

i = (int) i + 1.5f
i = (int) 2.5f
i = 2

Sending string via socket (python)

import socket
from threading import *

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            print('Client sent:', self.sock.recv(1024).decode())
            self.sock.send(b'Oi you sent something to me')

serversocket.listen(5)
print ('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

This is a very VERY simple design for how you could solve it. First of all, you need to either accept the client (server side) before going into your while 1 loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.

How to press/click the button using Selenium if the button does not have the Id?

    You can achieve this by using cssSelector 
    // Use of List web elements:
    String cssSelectorOfLoginButton="input[type='button'][id='login']"; 
    //****Add cssSelector of your 1st webelement
    //List<WebElement> button 
    =driver.findElements(By.cssSelector(cssSelectorOfLoginButton));
    button.get(0).click();

    I hope this work for you

Catch an exception thrown by an async void method

Your code doesn't do what you might think it does. Async methods return immediately after the method begins waiting for the async result. It's insightful to use tracing in order to investigate how the code is actually behaving.

The code below does the following:

  • Create 4 tasks
  • Each task will asynchronously increment a number and return the incremented number
  • When the async result has arrived it is traced.

 

static TypeHashes _type = new TypeHashes(typeof(Program));        
private void Run()
{
    TracerConfig.Reset("debugoutput");

    using (Tracer t = new Tracer(_type, "Run"))
    {
        for (int i = 0; i < 4; i++)
        {
            DoSomeThingAsync(i);
        }
    }
    Application.Run();  // Start window message pump to prevent termination
}


private async void DoSomeThingAsync(int i)
{
    using (Tracer t = new Tracer(_type, "DoSomeThingAsync"))
    {
        t.Info("Hi in DoSomething {0}",i);
        try
        {
            int result = await Calculate(i);
            t.Info("Got async result: {0}", result);
        }
        catch (ArgumentException ex)
        {
            t.Error("Got argument exception: {0}", ex);
        }
    }
}

Task<int> Calculate(int i)
{
    var t = new Task<int>(() =>
    {
        using (Tracer t2 = new Tracer(_type, "Calculate"))
        {
            if( i % 2 == 0 )
                throw new ArgumentException(String.Format("Even argument {0}", i));
            return i++;
        }
    });
    t.Start();
    return t;
}

When you observe the traces

22:25:12.649  02172/02820 {          AsyncTest.Program.Run 
22:25:12.656  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.657  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 0    
22:25:12.658  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.659  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.659  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 1    
22:25:12.660  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 2    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 3    
22:25:12.664  02172/02756          } AsyncTest.Program.Calculate Duration 4ms   
22:25:12.666  02172/02820          } AsyncTest.Program.Run Duration 17ms  ---- Run has completed. The async methods are now scheduled on different threads. 
22:25:12.667  02172/02756 Information AsyncTest.Program.DoSomeThingAsync Got async result: 1    
22:25:12.667  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 8ms    
22:25:12.667  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.665  02172/05220 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 0   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.668  02172/02756 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 2   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.724  02172/05220          } AsyncTest.Program.Calculate Duration 66ms      
22:25:12.724  02172/02756          } AsyncTest.Program.Calculate Duration 57ms      
22:25:12.725  02172/05220 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 0  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 106    
22:25:12.725  02172/02756 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 2  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 0      
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 70ms   
22:25:12.726  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   
22:25:12.726  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.726  02172/05220          } AsyncTest.Program.Calculate Duration 0ms   
22:25:12.726  02172/05220 Information AsyncTest.Program.DoSomeThingAsync Got async result: 3    
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   

You will notice that the Run method completes on thread 2820 while only one child thread has finished (2756). If you put a try/catch around your await method you can "catch" the exception in the usual way although your code is executed on another thread when the calculation task has finished and your contiuation is executed.

The calculation method traces the thrown exception automatically because I did use the ApiChange.Api.dll from the ApiChange tool. Tracing and Reflector helps a lot to understand what is going on. To get rid of threading you can create your own versions of GetAwaiter BeginAwait and EndAwait and wrap not a task but e.g. a Lazy and trace inside your own extension methods. Then you will get much better understanding what the compiler and what the TPL does.

Now you see that there is no way to get in a try/catch your exception back since there is no stack frame left for any exception to propagate from. Your code might be doing something totally different after you did initiate the async operations. It might call Thread.Sleep or even terminate. As long as there is one foreground thread left your application will happily continue to execute asynchronous tasks.


You can handle the exception inside the async method after your asynchronous operation did finish and call back into the UI thread. The recommended way to do this is with TaskScheduler.FromSynchronizationContext. That does only work if you have an UI thread and it is not very busy with other things.

How to debug a GLSL shader?

I am sharing a fragment shader example, how i actually debug.

#version 410 core

uniform sampler2D samp;
in VS_OUT
{
    vec4 color;
    vec2 texcoord;
} fs_in;

out vec4 color;

void main(void)
{
    vec4 sampColor;
    if( texture2D(samp, fs_in.texcoord).x > 0.8f)  //Check if Color contains red
        sampColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);  //If yes, set it to white
    else
        sampColor = texture2D(samp, fs_in.texcoord); //else sample from original
    color = sampColor;

}

enter image description here

How to get the html of a div on another page with jQuery ajax?

$.ajax({
  url:href,
  type:'get',
  success: function(data){
   console.log($(data)); 
  }
});

This console log gets an array like object: [meta, title, ,], very strange

You can use JavaScript:

var doc = document.documentElement.cloneNode()
doc.innerHTML = data
$content = $(doc.querySelector('#content'))

Sending a file over TCP sockets in Python

Client need to notify that it finished sending, using socket.shutdown (not socket.close which close both reading/writing part of the socket):

...
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()

UPDATE

Client sends Hello server! to the server; which is written to the file in the server side.

s.send("Hello server!")

Remove above line to avoid it.

How can I select random files from a directory in bash?

Here's a script that uses GNU sort's random option:

ls |sort -R |tail -$N |while read file; do
    # Something involving $file, or you can leave
    # off the while to just get the filenames
done

ArrayList or List declaration in Java

Possibly you can refer to this link http://docs.oracle.com/javase/6/docs/api/java/util/List.html

List is an interface.ArrayList,LinkedList etc are classes which implement list.Whenyou are using List Interface,you have to itearte elements using ListIterator and can move forward and backward,in the List where as in ArrayList Iterate using Iterator and its elements can be accessed unidirectional way.

How to enable GZIP compression in IIS 7.5

Global Gzip in HttpModule

If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule that gets added this code to every HttpApplication.Begin_Request event:-

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

No plot window in matplotlib

--pylab no longer works for Jupyter, but fortunately we can add a tweak in the ipython_config.py file to get both pylab as well as autoreload functionalities.

c.InteractiveShellApp.extensions = ['autoreload', 'pylab']
c.InteractiveShellApp.exec_lines = ['%autoreload 2', '%pylab']

Login to website, via C#

You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.

There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").


POSTing to the login form

Form posts are easy to simulate, it's just a case of formatting your post data as follows:

field1=value1&field2=value2

Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:

string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];

Here's an example of what you should see in the Set-cookie header for your login form:

PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-

GETting the page behind the login form

Now you can perform your GET request to a page that you need to be logged in for.

string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

EDIT:

If you need to view the results of the first POST, you can recover the HTML it returned with:

using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

Place this directly below cookieHeader = resp.Headers["Set-cookie"]; and then inspect the string held in pageSource.

Accessing Google Account Id /username via Android

Used these lines:

AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");

the length of array accounts is always 0.

Text size of android design TabLayout tabs

Work on api 22 & 23 Make this style :

<style name="TabLayoutStyle" parent="Base.Widget.Design.TabLayout">
    <item name="android:textSize">12sp</item>
    <item name="android:textAllCaps">true</item>
</style>

And apply it to your tablayout :

<android.support.design.widget.TabLayout
    android:id="@+id/contentTabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:background="@drawable/list_gray_border"
    app:tabTextAppearance="@style/TabLayoutStyle"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    app:tabTextColor="@color/colorGrey"
    app:tabMode="fixed"
    app:tabGravity="fill"/>

Generic List - moving an item within the list

I would expect either:

// Makes sure item is at newIndex after the operation
T item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);

... or:

// Makes sure relative ordering of newIndex is preserved after the operation, 
// meaning that the item may actually be inserted at newIndex - 1 
T item = list[oldIndex];
list.RemoveAt(oldIndex);
newIndex = (newIndex > oldIndex ? newIndex - 1, newIndex)
list.Insert(newIndex, item);

... would do the trick, but I don't have VS on this machine to check.

Is there a way to detach matplotlib plots so that the computation can continue?

I also wanted my plots to display run the rest of the code (and then keep on displaying) even if there is an error (I sometimes use plots for debugging). I coded up this little hack so that any plots inside this with statement behave as such.

This is probably a bit too non-standard and not advisable for production code. There is probably a lot of hidden "gotchas" in this code.

from contextlib import contextmanager

@contextmanager
def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True):
    '''
    To continue excecuting code when plt.show() is called
    and keep the plot on displaying before this contex manager exits
    (even if an error caused the exit).
    '''
    import matplotlib.pyplot
    show_original = matplotlib.pyplot.show
    def show_replacement(*args, **kwargs):
        kwargs['block'] = False
        show_original(*args, **kwargs)
    matplotlib.pyplot.show = show_replacement

    pylab_exists = True
    try:
        import pylab
    except ImportError: 
        pylab_exists = False
    if pylab_exists:
        pylab.show = show_replacement

    try:
        yield
    except Exception, err:
        if keep_show_open_on_exit and even_when_error:
            print "*********************************************"
            print "Error early edition while waiting for show():" 
            print "*********************************************"
            import traceback
            print traceback.format_exc()
            show_original()
            print "*********************************************"
            raise
    finally:
        matplotlib.pyplot.show = show_original
        if pylab_exists:
            pylab.show = show_original
    if keep_show_open_on_exit:
        show_original()

# ***********************
# Running example
# ***********************
import pylab as pl
import time
if __name__ == '__main__':
    with keep_plots_open():
        pl.figure('a')
        pl.plot([1,2,3], [4,5,6])     
        pl.plot([3,2,1], [4,5,6])
        pl.show()

        pl.figure('b')
        pl.plot([1,2,3], [4,5,6])
        pl.show()

        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        this_will_surely_cause_an_error

If/when I implement a proper "keep the plots open (even if an error occurs) and allow new plots to be shown", I would want the script to properly exit if no user interference tells it otherwise (for batch execution purposes).

I may use something like a time-out-question "End of script! \nPress p if you want the plotting output to be paused (you have 5 seconds): " from https://stackoverflow.com/questions/26704840/corner-cases-for-my-wait-for-user-input-interruption-implementation.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

PHP and references are somewhat unintuitive. If used appropriately references in the right places can provide large performance improvements or avoid very ugly workarounds and unusual code.

The following will produce an error:

 function f(&$v){$v = true;}
 f(&$v);

 function f($v){$v = true;}
 f(&$v);

None of these have to fail as they could follow the rules below but have no doubt been removed or disabled to prevent a lot of legacy confusion.

If they did work, both involve a redundant conversion to reference and the second also involves a redundant conversion back to a scoped contained variable.

The second one used to be possible allowing a reference to be passed to code that wasn't intended to work with references. This is extremely ugly for maintainability.

This will do nothing:

 function f($v){$v = true;}
 $r = &$v;
 f($r);

More specifically, it turns the reference back into a normal variable as you have not asked for a reference.

This will work:

 function f(&$v){$v = true;}
 f($v);

This sees that you are passing a non-reference but want a reference so turns it into a reference.

What this means is that you can't pass a reference to a function where a reference is not explicitly asked for making it one of the few areas where PHP is strict on passing types or in this case more of a meta type.

If you need more dynamic behaviour this will work:

 function f(&$v){$v = true;}
 $v = array(false,false,false);
 $r = &$v[1];
 f($r);

Here it sees that you want a reference and already have a reference so leaves it alone. It may also chain the reference but I doubt this.

From ND to 1D arrays

Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):

In [12]: a = np.array([[1,2,3], [4,5,6]])

In [13]: b = a.ravel()

In [14]: b
Out[14]: array([1, 2, 3, 4, 5, 6])

Note that ravel() returns a view of a when possible. So modifying b also modifies a. ravel() returns a view when the 1D elements are contiguous in memory, but would return a copy if, for example, a were made from slicing another array using a non-unit step size (e.g. a = x[::2]).

If you want a copy rather than a view, use

In [15]: c = a.flatten()

If you just want an iterator, use np.ndarray.flat:

In [20]: d = a.flat

In [21]: d
Out[21]: <numpy.flatiter object at 0x8ec2068>

In [22]: list(d)
Out[22]: [1, 2, 3, 4, 5, 6]

Query to display all tablespaces in a database and datafiles

Neither databases, nor tablespaces nor data files belong to any user. Are you coming to this from an MS SQL background?

select tablespace_name, 
       file_name
from dba_tablespaces
order by tablespace_name, 
         file_name;

Base64 decode snippet in C++

See Encoding and decoding base 64 with C++.

Here is the implementation from that page:

/*
   base64.cpp and base64.h

   Copyright (C) 2004-2008 René Nyffenegger

   This source code is provided 'as-is', without any express or implied
   warranty. In no event will the author be held liable for any damages
   arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose,
   including commercial applications, and to alter it and redistribute it
   freely, subject to the following restrictions:

   1. The origin of this source code must not be misrepresented; you must not
      claim that you wrote the original source code. If you use this source code
      in a product, an acknowledgment in the product documentation would be
      appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and must not be
      misrepresented as being the original source code.

   3. This notice may not be removed or altered from any source distribution.

   René Nyffenegger [email protected]

*/

static const std::string base64_chars =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";


static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}
std::string base64_decode(std::string const& encoded_string) {
  int in_len = encoded_string.size();
  int i = 0;
  int j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = base64_chars.find(char_array_4[i]);

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = base64_chars.find(char_array_4[j]);

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}

Python function overloading

By passing keyword args.

def add_bullet(**kwargs):
    #check for the arguments listed above and do the proper things

Calling a particular PHP function on form submit

you don't need this code

<?php
function display()
{
echo "hello".$_POST["studentname"];
}
?>

Instead, you can check whether the form is submitted by checking the post variables using isset.

here goes the code

if(isset($_POST)){
echo "hello ".$_POST['studentname'];
}

click here for the php manual for isset

How can we run a test method with multiple parameters in MSTest?

Not exactly the same as NUnit's Value (or TestCase) attributes, but MSTest has the DataSource attribute, which allows you to do a similar thing.

You can hook it up to database or XML file - it is not as straightforward as NUnit's feature, but it does the job.

Jquery .on('scroll') not firing the event while scrolling

Binding the scroll event after the ul has loaded using ajax has solved the issue. In my findings $(document).on( 'scroll', '#id', function () {...}) is not working and binding the scroll event after the ajax load found working.

$("#ulId").bind('scroll', function() {
   console.log('Event worked');
}); 

You may unbind the event after removing or replacing the ul.

Hope it may help someone.

How to put more than 1000 values into an Oracle IN clause

Where do you get the list of ids from in the first place? Since they are IDs in your database, did they come from some previous query?

When I have seen this in the past it has been because:-

  1. a reference table is missing and the correct way would be to add the new table, put an attribute on that table and join to it
  2. a list of ids is extracted from the database, and then used in a subsequent SQL statement (perhaps later or on another server or whatever). In this case, the answer is to never extract it from the database. Either store in a temporary table or just write one query.

I think there may be better ways to rework this code that just getting this SQL statement to work. If you provide more details you might get some ideas.

How do I set an ASP.NET Label text from code behind on page load?

In your ASP.NET page:

<asp:Label ID="UserNameLabel" runat="server" />

In your code behind (assuming you're using C#):

function Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
       UserNameLabel.Text = "User Name";
    }
}

What issues should be considered when overriding equals and hashCode in Java?

For equals, look into Secrets of Equals by Angelika Langer. I love it very much. She's also a great FAQ about Generics in Java. View her other articles here (scroll down to "Core Java"), where she also goes on with Part-2 and "mixed type comparison". Have fun reading them!

How do search engines deal with AngularJS applications?

Let's get definitive about AngularJS and SEO

Google, Yahoo, Bing, and other search engines crawl the web in traditional ways using traditional crawlers. They run robots that crawl the HTML on web pages, collecting information along the way. They keep interesting words and look for other links to other pages (these links, the amount of them and the number of them come into play with SEO).

So why don't search engines deal with javascript sites?

The answer has to do with the fact that the search engine robots work through headless browsers and they most often do not have a javascript rendering engine to render the javascript of a page. This works for most pages as most static pages don't care about JavaScript rendering their page, as their content is already available.

What can be done about it?

Luckily, crawlers of the larger sites have started to implement a mechanism that allows us to make our JavaScript sites crawlable, but it requires us to implement a change to our site.

If we change our hashPrefix to be #! instead of simply #, then modern search engines will change the request to use _escaped_fragment_ instead of #!. (With HTML5 mode, i.e. where we have links without the hash prefix, we can implement this same feature by looking at the User Agent header in our backend).

That is to say, instead of a request from a normal browser that looks like:

http://www.ng-newsletter.com/#!/signup/page

A search engine will search the page with:

http://www.ng-newsletter.com/?_escaped_fragment_=/signup/page

We can set the hash prefix of our Angular apps using a built-in method from ngRoute:

angular.module('myApp', [])
.config(['$location', function($location) {
  $location.hashPrefix('!');
}]);

And, if we're using html5Mode, we will need to implement this using the meta tag:

<meta name="fragment" content="!">

Reminder, we can set the html5Mode() with the $location service:

angular.module('myApp', [])
.config(['$location', 
function($location) {
  $location.html5Mode(true);
}]);

Handling the search engine

We have a lot of opportunities to determine how we'll deal with actually delivering content to search engines as static HTML. We can host a backend ourselves, we can use a service to host a back-end for us, we can use a proxy to deliver the content, etc. Let's look at a few options:

Self-hosted

We can write a service to handle dealing with crawling our own site using a headless browser, like phantomjs or zombiejs, taking a snapshot of the page with rendered data and storing it as HTML. Whenever we see the query string ?_escaped_fragment_ in a search request, we can deliver the static HTML snapshot we took of the page instead of the pre-rendered page through only JS. This requires us to have a backend that delivers our pages with conditional logic in the middle. We can use something like prerender.io's backend as a starting point to run this ourselves. Of course, we still need to handle the proxying and the snippet handling, but it's a good start.

With a paid service

The easiest and the fastest way to get content into search engine is to use a service Brombone, seo.js, seo4ajax, and prerender.io are good examples of these that will host the above content rendering for you. This is a good option for the times when we don't want to deal with running a server/proxy. Also, it's usually super quick.

For more information about Angular and SEO, we wrote an extensive tutorial on it at http://www.ng-newsletter.com/posts/serious-angular-seo.html and we detailed it even more in our book ng-book: The Complete Book on AngularJS. Check it out at ng-book.com.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

  1. ReCheck Proxy Settings with following commands

    docker info | grep Proxy

  2. Check VPN Connectivity

  3. If VPN not using CHECK NET connectivity

  4. Reinsrtall Docker and repeat above steps.

  5. Enjoy

How do I join two lists in Java?

In Java 8:

List<String> newList = Stream.concat(listOne.stream(), listTwo.stream())
                             .collect(Collectors.toList());

Scroll to bottom of Div on page load (jQuery)

You can use below code to scroll to bottom of div on page load.

$(document).ready(function(){
  $('div').scrollTop($('div').scrollHeight);
});

How create Date Object with values in java

Gotcha: passing 2 as month may give you unexpected result: in Calendar API, month is zero-based. 2 actually means March.

I don't know what is an "easy" way that you are looking for as I feel that using Calendar is already easy enough.

Remember to use correct constants for month:

 Date date = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();

Another way is to make use of DateFormat, which I usually have a util like this:

 public static Date parseDate(String date) {
     try {
         return new SimpleDateFormat("yyyy-MM-dd").parse(date);
     } catch (ParseException e) {
         return null;
     }
  }

so that I can simply write

Date myDate = parseDate("2014-02-14");

Yet another alternative I prefer: Don't use Java Date/Calendar anymore. Switch to JODA Time or Java Time (aka JSR310, available in JDK 8+). You can use LocalDate to represent a date, which can be easily created by

LocalDate myDate =LocalDate.parse("2014-02-14");
// or
LocalDate myDate2 = new LocalDate(2014, 2, 14);
// or, in JDK 8+ Time
LocalDate myDate3 = LocalDate.of(2014, 2, 14);

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

They are different functions. You should decide for your situation what do you need.

I don't consider using any of them as a bad practice. Most of the time IsNullOrEmpty() is enough. But you have the choice :)

String contains - ignore case

An optimized Imran Tariq's version

Pattern.compile(strptrn, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(str1).find();

Pattern.quote(strptrn) always returns "\Q" + s + "\E" even if there is nothing to quote, concatination spoils performance.

Check table exist or not before create it in Oracle

-- checks for table in specfic schema:

declare n number(10);

begin
    Select count(*) into n  from SYS.All_All_Tables where owner = 'MYSCHEMA' and TABLE_NAME =  'EMPLOYEE';

   if (n = 0) then 
     execute immediate 
     'create table MYSCHEMA.EMPLOYEE ( ID NUMBER(3), NAME VARCHAR2(30) NOT NULL)';      
   end if;
end;

How do I use Apache tomcat 7 built in Host Manager gui?

Just a note that all the above may not work for you with tomcat7 unless you've also done this:

sudo apt-get install tomcat7-admin

calling a function from class in python - different way

you have to use self as the first parameters of a method

in the second case you should use

class MathOperations:
    def testAddition (self,x, y):
        return x + y

    def testMultiplication (self,a, b):
        return a * b

and in your code you could do the following

tmp = MathOperations
print tmp.testAddition(2,3)

if you use the class without instantiating a variable first

print MathOperation.testAddtion(2,3)

it gives you an error "TypeError: unbound method"

if you want to do that you will need the @staticmethod decorator

For example:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

then in your code you could use

print MathsOperations.testAddition(2,3)

How to determine whether code is running in DEBUG / RELEASE build?

Apple already includes a DEBUG flag in debug builds, so you don't need to define your own.

You might also want to consider just redefining NSLog to a null operation when not in DEBUG mode, that way your code will be more portable and you can just use regular NSLog statements:

//put this in prefix.pch

#ifndef DEBUG
#undef NSLog
#define NSLog(args, ...)
#endif

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

For JSON data, it's much easier to POST it as "application/json" content-type. If you use GET, you have to URL-encode the JSON in a parameter and it's kind of messy. Also, there is no size limit when you do POST. GET's size if very limited (4K at most).

CSS: background image on background color

This actually works for me:

background-color: #6DB3F2;
background-image: url('images/checked.png');

You can also drop a solid shadow and set the background image:

background-image: url('images/checked.png');
box-shadow: inset 0 0 100% #6DB3F2;

If the first option is not working for some reason and you don't want to use the box shadow you can always use a pseudo element for the image without any extra HTML:

.btn{
    position: relative;
    background-color: #6DB3F2;
}
.btn:before{
    content: "";
    display: block;
    width: 100%;
    height: 100%;
    position:absolute;
    top:0;
    left:0;
    background-image: url('images/checked.png');
}

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

This question comes up ALL THE TIME on SO. It's one of the first things that new Swift developers struggle with.

Background:

Swift uses the concept of "Optionals" to deal with values that could contain a value, or not. In other languages like C, you might store a value of 0 in a variable to indicate that it contains no value. However, what if 0 is a valid value? Then you might use -1. What if -1 is a valid value? And so on.

Swift optionals let you set up a variable of any type to contain either a valid value, or no value.

You put a question mark after the type when you declare a variable to mean (type x, or no value).

An optional is actually a container than contains either a variable of a given type, or nothing.

An optional needs to be "unwrapped" in order to fetch the value inside.

The "!" operator is a "force unwrap" operator. It says "trust me. I know what I am doing. I guarantee that when this code runs, the variable will not contain nil." If you are wrong, you crash.

Unless you really do know what you are doing, avoid the "!" force unwrap operator. It is probably the largest source of crashes for beginning Swift programmers.

How to deal with optionals:

There are lots of other ways of dealing with optionals that are safer. Here are some (not an exhaustive list)

You can use "optional binding" or "if let" to say "if this optional contains a value, save that value into a new, non-optional variable. If the optional does not contain a value, skip the body of this if statement".

Here is an example of optional binding with our foo optional:

if let newFoo = foo //If let is called optional binding. {
  print("foo is not nil")
} else {
  print("foo is nil")
}

Note that the variable you define when you use optional biding only exists (is only "in scope") in the body of the if statement.

Alternately, you could use a guard statement, which lets you exit your function if the variable is nil:

func aFunc(foo: Int?) {
  guard let newFoo = input else { return }
  //For the rest of the function newFoo is a non-optional var
}

Guard statements were added in Swift 2. Guard lets you preserve the "golden path" through your code, and avoid ever-increasing levels of nested ifs that sometimes result from using "if let" optional binding.

There is also a construct called the "nil coalescing operator". It takes the form "optional_var ?? replacement_val". It returns a non-optional variable with the same type as the data contained in the optional. If the optional contains nil, it returns the value of the expression after the "??" symbol.

So you could use code like this:

let newFoo = foo ?? "nil" // "??" is the nil coalescing operator
print("foo = \(newFoo)")

You could also use try/catch or guard error handling, but generally one of the other techniques above is cleaner.

EDIT:

Another, slightly more subtle gotcha with optionals is "implicitly unwrapped optionals. When we declare foo, we could say:

var foo: String!

In that case foo is still an optional, but you don't have to unwrap it to reference it. That means any time you try to reference foo, you crash if it's nil.

So this code:

var foo: String!


let upperFoo = foo.capitalizedString

Will crash on reference to foo's capitalizedString property even though we're not force-unwrapping foo. the print looks fine, but it's not.

Thus you want to be really careful with implicitly unwrapped optionals. (and perhaps even avoid them completely until you have a solid understanding of optionals.)

Bottom line: When you are first learning Swift, pretend the "!" character is not part of the language. It's likely to get you into trouble.

How to prettyprint a JSON file?

Use pprint: https://docs.python.org/3.6/library/pprint.html

import pprint
pprint.pprint(json)

print() compared to pprint.pprint()

print(json)
{'feed': {'title': 'W3Schools Home Page', 'title_detail': {'type': 'text/plain', 'language': None, 'base': '', 'value': 'W3Schools Home Page'}, 'links': [{'rel': 'alternate', 'type': 'text/html', 'href': 'https://www.w3schools.com'}], 'link': 'https://www.w3schools.com', 'subtitle': 'Free web building tutorials', 'subtitle_detail': {'type': 'text/html', 'language': None, 'base': '', 'value': 'Free web building tutorials'}}, 'entries': [], 'bozo': 0, 'encoding': 'utf-8', 'version': 'rss20', 'namespaces': {}}

pprint.pprint(json)
{'bozo': 0,
 'encoding': 'utf-8',
 'entries': [],
 'feed': {'link': 'https://www.w3schools.com',
          'links': [{'href': 'https://www.w3schools.com',
                     'rel': 'alternate',
                     'type': 'text/html'}],
          'subtitle': 'Free web building tutorials',
          'subtitle_detail': {'base': '',
                              'language': None,
                              'type': 'text/html',
                              'value': 'Free web building tutorials'},
          'title': 'W3Schools Home Page',
          'title_detail': {'base': '',
                           'language': None,
                           'type': 'text/plain',
                           'value': 'W3Schools Home Page'}},
 'namespaces': {},
 'version': 'rss20'}

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

This may work for you. I used it for cleaning folders during deployments for deleting old deployment files.

clean_anyfolder() {
    local temp2="$1/**"; //PATH
    temp3=( $(ls -d $temp2 -t | grep "`date | awk '{print $2" "$3}'`") )
    j=0;
    while [ $j -lt ${#temp3[@]} ]
    do
            echo "to be removed ${temp3[$j]}"
            delete_file_or_folder ${temp3[$j]} 0 //DELETE HERE
        fi
        j=`expr $j + 1`
    done
}

How to use regex with find command?

Simple way - you can specify .* in the beginning because find matches the whole path.

$ find . -regextype egrep -regex '.*[a-f0-9\-]{36}\.jpg$'

find version

$ find --version
find (GNU findutils) 4.6.0
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 
<http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION 
FTS(FTS_CWDFD) CBO(level=2)

Div height 100% and expands to fit content

Modern browsers support the "viewport height" unit. This will expand the div to the available viewport height. I find it more reliable than any other approach.

#some_div {
    height: 100vh;
    background: black;
}

Rails: How can I rename a database column in a Ruby on Rails migration?

For Ruby on Rails 4:

def change
    rename_column :table_name, :column_name_old, :column_name_new
end

What is the best IDE for C Development / Why use Emacs over an IDE?

If you're on Windows then it's a total no-brainer: Get Visual C++ Express.

How to convert base64 string to image?

Just use the method .decode('base64') and go to be happy.

You need, too, to detect the mimetype/extension of the image, as you can save it correctly, in a brief example, you can use the code below for a django view:

def receive_image(req):
    image_filename = req.REQUEST["image_filename"] # A field from the Android device
    image_data = req.REQUEST["image_data"].decode("base64") # The data image
    handler = open(image_filename, "wb+")
    handler.write(image_data)
    handler.close()

And, after this, use the file saved as you want.

Simple. Very simple. ;)

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset bootstrap page with button click using jQuery :

function resetForm(){
        var validator = $( "#form_ID" ).validate();
        validator.resetForm();
}

Using above code you also have change the field colour as red to normal.

If you want to reset only fielded value then :

$("#form_ID")[0].reset();

Android SDK Setup under Windows 7 Pro 64 bit

Windows 7 isn't a supported platform as far as I know. I use the SDK on 64-bit Ubuntu 9.10 and it works fine, though I did have to install the ia32libs or libcurses bombed every time. That was Eclipse related.

The SDK sys reqs makes it clear whatever platform you run, you must be able to run 32-bit code.

How to reset selected file with input tag file type in Angular 2?

You can use ViewChild to access the input in your component. First, you need to add #someValue to your input so you can read it in the component:

<input #myInput type="file" placeholder="File Name" name="filename" (change)="onChange($event)">

Then in your component you need to import ViewChild from @angular/core:

import { ViewChild } from '@angular/core';

Then you use ViewChild to access the input from template:

@ViewChild('myInput')
myInputVariable: ElementRef;

Now you can use myInputVariable to reset the selected file because it's a reference to input with #myInput, for example create method reset() that will be called on click event of your button:

reset() {
    console.log(this.myInputVariable.nativeElement.files);
    this.myInputVariable.nativeElement.value = "";
    console.log(this.myInputVariable.nativeElement.files);
}

First console.log will print the file you selected, second console.log will print an empty array because this.myInputVariable.nativeElement.value = ""; deletes selected file(s) from the input. We have to use this.myInputVariable.nativeElement.value = ""; to reset the value of the input because input's FileList attribute is readonly, so it is impossible to just remove item from array. Here's working Plunker.

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

Why does it work in Chrome and not Firefox?

The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS requests returning a status of 401 still send the subsequent request.

Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.

How can I get the OPTIONS request to send and respond consistently?

Simply have the server (API in this example) respond to OPTIONS requests without requiring authentication.

Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.

Package signatures do not match the previously installed version

you need uninstall completely for LG devices by using cmd adb uninstall packageName

How to view the contents of an Android APK file?

You can also see the contents of an APK file within the Android device itself, which helps a lot in debugging.

All files including the manifest of an app can be viewed and also shared using email, cloud etc., no rooting required. App is available from:

https://play.google.com/store/apps/details?id=com.dasmic.android.apkpeek

Disclaimer: I am the author of this app.

C read file line by line

readLine() returns pointer to local variable, which causes undefined behaviour.

To get around you can:

  1. Create variable in caller function and pass its address to readLine()
  2. Allocate memory for line using malloc() - in this case line will be persistent
  3. Use global variable, although it is generally a bad practice

how to convert object to string in java

Solution 1: cast

String temp=(String)data.getParameterValue("request");

Solution 2: use typed map:

Map<String, String> param;

So you change Change the return type of your function

public String getParameterValue(String key)
{
    if(params.containsKey(key))
    {
        return params.get(key);
    }
    return null;
}

and then no need for cast or toString

String temp=data.getParameterValue("request");

Convert dictionary to list collection in C#

foreach (var item in dicNumber)
{
    listnumber.Add(item.Key);
}

Creating a search form in PHP to search a database?

try this out let me know what happens.

Form:

<form action="form.php" method="post"> 
Search: <input type="text" name="term" /><br /> 
<input type="submit" value="Submit" /> 
</form> 

Form.php:

$term = mysql_real_escape_string($_REQUEST['term']);    

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);

while ($row = mysql_fetch_array($r_query)){ 
echo 'Primary key: ' .$row['PRIMARYKEY']; 
echo '<br /> Code: ' .$row['Code']; 
echo '<br /> Description: '.$row['Description']; 
echo '<br /> Category: '.$row['Category']; 
echo '<br /> Cut Size: '.$row['CutSize'];  
} 

Edit: Cleaned it up a little more.

Final Cut (my test file):

<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';

// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($db_database, $con);
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
<form action="" method="post">  
Search: <input type="text" name="term" /><br />  
<input type="submit" value="Submit" />  
</form>  
<?php
if (!empty($_REQUEST['term'])) {

$term = mysql_real_escape_string($_REQUEST['term']);     

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'"; 
$r_query = mysql_query($sql); 

while ($row = mysql_fetch_array($r_query)){  
echo 'Primary key: ' .$row['PRIMARYKEY'];  
echo '<br /> Code: ' .$row['Code'];  
echo '<br /> Description: '.$row['Description'];  
echo '<br /> Category: '.$row['Category'];  
echo '<br /> Cut Size: '.$row['CutSize'];   
}  

}
?>
    </body>
</html>

What is Type-safe?

An explanation from a liberal arts major, not a comp sci major:

When people say that a language or language feature is type safe, they mean that the language will help prevent you from, for example, passing something that isn't an integer to some logic that expects an integer.

For example, in C#, I define a function as:

 void foo(int arg)

The compiler will then stop me from doing this:

  // call foo
  foo("hello world")

In other languages, the compiler would not stop me (or there is no compiler...), so the string would be passed to the logic and then probably something bad will happen.

Type safe languages try to catch more at "compile time".

On the down side, with type safe languages, when you have a string like "123" and you want to operate on it like an int, you have to write more code to convert the string to an int, or when you have an int like 123 and want to use it in a message like, "The answer is 123", you have to write more code to convert/cast it to a string.

'IF' in 'SELECT' statement - choose output value based on column values

Most simplest way is to use a IF(). Yes Mysql allows you to do conditional logic. IF function takes 3 params CONDITION, TRUE OUTCOME, FALSE OUTCOME.

So Logic is

if report.type = 'p' 
    amount = amount 
else 
    amount = -1*amount 

SQL

SELECT 
    id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
FROM  report

You may skip abs() if all no's are +ve only

How to mention C:\Program Files in batchfile

Now that bash is out for windows 10, if you want to access program files from bash, you can do it like so: cd /mnt/c/Program\ Files.

Bootstrap Modal before form Submit

You can use browser default prompt window. Instead of basic <input type="submit" (...) > try:

<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>

Convert NSDate to String in iOS Swift

you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here for e.g , do like

let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let myString = formatter.string(from: Date()) // string purpose I add here 
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)

print(myStringafd)

you get the output as

enter image description here

How to check if a table contains an element in Lua?

Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true as the value. +1 to interjay.

Any difference between await Promise.all() and multiple await?

Generally, using Promise.all() runs requests "async" in parallel. Using await can run in parallel OR be "sync" blocking.

test1 and test2 functions below show how await can run async or sync.

test3 shows Promise.all() that is async.

jsfiddle with timed results - open browser console to see test results

Sync behavior. Does NOT run in parallel, takes ~1800ms:

const test1 = async () => {
  const delay1 = await Promise.delay(600); //runs 1st
  const delay2 = await Promise.delay(600); //waits 600 for delay1 to run
  const delay3 = await Promise.delay(600); //waits 600 more for delay2 to run
};

Async behavior. Runs in paralel, takes ~600ms:

const test2 = async () => {
  const delay1 = Promise.delay(600);
  const delay2 = Promise.delay(600);
  const delay3 = Promise.delay(600);
  const data1 = await delay1;
  const data2 = await delay2;
  const data3 = await delay3; //runs all delays simultaneously
}

Async behavior. Runs in parallel, takes ~600ms:

const test3 = async () => {
  await Promise.all([
  Promise.delay(600), 
  Promise.delay(600), 
  Promise.delay(600)]); //runs all delays simultaneously
};

TLDR; If you are using Promise.all() it will also "fast-fail" - stop running at the time of the first failure of any of the included functions.

How to convert a string with comma-delimited items to a list in Python?

Just to add on to the existing answers: hopefully, you'll encounter something more like this in the future:

>>> word = 'abc'
>>> L = list(word)
>>> L
['a', 'b', 'c']
>>> ''.join(L)
'abc'

But what you're dealing with right now, go with @Cameron's answer.

>>> word = 'a,b,c'
>>> L = word.split(',')
>>> L
['a', 'b', 'c']
>>> ','.join(L)
'a,b,c'

How to apply Hovering on html area tag?

for complete this script , the function for draw circle ,

    function drawCircle(coordon)
    {
        var coord = coordon.split(',');

        var c = document.getElementById("myCanvas");
        var hdc = c.getContext("2d");
        hdc.beginPath();

        hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
        hdc.stroke();
    }

Pro JavaScript programmer interview questions (with answers)

Ask about "this". This is one good question which can be true test of JavaScript developer.

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

How to get the date from jQuery UI datepicker

You can retrieve the date by using the getDate function:

$("#datepicker").datepicker( 'getDate' );

The value is returned as a JavaScript Date object.

If you want to use this value when the user selects a date, you can use the onSelect event:

$("#datepicker").datepicker({
   onSelect: function(dateText, inst) { 
      var dateAsString = dateText; //the first parameter of this function
      var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
   }
});

The first parameter is in this case the selected Date as String. Use parseDate to convert it to a JS Date Object.

See http://docs.jquery.com/UI/Datepicker for the full jQuery UI DatePicker reference.

Add column in dataframe from list

A solution improving on the great one from @sparrow.

Let df, be your dataset, and mylist the list with the values you want to add to the dataframe.

Let's suppose you want to call your new column simply, new_column

First make the list into a Series:

column_values = pd.Series(mylist)

Then use the insert function to add the column. This function has the advantage to let you choose in which position you want to place the column. In the following example we will position the new column in the first position from left (by setting loc=0)

df.insert(loc=0, column='new_column', value=column_values)

How can I use Guzzle to send a POST request in JSON?

The answer from @user3379466 can be made to work by setting $data as follows:

$data = "{'some_key' : 'some_value'}";

What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):

$data = "{\"collection\" : [$existing_variable]}";

So with $existing_variable being, say, 90210, you get:

echo $data;
//{"collection" : [90210]}

Also worth noting is that you might want to also set the 'Accept' => 'application/json' as well in case the endpoint you're hitting cares about that kind of thing.

How to check for empty value in Javascript?

Comment as an answer:

if (timetime[0].value)

This works because any variable in JS can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.

Add IIS 7 AppPool Identities as SQL Server Logons

CREATE LOGIN [IIS APPPOOL\MyAppPool] FROM WINDOWS;
CREATE USER MyAppPoolUser FOR LOGIN [IIS APPPOOL\MyAppPool];

What does %s and %d mean in printf in the C language?

The first argument to printf is a string of identifiers.

%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].

div with dynamic min-height based on browser window height

to get dynamic height based on browser window. Use vh instead of %

e.g: pass following height: 100vh; to the specific div

count number of lines in terminal output

Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.

For example:

$ echo "asd" | wc -l

Will return 1 and

$ echo -n "asd" | wc -l

Will return 0


So what I often use is grep <anything> -c

$ echo "asd" | grep "^.*$" -c
1

$ echo -n "asd" | grep "^.*$" -c
1

This is closer to reality than what wc -l will return.

MySQL joins and COUNT(*) from another table

MySQL use HAVING statement for this tasks.

Your query would look like this:

SELECT g.group_id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m USING(group_id)
GROUP BY g.group_id
HAVING members > 4

example when references have different names

SELECT g.id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m ON g.id = m.group_id
GROUP BY g.id
HAVING members > 4

Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.

postgresql return 0 if returned value is null

(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).


There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.

For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).

$ create table foo (bar int);
CREATE TABLE

$ select avg(bar) from foo;
 avg 
-----

(1 row)

$ select coalesce(avg(bar), 0) from foo;
 coalesce 
----------
        0
(1 row)

$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
      coalesce      
--------------------
 6.0000000000000000
(1 row)

of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"

Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.

$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
      coalesce      
--------------------
 4.0000000000000000
(1 row)

Is there a Social Security Number reserved for testing/examples?

To expand on the Wikipedia-based answers:

The Social Security Administration (SSA) explicitly states in this document that the having "000" in the first group of numbers "will NEVER be a valid SSN":

I'd consider that pretty definitive.

However, that the 2nd or 3rd groups of numbers won't be "00" or "0000" can be inferred from a FAQ that the SSA publishes which indicates that allocation of those groups starts at "01" or "0001":

But this is only a FAQ and it's never outright stated that "00" or "0000" will never be used.

In another FAQ they provide (http://www.socialsecurity.gov/employer/randomizationfaqs.html#a0=6) that "00" or "0000" will never be used.

I can't find a reference to the 'advertisement' reserved SSNs on the SSA site, but it appears that no numbers starting with a 3 digit number higher than 772 (according to the document referenced above) have been assigned yet, but there's nothing I could find that states those numbers are reserved. Wikipedia's reference is a book that I don't have access to. The Wikipedia information on the advertisement reserved numbers is mentioned across the web, but many are clearly copied from Wikipedia. I think it would be nice to have a citation from the SSA, though I suspect that now that Wikipedia has made the idea popular that these number would now have to be reserved for advertisements even if they weren't initially.

The SSA has a page with a couple of stories about SSN's they've had to retire because they were used in advertisements/samples (maybe the SSA should post a link to whatever their current policy on this might be):

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
}

Make outer div be automatically the same height as its floating content

Use clear: both;

I spent over a week trying to figure this out!

Sending HTTP Post request with SOAP action using org.apache.http

The soapAction must passed as a http-header parameter - when used, it's not part of the http-body/payload.

Look here for an example with apache httpclient: http://svn.apache.org/repos/asf/httpcomponents/oac.hc3x/trunk/src/examples/PostSOAP.java

Javascript Get Element by Id and set the value

Given

<div id="This-is-the-real-id"></div>

then

function setText(id,newvalue) {
  var s= document.getElementById(id);
  s.innerHTML = newvalue;
}    
window.onload=function() { // or window.addEventListener("load",function() {
  setText("This-is-the-real-id","Hello there");
}

will do what you want


Given

<input id="This-is-the-real-id" type="text" value="">

then

function setValue(id,newvalue) {
  var s= document.getElementById(id);
  s.value = newvalue;
}    
window.onload=function() {
  setValue("This-is-the-real-id","Hello there");
}

will do what you want

_x000D_
_x000D_
function setContent(id, newvalue) {_x000D_
  var s = document.getElementById(id);_x000D_
  if (s.tagName.toUpperCase()==="INPUT") s.value = newvalue;_x000D_
  else s.innerHTML = newvalue;_x000D_
  _x000D_
}_x000D_
window.addEventListener("load", function() {_x000D_
  setContent("This-is-the-real-id-div", "Hello there");_x000D_
  setContent("This-is-the-real-id-input", "Hello there");_x000D_
})
_x000D_
<div id="This-is-the-real-id-div"></div>_x000D_
<input id="This-is-the-real-id-input" type="text" value="">
_x000D_
_x000D_
_x000D_

Counting Chars in EditText Changed Listener

Use

s.length()

The following was once suggested in one of the answers, but its very inefficient

textMessage.getText().toString().length()

How to set a cookie for another domain

You can't, at least not directly. That would be a nasty security risk.

While you can specify a Domain attribute, the specification says "The user agent will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server."

Since the origin server is a.com and that does not include b.com, it can't be set.

You would need to get b.com to set the cookie instead. You could do this via (for example) HTTP redirects to b.com and back.

MS Access VBA: Sending an email through Outlook

Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.

Public Function SendEmail2()

Dim varName As Variant          
Dim varCC As Variant            
Dim varSubject As Variant      
Dim varBody As Variant          

varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','

varSubject = "Hello"
'Email subject

varBody = "Let's get ice cream this week"

'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File

End Function

How to make Unicode charset in cmd.exe by default?

After I tried algirdas' solution, my Windows crashed (Win 7 Pro 64bit) so I decided to try a different solution:

  1. Start Run (Win+R)
  2. Type cmd /K chcp 65001

You will get mostly what you want. To start it from the taskbar or anywhere else, make a shortcut (you can name it cmd.unicode.exe or whatever you like) and change its Target to C:\Windows\System32\cmd.exe /K chcp 65001.

How to customize the background color of a UITableViewCell?

After trying out all different solutions, the following method is the most elegant one. Change the color in the following delegate method:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (...){
        cell.backgroundColor = [UIColor blueColor];
    } else {
        cell.backgroundColor = [UIColor whiteColor];
    }
}

Does Python have “private” variables in classes?

Python does not have any private variables like C++ or Java does. You could access any member variable at any time if wanted, too. However, you don't need private variables in Python, because in Python it is not bad to expose your classes member variables. If you have the need to encapsulate a member variable, you can do this by using "@property" later on without breaking existing client code.

In python the single underscore "_" is used to indicate, that a method or variable is not considered as part of the public api of a class and that this part of the api could change between different versions. You can use these methods/variables, but your code could break, if you use a newer version of this class.

The double underscore "__" does not mean a "private variable". You use it to define variables which are "class local" and which can not be easily overidden by subclasses. It mangles the variables name.

For example:

class A(object):
    def __init__(self):
        self.__foobar = None # will be automatically mangled to self._A__foobar

class B(A):
    def __init__(self):
        self.__foobar = 1 # will be automatically mangled to self._B__foobar

self.__foobar's name is automatically mangled to self._A__foobar in class A. In class B it is mangled to self._B__foobar. So every subclass can define its own variable __foobar without overriding its parents variable(s). But nothing prevents you from accessing variables beginning with double underscores. However, name-mangling prevents you from calling this variables /methods incidentally.

I strongly recommend to watch Raymond Hettingers talk "Pythons class development toolkit" from Pycon 2013 (should be available on Youtube), which gives a good example why and how you should use @property and "__"-instance variables.

If you have exposed public variables and you have the need to encapsulate them, then you can use @property. Therefore you can start with the simplest solution possible. You can leave member variables public unless you have a concrete reason to not do so. Here is an example:

class Distance:
    def __init__(self, meter):
        self.meter = meter


d = Distance(1.0)
print(d.meter)
# prints 1.0

class Distance:
    def __init__(self, meter):
        # Customer request: Distances must be stored in millimeters.
        # Public available internals must be changed.
        # This would break client code in C++.
        # This is why you never expose public variables in C++ or Java.
        # However, this is python.
        self.millimeter = meter * 1000

    # In python we have @property to the rescue.
    @property
    def meter(self):
        return self.millimeter *0.001

    @meter.setter
    def meter(self, value):
        self.millimeter = meter * 1000

d = Distance(1.0)
print(d.meter)
# prints 1.0

Checking to see if a DateTime variable has had a value assigned

I'd say the default value is always new DateTime(). So we can write

DateTime datetime;

if (datetime == new DateTime())
{
    //unassigned
}

Convert hex color value ( #ffffff ) to integer value

The real answer is to use:

Color.parseColor(myPassedColor) in Android, myPassedColor being the hex value like #000 or #000000 or #00000000.

However, this function does not support shorthand hex values such as #000.

Type of expression is ambiguous without more context Swift

The compiler can't figure out what type to make the Dictionary, because it's not homogenous. You have values of different types. The only way to get around this is to make it a [String: Any], which will make everything clunky as all hell.

return [
    "title": title,
    "is_draft": isDraft,
    "difficulty": difficulty,
    "duration": duration,
    "cost": cost,
    "user_id": userId,
    "description": description,
    "to_sell": toSell,
    "images": [imageParameters, imageToDeleteParameters].flatMap { $0 }
] as [String: Any]

This is a job for a struct. It'll vastly simplify working with this data structure.

Property 'value' does not exist on type 'EventTarget'

I believe it must work but any ways I'm not able to identify. Other approach can be,

<textarea (keyup)="emitWordCount(myModel)" [(ngModel)]="myModel"></textarea>


export class TextEditorComponent {
   @Output() countUpdate = new EventEmitter<number>();

   emitWordCount(model) {
       this.countUpdate.emit(
         (model.match(/\S+/g) || []).length);
       }
}

Javascript validation: Block special characters

You have two approaches to this:

  1. check the "keypress" event. If the user presses a special character key, stop him right there
  2. check the "onblur" event: when the input element loses focus, validate its contents. If the value is invalid, display a discreet warning beside that input box.

I would suggest the second method because its less irritating. Remember to also check onpaste . If you use only keypress Then We Can Copy and paste special characters so use onpaste also to restrict Pasting special characters

Additionally, I will also suggest that you reconsider if you really want to prevent users from entering special characters. Because many people have $, #, @ and * in their passwords.

I presume that this might be in order to prevent SQL injection; if so: its better that you handle the checks server-side. Or better still, escape the values and store them in the database.

How to get the focused element with jQuery?

$( document.activeElement )

Will retrieve it without having to search the whole DOM tree as recommended on the jQuery documentation

Angular IE Caching issue for $http

The guaranteed one that I had working was something along these lines:

myModule.config(['$httpProvider', function($httpProvider) {
    if (!$httpProvider.defaults.headers.common) {
        $httpProvider.defaults.headers.common = {};
    }
    $httpProvider.defaults.headers.common["Cache-Control"] = "no-cache";
    $httpProvider.defaults.headers.common.Pragma = "no-cache";
    $httpProvider.defaults.headers.common["If-Modified-Since"] = "Mon, 26 Jul 1997 05:00:00 GMT";
}]);

I had to merge 2 of the above solutions in order to guarantee the correct usage for all methods, but you can replace common with get or other method i.e. put, post, delete to make this work for different cases.

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.

In contrast, JSTL works entirely with scoped attributes, either at page, request or session scope. You need to rework your scriptlet to fish test out as an attribute:

<c:set var="test" value="test1"/>
<%
  String resp = "abc";
  String test = pageContext.getAttribute("test");
  resp = resp + test;
  pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>

If you look at the docs for <c:set>, you'll see you can specify scope as page, request or session, and it defaults to page.

Better yet, don't use scriptlets at all: they make the baby jesus cry.

Bootstrap Carousel image doesn't align properly

I am facing the same problem with you. Based on the hint of @thuliha, the following codes has solved my issues.

In the html file, modify as the following sample:

<img class="img-responsive center-block" src=".....png" alt="Third slide">

In the carousel.css, modify the class:

.carousel .item {
  text-align: center;
  height: 470px;
  background-color: #777;
}

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

add to your global file this action.

protected void Application_Start() {
   BundleConfig.RegisterBundles(BundleTable.Bundles);
}

CMake not able to find OpenSSL library

Just in case...this works for me. Sorry for specific version of OpenSSL, but might be desirable.

# On macOS, search Homebrew for keg-only versions of OpenSSL
# equivalent of # -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl/ -DOPENSSL_CRYPTO_LIBRARY=/usr/local/opt/openssl/lib/
if (CMAKE_HOST_SYSTEM_NAME MATCHES "Darwin")
    execute_process(
        COMMAND brew --prefix OpenSSL 
        RESULT_VARIABLE BREW_OPENSSL
        OUTPUT_VARIABLE BREW_OPENSSL_PREFIX
        OUTPUT_STRIP_TRAILING_WHITESPACE
    )
    if (BREW_OPENSSL EQUAL 0 AND EXISTS "${BREW_OPENSSL_PREFIX}")
        message(STATUS "Found OpenSSL keg installed by Homebrew at ${BREW_OPENSSL_PREFIX}")
        set(OPENSSL_ROOT_DIR "${BREW_OPENSSL_PREFIX}/")
        set(OPENSSL_INCLUDE_DIR "${BREW_OPENSSL_PREFIX}/include")
        set(OPENSSL_LIBRARIES "${BREW_OPENSSL_PREFIX}/lib")
        set(OPENSSL_CRYPTO_LIBRARY "${BREW_OPENSSL_PREFIX}/lib/libcrypto.dylib")
    endif()
endif()

...

find_package(OpenSSL REQUIRED)
if (OPENSSL_FOUND)
  # Add the include directories for compiling
  target_include_directories(${TARGET_SERVER} PUBLIC ${OPENSSL_INCLUDE_DIR})
  # Add the static lib for linking
  target_link_libraries(${TARGET_SERVER} OpenSSL::SSL OpenSSL::Crypto)
  message(STATUS "Found OpenSSL ${OPENSSL_VERSION}")
else()
  message(STATUS "OpenSSL Not Found")
endif()

How to loop in excel without VBA or macros?

The way to get the results of your formula would be to start in a new sheet.

In cell A1 put the formula

=IF('testsheet'!C1 <= 99,'testsheet'!A1,"") 

Copy that cell down to row 40 In cell B1 put the formula

=A1

In cell B2 put the formula

=B1 & A2

Copy that cell down to row 40.

The value you want is now in that column in row 40.

Not really the answer you want, but that is the fastest way to get things done excel wise without creating a custom formula that takes in a range and makes the calculation (which would be more fun to do).

file_put_contents(meta/services.json): failed to open stream: Permission denied

Problem solved

php artisan cache:clear
sudo chmod -R 777 vendor storage

this enables the write permission to app , framework, logs Hope this will Help

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

When stride is 1 (more typical with convolution than pooling), we can think of the following distinction:

  • "SAME": output size is the same as input size. This requires the filter window to slip outside input map, hence the need to pad.
  • "VALID": Filter window stays at valid position inside input map, so output size shrinks by filter_size - 1. No padding occurs.

Converting double to string

double total = 44;
String total2 = String.valueOf(total);

This will convert double to String

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

How to open a new HTML page using jQuery?

use window.open("file2.html"); to open on new window,

or use window.location.href = "file2.html" to open on same window.

Windows 7 SDK installation failure

You should really check the log. It seems that quite a few components can cause the Windows SDK installer to fail to install with this useless error message. For instance it could be the Visual C++ Redistributable Package as mentioned there.

Linq Query Group By and Selecting First Items

var results = list.GroupBy(x => x.Category)
            .Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());

For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.

Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.

Selecting pandas column by location

You can also use df.icol(n) to access a column by integer.

Update: icol is deprecated and the same functionality can be achieved by:

df.iloc[:, n]  # to access the column at the nth position

Strings in C, how to get subString

You can use snprintf to get a substring of a char array with precision. Here is a file example called "substring.c":

#include <stdio.h>

int main()
{
    const char source[] = "This is a string array";
    char dest[17];

    // get first 16 characters using precision
    snprintf(dest, sizeof(dest), "%.16s", source);

    // print substring
    puts(dest);
} // end main

Output:

This is a string

Note:

For further information see printf man page.

How do I compute derivative using Numpy?

Assuming you want to use numpy, you can numerically compute the derivative of a function at any point using the Rigorous definition:

def d_fun(x):
    h = 1e-5 #in theory h is an infinitesimal
    return (fun(x+h)-fun(x))/h

You can also use the Symmetric derivative for better results:

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Using your example, the full code should look something like:

def fun(x):
    return x**2 + 1

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Now, you can numerically find the derivative at x=5:

In [1]: d_fun(5)
Out[1]: 9.999999999621423

Best way to add Activity to an Android project in Eclipse?

The R.* classes are generated dynamically. I leave the "Build automatically" option on in the Project menu so that mine R.* classes are always up-to-date.

Additionally, when creating new Activities, I copy and rename old ones, especially if they are similar to the new Activity that I need because Eclipse renames everything for you.

Otherwise, as others have said, the File->New->Class command works well and will build your file for you including templates for required methods based on your class, its inheritance and interfaces.

How do you serialize a model instance in Django?

This is a project that it can serialize(JSON base now) all data in your model and put them to a specific directory automatically and then it can deserialize it whenever you want... I've personally serialized thousand records with this script and then load all of them back to another database without any losing data.

Anyone that would be interested in opensource projects can contribute this project and add more feature to it.

serializer_deserializer_model

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

I had the same problem. Adding the gems 'execjs' and 'therubyracer' not work for me. apt-get install nodejs - also dosn't works. I'm using 64bit ubuntu 10.04.

But it helped me the following: 1. I created empty folder (for example "java"). 2. From the terminal in folder that I created I do:

$ git clone git://github.com/ry/node.git
$ cd node
$ ./configure
$ make
$ sudo make install

After that I run "bundle install" as usual (from folder with ruby&rails project). And the problem was resolved. Ruby did not have to reinstall.

How to parseInt in Angular.js

<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">

Total: {{num1 + num2}}

and in js :

parseInt($scope.num1) + parseInt($scope.num2)

Javascript: Easier way to format numbers?

Just finished up a js library for formatting numbers Numeral.js. It handles decimals, dollars, percentages and even time formatting.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

try this.. i had the same issue, below implementation worked for me

Reader reader = Files.newBufferedReader(Paths.get(<yourfilewithpath>), StandardCharsets.ISO_8859_1);

then use Reader where ever you want.

foreg:

CsvToBean<anyPojo> csvToBean = null;
    try {
        Reader reader = Files.newBufferedReader(Paths.get(csvFilePath), 
                        StandardCharsets.ISO_8859_1);
        csvToBean = new CsvToBeanBuilder(reader)
                .withType(anyPojo.class)
                .withIgnoreLeadingWhiteSpace(true)
                .withSkipLines(1)
                .build();

    } catch (IOException e) {
        e.printStackTrace();
    }

What does git push -u mean?

When you push a new branch the first time use: >git push -u origin

After that, you can just type a shorter command: >git push

The first-time -u option created a persistent upstream tracking branch with your local branch.

$.widget is not a function

May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....

Change background colour for Visual Studio

You can also use the Visual Studio Theme Generator. I have only tried this with VS 2005, but the settings it generates may work with newer versions of VS as well.

In case the link goes dead in the future here is a dark theme I generated. Just put this text into a file named VS_2005_dark_theme.vssettings and import it using Tools -> Import and Export Settings:

<UserSettings>
    <ApplicationIdentity version="8.0"/>
    <ToolsOptions>
        <ToolsOptionsCategory name="Environment" RegisteredName="Environment"/>
    </ToolsOptions>
    <Category name="Environment_Group" RegisteredName="Environment_Group">
        <Category name="Environment_FontsAndColors" Category="{1EDA5DD4-927A-43a7-810E-7FD247D0DA1D}" Package="{DA9FB551-C724-11d0-AE1F-00A0C90FFFC3}" RegisteredName="Environment_FontsAndColors" PackageName="Visual Studio Environment Package">
            <PropertyValue name="Version">2</PropertyValue>
            <FontsAndColors Version="2.0">
                <Categories>
                    <Category GUID="{5C48B2CB-0366-4FBF-9786-0BB37E945687}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0000FF00" Background="0x00003700" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{9973EFDF-317D-431C-8BC1-5E88CBFD4F7F}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0057C732" Background="0x0017340E" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{A27B4E24-A735-4D1D-B8E7-9716E1E3D8E0}" FontName="Monaco" FontSize="9" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="00CFCFCF" Background="00383838" BoldFont="No"/>
                            <Item Name="Indicator Margin" Foreground="0x02000000" Background="00383838" BoldFont="No"/>
                            <Item Name="Line Numbers" Foreground="00828282" Background="00383838" BoldFont="No"/>
                            <Item Name="Visible White Space" Foreground="0x00808080" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Compiler Error" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Value" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Selector" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS String Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Element Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Identifier" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Number" Foreground="002FFE60" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Preprocessor Keyword" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Stale Code" Foreground="0x00808080" Background="0x00C0C0C0" BoldFont="No"/>
                            <Item Name="String" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="String (C# Verbatim)" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Task List Shortcut" Foreground="0x00FFFFFF" Background="0x02C0C0C0" BoldFont="No"/>
                            <Item Name="User Keywords" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="User Types" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Warning" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Class" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Name" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Value" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Processing Instruction" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>                            
                            <Item Name="XML @ Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Attribute" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Tag" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Processing Instruction" Foreground="0x0015496C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XSLT Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>                                                                 
                        </Items>
                    </Category>
                </Categories>
            </FontsAndColors>
        </Category>
    </Category>
</UserSettings>

How to remove an element slowly with jQuery?

All the answers are good, but I found they all lacked that professional "polish".

I came up with this, fading out, sliding up, then removing:

$target.fadeTo(1000, 0.01, function(){ 
    $(this).slideUp(150, function() {
        $(this).remove(); 
    }); 
});

How to include() all PHP files from a directory?

foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}

How to return value from an asynchronous callback function?

It makes no sense to return values from a callback. Instead, do the "foo()" work you want to do inside your callback.

Asynchronous callbacks are invoked by the browser or by some framework like the Google geocoding library when events happen. There's no place for returned values to go. A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.

Simple way to repeat a string

If speed is your concern, then you should use as less memory copying as possible. Thus it is required to work with arrays of chars.

public static String repeatString(String what, int howmany) {
    char[] pattern = what.toCharArray();
    char[] res = new char[howmany * pattern.length];
    int length = pattern.length;
    for (int i = 0; i < howmany; i++)
        System.arraycopy(pattern, 0, res, i * length, length);
    return new String(res);
}

To test speed, a similar optimal method using StirngBuilder is like this:

public static String repeatStringSB(String what, int howmany) {
    StringBuilder out = new StringBuilder(what.length() * howmany);
    for (int i = 0; i < howmany; i++)
        out.append(what);
    return out.toString();
}

and the code to test it:

public static void main(String... args) {
    String res;
    long time;

    for (int j = 0; j < 1000; j++) {
        res = repeatString("123", 100000);
        res = repeatStringSB("123", 100000);
    }

    time = System.nanoTime();
    res = repeatString("123", 1000000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatString: " + time);

    time = System.nanoTime();
    res = repeatStringSB("123", 1000000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatStringSB: " + time);

}

And here the run results from my system:

elapsed repeatString: 6006571
elapsed repeatStringSB: 9064937

Note that the test for loop is to kick in JIT and have optimal results.

How to list all the roles existing in Oracle database?

all_roles.sql

SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
     , SUBSTR(rp.grantee,1,16)              AS GRANTEE
     , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
     , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
     , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
     , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
     , SUBSTR(rtp.common,1,4)               AS COMMON
     , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
     , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
     , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
  FROM role_tab_privs rtp
  LEFT JOIN dba_role_privs rp
    ON (rtp.role = rp.granted_role)
 WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
   AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
   AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
   AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
 ORDER BY 1
        , 2
        , 3
        , 4
;

Usage

SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

Try escaping those characters:

[RegularExpression(@"^([a-zA-Z0-9 \.\&\'\-]+)$", ErrorMessage = "Invalid First Name")]

int to unsigned int conversion

This conversion is well defined and will yield the value UINT_MAX - 61. On a platform where unsigned int is a 32-bit type (most common platforms, these days), this is precisely the value that others are reporting. Other values are possible, however.

The actual language in the standard is

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type).

comparing elements of the same array in java

Try this or purpose will solve with lesser no of steps

for (int i = 0; i < a.length; i++) 
{
    for (int k = i+1; k < a.length; k++) 
    {
        if (a[i] != a[k]) 
         {
            System.out.println(a[i]+"not the same with"+a[k]+"\n");
        }
    }
}

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

How do I tar a directory of files and folders without including the directory itself?

Have a look at --transform/--xform, it gives you the opportunity to massage the file name as the file is added to the archive:

% mkdir my_directory
% touch my_directory/file1
% touch my_directory/file2
% touch my_directory/.hiddenfile1
% touch my_directory/.hiddenfile2
% tar -v -c -f my_dir.tgz --xform='s,my_directory/,,' $(find my_directory -type f)
my_directory/file2
my_directory/.hiddenfile1
my_directory/.hiddenfile2
my_directory/file1
% tar -t -f my_dir.tgz 
file2
.hiddenfile1
.hiddenfile2
file1

Transform expression is similar to that of sed, and we can use separators other than / (, in the above example).
https://www.gnu.org/software/tar/manual/html_section/tar_52.html

Retrieving the COM class factory for component failed

For IIS 8 I did basically the same thing as Monic. Im running my application as its own app pool on an x64 machine 1.In DCOMCNFG, right click on the My Computer and select properties.

2.Choose the COM Securities tab.

3.In Access Permissions, click Edit Defaults and add iis apppool\myapp to it and give it Allow local access permission. Do the same for iis apppool\myapp

4.In launch and Activation Permissions, click Edit Defaults and add iis apppool\myapp to it and give it Local launch and Local Activation permission. Do the same for iis apppool\myapp.

additionally I had to make the folders outlined under C:\Windows\SysWOW64\config\systemprofile\Desktop and give read \ write permissions to iis apppool\myapp also

MySQL timestamp select date range

SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'

OTP (token) should be automatically read from the message

I implemented something of that such. But, here is what I did when the message comes in, I retrieve only the six digit code, bundle it in an intent and send it to the activity or fragment needing it and verifies the code. The example shows you the way to get the sms already. Look at the code below for illustration on how to send using LocalBrodcastManager and if your message contains more texts E.g Greetings, standardize it to help you better. E.g "Your verification code is: 84HG73" you can create a regex pattern like this ([0-9]){2}([A-Z]){2}([0-9]){2} which means two ints, two [capital] letters and two ints. Good Luck!

After discarding all un needed info from the message

 Intent intent = new Intent("AddedItem");
 intent.putExtra("items", code);
 LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent); 

And the Fragment/Activity receiving it

@Override
public void onResume() {
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter("AddedItem"));
    super.onResume();
}

@Override
public void onPause() {
    super.onDestroy();
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
}

And the code meant to handle the payload you collected

 private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction()) {
            final String message = intent.getStringExtra("message");
            //Do whatever you want with the code here
        }
    }
};

Does that help a little bit. I did it better by using Callbacks

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

Insert value into a string at a certain position?

var sb = new StringBuilder();
sb.Append(beforeText);
sb.Insert(2, insertText);
afterText = sb.ToString();

Get current directory name (without full path) in a Bash script

This thread is great! Here is one more flavor:

pwd | awk -F / '{print $NF}'

Setting DEBUG = False causes 500 Error

I have the similar issue, in my case it was caused by having a Commented script inside the body tag.

<!--<script>  </script>-->

Good font for code presentations?

If you are doing a presentation, and you don't care about anything lining up, Verdana is a good choice.

If you are going to distribute your presentation, use a font that you know is on everyone's machine, since using something else is going to cause the machine to fall back to one of the common fonts (like Arial or Times) anyway.

If you do care about things lining up, and are not distributing the presentation, consider Consolas:

alt text

It is highly legible, reminiscent of Verdana, and is monospaced. The color choices are, of course, a matter of taste.

Calculate correlation for more than two variables?

You can also calculate correlations for all variables but exclude selected ones, for example:

mtcars <- data.frame(mtcars)
# here we exclude gear and carb variables
cors <- cor(subset(mtcars, select = c(-gear,-carb)))

Also, to calculate correlation between each variable and one column you can use sapply()

# sapply effectively calls the corelation function for each column of mtcars and mtcars$mpg
cors2 <- sapply(mtcars, cor, y=mtcars$mpg)

C# Wait until condition is true

You can use an async result and a delegate for this. If you read up on the documentation it should make it pretty clear what to do. I can write up some sample code if you like and attach it to this answer.

Action isExcelInteractive = IsExcelInteractive;

private async void btnOk_Click(object sender, EventArgs e)
{
    IAsyncResult result = isExcelInteractive.BeginInvoke(ItIsDone, null);
    result.AsyncWaitHandle.WaitOne();
    Console.WriteLine("YAY");
} 

static void IsExcelInteractive(){
   while (something_is_false) // do your check here
   {
       if(something_is_true)
          return true;
   }
   Thread.Sleep(1);
}

void ItIsDone(IAsyncResult result)
{
   this.isExcelInteractive.EndInvoke(result);
}

Apologies if this code isn't 100% complete, I don't have Visual Studio on this computer, but hopefully it gets you where you need to get to.

Where can I find the Java SDK in Linux after installing it?

Another best way to find Java folder path is to use alternatives command in Fedora Linux (I know its for Ubuntu but I hit this post from google just by its headline). Just want to share incase people like me looking for answers for fedora flavour.

To display all information regarding java

alternatives --display java

Scanner vs. BufferedReader

  1. BufferedReader will probably give you better performance (because Scanner is based on InputStreamReader, look sources). ups, for reading from files it uses nio. When I tested nio performance against BufferedReader performance for big files nio shows a bit better performance.
  2. For reading from file try Apache Commons IO.

Excel add one hour

=A1+TIME(1,0,0)

Although, maybe this should be posted on Super User.

Google Maps API v3 adding an InfoWindow to each marker

I had a similar problem. If all you want is for some info to be displayed when you hover over a marker, instead of clicking it, then I found that a good alternative to using an info Window was to set a title on the marker. That way whenever you hover the mouse over the marker the title displays like an ALT tag. 'marker.setTitle('Marker '+id);' It removes the need to create a listener for the marker too

Get file path of image on Android

I am doing this on click of Button.

private static final int CAMERA_PIC_REQUEST = 1;

private View.OnClickListener  OpenCamera=new View.OnClickListener() {

            @Override
            public void onClick(View paramView) {
                // TODO Auto-generated method stub

                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                NewSelectedImageURL=null;
                //outfile where we are thinking of saving it
                Date date = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

                String newPicFile = RecipeName+ df.format(date) + ".png";


                String outPath =Environment.getExternalStorageDirectory() + "/myFolderName/"+ newPicFile ;
                File outFile = new File(outPath);               

                CapturedImageURL=outFile.toString();
                Uri outuri = Uri.fromFile(outFile);
                cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outuri);            
                startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  

            }
        };

You can get the URL of the recently Captured Image from variable CapturedImageURL

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  


    //////////////////////////////////////
    if (requestCode == CAMERA_PIC_REQUEST) {  
        // do something  

         if (resultCode == RESULT_OK) 
         {
             Uri uri = null;

             if (data != null) 
             {
                 uri = data.getData();
             }
             if (uri == null && CapturedImageURL != null) 
             {
                 uri = Uri.fromFile(new File(CapturedImageURL));
             }
             File file = new File(CapturedImageURL);
             if (!file.exists()) {
                file.mkdir();
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
            }




         }


    }