Programs & Examples On #Event routing

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How can I open a website in my web browser using Python?

I had this problem.When I define firefox path my problem had been solved.

import webbrowser
urL='https://www.python.org'
mozilla_path="C:\\Program Files\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(mozilla_path))
webbrowser.get('firefox').open_new_tab(urL)

stdcall and cdecl

I want to improve on @adf88's answer. I feel that pseudocode for the STDCALL does not reflect the way of how it happens in reality. 'a', 'b', and 'c' aren't popped from the stack in the function body. Instead they are popped by the ret instruction (ret 12 would be used in this case) that in one swoop jumps back to the caller and at the same time pops 'a', 'b', and 'c' from the stack.

Here is my version corrected according to my understanding:

STDCALL:

/* 1. calling STDCALL in pseudo-assembler (similar to what the compiler outputs) */
push on the stack a copy of 'z', then copy of 'y', then copy of 'x'
call
move contents of register A to 'i' variable

/* 2. STDCALL 'Function' body in pseaudo-assembler */ copy 'a' (from stack) to register A copy 'b' (from stack) to register B add A and B, store result in A copy 'c' (from stack) to register B add A and B, store result in A jump back to caller code and at the same time pop 'a', 'b' and 'c' off the stack (a, b and c are removed from the stack in this step, result in register A)

Generate Controller and Model

See all Available Controller : You can do PHP artisan list to view all commands

For help: PHP artisan help make:controller

php artisan make:controller MyControllerName

enter image description here

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

I know this question is old. But this might be useful for someone who is having the problem with legend. In addition to the answer given by ZaneDarken, I modified the chart.js file to show the legend in my pie chart. I changed the legendTemplate(which is declared many times for every chart type) just above these lines :

_x000D_
_x000D_
Chart.Type.extend({_x000D_
      //Passing in a name registers this chart in the Chart namespace_x000D_
      name: "Doughnut",_x000D_
      //Providing a defaults will also register the deafults in the chart namespace_x000D_
      defaults: defaultConfig,_x000D_
      .......
_x000D_
_x000D_
_x000D_

My legendTemplate is changed from

_x000D_
_x000D_
legendTemplate : "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
  <% for (var i=0; i<datasets.length; i++){%>_x000D_
    <li><span style=\ "background-color:<%=datasets[i].strokeColor%>\"></span>_x000D_
      <%if(datasets[i].label){%>_x000D_
        <%=datasets[i].label%>_x000D_
          <%}%>_x000D_
    </li>_x000D_
    <%}%>_x000D_
</ul>"
_x000D_
_x000D_
_x000D_

To

_x000D_
_x000D_
legendTemplate: "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
  <% for (var i=0; i<segments.length; i++){%>_x000D_
    <li><span style=\ "-moz-border-radius:7px 7px 7px 7px; border-radius:7px 7px 7px 7px; margin-right:10px;width:15px;height:15px;display:inline-block;background-color:<%=segments[i].fillColor%>\"> </span>_x000D_
      <%if(segments[i].label){%>_x000D_
        <%=s egments[i].label%>_x000D_
          <%}%>_x000D_
    </li>_x000D_
    <%}%>_x000D_
</ul>"
_x000D_
_x000D_
_x000D_

How to do constructor chaining in C#

What is usage of "Constructor Chain"?
You use it for calling one constructor from another constructor.

How can implement "Constructor Chain"?
Use ": this (yourProperties)" keyword after definition of constructor. for example:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        /// ===== This method is "Chained Method" ===== ///
        this.requestCount= inputCount;
    }
}

Why is it useful?
Important reason is reduce coding, and prevention of duplicate code. such as repeated code for initializing property Suppose some property in class must be initialized with specific value (In our sample, requestDate). And class have 2 or more constructor. Without "Constructor Chain", you must repeat initializaion code in all constractors of class.

How it work? (Or, What is execution sequence in "Constructor Chain")?
in above example, method "a" will be executed first, and then instruction sequence will return to method "b". In other word, above code is equal with below:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        // ===== This method is "Chained Method" ===== ///

        /// *** --- > Compiler execute "MyBillClass()" first, And then continue instruction sequence from here
        this.requestCount= inputCount;
    }
}

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

use labelpad parameter:

pl.xlabel("...", labelpad=20)

or set it after:

ax.xaxis.labelpad = 20

How to call a shell script from python code?

The subprocess module will help you out.

Blatantly trivial example:

>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0 
>>> 

Where test.sh is a simple shell script and 0 is its return value for this run.

Creating a Shopping Cart using only HTML/JavaScript

I think it is a better idea to start working with a raw data and then translate it to DOM (document object model)

I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task.

You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm

You can try following approach:

//create array that will hold all ordered products
    var shoppingCart = [];

    //this function manipulates DOM and displays content of our shopping cart
    function displayShoppingCart(){
        var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
        //ensure we delete all previously added rows from ordered products table
        while(orderedProductsTblBody.rows.length>0) {
            orderedProductsTblBody.deleteRow(0);
        }

        //variable to hold total price of shopping cart
        var cart_total_price=0;
        //iterate over array of objects
        for(var product in shoppingCart){
            //add new row      
            var row=orderedProductsTblBody.insertRow();
            //create three cells for product properties 
            var cellName = row.insertCell(0);
            var cellDescription = row.insertCell(1);
            var cellPrice = row.insertCell(2);
            cellPrice.align="right";
            //fill cells with values from current product object of our array
            cellName.innerHTML = shoppingCart[product].Name;
            cellDescription.innerHTML = shoppingCart[product].Description;
            cellPrice.innerHTML = shoppingCart[product].Price;
            cart_total_price+=shoppingCart[product].Price;
        }
        //fill total cost of our shopping cart 
        document.getElementById("cart_total").innerHTML=cart_total_price;
    }


    function AddtoCart(name,description,price){
       //Below we create JavaScript Object that will hold three properties you have mentioned:    Name,Description and Price
       var singleProduct = {};
       //Fill the product object with data
       singleProduct.Name=name;
       singleProduct.Description=description;
       singleProduct.Price=price;
       //Add newly created product to our shopping cart 
       shoppingCart.push(singleProduct);
       //call display function to show on screen
       displayShoppingCart();

    }  


    //Add some products to our shopping cart via code or you can create a button with onclick event
    //AddtoCart("Table","Big red table",50);
    //AddtoCart("Door","Big yellow door",150);
    //AddtoCart("Car","Ferrari S23",150000);






<table cellpadding="4" cellspacing="4" border="1">
    <tr>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="0">
                <thead>
                    <tr>
                        <td colspan="2">
                            Products for sale
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            Table
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Door
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Car
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
                        </td>
                    </tr>
                </tbody>

            </table>
        </td>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
                <thead>
                    <tr>
                        <td>
                            Name
                        </td>
                        <td>
                            Description
                        </td>
                        <td>
                            Price
                        </td>
                    </tr>
                </thead>
                <tbody id="orderedProductsTblBody">

                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" align="right" id="cart_total">

                        </td>
                    </tr>
                </tfoot>
            </table>
        </td>
    </tr>
</table>

Please have a look at following free client-side shopping cart:

SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration.

Documentation

http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html

Hope you will find it useful.

Deserialize a JSON array in C#

This code is working fine for me,

var a = serializer.Deserialize<List<Entity>>(json);

Could not find a part of the path ... bin\roslyn\csc.exe

Here is a more MSBuild way of doing this.

<Target Name="CopyRoslynFiles" AfterTargets="AfterBuild" Condition="!$(Disable_CopyWebApplication) And '$(OutDir)' != '$(OutputPath)'">
    <ItemGroup>
      <RoslynFiles Include="$(CscToolPath)\*" />
    </ItemGroup>
    <MakeDir Directories="$(WebProjectOutputDir)\bin\roslyn" />
    <Copy SourceFiles="@(RoslynFiles)" DestinationFolder="$(WebProjectOutputDir)\bin\roslyn" SkipUnchangedFiles="true" Retries="$(CopyRetryCount)" RetryDelayMilliseconds="$(CopyRetryDelayMilliseconds)" />
</Target>

But I notice that the roslyn files are also in my bin directory (not in a folder). The app seems to work, though.

How do I push a new local branch to a remote Git repository and track it too?

You can do it in 2 steeps:

1. Use the checkout for create the local branch:

git checkout -b yourBranchName

Work with your Branch as you want.

2. Use the push command to autocreate the branch and send the code to the remote repository:

git push -u origin yourBanchName

There are mutiple ways to do this but I think that this way is really simple.

SQL Server - copy stored procedures from one db to another

You can generate scriptof the stored proc's as depicted in other answers. Once the script have been generated, you can use sqlcmd to execute them against target DB like

sqlcmd -S <server name> -U <user name> -d <DB name> -i <script file> -o <output log file> 

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Another option would be using flexbox.

While it's not supported by IE8 and IE9, you could consider:

  • Not minding about those old IE versions
  • Providing a fallback
  • Using a polyfill

Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    background-color: #4C4;_x000D_
    min-height: 50px;_x000D_
    width: 100%;_x000D_
}_x000D_
footer {_x000D_
    background-color: #4C4;_x000D_
    min-height: 30px;_x000D_
    width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

MySQL table is marked as crashed and last (automatic?) repair failed

This was my experience resolving this issue. I'm using XAMPP. I was getting the error below

 Fatal error: Can't open and lock privilege tables: Table '.\mysql\db' is marked as crashed and last (automatic?) repair failed  

This is what I did to resolve it, step by step:

  1. went to location C:\xampp\mysql, For you, location may be different, make sure you are in right file location.
  2. created backup of the data folder as data-old.
  3. copied folder "mysql" from C:\xampp\mysql\backup
  4. pasted it inside C:\xampp\mysql\data\ replacing the old mysql folder.

And it worked. Keep in mind, I have already tried around 10 solutions and they didnt work for me. This solutions may or may not work for you but regardless, make backup of your data folder before you do anything.

Note: I would always opt to resolve this with repair command but in my case, i wasnt able to get mysql started at all and i wasnt able to get myisamchk command to work.

Regardless of what you do, create a periodic backup of your database.

How to uninstall Golang?

I'm using Ubuntu. I spent a whole morning fixing this, tried all different solutions, when I type go version, it's still there, really annoying... Finally this worked for me, hope this will help!

sudo apt-get remove golang-go
sudo apt-get remove --auto-remove golang-go

How to include a child object's child object in Entity Framework 5

A good example of using the Generic Repository pattern and implementing a generic solution for this might look something like this.

public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)

{

    foreach (var include in includeProperties)
     {

        query = query.Include(include);
     }

        return query.ToList();
}

Difference between return and exit in Bash functions

Sometimes, you run a script using . or source.

. a.sh

If you include an exit in the a.sh, it will not just terminate the script, but end your shell session.

If you include a return in the a.sh, it simply stops processing the script.

How to export a table dataframe in PySpark to csv?

If data frame fits in a driver memory and you want to save to local files system you can convert Spark DataFrame to local Pandas DataFrame using toPandas method and then simply use to_csv:

df.toPandas().to_csv('mycsv.csv')

Otherwise you can use spark-csv:

  • Spark 1.3

    df.save('mycsv.csv', 'com.databricks.spark.csv')
    
  • Spark 1.4+

    df.write.format('com.databricks.spark.csv').save('mycsv.csv')
    

In Spark 2.0+ you can use csv data source directly:

df.write.csv('mycsv.csv')

How do I get Month and Date of JavaScript in 2 digit format?

currentDate(){
        var today = new Date();
        var dateTime =  today.getFullYear()+'-'+
                        ((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
                        (today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
                        (today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
                        (today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
                        (today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());        
            return dateTime;
},

How to get subarray from array?

_x000D_
_x000D_
const array_one = [11, 22, 33, 44, 55];_x000D_
const start = 1;_x000D_
const end = array_one.length - 1;_x000D_
const array_2 = array_one.slice(start, end);_x000D_
console.log(array_2);
_x000D_
_x000D_
_x000D_

Getting full URL of action in ASP.NET MVC

This question is specific to ASP .NET however I am sure some of you will benefit of system agnostic javascript which is beneficial in many situations.

UPDATE: The way to get url formed outside of the page itself is well described in answers above.

Or you could do a oneliner like following:

new UrlHelper(actionExecutingContext.RequestContext).Action(
    "SessionTimeout", "Home", 
    new {area = string.Empty}, 
    actionExecutingContext.Request.Url!= null? 
    actionExecutingContext.Request.Url.Scheme : "http"
);

from filter or:

new UrlHelper(this.Request.RequestContext).Action(
    "Details", 
    "Journey", 
    new { area = productType }, 
    this.Request.Url!= null? this.Request.Url.Scheme : "http"
);

However quite often one needs to get the url of current page, for those cases using Html.Action and putting he name and controller of page you are in to me feels awkward. My preference in such cases is to use JavaScript instead. This is especially good in systems that are half re-written MVT half web-forms half vb-script half God knows what - and to get URL of current page one needs to use different method every time.

One way is to use JavaScript to get URL is window.location.href another - document.URL

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

After doing a lot of things, I upgraded pip, setuptools and virtualenv.

  1. python -m pip install -U pip
  2. pip install -U setuptools
  3. pip install -U virtualenv

I did steps 1, 2 in my virtual environment as well as globally. Next, I installed the package through pip and it worked.

Add column with number of days between dates in DataFrame pandas

How about this:

times['days_since'] = max(list(df.index.values))  
times['days_since'] = times['days_since'] - times['months']  
times

How do I define global variables in CoffeeScript?

Since coffee script has no var statement it automatically inserts it for all variables in the coffee-script, that way it prevents the compiled JavaScript version from leaking everything into the global namespace.

So since there's no way to make something "leak" into the global namespace from the coffee-script side of things on purpose, you need to define your global variables as properties of the global object.

attach them as properties on window

This means you need to do something like window.foo = 'baz';, which handles the browser case, since there the global object is the window.

Node.js

In Node.js there's no window object, instead there's the exports object that gets passed into the wrapper that wraps the Node.js module (See: https://github.com/ry/node/blob/master/src/node.js#L321 ), so in Node.js what you would need to do is exports.foo = 'baz';.

Now let us take a look at what it states in your quote from the docs:

...targeting both CommonJS and the browser: root = exports ? this

This is obviously coffee-script, so let's take a look into what this actually compiles to:

var root;
root = (typeof exports !== "undefined" && exports !== null) ? exports : this;

First it will check whether exports is defined, since trying to reference a non existent variable in JavaScript would otherwise yield an SyntaxError (except when it's used with typeof)

So if exports exists, which is the case in Node.js (or in a badly written WebSite...) root will point to exports, otherwise to this. So what's this?

(function() {...}).call(this);

Using .call on a function will bind the this inside the function to the first parameter passed, in case of the browser this would now be the window object, in case of Node.js it would be the global context which is also available as the global object.

But since you have the require function in Node.js, there's no need to assign something to the global object in Node.js, instead you assign to the exports object which then gets returned by the require function.

Coffee-Script

After all that explanation, here's what you need to do:

root = exports ? this
root.foo = -> 'Hello World'

This will declare our function foo in the global namespace (whatever that happens to be).
That's all :)

Build an iOS app without owning a mac?

My experience is that Ionic Pro (https://ionicframework.com/pro) can do the most of the Development and Publish job but you still need Mac or Mac in cloud at these steps:

  • create .p12 Certification file
  • upload the .ipa file to the App Store

After you created your Certification file, You can upload it to Ionic Pro. You can build .ipa files with proper credentials in cloud. But unfortunately I didn't found another way to upload the .ipa file to App Store, only with Application Loader from Mac.

So I decided to use a pay-as-you-go Mac in cloud account (you pay only for minutes you are logged in) since the time I spend on Mac is very limited (few minutes per App publication).

Android Open External Storage directory(sdcard) for storing file

Try using

new File(Environment.getExternalStorageDirectory(),"somefilename");

And don't forget to add WRITE_EXTERNAL STORAGE and READ_EXTERNAL STORAGE permissions

Remove elements from collection while iterating

Let me give a few examples with some alternatives to avoid a ConcurrentModificationException.

Suppose we have the following collection of books

List<Book> books = new ArrayList<Book>();
books.add(new Book(new ISBN("0-201-63361-2")));
books.add(new Book(new ISBN("0-201-63361-3")));
books.add(new Book(new ISBN("0-201-63361-4")));

Collect and Remove

The first technique consists in collecting all the objects that we want to delete (e.g. using an enhanced for loop) and after we finish iterating, we remove all found objects.

ISBN isbn = new ISBN("0-201-63361-2");
List<Book> found = new ArrayList<Book>();
for(Book book : books){
    if(book.getIsbn().equals(isbn)){
        found.add(book);
    }
}
books.removeAll(found);

This is supposing that the operation you want to do is "delete".

If you want to "add" this approach would also work, but I would assume you would iterate over a different collection to determine what elements you want to add to a second collection and then issue an addAll method at the end.

Using ListIterator

If you are working with lists, another technique consists in using a ListIterator which has support for removal and addition of items during the iteration itself.

ListIterator<Book> iter = books.listIterator();
while(iter.hasNext()){
    if(iter.next().getIsbn().equals(isbn)){
        iter.remove();
    }
}

Again, I used the "remove" method in the example above which is what your question seemed to imply, but you may also use its add method to add new elements during iteration.

Using JDK >= 8

For those working with Java 8 or superior versions, there are a couple of other techniques you could use to take advantage of it.

You could use the new removeIf method in the Collection base class:

ISBN other = new ISBN("0-201-63361-2");
books.removeIf(b -> b.getIsbn().equals(other));

Or use the new stream API:

ISBN other = new ISBN("0-201-63361-2");
List<Book> filtered = books.stream()
                           .filter(b -> b.getIsbn().equals(other))
                           .collect(Collectors.toList());

In this last case, to filter elements out of a collection, you reassign the original reference to the filtered collection (i.e. books = filtered) or used the filtered collection to removeAll the found elements from the original collection (i.e. books.removeAll(filtered)).

Use Sublist or Subset

There are other alternatives as well. If the list is sorted, and you want to remove consecutive elements you can create a sublist and then clear it:

books.subList(0,5).clear();

Since the sublist is backed by the original list this would be an efficient way of removing this subcollection of elements.

Something similar could be achieved with sorted sets using NavigableSet.subSet method, or any of the slicing methods offered there.

Considerations:

What method you use might depend on what you are intending to do

  • The collect and removeAl technique works with any Collection (Collection, List, Set, etc).
  • The ListIterator technique obviously only works with lists, provided that their given ListIterator implementation offers support for add and remove operations.
  • The Iterator approach would work with any type of collection, but it only supports remove operations.
  • With the ListIterator/Iterator approach the obvious advantage is not having to copy anything since we remove as we iterate. So, this is very efficient.
  • The JDK 8 streams example don't actually removed anything, but looked for the desired elements, and then we replaced the original collection reference with the new one, and let the old one be garbage collected. So, we iterate only once over the collection and that would be efficient.
  • In the collect and removeAll approach the disadvantage is that we have to iterate twice. First we iterate in the foor-loop looking for an object that matches our removal criteria, and once we have found it, we ask to remove it from the original collection, which would imply a second iteration work to look for this item in order to remove it.
  • I think it is worth mentioning that the remove method of the Iterator interface is marked as "optional" in Javadocs, which means that there could be Iterator implementations that throw UnsupportedOperationException if we invoke the remove method. As such, I'd say this approach is less safe than others if we cannot guarantee the iterator support for removal of elements.

calling javascript function on OnClientClick event of a Submit button

OnClientClick="SomeMethod()" event of that BUTTON, it return by default "true" so after that function it do postback

for solution use

//use this code in BUTTON  ==>   OnClientClick="return SomeMethod();"

//and your function like this
<script type="text/javascript">
  function SomeMethod(){
    // put your code here 
    return false;
  }
</script>

Check if a file exists with wildcard in shell script

Here's a solution for your specific problem that doesn't require for loops or external commands like ls, find and the like.

if [ "$(echo xorg-x11-fonts*)" != "xorg-x11-fonts*" ]; then
    printf "BLAH"
fi

As you can see, it's just a tad more complicated than what you were hoping for, and relies on the fact that if the shell is not able to expand the glob, it means no files with that glob exist and echo will output the glob as is, which allows us to do a mere string comparison to check whether any of those files exist at all.

If we were to generalize the procedure, though, we should take into account the fact that files might contain spaces within their names and/or paths and that the glob char could rightfully expand to nothing (in your example, that would be the case of a file whose name is exactly xorg-x11-fonts).

This could be achieved by the following function, in bash.

function doesAnyFileExist {
   local arg="$*"
   local files=($arg)
   [ ${#files[@]} -gt 1 ] || [ ${#files[@]} -eq 1 ] && [ -e "${files[0]}" ]
}

Going back to your example, it could be invoked like this.

if doesAnyFileExist "xorg-x11-fonts*"; then
    printf "BLAH"
fi

Glob expansion should happen within the function itself for it to work properly, that's why I put the argument in quotes and that's what the first line in the function body is there for: so that any multiple arguments (which could be the result of a glob expansion outside the function, as well as a spurious parameter) would be coalesced into one. Another approach could be to raise an error if there's more than one argument, yet another could be to ignore all but the 1st argument.

The second line in the function body sets the files var to an array constituted by all the file names that the glob expanded to, one for each array element. It's fine if the file names contain spaces, each array element will contain the names as is, including the spaces.

The third line in the function body does two things:

  1. It first checks whether there's more than one element in the array. If so, it means the glob surely got expanded to something (due to what we did on the 1st line), which in turn implies that at least one file matching the glob exist, which is all we wanted to know.

  2. If at step 1. we discovered that we got less than 2 elements in the array, then we check whether we got one and if so we check whether that one exist, the usual way. We need to do this extra check in order to account for function arguments without glob chars, in which case the array contains only one, unexpanded, element.

Change value of input placeholder via model?

Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.

Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.

This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.

What’s the best way to reload / refresh an iframe?

<script type="text/javascript">
  top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script> 

How exactly does __attribute__((constructor)) work?

.init/.fini isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init/.fini is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor)). It's old-school but it has some benefits.

.ctors/.dtors mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor)) is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init/.fini instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini).

On system supporting both methods, one possible benefit is that code in .init is run before .ctors and code in .fini after .dtors. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.

A major drawback is that you can't easily have more than one _init and one _fini function per each loadable module and would probably have to fragment code in more .so than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini default functions (provided by crti.o). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here

Notice in the link above that a cascading to the original _init() is not needed as it's still in place. The call in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.

.init/.fini and .ctors/.detors mechanisms are similar, but not quite. Code in .init/.fini runs "as is". I.e. you can have several functions in .init/.fini, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so files.

.ctors/.dtors are differently organized than .init/.fini. .ctors/.dtors sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.

The following snippet adds new function pointers to the .ctors function array, principally the same way as __attribute__((constructor)) does (method can coexist with __attribute__((constructor))).

#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
   printf("Hello\n");
}
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors/.dtors loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).

I'd prefer __attribute__((constructor))/((destructor)) where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.

Some good reference in the book Linkers & loaders.

Jquery each - Stop loop and return object

Try this ...

  someArray = new Array();
  someArray[0] = 't5';
  someArray[1] = 'z12';
  someArray[2] = 'b88';
  someArray[3] = 's55';
  someArray[4] = 'e51';
  someArray[5] = 'o322';
  someArray[6] = 'i22';
  someArray[7] = 'k954';  

  var test =  findXX('o322'); 
  console.log(test);



function findXX(word)
{  
  for(var i in someArray){


    if(someArray[i] == word)
    {
      return someArray[i]; //<---  stop the loop!
    }   
  }
}

How to empty the message in a text area with jquery?

//since you are using AJAX, I believe that you can't rely in here with the submit //empty the action, you can include charset utf-8 as jQuery POST method uses that as well I think

HTML

<input name="user" id="nick" value="admin" type="hidden">

<p class="messagelabel"><label class="messagelabel">Message</label>

<textarea id="message" name="message" rows="2" cols="40"></textarea>

<input disabled="disabled" id="send" value="Sending..." type="submit">

JAVACRIPT

                            //reset the form to it's original state
            $.fn.reset = function () {

                              $(this).each (function() { 
                                this.reset();
                                 });
                                                    //any logic that you want to add besides the regular javascript reset
                                                /*$("select#select2").multiselect('refresh');    
                                                $("select").multiselect('destroy');
                                                redo();
                                                */
                            }


//start of jquery based function
 jQuery(function($)
 {
 //useful variable definitions




var page_action = 'index.php/admin/messages/insertShoutBox';

 var the_form_click=$("#form input[type='submit']");

 //useful in case that we want to make reference to it and update

 var just_the_form=$('#form');

 //bind to the events instead of the submit action


the_form_click.on('click keypress', function(event){

//original code, removed the submit event handler.. //$("#form").submit(function(){

if(checkForm()){

    //var nick = inputUser.attr("value");
    //var message = inputMessage.attr("value");

    //seems more adequate for your form, not tested
    var nick = $('#form input[type="text"]:first').attr('value');
    var message = $('#form input[type="textarea"]').attr('value');


    //we deactivate submit button while sending
     //$("#send").attr({ disabled:true, value:"Sending..." });

    //This is more convenient here, we remove the attribute disabled for the submit button and we change it's value

    the_form_click.removeAttr('disabled')
    //.val("Sending...");
    //not sure why this is here so lonely, when it's the same element.. instead trigger it to avoid any issues later
    .val("Sending...").trigger('blur');


  //$("#send").blur();


    //send the post to shoutbox.php
    $.ajax({
        type: "POST", 
        //see you were calling it at the form, on submit, but it's here where you update the url
        //url: "index.php/admin/dashboard/insertShoutBox", 


        url: page_action,

        //data: $('#form').serialize(),
        //Serialize the form data
        data: just_the_form.serialize(),

       // complete: function(data){
       //on complete we should just instead use console log, but I;m using alert to test
       complete: function(data){
       alert('Hurray on Complete triggered with AJAX here');
       },
       success: function(data){
            messageList.html(data.responseText);
            updateShoutbox();

      var timeset='750';
                setTimeout(" just_the_form.reset(); ",timeset); 
                //reset the form once again, the send button will return to disable false, and value will be submit

             //$('#message').val('').empty();
            //maybe you want to reset the form instead????

            //reactivate the send button
            //$("#send").attr({ disabled:false, value:"SUBMIT !" });
        }
     });
}
else alert("Please fill all fields!");


//we prevent the refresh of the page after submitting the form
//return false;

//we prevented it by removing the action at the form and adding return false there instead

event.preventDefault();
});   //end of function

}); //end jQuery function

</script>

Why is the use of alloca() not considered good practice?

Most answers here largely miss the point: there's a reason why using _alloca() is potentially worse than merely storing large objects in the stack.

The main difference between automatic storage and _alloca() is that the latter suffers from an additional (serious) problem: the allocated block is not controlled by the compiler, so there's no way for the compiler to optimize or recycle it.

Compare:

while (condition) {
    char buffer[0x100]; // Chill.
    /* ... */
}

with:

while (condition) {
    char* buffer = _alloca(0x100); // Bad!
    /* ... */
}

The problem with the latter should be obvious.

Removing black dots from li and ul

Relatable post

Those pesky black dots you are referencing to are called bullets.

They are pretty simple to remove, just add this line to your css:

ul {
    list-style-type: none;
}

Hope this helps

Why does an SSH remote command get fewer environment variables then when run manually?

How about sourcing the profile before running the command?

ssh user@host "source /etc/profile; /path/script.sh"

You might find it best to change that to ~/.bash_profile, ~/.bashrc, or whatever.

(As here (linuxquestions.org))

jQuery table sort

I came across this, and thought I'd throw in my 2 cents. Click on the column headers to sort ascending, and again to sort descending.

  • Works in Chrome, Firefox, Opera AND IE(8)
  • Only uses JQuery
  • Does alpha and numeric sorting - ascending and descending

_x000D_
_x000D_
$('th').click(function(){_x000D_
    var table = $(this).parents('table').eq(0)_x000D_
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))_x000D_
    this.asc = !this.asc_x000D_
    if (!this.asc){rows = rows.reverse()}_x000D_
    for (var i = 0; i < rows.length; i++){table.append(rows[i])}_x000D_
})_x000D_
function comparer(index) {_x000D_
    return function(a, b) {_x000D_
        var valA = getCellValue(a, index), valB = getCellValue(b, index)_x000D_
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)_x000D_
    }_x000D_
}_x000D_
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
th {_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
    <tr><th>Country</th><th>Date</th><th>Size</th></tr>_x000D_
    <tr><td>France</td><td>2001-01-01</td><td>25</td></tr>_x000D_
    <tr><td><a href=#>spain</a></td><td>2005-05-05</td><td></td></tr>_x000D_
    <tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr>_x000D_
    <tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>_x000D_
    <tr><td>USA</td><td></td><td>-6</td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

** Update: 2018

Clicking a checkbox with ng-click does not update the model

The order in which ng-click and ng-model will be executed is ambiguous (since neither explicitly set their priority). The most stable solution to this would be to avoid using them on the same element.

Also, you probably do not want the behavior that the examples show; you want the checkbox to respond to clicks on the complete label text, not only the checkbox. Hence, the cleanest solution would be to wrap the input (with ng-model) inside a label (with ng-click):

<label ng-click="onCompleteTodo(todo)">
  <input type='checkbox' ng-model="todo.done">
  {{todo.text}}
</label>

Working example: http://jsfiddle.net/b3NLH/1/

Login to remote site with PHP cURL

This is how I solved this in ImpressPages:

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

How do I replace a character in a string in Java?

If you're using Spring you can simply call HtmlUtils.htmlEscape(String input) which will handle the '&' to '&' translation.

Execute SQL script from command line

Take a look at the sqlcmd utility. It allows you to execute SQL from the command line.

http://msdn.microsoft.com/en-us/library/ms162773.aspx

It's all in there in the documentation, but the syntax should look something like this:

sqlcmd -U myLogin -P myPassword -S MyServerName -d MyDatabaseName 
    -Q "DROP TABLE MyTable"

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Update 2017:

Use authbind


Much better than CAP_NET_BIND_SERVICE or a custom kernel.

  • CAP_NET_BIND_SERVICE grants trust to the binary but provides no control over per-port access.
  • Authbind grants trust to the user/group and provides control over per-port access, and supports both IPv4 and IPv6 (IPv6 support has been added as of late).

    1. Install: apt-get install authbind

    2. Configure access to relevant ports, e.g. 80 and 443 for all users and groups:

      sudo touch /etc/authbind/byport/80
      sudo touch /etc/authbind/byport/443
      sudo chmod 777 /etc/authbind/byport/80
      sudo chmod 777 /etc/authbind/byport/443

    3. Execute your command via authbind
      (optionally specifying --deep or other arguments, see the man page):

      authbind --deep /path/to/binary command line args
      

      e.g.

      authbind --deep java -jar SomeServer.jar
      

As a follow-up to Joshua's fabulous (=not recommended unless you know what you do) recommendation to hack the kernel:

I've first posted it here.

Simple. With a normal or old kernel, you don't.
As pointed out by others, iptables can forward a port.
As also pointed out by others, CAP_NET_BIND_SERVICE can also do the job.
Of course CAP_NET_BIND_SERVICE will fail if you launch your program from a script, unless you set the cap on the shell interpreter, which is pointless, you could just as well run your service as root...
e.g. for Java, you have to apply it to the JAVA JVM

sudo /sbin/setcap 'cap_net_bind_service=ep' /usr/lib/jvm/java-8-openjdk/jre/bin/java

Obviously, that then means any Java program can bind system ports.
Dito for mono/.NET.

I'm also pretty sure xinetd isn't the best of ideas.
But since both methods are hacks, why not just lift the limit by lifting the restriction ?
Nobody said you have to run a normal kernel, so you can just run your own.

You just download the source for the latest kernel (or the same you currently have). Afterwards, you go to:

/usr/src/linux-<version_number>/include/net/sock.h:

There you look for this line

/* Sockets 0-1023 can't be bound to unless you are superuser */
#define PROT_SOCK       1024

and change it to

#define PROT_SOCK 0

if you don't want to have an insecure ssh situation, you alter it to this: #define PROT_SOCK 24

Generally, I'd use the lowest setting that you need, e.g 79 for http, or 24 when using SMTP on port 25.

That's already all.
Compile the kernel, and install it.
Reboot.
Finished - that stupid limit is GONE, and that also works for scripts.

Here's how you compile a kernel:

https://help.ubuntu.com/community/Kernel/Compile

# You can get the kernel-source via package linux-source, no manual download required
apt-get install linux-source fakeroot

mkdir ~/src
cd ~/src
tar xjvf /usr/src/linux-source-<version>.tar.bz2
cd linux-source-<version>

# Apply the changes to PROT_SOCK define in /include/net/sock.h

# Copy the kernel config file you are currently using
cp -vi /boot/config-`uname -r` .config

# Install ncurses libary, if you want to run menuconfig
apt-get install libncurses5 libncurses5-dev

# Run menuconfig (optional)
make menuconfig

# Define the number of threads you wanna use when compiling (should be <number CPU cores> - 1), e.g. for quad-core
export CONCURRENCY_LEVEL=3
# Now compile the custom kernel
fakeroot make-kpkg --initrd --append-to-version=custom kernel-image kernel-headers

# And wait a long long time

cd ..

In a nutshell, use iptables if you want to stay secure, compile the kernel if you want to be sure this restriction never bothers you again.

C++ - unable to start correctly (0xc0150002)

I faced this issue, when I was supplying the executable folder with a, by the .exe requested DLL. In my case, the DLL I supplied to the .exe was searching for another necessary DLL which was not available. The searching DLL was not capable of telling that it can not find the necessary DLL.

You might check the DLLs you're loading and the dependencies of these DLL's.

Flutter Circle Design

I would use a https://docs.flutter.io/flutter/widgets/Stack-class.html to be able to freely position widgets.

To create circles

  new BoxDecoration(
    color: effectiveBackgroundColor,
    image: backgroundImage != null
      ? new DecorationImage(image: backgroundImage, fit: BoxFit.cover)
      : null,
    shape: BoxShape.circle,
  ),

and https://docs.flutter.io/flutter/widgets/Transform/Transform.rotate.html to position the white dots.

Reorder HTML table rows using drag-and-drop

You may want to look at jQuery Sortable. I used it to reorder table rows.

How do I get the file name from a String containing the Absolute file path?

just use File.getName()

File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());

using String methods:

  File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");  
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));

How to add browse file button to Windows Form using C#

OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:\" ;
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}

In this code you can put your address in a text box.

How to clear all input fields in a specific div with jQuery?

For some who wants to reset the form can also use type="reset" inside any form.

<form action="/action_page.php">
Email: <input type="text" name="email"><br>
Pin: <input type="text" name="pin" maxlength="4"><br>
<input type="reset" value="Reset">
<input type="submit" value="Submit">
</form>

Determine whether a key is present in a dictionary

In terms of bytecode, in saves a LOAD_ATTR and replaces a CALL_FUNCTION with a COMPARE_OP.

>>> dis.dis(indict)
  2           0 LOAD_GLOBAL              0 (name)
              3 LOAD_GLOBAL              1 (d)
              6 COMPARE_OP               6 (in)
              9 POP_TOP             


>>> dis.dis(haskey)
  2           0 LOAD_GLOBAL              0 (d)
              3 LOAD_ATTR                1 (haskey)
              6 LOAD_GLOBAL              2 (name)
              9 CALL_FUNCTION            1
             12 POP_TOP             

My feelings are that in is much more readable and is to be preferred in every case that I can think of.

In terms of performance, the timing reflects the opcode

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
 10000000 loops, best of 3: 0.11 usec per loop

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
  1000000 loops, best of 3: 0.205 usec per loop

in is almost twice as fast.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I was face same problem when I am going to delete my record than some issue was occur , for this issue solution is that when you are going to delete your record than you missing some thing before deleting header/master record you must write to code for delete its detail before header/Master I hope you issue will be resolve.

Generate an integer that is not among four billion given ones

Perhaps I'm completely missing the point of this question, but you want to find an integer missing from a sorted file of integers?

Uhh... really? Let's think about what such a file would look like:

1 2 3 4 5 6 ... first missing number ... etc.

The solution to this problem seems trivial.

How to check if a number is between two values?

It's an old question, however might be useful for someone like me.

lodash has _.inRange() function https://lodash.com/docs/4.17.4#inRange

Example:

_.inRange(3, 2, 4);
// => true

Please note that this method utilizes the Lodash utility library, and requires access to an installed version of Lodash.

Hibernate: best practice to pull all lazy collections

When having to fetch multiple collections, you need to:

  1. JOIN FETCH one collection
  2. Use the Hibernate.initialize for the remaining collections.

So, in your case, you need a first JPQL query like this one:

MyEntity entity = session.createQuery("select e from MyEntity e join fetch e.addreses where e.id 
= :id", MyEntity.class)
.setParameter("id", entityId)
.getSingleResult();

Hibernate.initialize(entity.persons);

This way, you can achieve your goal with 2 SQL queries and avoid a Cartesian Product.

How can I work with command line on synology?

The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.

Launch Powershell or CMD, enter ssh yourAccountName@diskstation

The first time it will cache off your certificate.

EDIT:

Further detailed explanations can be found on the synology docs page:

How to login to DSM with root permission via SSH Telnet

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Try this (on Windows, i don't know how in others), if you have changed password a now don't work.

1) kill mysql 2) back up /mysql/data folder 3) go to folder /mysql/backup 4) copy files from /mysql/backup/mysql folder to /mysql/data/mysql (rewrite) 5) run mysql

In my XAMPP on Win7 it works.

Calculate logarithm in python

From the documentation:

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

But the log10 is made available as math.log10(), which does not resort to log division if possible.

Memory errors and list limits?

There is no memory limit imposed by Python. However, you will get a MemoryError if you run out of RAM. You say you have 20301 elements in the list. This seems too small to cause a memory error for simple data types (e.g. int), but if each element itself is an object that takes up a lot of memory, you may well be running out of memory.

The IndexError however is probably caused because your ListTemp has got only 19767 elements (indexed 0 to 19766), and you are trying to access past the last element.

It is hard to say what you can do to avoid hitting the limit without knowing exactly what it is that you are trying to do. Using numpy might help. It looks like you are storing a huge amount of data. It may be that you don't need to store all of it at every stage. But it is impossible to say without knowing.

How to add the JDBC mysql driver to an Eclipse project?

1: I have downloaded the mysql-connector-java-5.1.24-bin.jar

Okay.


2: I have created a lib folder in my project and put the jar in there.

Wrong. You need to drop JAR in /WEB-INF/lib folder. You don't need to create any additional folders.


3: properties of project->build path->add JAR and selected the JAR above.

Unnecessary. Undo it all to avoid possible conflicts.


4: I still get java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/mysql

This exception can have 2 causes:

  1. JDBC driver is not in runtime classpath. This is to be solved by doing 2) the right way.
  2. JDBC URL is not recognized by any of the loaded JDBC drivers. Indeed, the JDBC URL is wrong, there should as per the MySQL JDBC driver documentation be another colon between the scheme and the host.

    jdbc:mysql://localhost:3306/mysql
    

Is there a "between" function in C#?

Base @Dan J this version don't care max/min, more like sql :)

public static bool IsBetween(this decimal me, decimal a, decimal b, bool include = true)
{
    var left = Math.Min(a, b);
    var righ = Math.Max(a, b);

    return include
        ? (me >= left && me <= righ)
        : (me > left && me < righ)
    ;
}

What is an idiomatic way of representing enums in Go?

It's true that the above examples of using const and iota are the most idiomatic ways of representing primitive enums in Go. But what if you're looking for a way to create a more fully-featured enum similar to the type you'd see in another language like Java or Python?

A very simple way to create an object that starts to look and feel like a string enum in Python would be:

package main

import (
    "fmt"
)

var Colors = newColorRegistry()

func newColorRegistry() *colorRegistry {
    return &colorRegistry{
        Red:   "red",
        Green: "green",
        Blue:  "blue",
    }
}

type colorRegistry struct {
    Red   string
    Green string
    Blue  string
}

func main() {
    fmt.Println(Colors.Red)
}

Suppose you also wanted some utility methods, like Colors.List(), and Colors.Parse("red"). And your colors were more complex and needed to be a struct. Then you might do something a bit like this:

package main

import (
    "errors"
    "fmt"
)

var Colors = newColorRegistry()

type Color struct {
    StringRepresentation string
    Hex                  string
}

func (c *Color) String() string {
    return c.StringRepresentation
}

func newColorRegistry() *colorRegistry {

    red := &Color{"red", "F00"}
    green := &Color{"green", "0F0"}
    blue := &Color{"blue", "00F"}

    return &colorRegistry{
        Red:    red,
        Green:  green,
        Blue:   blue,
        colors: []*Color{red, green, blue},
    }
}

type colorRegistry struct {
    Red   *Color
    Green *Color
    Blue  *Color

    colors []*Color
}

func (c *colorRegistry) List() []*Color {
    return c.colors
}

func (c *colorRegistry) Parse(s string) (*Color, error) {
    for _, color := range c.List() {
        if color.String() == s {
            return color, nil
        }
    }
    return nil, errors.New("couldn't find it")
}

func main() {
    fmt.Printf("%s\n", Colors.List())
}

At that point, sure it works, but you might not like how you have to repetitively define colors. If at this point you'd like to eliminate that, you could use tags on your struct and do some fancy reflecting to set it up, but hopefully this is enough to cover most people.

Accessing member of base class

Working example. Notes below.

class Animal {
    constructor(public name) {
    }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    move() {
        alert(this.name + " is Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    move() {
        alert(this.name + " is Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);
  1. You don't need to manually assign the name to a public variable. Using public name in the constructor definition does this for you.

  2. You don't need to call super(name) from the specialised classes.

  3. Using this.name works.

Notes on use of super.

This is covered in more detail in section 4.9.2 of the language specification.

The behaviour of the classes inheriting from Animal is not dissimilar to the behaviour in other languages. You need to specify the super keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move() or this.move() you would be dealing with the specialised Snake or Horse function, so using super.move() explicitly calls the base class function.

There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name and this.name - there is simply this.name. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.

Pandas - Get first row value of a given column

Another way of getting the first row and preserving the index:

x = df.first('d') # Returns the first day. '3d' gives first three days.

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

Zero an array in C code

int arr[20];
memset(arr, 0, sizeof arr);

See the reference for memset

Converting an int to a binary string representation in Java?

The simplest approach is to check whether or not the number is odd. If it is, by definition, its right-most binary number will be "1" (2^0). After we've determined this, we bit shift the number to the right and check the same value using recursion.

@Test
public void shouldPrintBinary() {
    StringBuilder sb = new StringBuilder();
    convert(1234, sb);
}

private void convert(int n, StringBuilder sb) {

    if (n > 0) {
        sb.append(n % 2);
        convert(n >> 1, sb);
    } else {
        System.out.println(sb.reverse().toString());
    }
}

Creating an array from a text file in Bash

Use the mapfile command:

mapfile -t myArray < file.txt

The error is using for -- the idiomatic way to loop over lines of a file is:

while IFS= read -r line; do echo ">>$line<<"; done < file.txt

See BashFAQ/005 for more details.

How to install toolbox for MATLAB

There are many toolboxes. Since you mentioned one that is commercially available from MathWorks, I assume you mean how do you get a trial/license

http://www.mathworks.com/products/image/

There is a link for trials, purchase, demos. This will get you in touch with your sales representative. If you know your sales representative, you could just call to get attention faster.


If you mean just a general toolbox that is from a source other than MathWorks, I would check with the producer, as it will vary widely from "Put it on your path." to whatever their purchase and licensing procedure is.

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

calling java methods in javascript code

Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

Error 0x8007000d means URL rewriting module (referenced in web.config) is missing or proper version is not installed.

Just install URL rewriting module via web platform installer.

I recommend to check all dependencies from web.config and install them.

Very Long If Statement in Python

Here is the example directly from PEP 8 on limiting line length:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

.NET String.Format() to add commas in thousands place for a number

int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000

Remove by _id in MongoDB console

Very close. This will work:

db.test_users.deleteOne( {"_id": ObjectId("4d512b45cc9374271b02ec4f")});

i.e. you don't need a new for the ObjectId.

Also, note that in some drivers/tools, remove() is now deprecated and deleteOne or deleteMany should be used instead.

How to get distinct values from an array of objects in JavaScript?

Let assume we have data something like this arr=[{id:1,age:17},{id:2,age:19} ...], then we can find unique objects like this -

function getUniqueObjects(ObjectArray) {
    let uniqueIds = new Set();
    const list = [...new Set(ObjectArray.filter(obj => {
        if (!uniqueIds.has(obj.id)) {
            uniqueIds.add(obj.id);
            return obj;
        }
    }))];

    return list;
}

Check here Codepen Link

Jquery: Find Text and replace

How to change multiple "dogsss" to "dollsss":

$('#id1 p').each(function() {
var text = $(this).text();
// Use global flag i.e. g in the regex to replace all occurrences
$(this).text(text.replace(/dog/g, 'doll'));
});

https://jsfiddle.net/ashjpb9w/

Mailto: Body formatting

From the first result on Google:

mailto:[email protected]_t?subject=Header&body=This%20is...%20the%20first%20line%0D%0AThis%20is%20the%20second

Linux bash: Multiple variable assignment

I wanted to assign the values to an array. So, extending Michael Krelin's approach, I did:

read a[{1..3}] <<< $(echo 2 4 6); echo "${a[1]}|${a[2]}|${a[3]}"

which yields:

2|4|6 

as expected.

Printing image with PrintDocument. how to adjust the image to fit paper size

Answer:

public void Print(string FileName)
{
    StringBuilder logMessage = new StringBuilder();
    logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ START - {0} - {1} -------------------]", MethodBase.GetCurrentMethod(), DateTime.Now.ToShortDateString()));
    logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "Parameter: 1: [Name - {0}, Value - {1}", "None]", Convert.ToString("")));

    try
    {
        if (string.IsNullOrWhiteSpace(FileName)) return; // Prevents execution of below statements if filename is not selected.

        PrintDocument pd = new PrintDocument();

        //Disable the printing document pop-up dialog shown during printing.
        PrintController printController = new StandardPrintController();
        pd.PrintController = printController;

        //For testing only: Hardcoded set paper size to particular paper.
        //pd.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
        //pd.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);

        pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
        pd.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);

        pd.PrintPage += (sndr, args) =>
        {
            System.Drawing.Image i = System.Drawing.Image.FromFile(FileName);

            //Adjust the size of the image to the page to print the full image without loosing any part of the image.
            System.Drawing.Rectangle m = args.MarginBounds;

            //Logic below maintains Aspect Ratio.
            if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
            {
                m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
            }
            else
            {
                m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
            }
            //Calculating optimal orientation.
            pd.DefaultPageSettings.Landscape = m.Width > m.Height;
            //Putting image in center of page.
            m.Y = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Height - m.Height) / 2);
            m.X = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Width - m.Width) / 2);
            args.Graphics.DrawImage(i, m);
        };
        pd.Print();
    }
    catch (Exception ex)
    {
        log.ErrorFormat("Error : {0}\n By : {1}-{2}", ex.ToString(), this.GetType(), MethodBase.GetCurrentMethod().Name);
    }
    finally
    {
        logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ END  - {0} - {1} -------------------]", MethodBase.GetCurrentMethod().Name, DateTime.Now.ToShortDateString()));
        log.Info(logMessage.ToString());
    }
}

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

RuntimeWarning: invalid value encountered in divide

You are dividing by rr which may be 0.0. Check if rr is zero and do something reasonable other than using it in the denominator.

Getting Excel to refresh data on sheet from within VBA

This should do the trick...

'recalculate all open workbooks
Application.Calculate

'recalculate a specific worksheet
Worksheets(1).Calculate

' recalculate a specific range
Worksheets(1).Columns(1).Calculate

Can a table have two foreign keys?

create table Table1
(
  id varchar(2),
  name varchar(2),
  PRIMARY KEY (id)
)


Create table Table1_Addr
(
  addid varchar(2),
  Address varchar(2),
  PRIMARY KEY (addid)
)

Create table Table1_sal
(
  salid varchar(2),`enter code here`
  addid varchar(2),
  id varchar(2),
  PRIMARY KEY (salid),
  index(addid),
  index(id),
  FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
  FOREIGN KEY (id) REFERENCES Table1(id)
)

Named parameters in JDBC

You can't use named parameters in JDBC itself. You could try using Spring framework, as it has some extensions that allow the use of named parameters in queries.

Android java.exe finished with non-zero exit value 1

I resolve this problem with a joking way. I have two class with names startDl and StartDl. I just change one of them to StartDownload and my problem solved. also can resources have a name that already is reserved with anymore resource in project. just rename similar names to different.

What does servletcontext.getRealPath("/") mean and when should I use it

Introduction

The ServletContext#getRealPath() is intented to convert a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.

The "/" represents the web content root. I.e. it represents the web folder as in the below project structure:

YourWebProject
 |-- src
 |    :
 |
 |-- web
 |    |-- META-INF
 |    |    `-- MANIFEST.MF
 |    |-- WEB-INF
 |    |    `-- web.xml
 |    |-- index.jsp
 |    `-- login.jsp
 :    

So, passing the "/" to getRealPath() would return you the absolute disk file system path of the /web folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/some.war/ which you should be able to further use in File or FileInputStream.

Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use

String absolutePathToIndexJSP = servletContext.getRealPath("/") + "index.jsp"; // Wrong!

or even

String absolutePathToIndexJSP = servletContext.getRealPath("") + "index.jsp"; // Wronger!

instead of

String absolutePathToIndexJSP = servletContext.getRealPath("/index.jsp"); // Right!

Don't ever write files in there

Also note that even though you can write new files into it using FileOutputStream, all changes (e.g. new files or edited files) will get lost whenever the WAR is redeployed; with the simple reason that all those changes are not contained in the original WAR file. So all starters who are attempting to save uploaded files in there are doing it wrong.

Moreover, getRealPath() will always return null or a completely unexpected path when the server isn't configured to expand the WAR file into the disk file system, but instead into e.g. memory as a virtual file system.

getRealPath() is unportable; you'd better never use it

Use getRealPath() carefully. There are actually no sensible real world use cases for it. Based on my 20 years of Java EE experience, there has always been another way which is much better and more portable than getRealPath().

If all you actually need is to get an InputStream of the web resource, better use ServletContext#getResourceAsStream() instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream of index.jsp, then do not do:

InputStream input = new FileInputStream(servletContext.getRealPath("/index.jsp")); // Wrong!

But instead do:

InputStream input = servletContext.getResourceAsStream("/index.jsp"); // Right!

Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths() instead.

Set<String> resourcePaths = servletContext.getResourcePaths("/");

You can obtain an individual resource as URL via ServletContext#getResource(). This will return null when the resource does not exist.

URL resource = servletContext.getResource(path);

Or if you intend to save an uploaded file, or create a temporary file, then see the below "See also" links.

See also:

White space at top of page

Check for any webkit styles being applied to elements like ul, h4 etc. For me it was margin-before and after causing this.

-webkit-margin-before: 1.33em;
-webkit-margin-after: 1.33em;

JavaScript Loading Screen while page loads

You can wait until the body is ready:

_x000D_
_x000D_
function onReady(callback) {_x000D_
  var intervalId = window.setInterval(function() {_x000D_
    if (document.getElementsByTagName('body')[0] !== undefined) {_x000D_
      window.clearInterval(intervalId);_x000D_
      callback.call(this);_x000D_
    }_x000D_
  }, 1000);_x000D_
}_x000D_
_x000D_
function setVisible(selector, visible) {_x000D_
  document.querySelector(selector).style.display = visible ? 'block' : 'none';_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
  setVisible('.page', true);_x000D_
  setVisible('#loading', false);_x000D_
});
_x000D_
body {_x000D_
  background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;_x000D_
  font-family: 'Alex Brush', cursive !important;_x000D_
}_x000D_
_x000D_
.page    { display: none; padding: 0 0.5em; }_x000D_
.page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }_x000D_
.page p  { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }_x000D_
_x000D_
#loading {_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  z-index: 100;_x000D_
  width: 100vw;_x000D_
  height: 100vh;_x000D_
  background-color: rgba(192, 192, 192, 0.5);_x000D_
  background-image: url("https://i.stack.imgur.com/MnyxU.gif");_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>_x000D_
<link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">_x000D_
<div class="page">_x000D_
  <h1>The standard Lorem Ipsum passage</h1>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
<div id="loading"></div>
_x000D_
_x000D_
_x000D_

Here is a JSFiddle that demonstrates this technique.

mysqldump Error 1045 Access denied despite correct passwords etc

Put The GRANT privileges:

GRANT ALL PRIVILEGES ON mydb.* TO 'username'@'%' IDENTIFIED BY 'password';

How to use Fiddler to monitor WCF service

Standard WCF Tracing/Diagnostics

If for some reason you are unable to get Fiddler to work, or would rather log the requests another way, another option is to use the standard WCF tracing functionality. This will produce a file that has a nice viewer.

Docs

See https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/tracing-and-message-logging

Configuration

Add the following to your config, make sure c:\logs exists, rebuild, and make requests:

  <system.serviceModel>
    <diagnostics>
      <!-- Enable Message Logging here. -->
      <!-- log all messages received or sent at the transport or service model levels -->
      <messageLogging logEntireMessage="true"
                      maxMessagesToLog="300"
                      logMessagesAtServiceLevel="true"
                      logMalformedMessages="true"
                      logMessagesAtTransportLevel="true" />
    </diagnostics>
  </system.serviceModel>

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="Information,ActivityTracing"
        propagateActivity="true">
        <listeners>
          <add name="xml" />
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="xml" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="C:\logs\TracingAndLogging-client.svclog" type="System.Diagnostics.XmlWriterTraceListener"
        name="xml" />
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>

How do I make entire div a link?

the html:

 <a class="xyz">your content</a>

the css:

.xyz{
  display: block;
}

This will make the anchor be a block level element like a div.

How to throw a C++ exception

Wanted to ADD to the other answers described here an additional note, in the case of custom exceptions.

In the case where you create your own custom exception, that derives from std::exception, when you catch "all possible" exceptions types, you should always start the catch clauses with the "most derived" exception type that may be caught. See the example (of what NOT to do):

#include <iostream>
#include <string>

using namespace std;

class MyException : public exception
{
public:
    MyException(const string& msg) : m_msg(msg)
    {
        cout << "MyException::MyException - set m_msg to:" << m_msg << endl;
    }

   ~MyException()
   {
        cout << "MyException::~MyException" << endl;
   }

   virtual const char* what() const throw () 
   {
        cout << "MyException - what" << endl;
        return m_msg.c_str();
   }

   const string m_msg;
};

void throwDerivedException()
{
    cout << "throwDerivedException - thrown a derived exception" << endl;
    string execptionMessage("MyException thrown");
    throw (MyException(execptionMessage));
}

void illustrateDerivedExceptionCatch()
{
    cout << "illustrateDerivedExceptionsCatch - start" << endl;
    try 
    {
        throwDerivedException();
    }
    catch (const exception& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an std::exception, e.what:" << e.what() << endl;
        // some additional code due to the fact that std::exception was thrown...
    }
    catch(const MyException& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an MyException, e.what::" << e.what() << endl;
        // some additional code due to the fact that MyException was thrown...
    }

    cout << "illustrateDerivedExceptionsCatch - end" << endl;
}

int main(int argc, char** argv)
{
    cout << "main - start" << endl;
    illustrateDerivedExceptionCatch();
    cout << "main - end" << endl;
    return 0;
}

NOTE:

0) The proper order should be vice-versa, i.e.- first you catch (const MyException& e) which is followed by catch (const std::exception& e).

1) As you can see, when you run the program as is, the first catch clause will be executed (which is probably what you did NOT wanted in the first place).

2) Even though the type caught in the first catch clause is of type std::exception, the "proper" version of what() will be called - cause it is caught by reference (change at least the caught argument std::exception type to be by value - and you will experience the "object slicing" phenomena in action).

3) In case that the "some code due to the fact that XXX exception was thrown..." does important stuff WITH RESPECT to the exception type, there is misbehavior of your code here.

4) This is also relevant if the caught objects were "normal" object like: class Base{}; and class Derived : public Base {}...

5) g++ 7.3.0 on Ubuntu 18.04.1 produces a warning that indicates the mentioned issue:

In function ‘void illustrateDerivedExceptionCatch()’: item12Linux.cpp:48:2: warning: exception of type ‘MyException’ will be caught catch(const MyException& e) ^~~~~

item12Linux.cpp:43:2: warning: by earlier handler for ‘std::exception’ catch (const exception& e) ^~~~~

Again, I will say, that this answer is only to ADD to the other answers described here (I thought this point is worth mention, yet could not depict it within a comment).

How to plot all the columns of a data frame in R

I don't have R on this computer, but here is a crack at it. You can use par to display multiple plots in a window, or like this to prompt for a click before displaying the next page.

plotfun <- function(col) 
  plot(data[ , col], ylab = names(data[col]), type = "l")
par(ask = TRUE)
sapply(seq(1, length(data), 1), plotfun)

OnClick vs OnClientClick for an asp:CheckBox?

You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.

In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".

$(document).ready(function () {
    $('input[type=checkbox]').click(function(){                
        var areYouSure = confirm('Are you sure you want make this change?');
        if (areYouSure) {
            $(this).prop('checked', this.checked);
        } else {
            $(this).prop('checked', !this.checked);
        }
    });
}); 


<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />

protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
    using (myDataContext db = new myDataDataContext())
    {
        CheckBox chk = (CheckBox)sender;
        RepeaterItem row = (RepeaterItem) chk.NamingContainer;            
        var studentID = ((Label) row.FindControl("lblID")).Text;
        var z = (from b in db.StudentApplicants
        where b.StudentID == studentID
        select b).FirstOrDefault();                
        if(chk != null && chk.Checked != z.FinancialAid){
            z.FinancialAid = chk.Checked;                
            z.ModifiedDate = DateTime.Now;
            db.SubmitChanges();
            BindGrid();
        }
        gvData.DataBind();
    }
}

Display PDF file inside my android application

Maybe you can integrate MuPdf in your application. Here is I've described how to do this: Integrate MuPDF Reader in an app

How can I see the current value of my $PATH variable on OS X?

By entering $PATH on its own at the command prompt, you're trying to run it. This isn't like Windows where you can get your path output by simply typing path.

If you want to see what the path is, simply echo it:

echo $PATH

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How to POST a FORM from HTML to ASPX page

This is very possible. I mocked up 3 pages which should give you a proof of concept:

.aspx page:

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox TextMode="password" ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
</form>

code behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For Each s As String In Request.Form.AllKeys
        Response.Write(s & ": " & Request.Form(s) & "<br />")
    Next
End Sub

Separate HTML page:

<form action="http://localhost/MyTestApp/Default.aspx" method="post">
    <input name="TextBox1" type="text" value="" id="TextBox1" />
    <input name="TextBox2" type="password" id="TextBox2" />
    <input type="submit" name="Button1" value="Button" id="Button1" />
</form>

...and it regurgitates the form values as expected. If this isn't working, as others suggested, use a traffic analysis tool (fiddler, ethereal), because something probably isn't going where you're expecting.

How to access html form input from asp.net code behind

It should normally be done with Request.Form["elementName"].

For example, if you have <input type="text" name="email" /> then you can use Request.Form["email"] to access its value.

Pass multiple values with onClick in HTML link

If valuationId and user are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:

<a href=# onclick="return ReAssign(valuationId,user)">Re-Assign</a>

If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:

<?php
    echo '<a href=# onclick="return ReAssign(\'' + $valuationId + '\',\'' + $user + '\')">Re-Assign</a>';
?>

The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:

var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td><a href=# onclick="return ReAssign(\'' + valuationId + '\',\'' + user + '\')">Re-Assign</a> </td>  </tr>');

The moral of the story is

'someString(\''+'otherString'+','+'yetAnotherString'+'\')'

Will get evaluated as:

someString('otherString,yetAnotherString');

Whereas you would need:

someString('otherString','yetAnotherString');

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

Being new to this myself, here's what I did:

I'm using MS Visual Studio 2010 Pro.

  1. Download and install the OpenXML SDK
  2. Within my project in Visual Studio, select "Project" then "Add Reference"
  3. Select the "Browse" tab
  4. In the "Look in:" pull down, navigate to: C:\Program Files(x86)\Open XML SDK\V2.0\lib and select the "DocumentFormat.OpenXml.dll
  5. Hit OK
  6. In the "Solution Explorer" (on the right for me), the "References" folder now shows the DocumentFormat.OpenXML library.
  7. Right-click on it and select Properties
  8. In the Properties panel, change "Copy Local" to "True".

You should be off and running now using the DocumentFormat classes.

Can we instantiate an abstract class?

Here, i'm creating instance of my class

No, you are not creating the instance of your abstract class here. Rather you are creating an instance of an anonymous subclass of your abstract class. And then you are invoking the method on your abstract class reference pointing to subclass object.

This behaviour is clearly listed in JLS - Section # 15.9.1: -

If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class. Then:

  • If T denotes a class, then an anonymous direct subclass of the class named by T is declared. It is a compile-time error if the class denoted by T is a final class.
  • If T denotes an interface, then an anonymous direct subclass of Object that implements the interface named by T is declared.
  • In either case, the body of the subclass is the ClassBody given in the class instance creation expression.
  • The class being instantiated is the anonymous subclass.

Emphasis mine.

Also, in JLS - Section # 12.5, you can read about the Object Creation Process. I'll quote one statement from that here: -

Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden.

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

You can read about the complete procedure on the link I provided.


To practically see that the class being instantiated is an Anonymous SubClass, you just need to compile both your classes. Suppose you put those classes in two different files:

My.java:

abstract class My {
    public void myMethod() {
        System.out.print("Abstract");
    }
}

Poly.java:

class Poly extends My {
    public static void main(String a[]) {
        My m = new My() {};
        m.myMethod();
    }
}

Now, compile both your source files:

javac My.java Poly.java

Now in the directory where you compiled the source code, you will see the following class files:

My.class
Poly$1.class  // Class file corresponding to anonymous subclass
Poly.class

See that class - Poly$1.class. It's the class file created by the compiler corresponding to the anonymous subclass you instantiated using the below code:

new My() {};

So, it's clear that there is a different class being instantiated. It's just that, that class is given a name only after compilation by the compiler.

In general, all the anonymous subclasses in your class will be named in this fashion:

Poly$1.class, Poly$2.class, Poly$3.class, ... so on

Those numbers denote the order in which those anonymous classes appear in the enclosing class.

How to remove the default link color of the html hyperlink 'a' tag?

<style>
a {
color:      ;
}
</style>

This code changes the color from the default to what is specified in the style. Using a:hover, you can change the color of the text from the default on hover.

Difference between float and decimal data type

Not just specific to MySQL, the difference between float and decimal types is the way that they represent fractional values. Floating point types represent fractions in binary, which can only represent values as {m*2^n | m, n Integers} . values such as 1/5 cannot be precisely represented (without round off error). Decimal numbers are similarly limited, but represent numbers like {m*10^n | m, n Integers}. Decimals still cannot represent numbers like 1/3, but it is often the case in many common fields, like finance, that the expectation is that certain decimal fractions can always be expressed without loss of fidelity. Since a decimal number can represent a value like $0.20 (one fifth of a dollar), it is preferred in those situations.

How to replicate vector in c?

Vector and list aren't conceptually tied to C++. Similar structures can be implemented in C, just the syntax (and error handling) would look different. For example LodePNG implements a dynamic array with functionality very similar to that of std::vector. A sample usage looks like:

uivector v = {};
uivector_push_back(&v, 1);
uivector_push_back(&v, 42);
for(size_t i = 0; i < v.size; ++i)
    printf("%d\n", v.data[i]);
uivector_cleanup(&v);

As can be seen the usage is somewhat verbose and the code needs to be duplicated to support different types.

nothings/stb gives a simpler implementation that works with any types, but compiles only in C:

double *v = 0;
sb_push(v, 1.0);
sb_push(v, 42.0);
for(int i = 0; i < sb_count(v); ++i)
    printf("%g\n", v[i]);
sb_free(v);

A lot of C code, however, resorts to managing the memory directly with realloc:

void* newMem = realloc(oldMem, newSize);
if(!newMem) {
    // handle error
}
oldMem = newMem;

Note that realloc returns null in case of failure, yet the old memory is still valid. In such situation this common (and incorrect) usage leaks memory:

oldMem = realloc(oldMem, newSize);
if(!oldMem) {
    // handle error
}

Compared to std::vector and the C equivalents from above, the simple realloc method does not provide O(1) amortized guarantee, even though realloc may sometimes be more efficient if it happens to avoid moving the memory around.

Escaping special characters in Java Regular Expressions

I wrote this pattern:

Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");

And use it in this method:

String escapeSpecialRegexChars(String str) {

    return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}

Then you can use it like this, for example:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}

We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q and \E:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*\\Q" + text + "\\E.*")
}

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

Recursion or Iteration?

Using just Chrome 45.0.2454.85 m, recursion seems to be a nice amount faster.

Here is the code:

(function recursionVsForLoop(global) {
    "use strict";

    // Perf test
    function perfTest() {}

    perfTest.prototype.do = function(ns, fn) {
        console.time(ns);
        fn();
        console.timeEnd(ns);
    };

    // Recursion method
    (function recur() {
        var count = 0;
        global.recurFn = function recurFn(fn, cycles) {
            fn();
            count = count + 1;
            if (count !== cycles) recurFn(fn, cycles);
        };
    })();

    // Looped method
    function loopFn(fn, cycles) {
        for (var i = 0; i < cycles; i++) {
            fn();
        }
    }

    // Tests
    var curTest = new perfTest(),
        testsToRun = 100;

    curTest.do('recursion', function() {
        recurFn(function() {
            console.log('a recur run.');
        }, testsToRun);
    });

    curTest.do('loop', function() {
        loopFn(function() {
            console.log('a loop run.');
        }, testsToRun);
    });

})(window);

RESULTS

// 100 runs using standard for loop

100x for loop run. Time to complete: 7.683ms

// 100 runs using functional recursive approach w/ tail recursion

100x recursion run. Time to complete: 4.841ms

In the screenshot below, recursion wins again by a bigger margin when run at 300 cycles per test

Recursion wins again!

How to avoid annoying error "declared and not used"

According to the FAQ:

Some have asked for a compiler option to turn those checks off or at least reduce them to warnings. Such an option has not been added, though, because compiler options should not affect the semantics of the language and because the Go compiler does not report warnings, only errors that prevent compilation.

There are two reasons for having no warnings. First, if it's worth complaining about, it's worth fixing in the code. (And if it's not worth fixing, it's not worth mentioning.) Second, having the compiler generate warnings encourages the implementation to warn about weak cases that can make compilation noisy, masking real errors that should be fixed.

I don't necessarily agree with this for various reasons not worth going into. It is what it is, and it's not likely to change in the near future.

For packages, there's the goimports tool which automatically adds missing packages and removes unused ones. For example:

# Install it
$ go get golang.org/x/tools/cmd/goimports

# -w to write the source file instead of stdout
$ goimports -w my_file.go

You should be able to run this from any half-way decent editor - for example for Vim:

:!goimports -w %

The goimports page lists some commands for other editors, and you typically set it to be run automatically when you save the buffer to disk.

Note that goimports will also run gofmt.


As was already mentioned, for variables the easiest way is to (temporarily) assign them to _ :

// No errors
tasty := "ice cream"
horrible := "marmite"

// Commented out for debugging
//eat(tasty, horrible)

_, _ = tasty, horrible

What linux shell command returns a part of a string?

expr(1) has a substr subcommand:

expr substr <string> <start-index> <length>

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

Insert results of a stored procedure into a temporary table

After searching around I found a way to create a temp table dynamically for any stored procedure without using OPENROWSET or OPENQUERY using a generic schema of Stored Procedure's result definition especially when you are not database Administrator.

Sql server has a buit-in proc sp_describe_first_result_set that can provide you with schema of any procedures resultset. I created a schema table from results of this procedure and manually set all the field to NULLABLE.

declare @procname varchar(100) = 'PROCEDURENAME' -- your procedure name
declare @param varchar(max) = '''2019-06-06''' -- your parameters 
declare @execstr nvarchar(max) = N'exec ' + @procname
declare @qry nvarchar(max)

-- Schema table to store the result from sp_describe_first_result_set.
create table #d
(is_hidden  bit  NULL, column_ordinal   int  NULL, name sysname NULL, is_nullable   bit  NULL, system_type_id   int  NULL, system_type_name nvarchar(256) NULL,
max_length  smallint  NULL, precision   tinyint  NULL,  scale   tinyint  NULL,  collation_name  sysname NULL, user_type_id  int NULL, user_type_database    sysname NULL,
user_type_schema    sysname NULL,user_type_name sysname NULL,assembly_qualified_type_name   nvarchar(4000),xml_collection_id    int NULL,xml_collection_database    sysname NULL,
xml_collection_schema   sysname NULL,xml_collection_name    sysname NULL,is_xml_document    bit  NULL,is_case_sensitive bit  NULL,is_fixed_length_clr_type  bit  NULL,
source_server   sysname NULL,source_database    sysname NULL,source_schema  sysname NULL,source_table   sysname NULL,source_column  sysname NULL,is_identity_column bit NULL,
is_part_of_unique_key   bit NULL,is_updateable  bit NULL,is_computed_column bit NULL,is_sparse_column_set   bit NULL,ordinal_in_order_by_list   smallint NULL,
order_by_list_length    smallint NULL,order_by_is_descending    smallint NULL,tds_type_id   int  NULL,tds_length    int  NULL,tds_collation_id  int NULL,
tds_collation_sort_id   tinyint NULL)


-- Get result set definition of your procedure
insert into #d
EXEC sp_describe_first_result_set @exestr, NULL, 0

-- Create a query to generate and populate a global temp table from above results
select 
@qry = 'Create table ##t(' +
stuff(  
    (select ',' + name + ' '+ system_type_name + ' NULL'
    from #d d For XML Path, TYPE)
    .value(N'.[1]', N'nvarchar(max)')
, 1,1,'')
+ ')

insert into ##t 
Exec '+@procname+' ' + @param

Exec sp_executesql @qry

-- Use below global temp table to query the data as you may
select * from ##t

-- **WARNING** Don't forget to drop the global temp table ##t.
--drop table ##t
drop table #d 

Developed and tested on Sql Server version - Microsoft SQL Server 2016 (RTM) - 13.0.1601.5(Build 17134:)

You can tweak the schema for your SQL server version that you are using (if needed).

Logging with Retrofit 2

Try this:

Request request = chain.request();
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
String body = buffer.readUtf8();

After this, in the body there is the JSON you are interested in.

iCheck check if checkbox is checked

I wrote some simple thing:

When you initialize icheck as:

$('input').iCheck({
    checkboxClass: 'icheckbox_square-blue',
    radioClass: 'iradio_square-blue',
    increaseArea: '20%' // optional
});

Add this code under it:

$('input').on('ifChecked', function (event){
    $(this).closest("input").attr('checked', true);          
});
$('input').on('ifUnchecked', function (event) {
    $(this).closest("input").attr('checked', false);
});

After this you can easily find your original checkbox's state. I wrote this code for using icheck in gridView and accessed its state from server side by C#.

Simply find your checkBox from its id.

Converting java.sql.Date to java.util.Date

If you really want the runtime type to be util.Date then just do this:

java.util.Date utilDate = new java.util.Date(sqlDate.getTime());

Brian.

Difference between MongoDB and Mongoose

One more difference I found with respect to both is that it is fairly easy to connect to multiple databases with mongodb native driver while you have to use work arounds in mongoose which still have some drawbacks.

So if you wanna go for a multitenant application, go for mongodb native driver.

.includes() not working in Internet Explorer

I had the same problem when working in Angular 5. In order to make it work directly without writing a polyfill yourself, just add the following line to polyfills.ts file:

import "core-js/es7/array"

Also, tsconfig.json lib section might be relevant:

"lib": [
  "es2017",
  "dom"
],

Simple way to understand Encapsulation and Abstraction

Abstraction is Showing necessary info to the user where as Encapsulation hide the unwanted data from the user(Product from the user).

Encapsulation Implements the Abstraction.

Abstraction is the process where as Encapsulation actually implements it. For Eg. Adding user logic -> we need to validate the user , creating DB connection and insert the User. So user do not know fist need to call validate function , creating DB connection and then insert the Value in DB. He only call the AddUser function which call the internally all logic with in , this is only Encapsulation (Grouping the feature and hiding the methods).

How to find the difference in days between two dates?

on unix you should have GNU dates installed. you do not need to deviate from bash. here is the strung out solution considering days, just to show the steps. it can be simplified and extended to full dates.

DATE=$(echo `date`)
DATENOW=$(echo `date -d "$DATE" +%j`)
DATECOMING=$(echo `date -d "20131220" +%j`)
THEDAY=$(echo `expr $DATECOMING - $DATENOW`)

echo $THEDAY 

Turn off axes in subplots

You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.

Rather than using plt.axis('off') you should use ax.axis('off') where ax is a matplotlib.axes object. To do this for your code you simple need to add axarr[0,0].axis('off') and so on for each of your subplots.

The code below shows the result (I've removed the prune_matrix part because I don't have access to that function, in the future please submit fully working code.)

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm

img = mpimg.imread("stewie.jpg")

f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')

axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')

axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')

axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')

plt.show()

Stewie example

Note: To turn off only the x or y axis you can use set_visible() e.g.:

axarr[0,0].xaxis.set_visible(False) # Hide only x axis

Can we define min-margin and max-margin, max-padding and min-padding in css?

Comming late to the party, as said above there unfortunately is no such thing as max-margin. A sollution that helped me is to place a div above the item you want to have the max-margin applied to.

<body style="width:90vw; height:90vh;">
    <div name="parrentdiv/body" style="width:300px; height:100%; background-color: blue">
        <div name="margin top" style="width:300px; height:50%; min-height:200px; background-color: red"></div>
        <div name="item" style="width:300px; height:180px; background-color: lightgrey">Hello World!</div>
    </div>
</body>

Run above coded snippet in full page and resize the window to see this working. The lightgreypart will have the margin-top of 50% and a 'min-margin-top' of 200px. This margin is the red div (wich you can hide with display: none; if you want to). The blue part is what's left of the body.

I hope this will help people with the same problem in the future.

How to prevent going back to the previous activity?

finish() gives you method to close current Activity not whole application. And you better don't try to look for methods to kill application. Little advice.

Have you tried conjunction of Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY? Remember to use this flags in Intent starting activity!

Initializing a two dimensional std::vector

The recommended approach is to use fill constructor to initialize a two-dimensional vector with a given default value :

std::vector<std::vector<int>> fog(M, std::vector<int>(N, default_value));

where, M and N are dimensions for your 2D vector.

Django check for any exists for a query

As of Django 1.2, you can use exists():

https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

if some_queryset.filter(pk=entity_id).exists():
    print("Entry contained in queryset")

How to insert a timestamp in Oracle?

Inserting date in sql

insert
into tablename (timestamp_value)
values ('dd-mm-yyyy hh-mm-ss AM');

If suppose we wanted to insert system date

insert
into tablename (timestamp_value)
values (sysdate);

Python: access class property from string

x = getattr(self, source) will work just perfectly if source names ANY attribute of self, including the other_data in your example.

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

Alter table add multiple columns ms sql

You need to remove the brackets

ALTER TABLE Countries
ADD  
HasPhotoInReadyStorage  bit,
 HasPhotoInWorkStorage  bit,
 HasPhotoInMaterialStorage bit,
 HasText  bit;

Read XML file using javascript

You can use below script for reading child of the above xml. It will work with IE and Mozila Firefox both.

<script type="text/javascript">

function readXml(xmlFile){

var xmlDoc;

if(typeof window.DOMParser != "undefined") {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET",xmlFile,false);
    if (xmlhttp.overrideMimeType){
        xmlhttp.overrideMimeType('text/xml');
    }
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
}
else{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.load(xmlFile);
}
var tagObj=xmlDoc.getElementsByTagName("marker");
var typeValue = tagObj[0].getElementsByTagName("type")[0].childNodes[0].nodeValue;
var titleValue = tagObj[0].getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>

Using Jquery AJAX function with datatype HTML

Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.

Ajax call:

$.ajax({
  type : 'POST',
  url : 'post.php',
  dataType : 'html',
  data: {
      email : $('#email').val()
  },
  success : function(data){
      $('#waiting').hide(500);
      $('#message').removeClass().addClass((data == '') ? 'error' : 'success')
     .html(data).show(500);
      if (data == '') {
          $('#message').html("Format your email correcly");
          $('#demoForm').show(500);
      }
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
      $('#waiting').hide(500);
      $('#message').removeClass().addClass('error')
      .text('There was an error.').show(500);
      $('#demoForm').show(500);
  }

});

post.php

<?php
sleep(1);

function processEmail($email) {
    if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
        // your logic here (ex: add into database)
        return true;
    }
    return false;
}

if (processEmail($_POST['email'])) {
    echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}

Finding median of list in Python

You can try the quickselect algorithm if faster average-case running times are needed. Quickselect has average (and best) case performance O(n), although it can end up O(n²) on a bad day.

Here's an implementation with a randomly chosen pivot:

import random

def select_nth(n, items):
    pivot = random.choice(items)

    lesser = [item for item in items if item < pivot]
    if len(lesser) > n:
        return select_nth(n, lesser)
    n -= len(lesser)

    numequal = items.count(pivot)
    if numequal > n:
        return pivot
    n -= numequal

    greater = [item for item in items if item > pivot]
    return select_nth(n, greater)

You can trivially turn this into a method to find medians:

def median(items):
    if len(items) % 2:
        return select_nth(len(items)//2, items)

    else:
        left  = select_nth((len(items)-1) // 2, items)
        right = select_nth((len(items)+1) // 2, items)

        return (left + right) / 2

This is very unoptimised, but it's not likely that even an optimised version will outperform Tim Sort (CPython's built-in sort) because that's really fast. I've tried before and I lost.

How to make UIButton's text alignment center? Using IB

For those of you who are now using iOS 6 or higher, UITextAlignmentCenter has been deprecated. It is now NSTextAlignmentCenter

EXAMPLE: mylabel.textAlignment = NSTextAlignmentCenter; Works perfectly.

How can I print each command before executing?

set -o xtrace

or

bash -x myscript.sh

This works with standard /bin/sh as well IIRC (it might be a POSIX thing then)

And remember, there is bashdb (bash Shell Debugger, release 4.0-0.4)


To revert to normal, exit the subshell or

set +o xtrace

How to use gitignore command in git

git ignore is a convention in git. Setting a file by the name of .gitignore will ignore the files in that directory and deeper directories that match the patterns that the file contains. The most common use is just to have one file like this at the top level. But you can add others deeper in your directory structure to ignore even more patterns or stop ignoring them for that directory and subsequently deeper ones.

Likewise, you can "unignore" certain files in a deeper structure or a specific subset (ie, you ignore *.log but want to still track important.log) by specifying patterns beginning with !. eg:

*.log !important.log

will ignore all log files but will track files named important.log

If you are tracking files you meant to ignore, delete them, add the pattern to you .gitignore file and add all the changes

# delete files that should be ignored, or untrack them with 
# git rm --cached <file list or pattern>

# stage all the changes git commit
git add -A 

from now on your repository will not have them tracked.

If you would like to clean up your history, you can

# if you want to correct the last 10 commits
git rebase -i --preserve-merges HEAD~10 

then mark each commit with e or edit. Save the plan. Now git will replay your history stopping at each commit you marked with e. Here you delete the files you don't want, git add -A and then git rebase --continue until you are done. Your history will be clean. Make sure you tell you coworkers as you will have to force push and they will have to rebase what they didn't push yet.

IF a == true OR b == true statement

Comparison expressions should each be in their own brackets:

{% if (a == 'foo') or (b == 'bar') %}
    ...
{% endif %}

Alternative if you are inspecting a single variable and a number of possible values:

{% if a in ['foo', 'bar', 'qux'] %}
    ...
{% endif %}

how to stop a running script in Matlab

If ctrl+c doesn't respond right away because your script is too long/complex, hold it.

The break command doesn't run when matlab is executing some of its deeper scripts, and either it won't log a ctrl sequence in the buffer, or it clears the buffer just before or just after it completes those pieces of code. In either case, when matlab returns to execute more of your script, it will recognize that you are holding ctrl+c and terminate.

For longer running programs, I usually try to find a good place to provide a status update and I always accompany that with some measure of time using tic and toc. Depending on what I am doing, I might use run time, segment time, some kind of average, etc...

For really long running programs, I found this to be exceptionally useful http://www.mathworks.com/matlabcentral/fileexchange/16649-send-text-message-to-cell-phone/content/send_text_message.m

but it looks like they have some newer functions for this too.

ORACLE IIF Statement

Oracle doesn't provide such IIF Function. Instead, try using one of the following alternatives:

DECODE Function:

SELECT DECODE(EMP_ID, 1, 'True', 'False') from Employee

CASE Function:

SELECT CASE WHEN EMP_ID = 1 THEN 'True' ELSE 'False' END from Employee

How to make a simple image upload using Javascript/HTML

Here's a simple example with no jQuery. Use URL.createObjectURL, which

creates a DOMString containing a URL representing the object given in the parameter

Then, you can simply set the src of the image to that url:

_x000D_
_x000D_
window.addEventListener('load', function() {
  document.querySelector('input[type="file"]').addEventListener('change', function() {
      if (this.files && this.files[0]) {
          var img = document.querySelector('img');
          img.onload = () => {
              URL.revokeObjectURL(img.src);  // no longer needed, free memory
          }

          img.src = URL.createObjectURL(this.files[0]); // set src to blob url
      }
  });
});
_x000D_
<input type='file' />
<br><img id="myImg" src="#">
_x000D_
_x000D_
_x000D_

OpenCV in Android Studio

Integrating OpenCV v3.1.0 into Android Studio v1.4.1, instructions with additional detail and this-is-what-you-should-get type screenshots.

Most of the credit goes to Kiran, Kool, 1", and SteveLiles over at opencv.org for their explanations. I'm adding this answer because I believe that Android Studio's interface is now stable enough to work with on this type of integration stuff. Also I have to write these instructions anyway for our project.

Experienced A.S. developers will find some of this pedantic. This answer is targeted at people with limited experience in Android Studio.

  1. Create a new Android Studio project using the project wizard (Menu:/File/New Project):

    • Call it "cvtest1"
    • Form factor: API 19, Android 4.4 (KitKat)
    • Blank Activity named MainActivity

      You should have a cvtest1 directory where this project is stored. (the title bar of Android studio shows you where cvtest1 is when you open the project)

  2. Verify that your app runs correctly. Try changing something like the "Hello World" text to confirm that the build/test cycle is OK for you. (I'm testing with an emulator of an API 19 device).

  3. Download the OpenCV package for Android v3.1.0 and unzip it in some temporary directory somewhere. (Make sure it is the package specifically for Android and not just the OpenCV for Java package.) I'll call this directory "unzip-dir" Below unzip-dir you should have a sdk/native/libs directory with subdirectories that start with things like arm..., mips... and x86... (one for each type of "architecture" Android runs on)

  4. From Android Studio import OpenCV into your project as a module: Menu:/File/New/Import_Module:

    • Source-directory: {unzip-dir}/sdk/java
    • Module name: Android studio automatically fills in this field with openCVLibrary310 (the exact name probably doesn't matter but we'll go with this).
    • Click on next. You get a screen with three checkboxes and questions about jars, libraries and import options. All three should be checked. Click on Finish.

      Android Studio starts to import the module and you are shown an import-summary.txt file that has a list of what was not imported (mostly javadoc files) and other pieces of information. enter image description here

      But you also get an error message saying failed to find target with hash string 'android-14'.... This happens because the build.gradle file in the OpenCV zip file you downloaded says to compile using android API version 14, which by default you don't have with Android Studio v1.4.1. enter image description here

  5. Open the project structure dialogue (Menu:/File/Project_Structure). Select the "app" module, click on the Dependencies tab and add :openCVLibrary310 as a Module Dependency. When you select Add/Module_Dependency it should appear in the list of modules you can add. It will now show up as a dependency but you will get a few more cannot-find-android-14 errors in the event log.

  6. Look in the build.gradle file for your app module. There are multiple build.gradle files in an Android project. The one you want is in the cvtest1/app directory and from the project view it looks like build.gradle (Module: app). Note the values of these four fields:

    • compileSDKVersion (mine says 23)
    • buildToolsVersion (mine says 23.0.2)
    • minSdkVersion (mine says 19)
    • targetSdkVersion (mine says 23)
  7. Your project now has a cvtest1/OpenCVLibrary310 directory but it is not visible from the project view:

enter image description here

Use some other tool, such as any file manager, and go to this directory. You can also switch the project view from Android to Project Files and you can find this directory as shown in this screenshot: enter image description here

Inside there is another build.gradle file (it's highlighted in the above screenshot). Update this file with the four values from step 6.

  1. Resynch your project and then clean/rebuild it. (Menu:/Build/Clean_Project) It should clean and build without errors and you should see many references to :openCVLibrary310 in the 0:Messages screen.

    enter image description here

    At this point the module should appear in the project hierarchy as openCVLibrary310, just like app. (Note that in that little drop-down menu I switched back from Project View to Android View ). You should also see an additional build.gradle file under "Gradle Scripts" but I find the Android Studio interface a little bit glitchy and sometimes it does not do this right away. So try resynching, cleaning, even restarting Android Studio.

    You should see the openCVLibrary310 module with all the OpenCV functions under java like in this screenshot:

    enter image description here

  2. Copy the {unzip-dir}/sdk/native/libs directory (and everything under it) to your Android project, to cvtest1/OpenCVLibrary310/src/main/, and then rename your copy from libs to jniLibs. You should now have a cvtest1/OpenCVLibrary310/src/main/jniLibs directory. Resynch your project and this directory should now appear in the project view under openCVLibrary310.

    enter image description here

  3. Go to the onCreate method of MainActivity.java and append this code:

    if (!OpenCVLoader.initDebug()) {
        Log.e(this.getClass().getSimpleName(), "  OpenCVLoader.initDebug(), not working.");
    } else {
        Log.d(this.getClass().getSimpleName(), "  OpenCVLoader.initDebug(), working.");
    }
    

    Then run your application. You should see lines like this in the Android Monitor: enter image description here (I don't know why that line with the error message is there)

  4. Now try to actually use some openCV code. In the example below I copied a .jpg file to the cache directory of the cvtest1 application on the android emulator. The code below loads this image, runs the canny edge detection algorithm and then writes the results back to a .png file in the same directory.

    Put this code just below the code from the previous step and alter it to match your own files/directories.

    String inputFileName="simm_01";
    String inputExtension = "jpg";
    String inputDir = getCacheDir().getAbsolutePath();  // use the cache directory for i/o
    String outputDir = getCacheDir().getAbsolutePath();
    String outputExtension = "png";
    String inputFilePath = inputDir + File.separator + inputFileName + "." + inputExtension;
    
    
    Log.d (this.getClass().getSimpleName(), "loading " + inputFilePath + "...");
    Mat image = Imgcodecs.imread(inputFilePath);  
    Log.d (this.getClass().getSimpleName(), "width of " + inputFileName + ": " + image.width());
    // if width is 0 then it did not read your image.
    
    
    // for the canny edge detection algorithm, play with these to see different results
    int threshold1 = 70;
    int threshold2 = 100;
    
    Mat im_canny = new Mat();  // you have to initialize output image before giving it to the Canny method
    Imgproc.Canny(image, im_canny, threshold1, threshold2);
    String cannyFilename = outputDir + File.separator + inputFileName + "_canny-" + threshold1 + "-" + threshold2 + "." + outputExtension;
    Log.d (this.getClass().getSimpleName(), "Writing " + cannyFilename);
    Imgcodecs.imwrite(cannyFilename, im_canny);
    
  5. Run your application. Your emulator should create a black and white "edge" image. You can use the Android Device Monitor to retrieve the output or write an activity to show it.

The Gotchas:

  • If you lower your target platform below KitKat some of the OpenCV libraries will no longer function, specifically the classes related to org.opencv.android.Camera2Renderer and other related classes. You can probably get around this by simply removing the apprpriate OpenCV .java files.
  • If you raise your target platform to Lollipop or above my example of loading a file might not work because use of absolute file paths is frowned upon. So you might have to change the example to load a file from the gallery or somewhere else. There are numerous examples floating around.

Parse JSON String to JSON Object in C#.NET

Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.

It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.

And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D

There is a System.Json.dll you should add to your project References.

-Jesse

New self vs. new static

In addition to others' answers :

static:: will be computed using runtime information.

That means you can't use static:: in a class property because properties values :

Must be able to be evaluated at compile time and must not depend on run-time information.

class Foo {
    public $name = static::class;

}

$Foo = new Foo;
echo $Foo->name; // Fatal error

Using self::

class Foo {
    public $name = self::class;

}
$Foo = new Foo;
echo $Foo->name; // Foo

Please note that the Fatal error comment in the code i made doesn't indicate where the error happened, the error happened earlier before the object was instantiated as @Grapestain mentioned in the comments

Apache2: 'AH01630: client denied by server configuration'

This "bug" is actually the new normal behavior of Apache 2.4. In my case, I had a very specific rule to deny access to any folder or file with name starting with ".", so I had to set an exception for a particular public folder that requires such odd name.

For the record my particular Rewrite rule is:

RewriteRule "(?!\.trusted)(^|/)\." - [F]

This rule [F]obits everything starting with "." but .trusted, thanks to the magic of regex "?!" negation.

Java: Add elements to arraylist with FOR loop where element name has increasing number

I assume Answer as an Integer data type so in this case, you can easily use Scanner class for adding the multiple elements(say 50).

private static final Scanner obj = new Scanner(System.in);
private static ArrayList<Integer> arrayList = new ArrayList<Integer>(50);
public static void main(String...S){
for (int i=0;i<50;i++) {
  /*Using Scanner class object to take input.*/
  arrayList.add(obj.nextInt());
}
 /*You can also check the elements of your ArrayList.*/
for (int i=0;i<50;i++) {
 /*Using get function for fetching the value present at index 'i'.*/
 System.out.print(arrayList.get(i)+" ");
}}

This is a simple and easy method for adding multiple values in an ArrayList using for loop. As in the above code, I presume the Answer as Integer it could be String, Double, Long et Cetra. So, in that case, you can use next(), nextDouble(), and nextLong() respectively.

How to find rows in one table that have no corresponding row in another table

I can't tell you which of these methods will be best on H2 (or even if all of them will work), but I did write an article detailing all of the (good) methods available in TSQL. You can give them a shot and see if any of them works for you:

http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&referringTitle=Home

Type safety: Unchecked cast

If you really want to get rid of the warnings, one thing you can do is create a class that extends from the generic class.

For example, if you're trying to use

private Map<String, String> someMap = new HashMap<String, String>();

You can create a new class like such

public class StringMap extends HashMap<String, String>()
{
    // Override constructors
}

Then when you use

someMap = (StringMap) getApplicationContext().getBean("someMap");

The compiler DOES know what the (no longer generic) types are, and there will be no warning. This may not always be the perfect solution, some might argue this kind of defeats the purpose of generic classes, but you're still re-using all of the same code from the generic class, you're just declaring at compile time what type you want to use.

Check if a string matches a regex in Bash script

I would use expr match instead of =~:

expr match "$date" "[0-9]\{8\}" >/dev/null && echo yes

This is better than the currently accepted answer of using =~ because =~ will also match empty strings, which IMHO it shouldn't. Suppose badvar is not defined, then [[ "1234" =~ "$badvar" ]]; echo $? gives (incorrectly) 0, while expr match "1234" "$badvar" >/dev/null ; echo $? gives correct result 1.

We have to use >/dev/null to hide expr match's output value, which is the number of characters matched or 0 if no match found. Note its output value is different from its exit status. The exit status is 0 if there's a match found, or 1 otherwise.

Generally, the syntax for expr is:

expr match "$string" "$lead"

Or:

expr "$string" : "$lead"

where $lead is a regular expression. Its exit status will be true (0) if lead matches the leading slice of string (Is there a name for this?). For example expr match "abcdefghi" "abc"exits true, but expr match "abcdefghi" "bcd" exits false. (Credit to @Carlo Wood for pointing out this.

MomentJS getting JavaScript Date in UTC

Or simply:

Date.now

From MDN documentation:

The Date.now() method returns the number of milliseconds elapsed since January 1, 1970

Available since ECMAScript 5.1

It's the same as was mentioned above (new Date().getTime()), but more shortcutted version.

"starting Tomcat server 7 at localhost has encountered a prob"

Go to web.xml add <element> before <web-app> and close </element> after </web-app>

should be somethings like this

<?xml version="1.0" encoding="UTF-8"?>

<element>

<web-app>

....
</web-app>

</element>

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

They aren't the same though, are they? One is a copy, the other is a swap. Hence the function names.

My favourite is:

a = b;

Where a and b are vectors.

C# switch on type

There is a simple answer to this question which uses a dictionary of types to look up a lambda function. Here is how it might be used:

var ts = new TypeSwitch()
    .Case((int x) => Console.WriteLine("int"))
    .Case((bool x) => Console.WriteLine("bool"))
    .Case((string x) => Console.WriteLine("string"));

ts.Switch(42);
ts.Switch(false);
ts.Switch("hello");

There is also a generalized solution to this problem in terms of pattern matching (both types and run-time checked conditions):

var getRentPrice = new PatternMatcher<int>()
    .Case<MotorCycle>(bike => 100 + bike.Cylinders * 10) 
    .Case<Bicycle>(30) 
    .Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20)
    .Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20)
    .Default(0);

var vehicles = new object[] {
    new Car { EngineType = EngineType.Diesel, Doors = 2 },
    new Car { EngineType = EngineType.Diesel, Doors = 4 },
    new Car { EngineType = EngineType.Gasoline, Doors = 3 },
    new Car { EngineType = EngineType.Gasoline, Doors = 5 },
    new Bicycle(),
    new MotorCycle { Cylinders = 2 },
    new MotorCycle { Cylinders = 3 },
};

foreach (var v in vehicles)
{
    Console.WriteLine("Vehicle of type {0} costs {1} to rent", v.GetType(), getRentPrice.Match(v));
}

Exit single-user mode

The following worked for me:

USE [master]
SET DEADLOCK_PRIORITY HIGH
exec sp_dboption '[StuckDB]', 'single user', 'FALSE';
ALTER DATABASE [StuckDB] SET MULTI_USER WITH NO_WAIT
ALTER DATABASE [StuckDB] SET MULTI_USER WITH ROLLBACK IMMEDIATE

Hiding user input on terminal in Linux script

Update

In case you want to get fancy by outputting an * for each character they type, you can do something like this (using andreas' read -s solution):

unset password;
while IFS= read -r -s -n1 pass; do
  if [[ -z $pass ]]; then
     echo
     break
  else
     echo -n '*'
     password+=$pass
  fi
done

Without being fancy

echo "Please enter your username";
read username;

echo "Please enter your password";
stty -echo
read password;
stty echo

Selected tab's color in Bottom Navigation View

In order to set textColor, BottomNavigationView has two style properties you can set directly from the xml:

  • itemTextAppearanceActive
  • itemTextAppearanceInactive

In your layout.xml file:

<com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bnvMainNavigation"
            style="@style/NavigationView"/>
  

In your styles.xml file:

    <style name="NavigationView" parent="Widget.MaterialComponents.BottomNavigationView">
      <item name="itemTextAppearanceActive">@style/ActiveText</item>
      <item name="itemTextAppearanceInactive">@style/InactiveText</item>
    </style>
    <style name="ActiveText">
      <item name="android:textColor">@color/colorPrimary</item>
    </style>
    <style name="InactiveText">
      <item name="android:textColor">@color/colorBaseBlack</item>
    </style>

How to block until an event is fired in c#

You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:

ManualResetEvent oSignalEvent = new ManualResetEvent(false);

void SecondThread(){
    //DoStuff
    oSignalEvent.Set();
}

void Main(){
    //DoStuff
    //Call second thread
    System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
    oSecondThread.Start();

    oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
    oSignalEvent.Reset();
    //Do more stuff
}

How do you auto format code in Visual Studio?

Under Under Tools -> Options -> Text Editor, then going to the Formatting -> General section of whatever language you wish to format you will find General. Check all three formatting check-boxes.

Under Tools -> Options -> Text Editor, then going to the TABS section of whatever language you wish to format you will find Indenting. Select Smart and it will activate automatic formatting whenever you use one of the closing elements ; ) } within that block.

No need for keystrokes.

Why is quicksort better than mergesort?

While they're both in the same complexity class, that doesn't mean they both have the same runtime. Quicksort is usually faster than mergesort, just because it's easier to code a tight implementation and the operations it does can go faster. It's because that quicksort is generally faster that people use it instead of mergesort.

However! I personally often will use mergesort or a quicksort variant that degrades to mergesort when quicksort does poorly. Remember. Quicksort is only O(n log n) on average. It's worst case is O(n^2)! Mergesort is always O(n log n). In cases where realtime performance or responsiveness is a must and your input data could be coming from a malicious source, you should not use plain quicksort.

How can I convert this foreach code to Parallel.ForEach?

These lines Worked for me.

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
 //My Stuff
});

Parse error: Syntax error, unexpected end of file in my PHP code

I saw some errors, which I've fixed below.

This is what I got as being erroneous:

if (login())
{?>
<h2>Welcome Administrator</h2>
<a href=\"upload.php\">Upload Files</a>
<br />
<a href=\"points.php\">Edit Points Tally</a>
<?php}
else
{
echo "Incorrect login details. Please login";
}

This is how I would have done it:

<html>
    some code
<?php
function login()
{
    if (empty ($_POST['username']))
    {
        return false;
    }
    if (empty ($_POST['password']))
    {
        return false;
    }
    $username = trim ($_POST['username']);
    $password = trim ($_POST['password']);
    $scrambled = md5 ($password . 'foo');
    $link = mysqli_connect('localhost', 'root', 'password');
    if (!$link)
    {
        $error = "Unable to connect to the database server";
        include 'error.html.php';
        exit ();
    }
    if (!mysqli_set_charset ($link, 'utf8'))
    {
        $error = "Unable to set database connection encoding";
        include 'error.html.php';
        exit ();
    }
    if (!mysqli_select_db ($link, 'foo'))
    {
        $error = "Unable to locate the foo database";
        include 'error.html.php';
        exit ();
    }
    $sql = "SELECT COUNT(*) FROM admin WHERE username = '$username' AND password = '$scrambled'";
    $result = mysqli_query ($link, $sql);
    if (!$result)
    {
        return false;
        exit ();
    }
    $row = mysqli_fetch_array ($result);
    if ($row[0] > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
if (login())
{
echo '<h2>Welcome Administrator</h2>
<a href=\"upload.php\">Upload Files</a>
<br />
<a href=\"points.php\">Edit Points Tally</a>';
}
else
{
    echo "Incorrect login details. Please login";
}
?>
some more html code
</html>

Convert normal Java Array or ArrayList to Json Array in android

This is the correct syntax:

String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);

Install Android App Bundle on device

For MAC:

brew install bundletool
bundletool build-apks --bundle=./app.aab --output=./app.apks
bundletool install-apks --apks=app.apks

Prevent Default on Form Submit jQuery

This is an ancient question, but the accepted answer here doesn't really get to the root of the problem.

You can solve this two ways. First with jQuery:

$(document).ready( function() { // Wait until document is fully parsed
  $("#cpa-form").on('submit', function(e){

     e.preventDefault();

  });
})

Or without jQuery:

// Gets a reference to the form element
var form = document.getElementById('cpa-form');

// Adds a listener for the "submit" event.
form.addEventListener('submit', function(e) {

  e.preventDefault();

});

You don't need to use return false to solve this problem.

How to round down to nearest integer in MySQL?

Try this,

SELECT SUBSTR(12345.7344,1,LOCATE('.', 12345.7344) - 1)

or

SELECT FLOOR(12345.7344)

SQLFiddle Demo

Select method in List<t> Collection

I have used a script but to make a join, maybe I can help you

string Email = String.Join(", ", Emails.Where(i => i.Email != "").Select(i => i.Email).Distinct());

Calculate the execution time of a method

 using System.Diagnostics;
 class Program
 {
    static void Test1()
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine("Test1 " + i);
        }
    }
  static void Main(string[] args)
    {

        Stopwatch sw = new Stopwatch();
        sw.Start();
        Test1();
        sw.Stop();
        Console.WriteLine("Time Taken-->{0}",sw.ElapsedMilliseconds);
   }
 }

JavaScript for detecting browser language preference

There is no decent way to get that setting, at least not something browser independent.

But the server has that info, because it is part of the HTTP request header (the Accept-Language field, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)

So the only reliable way is to get an answer back from the server. You will need something that runs on the server (like .asp, .jsp, .php, CGI) and that "thing" can return that info. Good examples here: http://www.developershome.com/wap/detection/detection.asp?page=readHeader

read.csv warning 'EOF within quoted string' prevents complete reading of file

In the R help section, as pointed out above, just disabling quoting altogether, by simply adding:

    quote = "" 

to the read.csv() worked for me.

The error, "EOF within quoted string", occurred with:

    > iproscan.53A.neg     = read.csv("interproscan.53A.neg.n.csv",
    +                        colClasses=c(pb.id      = "character",
    +                                     genLoc     = "character",
    +                                     icode      = "character",
    +                                     length     = "character",
    +                                     proteinDB  = "character",
    +                                     protein.id = "character",
    +                                     prot.desc  = "character",
    +                                     start      = "character",
    +                                     end        = "character",
    +                                     evalue     = "character",
    +                                     tchar      = "character",
    +                                     date       = "character",
    +                                     ipro.id    = "character",
    +                                     prot.name  = "character",
    +                                     go.cat     = "character",
    +                                     reactome.id= "character"),
    +                                     as.is=T,header=F)
    Warning message:
    In scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
      EOF within quoted string
    > dim(iproscan.53A.neg)
    [1] 69383    16

And the file read in was missing 6,619 lines. But by disabling quoting

    > iproscan.53A.neg     = read.csv("interproscan.53A.neg.n.csv",
    +                        colClasses=c(pb.id      = "character",
    +                                     genLoc     = "character",
    +                                     icode      = "character",
    +                                     length     = "character",
    +                                     proteinDB  = "character",
    +                                     protein.id = "character",
    +                                     prot.desc  = "character",
    +                                     start      = "character",
    +                                     end        = "character",
    +                                     evalue     = "character",
    +                                     tchar      = "character",
    +                                     date       = "character",
    +                                     ipro.id    = "character",
    +                                     prot.name  = "character",
    +                                     go.cat     = "character",
    +                                     reactome.id= "character"),
    +                                     as.is=T,header=F,**quote=""**)    
    > 
    > dim(iproscan.53A.neg)
    [1] 76002    16

Worked without error and all lines were successfully read in.

How can I read a whole file into a string variable

If you just want the content as string, then the simple solution is to use the ReadFile function from the io/ioutil package. This function returns a slice of bytes which you can easily convert to a string.

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    b, err := ioutil.ReadFile("file.txt") // just pass the file name
    if err != nil {
        fmt.Print(err)
    }

    fmt.Println(b) // print the content as 'bytes'

    str := string(b) // convert content to a 'string'

    fmt.Println(str) // print the content as a 'string'
}

iPhone App Development on Ubuntu

Not officially, no. It's just Objective-C though and the compiler's open source - you could probably get the headers and compile it and somehow get the binary on the device. Another option is compiling on the device. All these options will require jailbreaking though.
A Mac Mini is just $599...

MySQL Multiple Left Joins

To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

List of foreign keys and the tables they reference in Oracle DB

Here is an all-purpose script we use that has been incredibly handy.

Save it off so you can execute it directly (@fkeys.sql). It will let you search by Owner and either the Parent or Child table and show foreign key relationships. The current script does explicitly spool to C:\SQLRPTS so you will need to create that folder of change that line to something you want to use.

REM ########################################################################
REM ##
REM ##   fkeys.sql
REM ##
REM ##   Displays the foreign key relationships
REM ##
REM #######################################################################

CLEAR BREAK
CLEAR COL
SET LINES 200
SET PAGES 54
SET NEWPAGE 0
SET WRAP OFF
SET VERIFY OFF
SET FEEDBACK OFF

break on table_name skip 2 on constraint_name on r_table_name skip 1

column CHILDCOL format a60 head 'CHILD COLUMN'
column PARENTCOL format a60 head 'PARENT COLUMN'
column constraint_name format a30 head 'FK CONSTRAINT NAME'
column delete_rule format a15
column bt noprint
column bo noprint

TTITLE LEFT _DATE CENTER 'FOREIGN KEY RELATIONSHIPS ON &new_prompt' RIGHT 'PAGE:'FORMAT 999 SQL.PNO SKIP 2

SPOOL C:\SQLRPTS\FKeys_&new_prompt
ACCEPT OWNER_NAME PROMPT 'Enter Table Owner (or blank for all): '
ACCEPT PARENT_TABLE_NAME PROMPT 'Enter Parent Table or leave blank for all: '
ACCEPT CHILD_TABLE_NAME PROMPT 'Enter Child Table or leave blank for all: '

  select b.owner || '.' || b.table_name || '.' || b.column_name CHILDCOL,
         b.position,
         c.owner || '.' || c.table_name || '.' || c.column_name PARENTCOL,
         a.constraint_name,
         a.delete_rule,
         b.table_name bt,
         b.owner bo
    from all_cons_columns b,
         all_cons_columns c,
         all_constraints a
   where b.constraint_name = a.constraint_name
     and a.owner           = b.owner
     and b.position        = c.position
     and c.constraint_name = a.r_constraint_name
     and c.owner           = a.r_owner
     and a.constraint_type = 'R'
     and c.owner      like case when upper('&OWNER_NAME') is null then '%'
                                else upper('&OWNER_NAME') end
     and c.table_name like case when upper('&PARENT_TABLE_NAME') is null then '%'
                                else upper('&PARENT_TABLE_NAME') end
     and b.table_name like case when upper('&CHILD_TABLE_NAME') is null then '%'
                                else upper('&CHILD_TABLE_NAME') end
order by 7,6,4,2
/
SPOOL OFF
TTITLE OFF
SET FEEDBACK ON
SET VERIFY ON
CLEAR BREAK
CLEAR COL
SET PAGES 24
SET LINES 100
SET NEWPAGE 1
UNDEF OWNER

Difference between <span> and <div> with text-align:center;?

Like other have said, span is an in-line element.

See here: http://www.w3.org/TR/CSS2/visuren.html

Additionally, you can make a span behave like a div by applying a

style="display: block; margin: 0px auto; text-align: center;"

Extract a substring using PowerShell

Building on Matt's answer, here's one that searches across newlines and is easy to modify for your own use

$String="----start----`nHello World`n----end----"
$SearchStart="----start----`n" #Will not be included in results
$SearchEnd="`n----end----" #Will not be included in results
$String -match "(?s)$SearchStart(?<content>.*)$SearchEnd"
$result=$matches['content']
$result

--

NOTE: if you want to run this against a file keep in mind Get-Content returns an array not a single string. You can work around this by doing the following:

$String=[string]::join("`n", (Get-Content $Filename))

Use Excel pivot table as data source for another Pivot Table

In a new sheet (where you want to create a new pivot table) press the key combination (Alt+D+P). In the list of data source options choose "Microsoft Excel list of database". Click Next and select the pivot table that you want to use as a source (select starting with the actual headers of the fields). I assume that this range is rather static and if you refresh the source pivot and it changes it's size you would have to re-size the range as well. Hope this helps.

What is the bower (and npm) version syntax?

In a nutshell, the syntax for Bower version numbers (and NPM's) is called SemVer, which is short for 'Semantic Versioning'. You can find documentation for the detailed syntax of SemVer as used in Bower and NPM on the API for the semver parser within Node/npm. You can learn more about the underlying spec (which does not mention ~ or other syntax details) at semver.org.

There's a super-handy visual semver calculator you can play with, making all of this much easier to grok and test.

SemVer isn't just a syntax! It has some pretty interesting things to say about the right ways to publish API's, which will help to understand what the syntax means. Crucially:

Once you identify your public API, you communicate changes to it with specific increments to your version number. Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.

So, your specific question about ~ relates to that Major.Minor.Patch schema. (As does the related caret operator ^.) You can use ~ to narrow the range of versions you're willing to accept to either:

  • subsequent patch-level changes to the same minor version ("bug fixes not affecting the API"), or:
  • subsequent minor-level changes to the same major version ("backwards compatible API additions/changes")

For example: to indicate you'll take any subsequent patch-level changes on the 1.2.x tree, starting with 1.2.0, but less than 1.3.0, you could use:

"angular": "~1.2"
  or:
"angular": "~1.2.0"

This also gets you the same results as using the .x syntax:

"angular": "1.2.x"

But, you can use the tilde/~ syntax to be even more specific: if you're only willing to accept patch-level changes starting with 1.2.4, but still less than 1.3.0, you'd use:

"angular": "~1.2.4"

Moving left, towards the major version, if you use...

"angular": "~1"

... it's the same as...

"angular": "1.x"
  or:
"angular": "^1.0.0"

...and matches any minor- or patch-level changes above 1.0.0, and less than 2.0:

Note that last variation above: it's called a 'caret range'. The caret looks an awful lot like a >, so you'd be excused for thinking it means "any version greater than 1.0.0". (I've certainly slipped on that.) Nope!

Caret ranges are basically used to say that you care only about the left-most significant digit - usually the major version - and that you'll permit any minor- or patch-level changes that don't affect that left-most digit. Yet, unlike a tilde range that specifies a major version, caret ranges let you specify a precise minor/patch starting point. So, while ^1.0.0 === ~1, a caret range such as ^1.2.3 lets you say you'll take any changes >=1.2.3 && <2.0.0. You couldn't do that with a tilde range.

That all seems confusing at first, when you look at it up-close. But zoom out for a sec, and think about it this way: the caret simply lets you say that you're most concerned about whatever significant digit is left-most. The tilde lets you say you're most concerned about whichever digit is right-most. The rest is detail.

It's the expressive power of the tilde and the caret that explains why people use them much more than the simpler .x syntax: they simply let you do more. That's why you'll see the tilde used often even where .x would serve. As an example, see npm itself: its own package.json file includes lots of dependencies in ~2.4.0 format, rather than the 2.4.x format it could use. By sticking to ~, the syntax is consistent all the way down a list of 70+ versioned dependencies, regardless of which beginning patch number is acceptable.

Anyway, there's still more to SemVer, but I won't try to detail it all here. Check it out on the node semver package's readme. And be sure to use the semantic versioning calculator while you're practicing and trying to get your head around how SemVer works.


RE: Non-Consecutive Version Numbers: OP's final question seems to be about specifying non-consecutive version numbers/ranges (if I have edited it fairly). Yes, you can do that, using the common double-pipe "or" operator: ||. Like so:

"angular": "1.2 <= 1.2.9 || >2.0.0"

Convert string to variable name in JavaScript

let me make it more clear

function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file

How to insert a picture into Excel at a specified cell position with VBA

I have been working on a system that ran on a PC and Mac and was battling to find code that worked for inserting pictures on both PC and Mac. This worked for me so hopefully someone else can make use of it!

Note: the strPictureFilePath and strPictureFileName variables need to be set to valid PC and Mac paths Eg

For PC: strPictureFilePath = "E:\Dropbox\" and strPictureFileName = "TestImage.jpg" and with Mac: strPictureFilePath = "Macintosh HD:Dropbox:" and strPictureFileName = "TestImage.jpg"

Code as Follows:

    On Error GoTo ErrorOccured

    shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Select

    ActiveSheet.Pictures.Insert(Trim(strPictureFilePath & strPictureFileName)).Select

    Selection.ShapeRange.Left = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Left
    Selection.ShapeRange.Top = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Top + 10
    Selection.ShapeRange.LockAspectRatio = msoTrue
    Selection.ShapeRange.Height = 130

How to use pip with Python 3.x alongside Python 2.x

First, install Python 3 pip using:

sudo apt-get install python3-pip

Then, to use Python 3 pip use:

pip3 install <module-name>

For Python 2 pip use:

pip install <module-name>

Stock ticker symbol lookup API

Currently, the NASDAQ web site publicly provides CSV files containing bulk listings -- it is broken up by first letter.

http://www.nasdaq.com/screening/companies-by-name.aspx?letter=A&render=download

A long bigger than Long.MAX_VALUE

If triangle.lborderA is indeed a long then the test in the original code is trivially true, and there is no way to test it. It is also useless.

However, if triangle.lborderA is a double, the comparison is useful and can be tested. isBiggerThanMaxLong(1e300) does return true.

  public static boolean isBiggerThanMaxLong(double in){
    return in > Long.MAX_VALUE;
  }

Remote Connections Mysql Ubuntu

Add few points on top of apesa's excellent post:

1) You can use command below to check the ip address mysql server is listening

netstat -nlt | grep 3306

sample result:

tcp 0  0  xxx.xxx.xxx.xxx:3306  0.0.0.0:*   LISTEN

2) Use FLUSH PRIVILEGES to force grant tables to be loaded if for some reason the changes not take effective immediately

GRANT ALL ON *.* TO 'user'@'localhost' IDENTIFIED BY 'passwd' WITH GRANT OPTION;
GRANT ALL ON *.* TO 'user'@'%' IDENTIFIED BY 'passwd' WITH GRANT OPTION;
FLUSH PRIVILEGES; 
EXIT;

user == the user u use to connect to mysql ex.root
passwd == the password u use to connect to mysql with

3) If netfilter firewall is enabled (sudo ufw enable) on mysql server machine, do the following to open port 3306 for remote access:

sudo ufw allow 3306

check status using

sudo ufw status

4) Once a remote connection is established, it can be verified in either client or server machine using commands

netstat -an | grep 3306
netstat -an | grep -i established

open existing java project in eclipse

  1. File -> Import -> Existing Project into Workspace
  2. Browse for that directory.

Alternative: Check out the code in SVN to some folder

  1. Create a new folder in windows
  2. In eclipse File -> switchWorkspace -> newFolderName
  3. close the welcome window in eclipse
  4. In eclipse File -> Import -> Existing project into workspce-> select root dir -> browse and show the svn checkout folder

How to sort an array in Bash

I am not convinced that you'll need an external sorting program in Bash.

Here is my implementation for the simple bubble-sort algorithm.

function bubble_sort()
{   #
    # Sorts all positional arguments and echoes them back.
    #
    # Bubble sorting lets the heaviest (longest) element sink to the bottom.
    #
    local array=($@) max=$(($# - 1))
    while ((max > 0))
    do
        local i=0
        while ((i < max))
        do
            if [ ${array[$i]} \> ${array[$((i + 1))]} ]
            then
                local t=${array[$i]}
                array[$i]=${array[$((i + 1))]}
                array[$((i + 1))]=$t
            fi
            ((i += 1))
        done
        ((max -= 1))
    done
    echo ${array[@]}
}

array=(a c b f 3 5)
echo " input: ${array[@]}"
echo "output: $(bubble_sort ${array[@]})"

This shall print:

 input: a c b f 3 5
output: 3 5 a b c f

How to get last month/year in java?

Your solution is here but instead of addition you need to use subtraction

c.add(Calendar.MONTH, -1);

Then you can call getter on the Calendar to acquire proper fields

int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year  = c.get(Calendar.YEAR);

What is the equivalent of "!=" in Excel VBA?

Try to use <> instead of !=.

jQuery: Clearing Form Inputs

Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.

I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.

I got this too work by adding a reset button to the form, which had an id of myform:

$("#myform > input[type=reset]").trigger('click');

This for me had the correct outcome on resetting the form, oh and dont forget the

event.preventDefault();

to stop the form submitting in browser, like I did :).

Regards

Jacko

How to split a delimited string in Ruby and convert it to an array?

>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]

Or for integers:

>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]

Or for later versions of ruby (>= 1.9 - as pointed out by Alex):

>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]

How to set 24-hours format for date on java?

Try below code

    String dateStr = "Jul 27, 2011 8:35:29 PM";
    DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
    DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
       date = readFormat.parse( dateStr );
    } catch ( ParseException e ) {
        e.printStackTrace();
    }

    String formattedDate = "";
    if( date != null ) {
    formattedDate = writeFormat.format( date );
    }

    System.out.println(formattedDate);

Good Luck!!!

Check for various formats.

Regular expression for checking if capital letters are found consecutively in a string?

^([A-Z][a-z]+)+$

This looks for sequences of an uppercase letter followed by one or more lowercase letters. Consecutive uppercase letters will not match, as only one is allowed at a time, and it must be followed by a lowercase one.

Wait for a process to finish

FreeBSD and Solaris have this handy pwait(1) utility, which does exactly, what you want.

I believe, other modern OSes also have the necessary system calls too (MacOS, for example, implements BSD's kqueue), but not all make it available from command-line.

iPhone/iOS JSON parsing tutorial

SBJSON *parser = [[SBJSON alloc] init];

NSString *url_str=[NSString stringWithFormat:@"Example APi Here"];

url_str = [url_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url_str]];

NSData *response = [NSURLConnection sendSynchronousRequest:request  returningResponse:nil error:nil];

NSString *json_string = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding]

NSDictionary *statuses = [parser2 objectWithString:json_string error:nil];

 NSArray *news_array=[[statuses3 objectForKey:@"sold_list"] valueForKey:@"list"];

    for(NSDictionary *news in news_array)
{

    @try {
        [title_arr addObject:[news valueForKey:@"gtitle"]];    //values Add to title array

    }
    @catch (NSException *exception) {

        [title_arr addObject:[NSString stringWithFormat:@""]];
    }

Pandas create empty DataFrame with only column names

Are you looking for something like this?

    COLUMN_NAMES=['A','B','C','D','E','F','G']
    df = pd.DataFrame(columns=COLUMN_NAMES)
    df.columns

   Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')

Floating Div Over An Image

Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:

_x000D_
_x000D_
    .container {_x000D_
       border: 1px solid #DDDDDD;_x000D_
       width: 200px;_x000D_
       height: 200px;_x000D_
       position: relative;_x000D_
    }_x000D_
    .tag {_x000D_
       float: left;_x000D_
       position: absolute;_x000D_
       left: 0px;_x000D_
       top: 0px;_x000D_
       z-index: 1000;_x000D_
       background-color: #92AD40;_x000D_
       padding: 5px;_x000D_
       color: #FFFFFF;_x000D_
       font-weight: bold;_x000D_
    }
_x000D_
<div class="container">_x000D_
       <div class="tag">Featured</div>_x000D_
       <img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The key is the container has to be positioned relative and the tag positioned absolute.