Programs & Examples On #Gba

Flutter: RenderBox was not laid out

Wrap your ListView in an Expanded widget

 Expanded(child:MyListView())

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Others have pointed to the root issue, but in my case I was using dbeaver and initially when setting up the mysql connection with dbeaver was selecting the wrong mysql driver (credit here for answer: https://github.com/dbeaver/dbeaver/issues/4691#issuecomment-442173584 )

Selecting the MySQL choice in the below figure will give the error mentioned as the driver is mysql 4+ which can be seen in the database information tip.


For this error selecting the top mysql 4+ choice in this figure will give the error mentioned in this quesiton


Rather than selecting the MySQL driver instead select the MySQL 8+ driver, shown in the figure below.


enter image description here

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

I was trying to create a web application with spring boot and I got the same error. After inspecting I found that I was missing a dependency. So, be sure to add following dependency to your pom.xml file.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency> 

Change arrow colors in Bootstraps carousel

You should use also: <span><i class="fa fa-angle-left" aria-hidden="true"></i></span> using fontawesome. You have to overwrite the original code. Do the following and you'll be free to customize on CSS:

<a class="carousel-control-prev" href="#carouselExampleIndicatorsTestim" role="button" data-slide="prev">
    <span><i class="fa fa-angle-left" aria-hidden="true"></i></span>
    <span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicatorsTestim" role="button" data-slide="next">
    <span><i class="fa fa-angle-right" aria-hidden="true"></i></span>
    <span class="sr-only">Next</span>
 </a>

The original code

<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
</a>

<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
</a>

Hibernate Error executing DDL via JDBC Statement

I have got this error when trying to create JPA entity with the name "User" (in Postgres) that is reserved. So the way it is resolved is to change the table name by @Table annotation:

@Entity
@Table(name="users")
public class User {..}

Or change the table name manually.

Set height of chart in Chart.js

Seems like var ctx = $('#myChart'); is returning a list of elements. You would need to reference the first by using ctx[0]. Also height is a property, not a function.

I did it this way in my code:

var ctx = document.getElementById("myChart");
ctx.height = 500;

How to set shadows in React Native for android?

I had the same problem shadow/elevation not showing on Android with elevation:2. Then i noticed that the view element is fool width, so I added margin:2 to the view element and elevation properly appeared.

Style:

    margin: 2,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1
    },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,
    elevation: 2

Android: enter image description here

iOS: enter image description here

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

Css transition from display none to display block, navigation with subnav

As you know the display property cannot be animated BUT just by having it in your CSS it overrides the visibility and opacity transitions.

The solution...just removed the display properties.

_x000D_
_x000D_
nav.main ul ul {_x000D_
  position: absolute;_x000D_
  list-style: none;_x000D_
  opacity: 0;_x000D_
  visibility: hidden;_x000D_
  padding: 10px;_x000D_
  background-color: rgba(92, 91, 87, 0.9);_x000D_
  -webkit-transition: opacity 600ms, visibility 600ms;_x000D_
  transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
nav.main ul li:hover ul {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<nav class="main">_x000D_
  <ul>_x000D_
    <li>_x000D_
      <a href="">Lorem</a>_x000D_
      <ul>_x000D_
        <li><a href="">Ipsum</a>_x000D_
        </li>_x000D_
        <li><a href="">Dolor</a>_x000D_
        </li>_x000D_
        <li><a href="">Sit</a>_x000D_
        </li>_x000D_
        <li><a href="">Amet</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

how to set start value as "0" in chartjs?

If you need use it as a default configuration, just place min: 0 inside the node defaults.scale.ticks, as follows:

defaults: {
  global: {...},
  scale: {
    ...
    ticks: { min: 0 },
  }
},

Reference: https://www.chartjs.org/docs/latest/axes/

Make div fill remaining space along the main axis in flexbox

Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex on the row container and at least making sure your middle container on the row has a flex-grow value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow properties applied, middle container only needs 1 for flex-grow).

Here's a pic of what I was trying to do and sample code for how I solved it.

enter image description here

_x000D_
_x000D_
.row {
  background: lightgray;
  height: 30px;
  width: 100%;
  display: flex;
  align-items:flex-end;
  margin-top:5px;
}
.left {
  background:lightblue;
}
.separator{
  flex-grow:1;
  border-bottom:dotted 2px black;
}
.right {
  background:coral;
}
_x000D_
<div class="row">
  <div class="left">Left</div>
  <div class="separator"></div>
  <div class="right">Right With Text</div>
</div>
<div class="row">
  <div class="left">Left With More Text</div>
  <div class="separator"></div>
  <div class="right">Right</div>
</div>
<div class="row">
  <div class="left">Left With Text</div>
  <div class="separator"></div>
  <div class="right">Right With More Text</div>
</div>
_x000D_
_x000D_
_x000D_

This page didn't load Google Maps correctly. See the JavaScript console for technical details

You could also get the error if your Billing is not set up correctly.

Google hands out credit worth $300 or 12 months of free usage whichever runs out faster. After that you would need to enable billing.

enter image description here

How to add a color overlay to a background image?

background-image takes multiple values.

so a combination of just 1 color linear-gradient and css blend modes will do the trick.

.testclass {
    background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
    background-blend-mode: overlay;
}

note that there is no support on IE/Edge for CSS blend-modes at all.

Bootstrap 4 - Responsive cards in card-columns

I have created a Cards Layout - 3 cards in a row using Bootstrap 4 / CSS3 (of course its responsive). The following example uses basic Bootstrap 4 classes such as container, row, col-x, list-group and list-group-item. Thought to share here if someone is interested in this sort of a layout.

enter image description here

HTML

<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">        
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
  </div>
</div>

CSS / SCSS

$primary-color: #ccc;
$col-bg-color: #eee;
$col-footer-bg-color: #eee;
$col-header-bg-color: #007bff;
$col-content-bg-color: #fff;

body {
  background-color: $primary-color;
}  

.custom-column {  
  background-color: $col-bg-color;
  border: 5px solid $col-bg-color;    
  padding: 10px;
  box-sizing: border-box;  
}

.custom-column-header {
  font-size: 24px;
  background-color: #007bff;  
  color: white;
  padding: 15px;  
  text-align: center;
}

.custom-column-content {
  background-color: $col-content-bg-color;
  border: 2px solid white;  
  padding: 20px;  
}

.custom-column-footer {
  background-color: $col-footer-bg-color;   
  padding-top: 20px;
  text-align: center;
}

Link :- https://codepen.io/anjanasilva/pen/JmdOpb

In Chart.js set chart title, name of x axis and y axis?

          <Scatter
            data={data}
            // style={{ width: "50%", height: "50%" }}
            options={{
              scales: {
                yAxes: [
                  {
                    scaleLabel: {
                      display: true,
                      labelString: "Probability",
                    },
                  },
                ],
                xAxes: [
                  {
                    scaleLabel: {
                      display: true,
                      labelString: "Hours",
                    },
                  },
                ],
              },
            }}
          />

Make button width fit to the text

If you are developing to a modern browser. https://caniuse.com/#search=fit%20content

You can use:

width: fit-content;

How can I make a CSS glass/blur effect work for an overlay?

If you're looking for a reliable cross-browser approach today, you won't find a great one. The best option you have is to create two images (this could be automated in some environments), and arrange them such that one overlays the other. I've created a simple example below:

<figure class="js">
    <img src="http://i.imgur.com/3oenmve.png" />
    <img src="http://i.imgur.com/3oenmve.png?1" class="blur" />
</figure>
figure.js {
    position: relative;
    width: 250px; height: 250px;
}

figure.js .blur {
    top: 0; left: 0;
    position: absolute;
    clip: rect( 0, 250px, 125px, 0 );
}

Though effective, even this approach isn't necessarily ideal. That being said, it does yield the desired result.

enter image description here

Nested Recycler view height doesn't wrap its content

Android Support Library now handles WRAP_CONTENT property as well. Just import this in your gradle.

compile 'com.android.support:recyclerview-v7:23.2.0'

And done!

Different color for each bar in a bar chart; ChartJS

This works for me in the current version 2.7.1:

function colorizePercentageChart(myObjBar) {

var bars = myObjBar.data.datasets[0].data;
console.log(myObjBar.data.datasets[0]);
for (i = 0; i < bars.length; i++) {

    var color = "green";

    if(parseFloat(bars[i])  < 95){
        color = "yellow";
    }
    if(parseFloat(bars[i])  < 50){
         color = "red";
    }

    console.log(color);
    myObjBar.data.datasets[0].backgroundColor[i] = color;

}
myObjBar.update(); 

}

Getting individual colors from a color map in matplotlib

To build on the solutions from Ffisegydd and amaliammr, here's an example where we make CSV representation for a custom colormap:

#! /usr/bin/env python3
import matplotlib
import numpy as np 

vmin = 0.1
vmax = 1000

norm = matplotlib.colors.Normalize(np.log10(vmin), np.log10(vmax))
lognum = norm(np.log10([.5, 2., 10, 40, 150,1000]))

cdict = {
    'red':
    (
        (0., 0, 0),
        (lognum[0], 0, 0),
        (lognum[1], 0, 0),
        (lognum[2], 1, 1),
        (lognum[3], 0.8, 0.8),
        (lognum[4], .7, .7),
    (lognum[5], .7, .7)
    ),
    'green':
    (
        (0., .6, .6),
        (lognum[0], 0.8, 0.8),
        (lognum[1], 1, 1),
        (lognum[2], 1, 1),
        (lognum[3], 0, 0),
        (lognum[4], 0, 0),
    (lognum[5], 0, 0)
    ),
    'blue':
    (
        (0., 0, 0),
        (lognum[0], 0, 0),
        (lognum[1], 0, 0),
        (lognum[2], 0, 0),
        (lognum[3], 0, 0),
        (lognum[4], 0, 0),
    (lognum[5], 1, 1)
    )
}


mycmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)   
norm = matplotlib.colors.LogNorm(vmin, vmax)
colors = {}
count = 0
step_size = 0.001
for value in np.arange(vmin, vmax+step_size, step_size):
    count += 1
    print("%d/%d %f%%" % (count, vmax*(1./step_size), 100.*count/(vmax*(1./step_size))))
    rgba = mycmap(norm(value), bytes=True)
    color = (rgba[0], rgba[1], rgba[2])
    if color not in colors.values():
        colors[value] = color

print ("value, red, green, blue")
for value in sorted(colors.keys()):
    rgb = colors[value]
    print("%s, %s, %s, %s" % (value, rgb[0], rgb[1], rgb[2]))

JavaScript Loading Screen while page loads

If in your site you have ajax calls loading some data, and this is the reason the page is loading slow, the best solution I found is with

$(document).ajaxStop(function(){
    alert("All AJAX requests completed");
});

https://jsfiddle.net/44t5a8zm/ - here you can add some ajax calls and test it.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

Cause you need to add jQuery library to your file:

jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.

<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>

Blur the edges of an image or background image with CSS

If you set the image in div, you also must set both height and width. This may cause the image to lose its proportion. In addition, you must set the image URL in CSS instead of HTML.

Instead, you can set the image using the IMG tag. In the container class you can only set the width in percent or pixel and the height will automatically maintain proportion.

This is also more effective for accessibility of search engines and reading engines to define an image using an IMG tag.

_x000D_
_x000D_
.container {_x000D_
 margin: auto;_x000D_
 width: 200px;_x000D_
 position: relative;_x000D_
}_x000D_
_x000D_
img {_x000D_
 width: 100%;_x000D_
}_x000D_
_x000D_
.block {_x000D_
 width: 100%;_x000D_
 position: absolute;_x000D_
 bottom: 0px;_x000D_
 top: 0px;_x000D_
 box-shadow: inset 0px 0px 10px 20px white;_x000D_
}
_x000D_
<div class="container">_x000D_
 <img src="http://lorempixel.com/200/200/city">_x000D_
 <div class="block"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

justify-content property isn't working

justify-content only has an effect if there's space left over after your flex items have flexed to absorb the free space. In most/many cases, there won't be any free space left, and indeed justify-content will do nothing.

Some examples where it would have an effect:

  • if your flex items are all inflexible (flex: none or flex: 0 0 auto), and smaller than the container.

  • if your flex items are flexible, BUT can't grow to absorb all the free space, due to a max-width on each of the flexible items.

In both of those cases, justify-content would be in charge of distributing the excess space.

In your example, though, you have flex items that have flex: 1 or flex: 6 with no max-width limitation. Your flexible items will grow to absorb all of the free space, and there will be no space left for justify-content to do anything with.

Disable Logback in SpringBoot

If this error occurred in SpringBoot when you are trying to use log4j2 then do these steps:

  • Remove the jar from while packeging by adding this "excludeGroupIds log4j-slf4j-impl /excludeGroupIds"
  • Find out the which library is depends on "logback-classic" by using command "mvn dependecy:tree"
  • Wherever you find it exclude it from the dependency.

This error occurred because logback override the log4j2 changes. SO if you want to use log4j2 then you have to remove logback library and dependencies.

Hope this will help someone.

Is there such a thing as min-font-size and max-font-size?

Please note that setting font-sizing with px is not recommended due to accessibility concerns:

"defining font sizes in px is not accessible, because the user cannot change the font size in some browsers. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer." (see https://developer.mozilla.org/en-US/docs/Web/CSS/font-size)

A more accessible approach is to set font-size: 100% in the html, which respects user default size settings, and THEN using either percentages or relative units when resizing (em or rem), for example with a @media query.

(see https://betterwebtype.com/articles/2019/06/16/5-keys-to-accessible-web-typography/)

Remove x-axis label/text in chart.js

_x000D_
_x000D_
var lineChartData = {_x000D_
    labels: ["", "", "", "", "", "", ""] // To hide horizontal labels_x000D_
 ,datasets : [_x000D_
  {_x000D_
   label: "My First dataset",_x000D_
   fillColor : "rgba(220,220,220,0.2)",_x000D_
   strokeColor : "rgba(220,220,220,1)",_x000D_
   pointColor : "rgba(220,220,220,1)",_x000D_
   pointStrokeColor : "#fff",_x000D_
   pointHighlightFill : "#fff",_x000D_
   pointHighlightStroke : "rgba(220,220,220,1)",_x000D_
   _x000D_
   data: [28, 48, 40, 19, 86, 27, 90]_x000D_
  }_x000D_
 ]_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
window.onload = function(){_x000D_
 var options = {_x000D_
  scaleShowLabels : false // to hide vertical lables_x000D_
 };_x000D_
 var ctx = document.getElementById("canvas1").getContext("2d");_x000D_
 window.myLine = new Chart(ctx).Line(lineChartData, options);_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Transparent scrollbar with css

It might be too late, but still. For those who have not been helped by any method I suggest making custom scrollbar bar in pure javascript.

For a start, disable the standard scrollbar in style.css

::-webkit-scrollbar{
    width: 0;
}

Now let's create the scrollbar container and the scrollbar itself

<!DOCTYPE HTML>
<html lang="ru">
<head>
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <script src="main.js"></script>
 ...meta
</head>

<body>

<div class="custom_scroll">
    <div class="scroll_block"></div>
</div>

...content

<script>customScroll();</script>
</body>
</html>

at the same time, we will connect the customScroll() function, and create it in the file main.js

 function customScroll() {
    let scrollBlock = documentSite.querySelector(".scroll_block");
    let body = documentSite.querySelector("body");
    let screenSize = screenHeight - scrollBlock.offsetHeight;
    documentSite.addEventListener("scroll", () => {
        scrollBlock.style.top = (window.pageYOffset / body.offsetHeight * (screenSize + (screenSize * (body.offsetHeight - (body.offsetHeight - screenHeight)) / (body.offsetHeight - screenHeight)) )) + "px";
    });
    setScroll(scrollBlock, body);
}

function setScroll(scrollBlock, body) {
    let newPos = 0, lastPos = 0;
        scrollBlock.onmousedown = onScrollSet;
        scrollBlock.onselectstart = () => {return false;};

    function onScrollSet(e) {
        e = e || window.event;
        lastPos = e.clientY;
        document.onmouseup = stopScroll;
        document.onmousemove = moveScroll;
        return false;
    }

    function moveScroll(e) {
        e = e || window.event;
        newPos = lastPos - e.clientY;
        lastPos = e.clientY;
        if(scrollBlock.offsetTop - newPos >= 0 && scrollBlock.offsetTop - newPos <= Math.ceil(screenHeight - scrollBlock.offsetHeight)) {
            window.scrollBy(0, -newPos / screenHeight *  body.offsetHeight);
        }
    }

    function stopScroll() {
        document.onmouseup = null;
        document.onmousemove = null;
    }
}

adding styles for the scrollbar

.custom_scroll{
    width: 0.5vw;
    height: 100%;
    position: fixed;
    right: 0;
    z-index: 100;
}

.scroll_block{
    width: 0.5vw;
    height: 20vh;
    background-color: #ffffff;
    z-index: 101;
    position: absolute;
    border-radius: 4px;
}

Done!

scrollbar

What is offsetHeight, clientHeight, scrollHeight?

* offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

* clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

* scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

Same is the case for all of these with width instead of height.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

I've had similar problems when the main method is on a different class than that passed to SpringApplcation.run()

So the solution would be to use the line you've commented out:

public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Image overlay on responsive sized images bootstrap

I had a bit of trouble getting this to work as well. Using brouxhaha's answer got me 90% of the way to what I was looking for. But the padding adjust wouldn't allow me to put the text anywhere I wanted. Using top and left seemed to work better for my purposes.

.project-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    color: #fff;
    top: 80%;
    left: 20%;
}

http://jsfiddle.net/1rz0b7d8/1/

Responsive timeline UI with Bootstrap3

_x000D_
_x000D_
.timeline {_x000D_
  list-style: none;_x000D_
  padding: 20px 0 20px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.timeline:before {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  position: absolute;_x000D_
  content: " ";_x000D_
  width: 3px;_x000D_
  background-color: #eeeeee;_x000D_
  left: 50%;_x000D_
  margin-left: -1.5px;_x000D_
}_x000D_
_x000D_
.timeline > li {_x000D_
  margin-bottom: 20px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
  content: " ";_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
  content: " ";_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel {_x000D_
  width: 46%;_x000D_
  float: left;_x000D_
  border: 1px solid #d4d4d4;_x000D_
  border-radius: 2px;_x000D_
  padding: 20px;_x000D_
  position: relative;_x000D_
  -webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:before {_x000D_
  position: absolute;_x000D_
  top: 26px;_x000D_
  right: -15px;_x000D_
  display: inline-block;_x000D_
  border-top: 15px solid transparent;_x000D_
  border-left: 15px solid #ccc;_x000D_
  border-right: 0 solid #ccc;_x000D_
  border-bottom: 15px solid transparent;_x000D_
  content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:after {_x000D_
  position: absolute;_x000D_
  top: 27px;_x000D_
  right: -14px;_x000D_
  display: inline-block;_x000D_
  border-top: 14px solid transparent;_x000D_
  border-left: 14px solid #fff;_x000D_
  border-right: 0 solid #fff;_x000D_
  border-bottom: 14px solid transparent;_x000D_
  content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-badge {_x000D_
  color: #fff;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  line-height: 50px;_x000D_
  font-size: 1.4em;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  top: 16px;_x000D_
  left: 50%;_x000D_
  margin-left: -25px;_x000D_
  background-color: #999999;_x000D_
  z-index: 100;_x000D_
  border-top-right-radius: 50%;_x000D_
  border-top-left-radius: 50%;_x000D_
  border-bottom-right-radius: 50%;_x000D_
  border-bottom-left-radius: 50%;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel {_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:before {_x000D_
  border-left-width: 0;_x000D_
  border-right-width: 15px;_x000D_
  left: -15px;_x000D_
  right: auto;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:after {_x000D_
  border-left-width: 0;_x000D_
  border-right-width: 14px;_x000D_
  left: -14px;_x000D_
  right: auto;_x000D_
}_x000D_
_x000D_
.timeline-badge.primary {_x000D_
  background-color: #2e6da4 !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.success {_x000D_
  background-color: #3f903f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.warning {_x000D_
  background-color: #f0ad4e !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.danger {_x000D_
  background-color: #d9534f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.info {_x000D_
  background-color: #5bc0de !important;_x000D_
}_x000D_
_x000D_
.timeline-title {_x000D_
  margin-top: 0;_x000D_
  color: inherit;_x000D_
}_x000D_
_x000D_
.timeline-body > p,_x000D_
.timeline-body > ul {_x000D_
  margin-bottom: 0;_x000D_
}_x000D_
_x000D_
.timeline-body > p + p {_x000D_
  margin-top: 5px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1 id="timeline">Timeline</h1>_x000D_
  </div>_x000D_
  <ul class="timeline">_x000D_
    <li>_x000D_
      <div class="timeline-badge"><i class="glyphicon glyphicon-check"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
         <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
          <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-badge warning"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
          <p>Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Interagi no mé, cursus quis, vehicula ac nisi. Aenean vel dui dui. Nullam leo erat, aliquet quis tempus a, posuere ut mi. Ut scelerisque neque et turpis posuere_x000D_
            pulvinar pellentesque nibh ullamcorper. Pharetra in mattis molestie, volutpat elementum justo. Aenean ut ante turpis. Pellentesque laoreet mé vel lectus scelerisque interdum cursus velit auctor. Lorem ipsum dolor sit amet, consectetur adipiscing_x000D_
            elit. Etiam ac mauris lectus, non scelerisque augue. Aenean justo massa.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-badge danger"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-badge info"><i class="glyphicon glyphicon-floppy-disk"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
          <hr>_x000D_
          <div class="btn-group">_x000D_
            <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">_x000D_
              <i class="glyphicon glyphicon-cog"></i> <span class="caret"></span>_x000D_
            </button>_x000D_
            <ul class="dropdown-menu" role="menu">_x000D_
              <li><a href="#">Action</a></li>_x000D_
              <li><a href="#">Another action</a></li>_x000D_
              <li><a href="#">Something else here</a></li>_x000D_
              <li class="divider"></li>_x000D_
              <li><a href="#">Separated link</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-badge success"><i class="glyphicon glyphicon-thumbs-up"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://codepen.io/bsngr/pen/Ifvbi/

Best way to style a TextBox in CSS

You could target all text boxes with input[type=text] and then explicitly define the class for the textboxes who need it.

You can code like below :

_x000D_
_x000D_
input[type=text] {_x000D_
  padding: 0;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  outline: none;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-color: rgba(0, 0, 0, .15);_x000D_
  background-color: white;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
  width: 526px;_x000D_
  margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
_x000D_
_x000D_

CSS - display: none; not working

This is because the inline style display:block is overwriting your CSS. You'll need to either remove this inline style or use:

#tfl {
  display: none !important;
}

This overrides inline styles. Note that using !important is generally not recommended unless it's a last resort.

Android Studio: Unable to start the daemon process

I think it's wrong JAVA_HOME make this error. when i get error i try all the way,but it don't work for me. i try delete c:.gradle and Compiler Android studio but it's still don't work. i Re-install the system it work, when update system i get the error again. I try Compiler JAVA_HOME user environment and system environment: enter image description here

when i use cmd input java:

enter image description here

when cmd.exe show the masage it mean it's work, try to runing Android Studio, it will fix the error. enter image description here

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

Controlling fps with requestAnimationFrame?

These are all good ideas in theory, until you go deep. The problem is you can't throttle an RAF without de-synchronizing it, defeating it's very purpose for existing. So you let it run at full-speed, and update your data in a separate loop, or even a separate thread!

Yes, I said it. You can do multi-threaded JavaScript in the browser!

There are two methods I know that work extremely well without jank, using far less juice and creating less heat. Accurate human-scale timing and machine efficiency are the net result.

Apologies if this is a little wordy, but here goes...


Method 1: Update data via setInterval, and graphics via RAF.

Use a separate setInterval for updating translation and rotation values, physics, collisions, etc. Keep those values in an object for each animated element. Assign the transform string to a variable in the object each setInterval 'frame'. Keep these objects in an array. Set your interval to your desired fps in ms: ms=(1000/fps). This keeps a steady clock that allows the same fps on any device, regardless of RAF speed. Do not assign the transforms to the elements here!

In a requestAnimationFrame loop, iterate through your array with an old-school for loop-- do not use the newer forms here, they are slow!

for(var i=0; i<sprite.length-1; i++){  rafUpdate(sprite[i]);  }

In your rafUpdate function, get the transform string from your js object in the array, and its elements id. You should already have your 'sprite' elements attached to a variable or easily accessible through other means so you don't lose time 'get'-ing them in the RAF. Keeping them in an object named after their html id's works pretty good. Set that part up before it even goes into your SI or RAF.

Use the RAF to update your transforms only, use only 3D transforms (even for 2d), and set css "will-change: transform;" on elements that will change. This keeps your transforms synced to the native refresh rate as much as possible, kicks in the GPU, and tells the browser where to concentrate most.

So you should have something like this pseudocode...

// refs to elements to be transformed, kept in an array
var element = [
   mario: document.getElementById('mario'),
   luigi: document.getElementById('luigi')
   //...etc.
]

var sprite = [  // read/write this with SI.  read-only from RAF
   mario: { id: mario  ....physics data, id, and updated transform string (from SI) here  },
   luigi: {  id: luigi  .....same  }
   //...and so forth
] // also kept in an array (for efficient iteration)

//update one sprite js object
//data manipulation, CPU tasks for each sprite object
//(physics, collisions, and transform-string updates here.)
//pass the object (by reference).
var SIupdate = function(object){
  // get pos/rot and update with movement
  object.pos.x += object.mov.pos.x;  // example, motion along x axis
  // and so on for y and z movement
  // and xyz rotational motion, scripted scaling etc

  // build transform string ie
  object.transform =
   'translate3d('+
     object.pos.x+','+
     object.pos.y+','+
     object.pos.z+
   ') '+

   // assign rotations, order depends on purpose and set-up. 
   'rotationZ('+object.rot.z+') '+
   'rotationY('+object.rot.y+') '+
   'rotationX('+object.rot.x+') '+

   'scale3d('.... if desired
  ;  //...etc.  include 
}


var fps = 30; //desired controlled frame-rate


// CPU TASKS - SI psuedo-frame data manipulation
setInterval(function(){
  // update each objects data
  for(var i=0; i<sprite.length-1; i++){  SIupdate(sprite[i]);  }
},1000/fps); //  note ms = 1000/fps


// GPU TASKS - RAF callback, real frame graphics updates only
var rAf = function(){
  // update each objects graphics
  for(var i=0; i<sprite.length-1; i++){  rAF.update(sprite[i])  }
  window.requestAnimationFrame(rAF); // loop
}

// assign new transform to sprite's element, only if it's transform has changed.
rAF.update = function(object){     
  if(object.old_transform !== object.transform){
    element[object.id].style.transform = transform;
    object.old_transform = object.transform;
  }
} 

window.requestAnimationFrame(rAF); // begin RAF

This keeps your updates to the data objects and transform strings synced to desired 'frame' rate in the SI, and the actual transform assignments in the RAF synced to GPU refresh rate. So the actual graphics updates are only in the RAF, but the changes to the data, and building the transform string are in the SI, thus no jankies but 'time' flows at desired frame-rate.


Flow:

[setup js sprite objects and html element object references]

[setup RAF and SI single-object update functions]

[start SI at percieved/ideal frame-rate]
  [iterate through js objects, update data transform string for each]
  [loop back to SI]

[start RAF loop]
  [iterate through js objects, read object's transform string and assign it to it's html element]
  [loop back to RAF]

Method 2. Put the SI in a web-worker. This one is FAAAST and smooth!

Same as method 1, but put the SI in web-worker. It'll run on a totally separate thread then, leaving the page to deal only with the RAF and UI. Pass the sprite array back and forth as a 'transferable object'. This is buko fast. It does not take time to clone or serialize, but it's not like passing by reference in that the reference from the other side is destroyed, so you will need to have both sides pass to the other side, and only update them when present, sort of like passing a note back and forth with your girlfriend in high-school.

Only one can read and write at a time. This is fine so long as they check if it's not undefined to avoid an error. The RAF is FAST and will kick it back immediately, then go through a bunch of GPU frames just checking if it's been sent back yet. The SI in the web-worker will have the sprite array most of the time, and will update positional, movement and physics data, as well as creating the new transform string, then pass it back to the RAF in the page.

This is the fastest way I know to animate elements via script. The two functions will be running as two separate programs, on two separate threads, taking advantage of multi-core CPU's in a way that a single js script does not. Multi-threaded javascript animation.

And it will do so smoothly without jank, but at the actual specified frame-rate, with very little divergence.


Result:

Either of these two methods will ensure your script will run at the same speed on any PC, phone, tablet, etc (within the capabilities of the device and the browser, of course).

CSS3 Transform Skew One Side

I know this is old, but I would like to suggest using a linear-gradient to achieve the same effect instead of margin offset. This is will maintain any content at its original place.

http://jsfiddle.net/zwXaf/2/

HTML

<ul>
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
</ul>

CSS

/* reset */
ul, li, a {
    margin: 0; padding: 0;
}
/* nav stuff */
ul, li, a {
    display: inline-block;
    text-align: center;
}
/* appearance styling */
ul {
    /* hacks to make one side slant only */
    overflow: hidden;
    background: linear-gradient(to right, red, white, white, red);
}
li {
    background-color: red;
     transform:skewX(-20deg);
    -ms-transform:skewX(-20deg);
    -webkit-transform:skewX(-20deg);
}
li a {
    padding: 3px 6px 3px 6px;
    color: #ffffff;
    text-decoration: none;
    width: 80px;
     transform:skewX(20deg);
    -ms-transform:skewX(20deg);
    -webkit-transform:skewX(20deg);
}

Show popup after page load

try something like this

<script type="text/javascript">
function PopUp(hideOrshow) {
    if (hideOrshow == 'hide') document.getElementById('ac-wrapper').style.display = "none";
    else document.getElementById('ac-wrapper').removeAttribute('style');
}
window.onload = function () {
    setTimeout(function () {
        PopUp('show');
    }, 5000);
}
</script>

and your html

<div id="ac-wrapper" style='display:none'>
    <div id="popup">
        <center>
             <h2>Popup Content Here</h2>    
            <input type="submit" name="submit" value="Submit" onClick="PopUp('hide')" />
        </center>
    </div>
</div>

Demo JsFiddle

Console.log not working at all

You may have used the filter function in the console which will hide anything that doesn't match your query. Remove the query and your messages will display.

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

How do I add a margin between bootstrap columns without wrapping

If you do not need to add a border on columns, you can also simply add a transparent border on them:

[class*="col-"] {
    background-clip: padding-box;
    border: 10px solid transparent;
}

Flex-box: Align last row to grid

If you want a grid with some space between the items and the items starting without any initial space then this simple solution works:

.grid {
    display: flex;
    flex-flow: row wrap;
    margin: 0 -5px; // remove the inital 5px space
    width: auto;
}
.grid__item {
    width: 25%;
    padding: 0 5px; // should be same as the negative margin above.
}

If you want the initial 5px space then just remove the negative margin :) Simple.

https://jsfiddle.net/b97ewrno/2/

The accepted answer, whilst good, it causes there to be no space between the elements on the second row..

Decreasing height of bootstrap 3.0 navbar

After spending few hours, adding the following css class fixed my issue.

Work with Bootstrap 3.0.*

.tnav .navbar .container { height: 28px; }

Work with Bootstrap 3.3.4

.navbar-nav > li > a, .navbar-brand {
    padding-top:4px !important; 
    padding-bottom:0 !important;
    height: 28px;
}
.navbar {min-height:28px !important;}

Update Complete code to customize and decrease height of navbar with screenshot.

enter image description here

CSS:

/* navbar */
.navbar-primary .navbar { background:#9f58b5; border-bottom:none; }
.navbar-primary .navbar .nav > li > a {color: #501762;}
.navbar-primary .navbar .nav > li > a:hover {color: #fff; background-color: #8e49a3;}
.navbar-primary .navbar .nav .active > a,.navbar .nav .active > a:hover {color: #fff; background-color: #501762;}
.navbar-primary .navbar .nav li > a .caret, .tnav .navbar .nav li > a:hover .caret {border-top-color: #fff;border-bottom-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover {}
.navbar-primary .navbar .nav > li.dropdown.open > a {color: #fff;background-color: #9f58b5;border-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover .caret, .tnav .navbar .nav > li.dropdown.open > a .caret {border-top-color: #fff;}
.navbar-primary .navbar .navbar-brand {color:#fff;}
.navbar-primary .navbar .nav.pull-right {margin-left: 10px; margin-right: 0;}
.navbar-xs .navbar-primary .navbar { min-height:28px; height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 28px; }
.navbar-sm .navbar-primary .navbar { min-height:40px; height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 40px; }

Usage Code:

<div class="navbar-xs">
   <div class="navbar-primary">
       <nav class="navbar navbar-static-top" role="navigation">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-8">
                 <span class="sr-only">Toggle navigation</span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Brand</a>
          </div>
          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-8">
              <ul class="nav navbar-nav">
                  <li class="active"><a href="#">Home</a></li>
                  <li><a href="#">Link</a></li>
                   <li><a href="#">Link</a></li>
              </ul>
          </div><!-- /.navbar-collapse -->
      </nav>
  </div>
</div>

Allow a div to cover the whole page instead of the area within the container

please try with setting margin and padding to 0 on body.

<body style="margin: 0 0 0 0; padding: 0 0 0 0;">

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

Some good answers, but the problem with all solutions I have tried is that the images doesn´t fade into each other. Instead the first one fades completely out and than the next one fades in.

After a few hours of testing a found this sollution. Thx to http://www.1squarepear.com/adding-a-responsive-bootstrap-image-carousel-that-fades-instead-of-slides/

  1. In the HTML code change from .slide to .fade on the .carousel element
  2. Add this in the css:

    .carousel.fade { opacity: 1; } .carousel.fade .item { transition: opacity ease-out .7s; left: 0; opacity: 0; /* hide all slides */ top: 0; position: absolute; width: 100%; display: block; } .carousel.fade .item:first-child { top: auto; opacity: 1; /* show first slide */ position: relative; } .carousel.fade .item.active { opacity: 1; }

Toggle visibility property of div

To do it with an effect like with $.fadeIn() and $.fadeOut() you can use transitions

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 1s linear;
}
.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 1s, opacity 1s linear;
}

Textarea Auto height

html

<textarea id="wmd-input" name="md-content"></textarea>

js

var textarea = $('#wmd-input'),
    top = textarea.scrollTop(),
    height = textarea.height();
    if(top > 0){
       textarea.css("height",top + height)
    }

css

#wmd-input{
    width: 100%;
    overflow: hidden;
    padding: 10px;
}

Dynamically update values of a chartjs chart

So simple, Just replace the chart canvas element.

$('#canvas').replaceWith(' id="canvas" height="200px" width="368px">');

Set auto height and width in CSS/HTML for different screen sizes

///UPDATED DEMO 2 WATCH SOLUTION////

I hope that is the solution you're looking for! DEMO1 DEMO2

With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!

You can do that with that code here:

<div class="navTop">
<h1>Title</h1>
    <nav>Dynamic menu</nav>
</div>
<div class="container">
    <section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
    Footer
</footer>

With that css:

.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}

And a bit of jquery:

$(document).ready(function() {
  function setHeight() {
    var top = $('.navTop').outerHeight();
    var bottom = $('footer').outerHeight();
    var totHeight = $(window).height();
    $('section').css({ 
      'height': totHeight - top - bottom + 'px'
    });
  }

  $(window).on('resize', function() { setHeight(); });
  setHeight();
});

DEMO 1

If you don't want jquery

<div class="row">
    <h1>Title</h1>
    <nav>NAV</nav>
</div>

<div class="row container">
    <div class="content">
        <div class="sidebar">
            SIDEBAR
        </div>
        <div class="contents">
            CONTENTS
        </div>
    </div>
    <footer>Footer</footer>
</div>

CSS

*{
margin:0;padding:0;    
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%; 
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{ 
position: fixed; 
bottom: 0; 
left: 0; 
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}

DEMO 2

Overlay a background-image with an rgba background-color

I've gotten the following to work:

html {
  background:
      linear-gradient(rgba(0,184,255,0.45),rgba(0,184,255,0.45)),
      url('bgimage.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

The above will produce a nice opaque blue overlay.

CSS Input with width: 100% goes outside parent's bound

Padding is added to the overall width. Because your container has a pixel width, you are better off giving the inputs a pixel width too, but remember to remove the padding and border from the width you set to avoid the same issue.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

CSS to set A4 paper size

https://github.com/cognitom/paper-css seems to solve all my needs.

Paper CSS for happy printing

Front-end printing solution - previewable and live-reloadable!

Use css gradient over background image

_x000D_
_x000D_
#multiple-background{_x000D_
 box-sizing: border-box;_x000D_
 width: 123px;_x000D_
 height: 30px;_x000D_
 font-size: 12pt;_x000D_
 border-radius: 7px;  _x000D_
 background: url("https://cdn0.iconfinder.com/data/icons/woocons1/Checkbox%20Full.png"), linear-gradient(to bottom, #4ac425, #4ac425);_x000D_
 background-repeat: no-repeat, repeat;_x000D_
 background-position: 5px center, 0px 0px;_x000D_
    background-size: 18px 18px, 100% 100%;_x000D_
 color: white; _x000D_
 border: 1px solid #e4f6df;_x000D_
 box-shadow: .25px .25px .5px .5px black;_x000D_
 padding: 3px 10px 0px 5px;_x000D_
 text-align: right;_x000D_
 }
_x000D_
<div id="multiple-background"> Completed </div>
_x000D_
_x000D_
_x000D_

how to overlap two div in css?

add to second div bottomDiv

and add this to css.

 .bottomDiv{
       position:relative;
       bottom:150px;
       left:150px;
    }

http://jsfiddle.net/aw8RD/1/

Win32Exception (0x80004005): The wait operation timed out

We encountered this error after an upgrade from 2008 to 2014 SQL Server where our some of our previous connection strings for local development had a Data Source=./ like this

        <add name="MyLocalDatabase" connectionString="Data Source=./;Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>

Changing that from ./ to either (local) or localhost fixed the problem.

<add name="MyLocalDatabase" connectionString="Data Source=(local);Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>

Bootstrap Carousel Full Screen

Update Bootstrap 4

Bootstrap 4 has utility classes that make it easier to create a full screen carousel. For example, use the min-vh-100 class on the carousel-item content...

<div class="carousel slide" data-ride="carousel">
      <div class="carousel-inner bg-info" role="listbox">
            <div class="carousel-item active">
                <div class="d-flex align-items-center justify-content-center min-vh-100">
                    <h1 class="display-1">ONE</h1>
                </div>
            </div>
      </div>
</div>

Full screen carousel demo

This works to make the carousel items full screen, but carousel items that contain images or videos that have a specific size & aspect ratio require further consideration.

Since the viewport h/w ratio is likely to be different than the image or video h/w ratio, usually background images or object-fit are commonly used to size images and videos to "full screen". For videos, use the Bootstrap responsive embed classes as needed for the video ratio (21:9, 19:9, etc...).

Full screen videos demo

Also see: https://stackoverflow.com/a/58765043/171456


Original answer (Bootstrap 3)

Make sure the img inside the carousel item is set to height and width 100%. You also have to make sure the carousel and any of the .item containers (html,body) are 100%...

html,body{height:100%;}
.carousel,.item,.active{height:100%;}
.carousel-inner{height:100%;}

Boostrap 3 Full Screen Carousel Demo

Here's an example for Bootstrap 3.x: http://www.codeply.com/go/2tVXo3mAtV

How to change border color of textarea on :focus

.input:focus {
    outline: none !important;
    border:1px solid red;
    box-shadow: 0 0 10px #719ECE;
}

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0) you are less likely to to see a difference between the two approaches.

What is the equivalent of Select Case in Access SQL?

You could do below:

select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table

Set max-height on inner div so scroll bars appear, but not on parent div

It might be easier to use JavaScript or jquery for this. Assuming that the height of the header and the footer is 200 then the code will be:

function SetHeight(){
    var h = $(window).height();
    $("#inner-right").height(h-200);    
}

$(document).ready(SetHeight);
$(window).resize(SetHeight);

CSS3 opacity gradient?

We can do it by css like.

body {
  background: #000;
  background-image: linear-gradient(90deg, rgba(255, 255, 255, .3) 0%, rgba(231, 231, 231, .3) 22.39%, rgba(209, 209, 209,  .3) 42.6%, rgba(182, 182, 182, .3) 79.19%, rgba(156, 156, 156, .3) 104.86%);
  
}

Breaking to a new line with inline-block?

Set the items into display: inline and use :after:

.text span { display: inline }
.break-after:after { content: '\A'; white-space:pre; }

and add the class into your html spans:

<span class="medium break-after">We</span>

How to generate random colors in matplotlib?

Here is a more concise version of Ali's answer giving one distinct color per plot :

import matplotlib.pyplot as plt

N = len(data)
cmap = plt.cm.get_cmap("hsv", N+1)
for i in range(N):
    X,Y = data[i]
    plt.scatter(X, Y, c=cmap(i))

How to create a sticky navigation bar that becomes fixed to the top after scrolling

In answer to Shubham Patwa: This way, the page is "jumpy" soon as the class "navbar-fixed-top" applies. That's because the #mainnav is throwen in and out of the document's DOM flow. This can result in an ugly UX if the page has a "critical height", jumping between fixed and un-fixed #mainnav position.

I altered the code this way, which seems to work fine (not pixel-perfect, but fine):

$(document).ready(function() {
  var navpos = $('#mainnav').offset();
  var navheight = $('#mainnav').outerHeight();

$(window).bind('scroll', function() {
  if ($(window).scrollTop() > navpos.top) {
   $('#mainnav').addClass('navbar-fixed-top');
   $('body').css('marginTop',navheight);
   }
   else {
     $('#mainnav').removeClass('navbar-fixed-top');
     $('body').css('marginTop','0');
   }
});

Background blur with CSS

In recent versions of major browsers you can use backdrop-filter property.

HTML

<div>backdrop blur</div>

CSS

div {
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
}

or if you need different background color for browsers without support:

div {
    background-color: rgba(255, 255, 255, 0.9);
}

@supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
    div {
        -webkit-backdrop-filter: blur(10px);
        backdrop-filter: blur(10px);
        background-color: rgba(255, 255, 255, 0.5);  
    }
}

Demo: JSFiddle

Docs: Mozilla Developer: backdrop-filter

Is it for me?: CanIUse

CSS animation delay in repeating

Delay is possible only once at the beginning with infinite. in sort delay doesn't work with infinite loop. for that you have to keep keyframes animation blanks example:

@-webkit-keyframes barshine {
  10% {background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(100%,#7db9e8));
    }
  60% {background: -webkit-linear-gradient(top, #7db9e8 0%,#d32a2d 100%);}
}

it will animate 10% to 60% and wait to complete 40% more. So 40% comes in delay.

find fiddle example

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Change select box option background color

Here it goes what I've learned about the subject!

The CSS 2 specification did not address the problem of how form elements should be presented to users period!

Read here: smashing magazine

Eventually, you will never find any technical article from w3c or other addressed to this topic. Styling form elements in particular select boxes is not fully supported however, you can drive around... with some effort!

Styling HTML Form Elements

Building Custom Widgets

Don't waste time with hacks e such read the links and learn how pros get the job done!

Add/remove class with jquery based on vertical scroll?

For Android mobile $(window).scroll(function() and $(document).scroll(function() may or may not work. So instead use the following.

jQuery(document.body).scroll(function() {
        var scroll = jQuery(document.body).scrollTop();

        if (scroll >= 300) {
            //alert();
            header.addClass("sticky");
        } else {
            header.removeClass('sticky');
        }
    });

This code worked for me. Hope it will help you.

Using margin:auto to vertically-align a div

Update Aug 2020

Although the below is still worth reading for the useful info, we have had Flexbox for some time now, so just use that, as per this answer.


You can't use:

vertical-align:middle because it's not applicable to block-level elements

margin-top:auto and margin-bottom:auto because their used values would compute as zero

margin-top:-50% because percentage-based margin values are calculated relative to the width of containing block

In fact, the nature of document flow and element height calculation algorithms make it impossible to use margins for centering an element vertically inside its parent. Whenever a vertical margin's value is changed, it will trigger a parent element height re-calculation (re-flow), which would in turn trigger a re-center of the original element... making it an infinite loop.

You can use:

A few workarounds like this which work for your scenario; the three elements have to be nested like so:

_x000D_
_x000D_
.container {
    display: table;
    height: 100%;
    position: absolute;
    overflow: hidden;
    width: 100%;
}
.helper {
    #position: absolute;
    #top: 50%;
    display: table-cell;
    vertical-align: middle;
}
.content {
    #position: relative;
    #top: -50%;
    margin: 0 auto;
    width: 200px;
    border: 1px solid orange;
}
_x000D_
<div class="container">
    <div class="helper">
        <div class="content">
            <p>stuff</p>
        </div>
    </div>
</div
_x000D_
_x000D_
_x000D_

JSFiddle works fine according to Browsershot.

CSS3 scrollbar styling on a div

.scroll {
   width: 200px; height: 400px;
   overflow: auto;
}

Windows service on Local Computer started and then stopped error

If the service starts and stops like that, it means your code is throwing an unhandled exception. This is pretty difficult to debug, but there are a few options.

  1. Consult the Windows Event Viewer. Normally you can get to this by going to the computer/server manager, then clicking Event Viewer -> Windows Logs -> Application. You can see what threw the exception here, which may help, but you don't get the stack trace.
  2. Extract your program logic into a library class project. Now create two different versions of the program: a console app (for debugging), and the windows service. (This is a bit of initial effort, but saves a lot of angst in the long run.)
  3. Add more try/catch blocks and logging to the app to get a better picture of what's going on.

Add JsonArray to JsonObject

I think it is a problem(aka. bug) with the API you are using. JSONArray implements Collection (the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject has an overloaded put() method which takes a Collection and wraps it in a JSONArray (thus causing the problem). I think you need to force the other JSONObject.put() method to be used:

    jsonObject.put("aoColumnDefs",(Object)arr);

You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection) method is broken.

How to get box-shadow on left & right sides only

Another way is with: overflow-y:hidden on the parent with padding.

#wrap {
    overflow-y: hidden;
    padding: 0 10px;
}
#wrap > div {
    width: 100px;
    height: 100px;
    box-shadow: 0 0 20px -5px red;
}

http://jsfiddle.net/qqx221c8/

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

There is a documentation in SLf4J site to resolve this. I followed that and added slf4j-simple-1.6.1.jar to my aplication along with slf4j-api-1.6.1.jar which i already had.This solved my problem

slf4j

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

CSS Styling for a Button: Using <input type="button> instead of <button>

Float:left... Although I presume you want the input to be styled not the div?

.button input{
    color:#08233e;float:left;
    font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
    font-size:70%;
    padding:14px;
    background:url(overlay.png) repeat-x center #ffcc00;
    background-color:rgba(255,204,0,1);
    border:1px solid #ffcc00;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px;
    border-bottom:1px solid #9f9f9f;
    -moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
    -webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
    box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
    cursor:pointer;
}
.button input:hover{
    background-color:rgba(255,204,0,0.8);
}

Sass - Converting Hex to RGBa for background opacity

There is a builtin mixin: transparentize($color, $amount);

background-color: transparentize(#F05353, .3);

The amount should be between 0 to 1;

Official Sass Documentation (Module: Sass::Script::Functions)

Border Radius of Table is not working

<div class="leads-search-table">
                    <div class="row col-md-6 col-md-offset-2 custyle">
                    <table class="table custab bordered">
                    <thead>

                        <tr>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Parent ID</th>
                            <th class="text-center">Action</th>
                        </tr>
                    </thead>
                            <tr>
                                <td>1</td>
                                <td>News</td>
                                <td>News Cate</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                            <tr>
                                <td>2</td>
                                <td>Products</td>
                                <td>Main Products</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                            <tr>
                                <td>3</td>
                                <td>Blogs</td>
                                <td>Parent Blogs</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                    </table>
                    </div>
                </div>

Css

.custab{
    border: 1px solid #ccc;
    margin: 5% 0;
    transition: 0.5s;
    background-color: #fff;
    -webkit-border-radius:4px;
    border-radius: 4px;
    border-collapse: separate;
}

Twitter Bootstrap modal on mobile devices

The solution by niftylettuce in issue 2130 seems to fix modals in all mobile platforms...

9/1/12 UPDATE: The fix has been updated here: twitter bootstrap jquery plugins

(the code below is older but still works)

// # Twitter Bootstrap modal responsive fix by @niftylettuce
//  * resolves #407, #1017, #1339, #2130, #3361, #3362, #4283
//   <https://github.com/twitter/bootstrap/issues/2130>
//  * built-in support for fullscreen Bootstrap Image Gallery
//    <https://github.com/blueimp/Bootstrap-Image-Gallery>

// **NOTE:** If you are using .modal-fullscreen, you will need
//  to add the following CSS to `bootstrap-image-gallery.css`:
//
//  @media (max-width: 480px) {
//    .modal-fullscreen {
//      left: 0 !important;
//      right: 0 !important;
//      margin-top: 0 !important;
//      margin-left: 0 !important;
//    }
//  }
//

var adjustModal = function($modal) {
  var top;
  if ($(window).width() <= 480) {
    if ($modal.hasClass('modal-fullscreen')) {
      if ($modal.height() >= $(window).height()) {
        top = $(window).scrollTop();
      } else {
        top = $(window).scrollTop() + ($(window).height() - $modal.height()) / 2;
      }
    } else if ($modal.height() >= $(window).height() - 10) {
      top = $(window).scrollTop() + 10;
    } else {
      top = $(window).scrollTop() + ($(window).height() - $modal.height()) / 2;
    }
  } else {
    top = '50%';
    if ($modal.hasClass('modal-fullscreen')) {
      $modal.stop().animate({
          marginTop  : -($modal.outerHeight() / 2)
        , marginLeft : -($modal.outerWidth() / 2)
        , top        : top
      }, "fast");
      return;
    }
  }
  $modal.stop().animate({ 'top': top }, "fast");
};

var show = function() {
  var $modal = $(this);
  adjustModal($modal);
};

var checkShow = function() {
  $('.modal').each(function() {
    var $modal = $(this);
    if ($modal.css('display') !== 'block') return;
    adjustModal($modal);
  });
};

var modalWindowResize = function() {
  $('.modal').not('.modal-gallery').on('show', show);
  $('.modal-gallery').on('displayed', show);
  checkShow();
};

$(modalWindowResize);
$(window).resize(modalWindowResize);
$(window).scroll(checkShow);

vertical-align image in div

Old question but nowadays CSS3 makes vertical alignment really simple!

Just add to the <div> this css:

display:flex;
align-items:center;
justify-content:center;

JSFiddle demo

Live Example:

_x000D_
_x000D_
.img_thumb {_x000D_
    float: left;_x000D_
    height: 120px;_x000D_
    margin-bottom: 5px;_x000D_
    margin-left: 9px;_x000D_
    position: relative;_x000D_
    width: 147px;_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    border-radius: 3px;_x000D_
    display:flex;_x000D_
    align-items:center;_x000D_
    justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
    <a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
       <img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get Last record from Sqlite?

The previous answers assume that there is an incrementing integer ID column, so MAX(ID) gives the last row. But sometimes the keys are of text type, not ordered in a predictable way. So in order to take the last 1 or N rows (#Nrows#) we can follow a different approach:

Select * From [#TableName#]  LIMIT #Nrows# offset cast((SELECT count(*)  FROM [#TableName#]) AS INT)- #Nrows#

apply drop shadow to border-top only?

In case you want to apply the shadow to the inside of the element (inset) but only want it to appear on one single side you can define a negative value to the "spread" parameter (5th parameter in the second example).

To completely remove it, make it the same size as the shadows blur (4th parameter in the second example) but as a negative value.

Also remember to add the offset to the y-position (3rd parameter in the second example) so that the following:

box-shadow:         inset 0px 4px 3px rgba(50, 50, 50, 0.75);

becomes:

box-shadow:         inset 0px 7px 3px -3px rgba(50, 50, 50, 0.75);

Check this updated fiddle: http://jsfiddle.net/FrEnY/1282/ and more on the box-shadow parameters here: http://www.w3schools.com/cssref/css3_pr_box-shadow.asp

CSS transition when class removed

CSS transitions work by defining two states for the object using CSS. In your case, you define how the object looks when it has the class "saved" and you define how it looks when it doesn't have the class "saved" (it's normal look). When you remove the class "saved", it will transition to the other state according to the transition settings in place for the object without the "saved" class.

If the CSS transition settings apply to the object (without the "saved" class), then they will apply to both transitions.

We could help more specifically if you included all relevant CSS you're using to with the HTML you've provided.

My guess from looking at your HTML is that your transition CSS settings only apply to .saved and thus when you remove it, there are no controls to specify a CSS setting. You may want to add another class ".fade" that you leave on the object all the time and you can specify your CSS transition settings on that class so they are always in effect.

Semi-transparent color layer over background-image?

Try this. Works for me.

.background {
    background-image: url(images/images.jpg);
    display: block;
    position: relative;
}

.background::after {
    content: "";
    background: rgba(45, 88, 35, 0.7);
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
}

.background > * {
    z-index: 10;
}

Convert RGBA PNG to RGB with PIL

Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG support for sorl thumbnails.

from PIL import Image

png = Image.open(object.logo.path)
png.load() # required for png.split()

background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel

background.save('foo.jpg', 'JPEG', quality=80)

Result @80%

enter image description here

Result @ 50%
enter image description here

Using Colormaps to set color of line in matplotlib

I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.

import matplotlib.pyplot as plt

from matplotlib import cm
from numpy import linspace

start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines) 

colors = [ cm.jet(x) for x in cm_subsection ]

for i, color in enumerate(colors):
    plt.axhline(i, color=color)

plt.ylabel('Line Number')
plt.show()

This results in 1000 uniquely-colored lines that span the entire cm.jet colormap as pictured below. If you run this script you'll find that you can zoom in on the individual lines.

cm.jet between 0.0 and 1.0 with 1000 graduations

Now say I want my 1000 line colors to just span the greenish portion between lines 400 to 600. I simply change my start and stop values to 0.4 and 0.6 and this results in using only 20% of the cm.jet color map between 0.4 and 0.6.

enter image description here

So in a one line summary you can create a list of rgba colors from a matplotlib.cm colormap accordingly:

colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]

In this case I use the commonly invoked map named jet but you can find the complete list of colormaps available in your matplotlib version by invoking:

>>> from matplotlib import cm
>>> dir(cm)

matplotlib savefig in jpeg format

Just install pillow with pip install pillow and it will work.

CSS Inset Borders

You may use background-clip: border-box;

Example:

.example {
padding: 2em;
border: 10px solid rgba(51,153,0,0.65);
background-clip: border-box;
background-color: yellow;
}

<div class="example">Example with background-clip: border-box;</div>

create a white rgba / CSS3

For completely transparent color, use:

rbga(255,255,255,0)

A little more visible:

rbga(255,255,255,.3)

Logging levels - Logback - rule-of-thumb to assign log levels

I mostly build large scale, high availability type systems, so my answer is biased towards looking at it from a production support standpoint; that said, we assign roughly as follows:

  • error: the system is in distress, customers are probably being affected (or will soon be) and the fix probably requires human intervention. The "2AM rule" applies here- if you're on call, do you want to be woken up at 2AM if this condition happens? If yes, then log it as "error".

  • warn: an unexpected technical or business event happened, customers may be affected, but probably no immediate human intervention is required. On call people won't be called immediately, but support personnel will want to review these issues asap to understand what the impact is. Basically any issue that needs to be tracked but may not require immediate intervention.

  • info: things we want to see at high volume in case we need to forensically analyze an issue. System lifecycle events (system start, stop) go here. "Session" lifecycle events (login, logout, etc.) go here. Significant boundary events should be considered as well (e.g. database calls, remote API calls). Typical business exceptions can go here (e.g. login failed due to bad credentials). Any other event you think you'll need to see in production at high volume goes here.

  • debug: just about everything that doesn't make the "info" cut... any message that is helpful in tracking the flow through the system and isolating issues, especially during the development and QA phases. We use "debug" level logs for entry/exit of most non-trivial methods and marking interesting events and decision points inside methods.

  • trace: we don't use this often, but this would be for extremely detailed and potentially high volume logs that you don't typically want enabled even during normal development. Examples include dumping a full object hierarchy, logging some state during every iteration of a large loop, etc.

As or more important than choosing the right log levels is ensuring that the logs are meaningful and have the needed context. For example, you'll almost always want to include the thread ID in the logs so you can follow a single thread if needed. You may also want to employ a mechanism to associate business info (e.g. user ID) to the thread so it gets logged as well. In your log message, you'll want to include enough info to ensure the message can be actionable. A log like " FileNotFound exception caught" is not very helpful. A better message is "FileNotFound exception caught while attempting to open config file: /usr/local/app/somefile.txt. userId=12344."

There are also a number of good logging guides out there... for example, here's an edited snippet from JCL (Jakarta Commons Logging):

  • error - Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
  • warn - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
  • info - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
  • debug - detailed information on the flow through the system. Expect these to be written to logs only.
  • trace - more detailed information. Expect these to be written to logs only.

Is there a css cross-browser value for "width: -moz-fit-content;"?

Is there a single declaration that fixes this for Webkit, Gecko, and Blink? No. However, there is a cross-browser solution by specifying multiple width property values that correspond to each layout engine's convention.

.mydiv {  
  ...
  width: intrinsic;           /* Safari/WebKit uses a non-standard name */
  width: -moz-max-content;    /* Firefox/Gecko */
  width: -webkit-max-content; /* Chrome */
  ...
}

Adapted from: MDN

ListView with OnItemClickListener

In Java as other suggest

listitem.setClickable(false);

Or in xml:

android:clickable="false"

It works very fine

Getting RSA private key from PEM BASE64 Encoded private key file

As others have responded, the key you are trying to parse doesn't have the proper PKCS#8 headers which Oracle's PKCS8EncodedKeySpec needs to understand it. If you don't want to convert the key using openssl pkcs8 or parse it using JDK internal APIs you can prepend the PKCS#8 header like this:

static final Base64.Decoder DECODER = Base64.getMimeDecoder();

private static byte[] buildPKCS8Key(File privateKey) throws IOException {
  final String s = new String(Files.readAllBytes(privateKey.toPath()));
  if (s.contains("--BEGIN PRIVATE KEY--")) {
    return DECODER.decode(s.replaceAll("-----\\w+ PRIVATE KEY-----", ""));
  }
  if (!s.contains("--BEGIN RSA PRIVATE KEY--")) {
    throw new RuntimeException("Invalid cert format: "+ s);
  }

  final byte[] innerKey = DECODER.decode(s.replaceAll("-----\\w+ RSA PRIVATE KEY-----", ""));
  final byte[] result = new byte[innerKey.length + 26];
  System.arraycopy(DECODER.decode("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKY="), 0, result, 0, 26);
  System.arraycopy(BigInteger.valueOf(result.length - 4).toByteArray(), 0, result, 2, 2);
  System.arraycopy(BigInteger.valueOf(innerKey.length).toByteArray(), 0, result, 24, 2);
  System.arraycopy(innerKey, 0, result, 26, innerKey.length);
  return result;
}

Once that method is in place you can feed it's output to the PKCS8EncodedKeySpec constructor like this: new PKCS8EncodedKeySpec(buildPKCS8Key(privateKey));

How to have multiple CSS transitions on an element?

EDIT: I'm torn on whether to delete this post. As a matter of understanding the CSS syntax, it's good that people know all exists, and it may at times be preferable to a million individual declarations, depending on the structure of your CSS. On the other hand, it may have a performance penalty, although I've yet to see any data supporting that hypothesis. For now, I'll leave it, but I want people to be aware it's a mixed bag.

Original post:

You can also simply significantly with:

.nav a {
    transition: all .2s;
}

FWIW: all is implied if not specified, so transition: .2s; will get you to the same place.

CSS hexadecimal RGBA?

The CSS Color Module Level 4 will probably support 4 and 8-digit hexadecimal RGBA notation!

Three weeks ago (18th of December 2014) the CSS Color Module Level 4 editor's draft was submitted to the CSS W3C Working Group. Though in a state which is heavily susceptible to change, the current version of the document implies that in the somewhat near future CSS will support both the 4 and 8-digit hexadecimal RGBA notation.

Note: the following quote has irrelevant chunks cut out and the source may have been heavily modified by the time you read this (as mentioned above, it's an editor's draft and not a finalised document).
If things have heavily changed, please leave a comment letting me know so I can update this answer!

§ 4.2. The RGB hexadecimal notations: #RRGGBB

The syntax of a <hex-color> is a <hash-token> token whose value consists of 3, 4, 6, or 8 hexadecimal digits. In other words, a hex color is written as a hash character, "#", followed by some number of digits 0-9 or letters a-f (the case of the letters doesn’t matter - #00ff00 is identical to #00FF00).

8 digits

The first 6 digits are interpreted identically to the 6-digit notation. The last pair of digits, interpreted as a hexadecimal number, specifies the alpha channel of the color, where 00 represents a fully transparent color and ff represent a fully opaque color.

Example 3
In other words, #0000ffcc represents the same color as rgba(0, 0, 100%, 80%) (a slightly-transparent blue).

4 digits

This is a shorter variant of the 8-digit notation, "expanded" in the same way as the 3-digit notation is. The first digit, interpreted as a hexadecimal number, specifies the red channel of the color, where 0 represents the minimum value and f represents the maximum. The next three digits represent the green, blue, and alpha channels, respectively.

What does this mean for the future of CSS colours?

This means that assuming this isn't completely removed from the Level 4 document, we'll soon be able to define our RGBA colours (or HSLA colours, if you're one of those guys) in hexadecimal format in browsers which support the Color Module Level 4's syntax.

Example

elem {
    background: rgb(0, 0, 0);           /* RGB notation (no alpha). */
    background: #000;                   /* 3-digit hexadecimal notation (no alpha). */
    background: #000000;                /* 6-digit hexadecimal notation (no alpha). */
    background: rgba(0, 0, 0, 1.0);     /* RGBA notation. */

    /* The new 4 and 8-digit hexadecimal notation. */
    background: #0000;                  /* 4-digit hexadecimal notation. */
    background: #00000000;              /* 8-digit hexadecimal notation. */
}

When will I be able to use this in my client-facing products?

Tumble weed is the only real response...

All jokes aside: it's currently only the start of 2015, so these will not be supported in any browser for quite some time yet - even if your product is only designed to work on the most up-to-date of browsers you'll probably not be seeing this in action in a production browser any time soon.

View current browser support for #RRGGBBAA color notation

However, that said, the way CSS works means that we can actually start using these today! If you really want to start using them right now, as long as you add a fall back any non-supporting browsers will simply ignore the new properties until they are deemed valid:

_x000D_
_x000D_
figure {_x000D_
  margin: 0;_x000D_
  padding: 4px;_x000D_
  _x000D_
  /* Fall back (...to browsers which don't support alpha transparency). */_x000D_
  background: #FEFE7F;_x000D_
  color: #3F3FFE;_x000D_
  _x000D_
  /* Current 'modern' browser support. */_x000D_
  background: rgba(255, 255, 0, 0.5);_x000D_
  color: rgba(0, 0, 255, 0.75);_x000D_
  _x000D_
  /* Fall... foward? */_x000D_
  background: #ffff007F; /* Or, less accurately, #ff08 */_x000D_
  color: #0000ffbe;      /* Or #00fc */_x000D_
}
_x000D_
<figure>Hello, world!</figure>
_x000D_
_x000D_
_x000D_

As long as you're viewing this answer on a browser which supports the background and color properties in CSS, the <figure> element in result of the above snippet will look very similar to this:

Code Snippet Result Image

Using the most recent version of Chrome on Windows (v39.0.2171) to inspect our <figure> element, we'll see the following:

Element Inspector Example

The 6-digit hexadecimal fall back is overridden by the rgba() values, and our 8-digit hexadecimal values are ignored as they are currently deemed invalid by Chrome's CSS parser. As soon as our browser supports these 8-digit values, these will override the rgba() ones.

UPDATE 2018-07-04: Firefox, Chrome and Safari are support this notation now, Edge still missing but will probably follow (https://caniuse.com/#feat=css-rrggbbaa).

Html.RenderPartial() syntax with Razor

Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

Void methods require a semicolon at the end of the calling code.

In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

like so

<% Html.RenderPartial("Path/to/my/partial/view"); %>

when you are using the Razor view engine the equivalent is

@{Html.RenderPartial("Path/to/my/partial/view");}

Soft Edges using CSS?

Another option is to use one of my personal favorite CSS tools: box-shadow.

A box shadow is really a drop-shadow on the node. It looks like this:

-moz-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
-webkit-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
box-shadow: 1px 2px 3px rgba(0,0,0,.5);

The arguments are:

1px: Horizontal offset of the effect. Positive numbers shift it right, negative left.
2px: Vertical offset of the effect. Positive numbers shift it down, negative up.
3px: The blur effect.  0 means no blur.
color: The color of the shadow.

So, you could leave your current design, and add a box-shadow like:

box-shadow: 0px -2px 2px rgba(34,34,34,0.6);

This should give you a 'blurry' top-edge.

This website will help with more information: http://css-tricks.com/snippets/css/css-box-shadow/

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

It is worth trying these 2 options below while we're still waiting for the fix in FF35:

select {
    -moz-appearance: scrollbartrack-vertical;
}

or

select {
    -moz-appearance: treeview;
}

They will just hide any arrow background image you have put in to custom style your select element. So you get a bog standard browser arrow instead of a horrible combo of both browser arrow and your own custom arrow.

Use CSS3 transitions with gradient backgrounds

Can't hurt to post another view since there's still not an official way to do this. Wrote a lightweight jQuery plugin with which you can define a background radial gradient and a transition speed. This basic usage will then let it fade in, optimised with requestAnimationFrame (very smooth) :

$('#element').gradientFade({

    duration: 2000,
    from: '(20,20,20,1)',
    to: '(120,120,120,0)'
});

http://codepen.io/Shikkediel/pen/xbRaZz?editors=001

Keeps original background and all properties intact. Also has highlight tracking as a setting :

http://codepen.io/Shikkediel/pen/VYRZZY?editors=001

How can I decrease the size of Ratingbar?

In RatingBar give attribute:

style="?android:attr/ratingBarStyleIndicator" 

Javascript to stop HTML5 video playback on modal window close

I'm using the following trick to stop HTML5 video. pause() the video on modal close and set currentTime = 0;

<script>
     var video = document.getElementById("myVideoPlayer");
     function stopVideo(){
          video.pause();
          video.currentTime = 0;
     }
</script>

Now you can use stopVideo() method to stop HTML5 video. Like,

$("#stop").on('click', function(){
    stopVideo();
});

Opacity of div's background without affecting contained element in IE 8?

It affects the whole child divs when you use the opacity feature with positions other than absolute. So another way to achieve it not to put divs inside each other and then use the position absolute for the divs. Dont use any background color for the upper div.

How can I configure Logback to log different levels for a logger to different destinations?

<configuration scan="true" scanPeriod="60 seconds">
 <appender name="A1" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${storm.log.dir}/${logfile.name}</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      <fileNamePattern>${storm.log.dir}/${logfile.name}.%i</fileNamePattern>
      <minIndex>1</minIndex>
      <maxIndex>9</maxIndex>
    </rollingPolicy>

    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
      <maxFileSize>100MB</maxFileSize>
    </triggeringPolicy>

    <encoder>
      <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSZZ} %c{1} [%p] %m%n</pattern>
    </encoder>
 </appender>

 <appender name="ACCESS" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${storm.log.dir}/access.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      <fileNamePattern>${storm.log.dir}/access.log.%i</fileNamePattern>
      <minIndex>1</minIndex>
      <maxIndex>9</maxIndex>
    </rollingPolicy>

    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
      <maxFileSize>100MB</maxFileSize>
    </triggeringPolicy>

    <encoder>
      <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSZZ} %c{1} [%p] %m%n</pattern>
    </encoder>
  </appender>

  <appender name="METRICS" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${storm.log.dir}/metrics.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      <fileNamePattern>${storm.log.dir}/logs/metrics.log.%i</fileNamePattern>
      <minIndex>1</minIndex>
      <maxIndex>9</maxIndex>
    </rollingPolicy>

    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
      <maxFileSize>2MB</maxFileSize>
    </triggeringPolicy>

    <encoder>
      <pattern>%d %-8r %m%n</pattern>
    </encoder>
  </appender>

  <root level="INFO">
    <appender-ref ref="A1"/>
  </root>

  <logger name="backtype.storm.security.auth.authorizer" additivity="false">
    <level value="INFO" />
    <appender-ref ref="ACCESS" />
  </logger>

  <logger name="backtype.storm.metric.LoggingMetricsConsumer" additivity="false" >
    <level value="INFO"/>
    <appender-ref ref="METRICS"/>
  </logger>

</configuration>

So here is the logback file in which I am not printing backtype.storm.metric.LoggingMetricsConsumer info level if i say additivity = "true" then for for all classes in backtype.* this rule will be applied

what does this mean ? image/png;base64?

That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

adb server version doesn't match this client

System: Windows 10

My issue: Setting Genymotion to point to the custom SDK didn't have any affect. I still received the:

Couldn't start project on Android: could not install smartsocket listener: cannot bind to 127.0.0.1:5037: Only one usage of each socket address (protocol/network address/port) is normally permitted. (10048) could not read ok from ADB Server * failed to start daemon * error: cannot connect to daemon

What I discovered was there was a difference in ADB versions being used throughout the system. Here is the command I used to find them:

where /r C:\ adb.exe

This produced the results:

C:\Program Files\Expo XDE\resources\app\node_modules\xdl\binaries\windows\adb\adb.exe
C:\Program Files\Genymobile\Genymotion\tools\adb.exe
C:\Users\kyle\AppData\Local\Android\Sdk\platform-tools\adb.exe
C:\Users\kyle\AppData\Local\Android\Sdk\platform-tools\adb backup\adb.exe

Navigating to each directory and running:

adb.exe version

Allowed me to see that Expo was running ADB version:

Android Debug Bridge version 1.0.36
Revision fd9e4d07b0f5-android

While Genymotion using the custom SDK had version (c:\Users\kyle\AppData\Local\Android\Sdk\platform-tools\adb.exe):

Android Debug Bridge version 1.0.39
Revision 3db08f2c6889-android

As a test I took the adb files (adb.exe, AdbWinApi.dll, AdbWinUsbApi.dll) from

c:\Users\kyle\AppData\Local\Android\Sdk\platform-tools\adb.exe

and placed them into a backup folder. I then moved the adb files located at

c:\Program Files\Expo XDE\resources\app\node_modules\xdl\binaries\windows\adb\adb.exe

into that same location. I killed adb with:

adb kill-server

which caused a restart of the adb server automatically due to having my Genymotion device already running. I hit the "Restart" button inside of the Expo XDE and it immediately began working. Here is the log where I hit the restart button at 1:13:04 AM:

12:45:53 AM
could not install *smartsocket* listener: cannot bind to 127.0.0.1:5037: Only one usage of each socket address (protocol/network address/port) is normally permitted. (10048)
could not read ok from ADB Server
* failed to start daemon *
error: cannot connect to daemon
1:13:04 AM
Restarting project and clearing packager cache (Hold shift while clicking restart to avoid clearing cache).
1:13:11 AM
Starting React Native packager...
1:13:17 AM
Scanning 543 folders for symlinks in C:\Users\kyle\git\betalog\node_modules (49ms)
1:13:17 AM
1:13:19 AM
Couldn't adb reverse: closed
1:13:20 AM
Project opened! You can now use the "Share" or "Device" buttons to view your project.
1:13:26 AM
Couldn't adb reverse: closed
1:13:26 AM
Downloading latest version of Expo
1:13:28 AM
Installing Expo on device
1:13:33 AM
Opening on Android device
1:13:56 AM
Building JavaScript bundle: finished in 59643ms.
1:14:01 AM
Dependency graph loaded.
1:14:03 AM
Your JavaScript transform cache is empty, rebuilding (this may take a minute).

Conclusion: Genymotion and Expo may need to use the same version of adb so that Expo can properly communicate with the simulated device. Pointing Genymotion to your android SDK location as well as ensuring Expo XDE has that same version will allow correct communication between devices. I moved the Expo XDE version to the SDK location, but you might be able to go the other way (take the sdk ADB files and place them in the Expo XDE resource location).

P.S. I've been all through the stackoverflow posts related to this issue. Just so you guys know my task manager shows three instances of adb.exe running. If you kill any of them they just come back.

Hope this helps /cheers

Set opacity of background image without affecting child elements

#footer ul li {
  position: relative;
  opacity: 0.99;
}

#footer ul li::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: url(/images/arrow.png) no-repeat 0 50%;
  opacity: 0.5;
}

Hack with opacity .99 (less than 1) creates z-index context so you can not worry about global z-index values. (Try to remove it and see what happens in the next demo where parent wrapper has positive z-index.)
If your element already has z-index, then you don't need this hack.

Demo of this technique.

HTML Canvas Full Screen

it's simple, set canvas width and height to screen.width and screen.height. then press F11! think F11 should make full screen in most browsers does in FFox and IE.

CSS background opacity with rgba not working in IE 8

After searching a lot, I found the following solution which is working in my cases:

.opacity_30{
    background:rgb(255,255,255); /* Fallback for web browsers that don't support neither RGBa nor filter */ 
    background: transparent\9; /* Backslash 9 hack to prevent IE 8 from falling into the fallback */
    background:rgba(255,255,255,0.3); /* RGBa declaration for modern browsers */
    -ms-filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4CFFFFFF,endColorstr=#4CFFFFFF); /* IE 8 suppoerted; Sometimes Hover issues may occur, then we can use transparent repeating background image :( */
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4CFFFFFF,endColorstr=#4CFFFFFF); /* needed for IE 6-7 */
    zoom: 1; /* Hack needed for IE 6-8 */
}

/* To avoid IE more recent versions to apply opacity twice (once with rgba and once with filter), we need the following CSS3 selector hack (not supported by IE 6-8) */
.opacity_30:nth-child(n) {
    filter: none;
}

*Important: To calculate ARGB(for IEs) from RGBA, we can use online tools:

  1. https://kilianvalkhof.com/2010/css-xhtml/how-to-use-rgba-in-ie/
  2. http://web.archive.org/web/20131207234608/http://kilianvalkhof.com/2010/css-xhtml/how-to-use-rgba-in-ie/

How to make RatingBar to show five stars

The RatingBar.setNumStar documentation says:

Sets the number of stars to show. In order for these to be shown properly, it is recommended the layout width of this widget be wrap content.

So setting the layout width to wrap_content should solve this problem.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

if The given id is not exist in the DB ,then you may get this exception.

Exception in thread "main" org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

How to change root logging level programmatically for logback

Here's a controller

@RestController
@RequestMapping("/loggers")
public class LoggerConfigController {

private final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(PetController.class);

@GetMapping()
public List<LoggerDto> getAllLoggers() throws CoreException {
    
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    
    List<Logger> loggers = loggerContext.getLoggerList();
    
    List<LoggerDto> loggerDtos = new ArrayList<>();
    
    for (Logger logger : loggers) {
        
        if (Objects.isNull(logger.getLevel())) {
            continue;
        }
        
        LoggerDto dto = new LoggerDto(logger.getName(), logger.getLevel().levelStr);
        loggerDtos.add(dto);
    }
    
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("All loggers retrieved. Total of {} loggers found", loggerDtos.size());
    }
    
    return loggerDtos;
}

@PutMapping
public boolean updateLoggerLevel(
        @RequestParam String name, 
        @RequestParam String level
)throws CoreException {
    
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    
    Logger logger = loggerContext.getLogger(name);
    
    if (Objects.nonNull(logger) && StringUtils.isNotBlank(level)) {
        
        switch (level) {
            case "INFO":
                logger.setLevel(Level.INFO);
                LOGGER.info("Logger [{}] updated to [{}]", name, level);
                break;
                
            case "DEBUG":
                logger.setLevel(Level.DEBUG);
                LOGGER.info("Logger [{}] updated to [{}]", name, level);
                break;
                
            case "ALL":
                logger.setLevel(Level.ALL);
                LOGGER.info("Logger [{}] updated to [{}]", name, level);
                break;
                
            case "OFF":
            default: 
                logger.setLevel(Level.OFF);
                LOGGER.info("Logger [{}] updated to [{}]", name, level);
        }
    }
    
    return true;
}

}

overlay opaque div over youtube iframe

Note that the wmode=transparent fix only works if it's first so

http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent&rel=0

Not

http://www.youtube.com/embed/K3j9taoTd0E?rel=0&wmode=transparent

Can regular JavaScript be mixed with jQuery?

Why is MichalBE getting downvoted? He's right - using jQuery (or any library) just to fire a function on page load is overkill, potentially costing people money on mobile connections and slowing down the user experience. If the original poster doesn't want to use onload in the body tag (and he's quite right not to), add this after the draw() function:

if (draw) window.onload = draw;

Or this, by Simon Willison, if you want more than one function to be executed:

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You can find your sample code completely here: http://www.java2s.com/Code/Java/Hibernate/OneToManyMappingbasedonSet.htm

Have a look and check the differences. specially the even_id in :

<set name="attendees" cascade="all">
    <key column="event_id"/>
    <one-to-many class="Attendee"/>
</set> 

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

CSS horizontal centering of a fixed div?

If using inline-blocks is an option I would recommend this approach:

.container { 
    /* fixed position a zero-height full width container */
    position: fixed;
    top: 0; /* or whatever position is desired */
    left: 0;
    right: 0;
    height: 0;
    /* center all inline content */
    text-align: center;
}

.container > div {
    /* make the block inline */
    display: inline-block;
    /* reset container's center alignment */
    text-align: left;
} 

I wrote a short post on this here: http://salomvary.github.com/position-fixed-horizontally-centered.html

Inner text shadow with CSS

I've had a few instances where I've needed inner shadows on text, and the following has worked out well for me:

.inner {
    color: rgba(252, 195, 67, 0.8);
    font-size: 48px;
    text-shadow: 1px 2px 3px #fff, 0 0 0 #000;
}

This sets the opacity of the text to 80%, and then creates two shadows:

  • The first is a white shadow (assuming the text is on a white background) offset 1px from the left and 2px from the top, blurred 3px.
  • The second is a black shadow which is visible through the 80% opacity text but not through the first shadow, which means it's visible inside the text letters only where the first shadow is displaced (1px from the left and 2px from the top). To change the blur of the this visible shadow, modify the blur parameter for the first layer shadow.

Caveats

  • This will only work if the desired color of the text can be achieved without it having to be at 100% opacity.
  • This will only work if the background color is solid (so, it won't work for the questioner's specific example where the text sits on a textured background).

How to make a smaller RatingBar?

Just use:

android:scaleX="0.5"
android:scaleY="0.5"

Change the scale factor according to your need.

In order to scale without creating a padding on the left also add

android:transformPivotX="0dp"

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

I just encountered this problem and found out I was deleting a record and trying to update it afterwards in a Hibernate transaction.

Focusable EditText inside ListView

If the list is dynamic and contains focusable widgets, then the right option is to use RecyclerView instead of ListView IMO.

The workarounds that set adjustPan, FOCUS_AFTER_DESCENDANTS, or manually remember focused position, are indeed just workarounds. They have corner cases (scrolling + soft keyboard issues, caret changing position in EditText). They don't change the fact that ListView creates/destroys views en masse during notifyDataSetChanged.

With RecyclerView, you notify about individual inserts, updates, and deletes. The focused view is not being recreated so no issues with form controls losing focus. As an added bonus, RecyclerView animates the list item insertions and removals.

Here's an example from official docs on how to get started with RecyclerView: Developer guide - Create a List with RecyclerView

Android RatingBar change star colors

Use android:theme attribute:

styles.xml

<style name="Theme.Rating" parent="Theme.AppCompat.Light">
    <item name="colorAccent">@color/rating</item>
</style>

layout.xml

<android.support.v7.widget.AppCompatRatingBar
    android:theme="@style/Theme.Rating"
    android:numStars="5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

CSS3 Transparency + Gradient

Here is my code:

background: #e8e3e3; /* Old browsers */
  background: -moz-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%, rgba(246, 242, 242, 0.95) 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(232, 227, 227, 0.95)), color-stop(100%,rgba(246, 242, 242, 0.95))); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* IE10+ */
  background: linear-gradient(to bottom,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* W3C */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='rgba(232, 227, 227, 0.95)', endColorstr='rgba(246, 242, 242, 0.95)',GradientType=0 ); /* IE6-9 */

Pushing value of Var into an Array

.val() does not return an array from a DOM element: $('#fruit') is going to find the element in the document with an ID of #fruit and get its value (if it has a value).

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

UIImage is a wrapper the bytes are CGImage or CIImage

According the the Apple Reference on UIImage the object is immutable and you have no access to the backing bytes. While it is true that you can access the CGImage data if you populated the UIImage with a CGImage (explicitly or implicitly), it will return NULL if the UIImage is backed by a CIImage and vice-versa.

Image objects not provide direct access to their underlying image data. However, you can retrieve the image data in other formats for use in your app. Specifically, you can use the cgImage and ciImage properties to retrieve versions of the image that are compatible with Core Graphics and Core Image, respectively. You can also use the UIImagePNGRepresentation(:) and UIImageJPEGRepresentation(:_:) functions to generate an NSData object containing the image data in either the PNG or JPEG format.

Common tricks to getting around this issue

As stated your options are

  • UIImagePNGRepresentation or JPEG
  • Determine if image has CGImage or CIImage backing data and get it there

Neither of these are particularly good tricks if you want output that isn't ARGB, PNG, or JPEG data and the data isn't already backed by CIImage.

My recommendation, try CIImage

While developing your project it might make more sense for you to avoid UIImage altogether and pick something else. UIImage, as a Obj-C image wrapper, is often backed by CGImage to the point where we take it for granted. CIImage tends to be a better wrapper format in that you can use a CIContext to get out the format you desire without needing to know how it was created. In your case, getting the bitmap would be a matter of calling

- render:toBitmap:rowBytes:bounds:format:colorSpace:

As an added bonus you can start doing nice manipulations to the image by chaining filters onto the image. This solves a lot of the issues where the image is upside down or needs to be rotated/scaled etc.

log4j vs logback

Not exactly answering your question, but if you could move away from your self-made wrapper then there is Simple Logging Facade for Java (SLF4J) which Hibernate has now switched to (instead of commons logging).

SLF4J suffers from none of the class loader problems or memory leaks observed with Jakarta Commons Logging (JCL).

SLF4J supports JDK logging, log4j and logback. So then it should be fairly easy to switch from log4j to logback when the time is right.

Edit: Aplogies that I hadn't made myself clear. I was suggesting using SLF4J to isolate yourself from having to make a hard choice between log4j or logback.

Find a private field with Reflection?

Get private variable's value using Reflection:

var _barVariable = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectForFooClass);

Set value for private variable using Reflection:

typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectForFoocClass, "newValue");

Where objectForFooClass is a non null instance for the class type Foo.

Finding a branch point with Git?

You may be looking for git merge-base:

git merge-base finds best common ancestor(s) between two commits to use in a three-way merge. One common ancestor is better than another common ancestor if the latter is an ancestor of the former. A common ancestor that does not have any better common ancestor is a best common ancestor, i.e. a merge base. Note that there can be more than one merge base for a pair of commits.

'nuget' is not recognized but other nuget commands working

You can also try setting the system variable path to the location of your nuget exe and restarting VS.

  1. Open your system PATH variable and add the location of your nuget.exe (for me this is: C:\Program Files (x86)\NuGet\Visual Studio 2013)
  2. Restart Visual Studio

I would have posted this as a comment to your answer @done_merson but I didn't have the required reputation to do that.

Get file content from URL?

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

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

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

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

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

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

Can we overload the main method in Java?

yes we can overload main method. main method must not be static main method.

Python Database connection Close

You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.

import pyodbc

class MS_DB():
    """ Collection of helper methods to query the MS SQL Server database.
    """

    def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
        self.username = username
        self._password = password
        self.host = host
        self.port = str(port)
        self.db = initial_db
        conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
                    self.host + ';PORT='+ self.port +';DATABASE='+ \
                    self.db +';UID='+ self.username +';PWD='+ \ 
                    self._password +';'
        print('Connected to DB:', conn_str)
        self._connection = pyodbc.connect(conn_str)        
        pyodbc.pooling = False

    def __repr__(self):
        return f"MS-SQLServer('{self.username}', <password hidden>, '{self.host}', '{self.port}', '{self.db}')"

    def __str__(self):
        return f"MS-SQLServer Module for STP on {self.host}"

    def __del__(self):
        self._connection.close()
        print("Connection closed.")

    @contextmanager
    def cursor(self, commit: bool = False):
        """
        A context manager style of using a DB cursor for database operations. 
        This function should be used for any database queries or operations that 
        need to be done. 

        :param commit:
        A boolean value that says whether to commit any database changes to the database. Defaults to False.
        :type commit: bool
        """
        cursor = self._connection.cursor()
        try:
            yield cursor
        except pyodbc.DatabaseError as err:
            print("DatabaseError {} ".format(err))
            cursor.rollback()
            raise err
        else:
            if commit:
                cursor.commit()
        finally:
            cursor.close()

ms_db = MS_DB(username='my_user', password='my_secret', host='hostname')
with ms_db.cursor() as cursor:
        cursor.execute("SELECT @@version;")
        print(cur.fetchall())

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

nodejs vs node on ubuntu 12.04

You need to manually create a symlink /usr/bin/node. Shortcut for bash compatible shells:

sudo ln -s `which nodejs` /usr/bin/node

Or if you use non-standard shells, just hardcode the path you find with which nodejs:

sudo ln -s /usr/bin/nodejs /usr/bin/node

Later edit

I found this explanation in the link you posted

There is a naming conflict with the node package (Amateur Packet Radio Node Program), and the nodejs binary has been renamed from node to nodejs. You'll need to symlink /usr/bin/node to /usr/bin/nodejs or you could uninstall the Amateur Packet Radio Node Program to avoid that conflict.

Later later edit

It's been a while since I answered this. Although the solution I posted up here worked for me several times, users have reported a few more solutions within the comments:

From @user229115

sudo update-alternatives --install /usr/bin/node node /usr/bin/nodejs 10

From AskUbuntu (user leftium)

sudo apt-get --purge remove node
sudo apt-get --purge remove nodejs
sudo apt-get install nodejs

Javascript, viewing [object HTMLInputElement]

<input type="text" />
<script>
$("input:text").change(function() {
    var value=$("input:text").val();
    alert(value);
});
</script>

use .val() to get value of the element (jquery method), $("input:text") this selector to select your input, .change() to bind an event handler to the "change" JavaScript event.

Split a string into array in Perl

Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:

my $line = "file1.gz file1.gz file3.gz";
my @abc = split(/\s+/, $line);

Is there a method that calculates a factorial in Java?

Use Guava's BigIntegerMath as follows:

BigInteger factorial = BigIntegerMath.factorial(n);

(Similar functionality for int and long is available in IntMath and LongMath respectively.)

Hide console window from Process.Start C#

This doesn't show the window:

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;

...
cmd.Start();

Generating a unique machine id

In my program I first check for Terminal Server and use the WTSClientHardwareId. Else the MAC address of the local PC should be adequate.

If you really want to use the list of properties you provided leave out things like Name and DriverVersion, Clockspeed, etc. since it's possibly OS dependent. Try outputting the same info on both operating systems and leave out that which differs between.

jQuery callback on image load (even when the image is cached)

Just re-add the src argument on a separate line after the img oject is defined. This will trick IE into triggering the lad-event. It is ugly, but it is the simplest workaround I've found so far.

jQuery('<img/>', {
    src: url,
    id: 'whatever'
})
.load(function() {
})
.appendTo('#someelement');
$('#whatever').attr('src', url); // trigger .load on IE

How to convert an int value to string in Go?

In this case both strconv and fmt.Sprintf do the same job but using the strconv package's Itoa function is the best choice, because fmt.Sprintf allocate one more object during conversion.

check the nenchmark result of both check the benchmark here: https://gist.github.com/evalphobia/caee1602969a640a4530

see https://play.golang.org/p/hlaz_rMa0D for example.

How to pass parameter to click event in Jquery

 $('elements-to-match').click(function(){
        alert("The id is "+ this.id );
    });

no need to wrap it in a jquery object

Catch KeyError in Python

You should consult the documentation of whatever library is throwing the exception, to see how to get an error message out of its exceptions.

Alternatively, a good way to debug this kind of thing is to say:

except Exception, e:
    print dir(e)

to see what properties e has - you'll probably find it has a message property or similar.

Why do I always get the same sequence of random numbers with rand()?

You have to seed it. Seeding it with the time is a good idea:

srand()

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  srand ( time(NULL) );
  printf ("Random Number: %d\n", rand() %100);
  return 0;
}

You get the same sequence because rand() is automatically seeded with the a value of 1 if you do not call srand().

Edit

Due to comments

rand() will return a number between 0 and RAND_MAX (defined in the standard library). Using the modulo operator (%) gives the remainder of the division rand() / 100. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000.

How to add hours to current date in SQL Server?

DATEADD (datepart , number , date )

declare @num_hours int; 
    set @num_hours = 5; 

select dateadd(HOUR, @num_hours, getdate()) as time_added, 
       getdate() as curr_date  

What does -z mean in Bash?

-z string True if the string is null (an empty string)

should use size_t or ssize_t

ssize_t is not included in the standard and isn't portable. size_t should be used when handling the size of objects (there's ptrdiff_t too, for pointer differences).

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Update multiple rows using select statement

Run a select to make sure it is what you want

SELECT t1.value AS NEWVALUEFROMTABLE1,t2.value AS OLDVALUETABLE2,*
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Update

UPDATE Table2
SET Value = t1.Value
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Also, consider using BEGIN TRAN so you can roll it back if needed, but make sure you COMMIT it when you are satisfied.

Pretty printing XML in Python

I had some problems with minidom's pretty print. I'd get a UnicodeError whenever I tried pretty-printing a document with characters outside the given encoding, eg if I had a ß in a document and I tried doc.toprettyxml(encoding='latin-1'). Here's my workaround for it:

def toprettyxml(doc, encoding):
    """Return a pretty-printed XML document in a given encoding."""
    unistr = doc.toprettyxml().replace(u'<?xml version="1.0" ?>',
                          u'<?xml version="1.0" encoding="%s"?>' % encoding)
    return unistr.encode(encoding, 'xmlcharrefreplace')

How can you export the Visual Studio Code extension list?

Benny's answer on Windows with the Linux subsystem:

code --list-extensions | wsl xargs -L 1 echo code --install-extension

SSIS Excel Import Forcing Incorrect Column Type

I had the same issue, multiple data type values in single column, package load only numeric values. Remains all it updated as null.

Solution

To fix this changing the excel data type is one of the solution. In Excel Copy the column data and paste in different file. Delete that column and insert new column as Text datatype and paste that copied data in new column.

Now in ssis package delete and recreate the Excel source and destination table change the column data type as varchar.

This will work.

How do I get the base URL with PHP?

$some_variable =  substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1);

and you get something like

lalala/tralala/something/

CSS Div width percentage and padding without breaking layout

If you want the #header to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).

Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:

#container {
    position: relative;
    width: 80%;
}

#header {
    position: relative;
    height: 50px;
    padding: 10px;
}

You can see it in action here.

The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block child with no width set.


Update

Another option for dealing with this is to use the box-sizing CSS rule:

#container { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    /* Since this element now uses border-box sizing, the 10px of horizontal
       padding will be drawn inside the 80% width */
    width: 80%;
    padding: 0 10px;
}

Here's a post talking about how box-sizing works.

Saving images in Python at a very high quality

Okay, I found spencerlyon2's answer working. However, in case anybody would find himself/herself not knowing what to do with that one line, I had to do it this way:

beingsaved = plt.figure()

# Some scatter plots
plt.scatter(X_1_x, X_1_y)
plt.scatter(X_2_x, X_2_y)

beingsaved.savefig('destination_path.eps', format='eps', dpi=1000)

Access to the path is denied

My problem was something like that:

FileStream ms = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);

but instead of using path I should use File.FullName... I don't know if it's going to help anyone else, just passing my own experience with this erro given!

Rename a table in MySQL

Running The Alter Command

1.Click the SQL tab at the top.

2.In the text box enter the following command: ALTER TABLE exampletable RENAME TO new_table_name;

3.Click the go button.

source : https://my.bluehost.com/hosting/help/2158

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

Specify the name of columns in the CSV in the load data infile statement.

The code is like this:

LOAD DATA INFILE '/path/filename.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(column_name3, column_name5);

Here you go with adding data to only two columns(you can choose them with the name of the column) to the table.

The only thing you have to take care is that you have a CSV file(filename.csv) with two values per line(row). Otherwise please mention. I have a different solution.

Thank you.

How to view DB2 Table structure

In DB2, enter on db2 command prompt.

  db2  =>  describe  table MyTableName

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Multiple returns from a function

<?php
function foo(){
  $you = 5;
  $me = 10;
  return $you;
  return $me;
}

echo foo();
//output is just 5 alone so we cant get second one it only retuns first one so better go with array


function goo(){
  $you = 5;
  $me = 10;
  return $you_and_me =  array($you,$me);
}

var_dump(goo()); // var_dump result is array(2) { [0]=> int(5) [1]=> int(10) } i think thats fine enough

?>

Multiple Where clauses in Lambda expressions

Maybe

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty)
    .Where(l => l.InternalName != string.Empty)

?

You can probably also put it in the same where clause:

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty && l.InternalName != string.Empty)

Make XAMPP / Apache serve file outside of htdocs folder

If you're trying to get XAMPP to use a network drive as your document root you have to use UNC paths in httpd.conf. XAMPP will not recognize your mapped network drives.

For example the following won't work, DocumentRoot "X:/webroot"

But this will, DocumentRoot "//192.168.10.100/webroot" (note the forward slashes, not back slashes)

Remove json element

You can try to delete the JSON as follows:

var bleh = {first: '1', second: '2', third:'3'}

alert(bleh.first);

delete bleh.first;

alert(bleh.first);

Alternatively, you can also pass in the index to delete an attribute:

delete bleh[1];

However, to understand some of the repercussions of using deletes, have a look here

Different class for the last element in ng-repeat

You can use $last variable within ng-repeat directive. Take a look at doc.

You can do it like this:

 <div ng-repeat="file in files" ng-class="computeCssClass($last)">
 {{file.name}}
 </div>

Where computeCssClass is function of controller which takes sole argument and returns 'last' or null.

Or

  <div ng-repeat="file in files" ng-class="{'last':$last}">
  {{file.name}}
  </div>

How to set timeout in Retrofit library?

You can set timeouts on the underlying HTTP client. If you don't specify a client, Retrofit will create one with default connect and read timeouts. To set your own timeouts, you need to configure your own client and supply it to the RestAdapter.Builder.

An option is to use the OkHttp client, also from Square.

1. Add the library dependency

In the build.gradle, include this line:

compile 'com.squareup.okhttp:okhttp:x.x.x'

Where x.x.x is the desired library version.

2. Set the client

For example, if you want to set a timeout of 60 seconds, do this way for Retrofit before version 2 and Okhttp before version 3 (FOR THE NEWER VERSIONS, SEE THE EDITS):

public RestAdapter providesRestAdapter(Gson gson) {
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);

    return new RestAdapter.Builder()
        .setEndpoint(BuildConfig.BASE_URL)
        .setConverter(new GsonConverter(gson))
        .setClient(new OkClient(okHttpClient))
        .build();
}

EDIT 1

For okhttp versions since 3.x.x, you have to set the dependency this way:

compile 'com.squareup.okhttp3:okhttp:x.x.x'

And set the client using the builder pattern:

final OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .build();

More info in Timeouts


EDIT 2

Retrofit versions since 2.x.x also uses the builder pattern, so change the return block above to this:

return new Retrofit.Builder()
    .baseUrl(BuildConfig.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttpClient)
    .build();

If using a code like my providesRestAdapter method, then change the method return type to Retrofit.

More info in Retrofit 2 — Upgrade Guide from 1.9


ps: If your minSdkVersion is greater than 8, you can use TimeUnit.MINUTES:

okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);

For more details about the units, see TimeUnit.

Accessing JPEG EXIF rotation data in JavaScript on the client side

Firefox 26 supports image-orientation: from-image: images are displayed portrait or landscape, depending on EXIF data. (See sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation.)

There is also a bug to implement this in Chrome.

Beware that this property is only supported by Firefox and is likely to be deprecated.

How to change the sender's name or e-mail address in mutt?

before you send the email you can press <ESC> f (Escape followed by f) to change the From: Address.

Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!

How can I check if a view is visible or not in Android?

Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.

View.VISIBLE The view is visible.

View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"

View.GONE The view is gone, you can't see it and it doesn't take up the "spot".

So to answer your question, you're looking for:

if (myImageView.getVisibility() == View.VISIBLE) {
    // Its visible
} else {
    // Either gone or invisible
}

ToList().ForEach in Linq

employees.ToList().Foreach(u=> { u.SomeProperty = null; u.OtherProperty = null; });

Notice that I used semicolons after each set statement that is -->

u.SomeProperty = null;
u.OtherProperty = null;

I hope this will definitely solve your problem.

How to read line by line of a text area HTML tag

Two options: no JQuery required, or JQuery version

No JQuery (or anything else required)

var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n');    // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

JQuery version

var lines = $('#myTextAreaId').val().split('\n');   // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

Side note, if you prefer forEach a sample loop is

lines.forEach(function(line) {
  console.log('Line is ' + line)
})

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

try this:

ComboBox cbx = new ComboBox();
cbx.DisplayMember = "Text";
cbx.ValueMember = "Value";

EDIT (a little explanation, sory, I also didn't notice your combobox wasn't bound, I blame the lack of caffeine):

The difference between SelectedValue and SelectedItem are explained pretty well here: ComboBox SelectedItem vs SelectedValue

So, if your combobox is not bound to datasource, DisplayMember and ValueMember doesn't do anything, and SelectedValue will always be null, SelectedValueChanged won't be called. So either bind your combobox:

            comboBox1.DisplayMember = "Text";
            comboBox1.ValueMember = "Value";

            List<ComboboxItem> list = new List<ComboboxItem>();

            ComboboxItem item = new ComboboxItem();
            item.Text = "choose a server...";
            item.Value = "-1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S1";
            item.Value = "1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S2";
            item.Value = "2";
            list.Add(item);

            cbx.DataSource = list; // bind combobox to a datasource

or use SelectedItem property:

if (cbx.SelectedItem != null)
             Console.WriteLine("ITEM: "+comboBox1.SelectedItem.ToString());

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

I have tried www.wheresmymac.com they are cheap and they have great bandwith so their is low latency. You need teamviewer to log into the virtual system though

json_encode(): Invalid UTF-8 sequence in argument

Using setLocale('fr_FR.UTF8') before json_encode solved the problem.

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

How to make a progress bar

You can use progressbar.js; Animated progress bar control and tiny chart (sparkline)

Demo and download link

enter image description here

HTML usage;

<div id="my-progressbar"></div>

Javascript usage;

var progressBar;

window.onload = function(){

    progressBar = new ProgressBar("my-progressbar", {'width':'100%', 'height':'3px'});
    progressBar.setPercent(60);

}

CKEditor automatically strips classes from div

I found that switching to use full html instead of filtered html (below the editor in the Text Format dropdown box) is what fixed this problem for me. Otherwise the style would disappear.

How to close form

Why not use the DialogResult method to close the form?

if(DialogSettingsCancel.ShowDialog() == DialogResult.Yes)
{
     //this will close the form but will keep application open if your 
     //application type is "console" in the properties of the project
     this.Close();
}

For this to work however you will need to do it inside your "WindowSettings" form while you call the DialogSettingsCancel form. Much the same way you would call the OpenFileDialog, or any other Dialog form.

How can I pass a username/password in the header to a SOAP WCF Service

The answers above are so wrong! DO NOT add custom headers. Judging from your sample xml, it is a standard WS-Security header. WCF definitely supports it out of the box. When you add a service reference you should have basicHttpBinding binding created for you in the config file. You will have to modify it to include security element with mode TransportWithMessageCredential and message element with clientCredentialType = UserName:

<basicHttpBinding>
  <binding name="usernameHttps">
    <security mode="TransportWithMessageCredential">
      <message clientCredentialType="UserName"/>
    </security>
  </binding>
</basicHttpBinding>

The config above is telling WCF to expect userid/password in the SOAP header over HTTPS. Then you can set id/password in your code before making a call:

var service = new MyServiceClient();
service.ClientCredentials.UserName.UserName = "username";
service.ClientCredentials.UserName.Password = "password";

Unless this particular service provider deviated from the standard, it should work.

Check if checkbox is checked with jQuery

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

Laravel requires the Mcrypt PHP extension

In Ubuntu (PHP-FPM,Nginx)

sudo apt-get install php5-mcrypt

After installing php5-mcrypt

you have to make a symlink to ini files in mods-available:

sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/mcrypt.ini

enable:

sudo php5enmod mcrypt

restart php5-fpm:

sudo service php5-fpm restart

More detail

How to get memory usage at runtime using C++?

Old:

maxrss states the maximum available memory for the process. 0 means that no limit is put upon the process. What you probably want is unshared data usage ru_idrss.

New: It seems that the above does not actually work, as the kernel does not fill most of the values. What does work is to get the information from proc. Instead of parsing it oneself though, it is easier to use libproc (part of procps) as follows:

// getrusage.c
#include <stdio.h>
#include <proc/readproc.h>

int main() {
  struct proc_t usage;
  look_up_our_self(&usage);
  printf("usage: %lu\n", usage.vsize);
}

Compile with "gcc -o getrusage getrusage.c -lproc"

Docker-compose: node_modules not present in a volume after npm install succeeds

You can just move node_modules into a / folder.

How it works

FROM node:0.12

WORKDIR /worker

COPY package.json /worker/
RUN npm install \
  && mv node_modules /node_modules

COPY . /worker/

In Python, how do I use urllib to see if a website is 404 or 200?

The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.

>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200

How do I center text horizontally and vertically in a TextView?

<TextView  
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:gravity="center"
android:text="In the center"/>

Above is to set it using .xml file.

but I prefer java version because you can also disable it in code while in running condition if necessary. Following is java code.

textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

What's the best way to check if a String represents an integer in Java?

This is shorter, but shorter isn't necessarily better (and it won't catch integer values which are out of range, as pointed out in danatel's comment):

input.matches("^-?\\d+$");

Personally, since the implementation is squirrelled away in a helper method and correctness trumps length, I would just go with something like what you have (minus catching the base Exception class rather than NumberFormatException).

ActionController::InvalidAuthenticityToken

Just adding the authenticity_token in form fixed it for me.

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

Drop the user, flush the privileges; then, create the user. It does work!

What's the best practice for primary keys in tables?

Natural versus artificial keys to me is a matter of how much of the business logic you want in your database. Social Security number (SSN) is a great example.

"Each client in my database will, and must, have an SSN." Bam, done, make it the primary key and be done with it. Just remember when your business rule changes you're burned.

I don't like natural keys myself, due to my experience with changing business rules. But if your sure it won't change, it might prevent a few critical joins.

How to add a constant column in a Spark DataFrame?

Spark 2.2+

Spark 2.2 introduces typedLit to support Seq, Map, and Tuples (SPARK-19254) and following calls should be supported (Scala):

import org.apache.spark.sql.functions.typedLit

df.withColumn("some_array", typedLit(Seq(1, 2, 3)))
df.withColumn("some_struct", typedLit(("foo", 1, 0.3)))
df.withColumn("some_map", typedLit(Map("key1" -> 1, "key2" -> 2)))

Spark 1.3+ (lit), 1.4+ (array, struct), 2.0+ (map):

The second argument for DataFrame.withColumn should be a Column so you have to use a literal:

from pyspark.sql.functions import lit

df.withColumn('new_column', lit(10))

If you need complex columns you can build these using blocks like array:

from pyspark.sql.functions import array, create_map, struct

df.withColumn("some_array", array(lit(1), lit(2), lit(3)))
df.withColumn("some_struct", struct(lit("foo"), lit(1), lit(.3)))
df.withColumn("some_map", create_map(lit("key1"), lit(1), lit("key2"), lit(2)))

Exactly the same methods can be used in Scala.

import org.apache.spark.sql.functions.{array, lit, map, struct}

df.withColumn("new_column", lit(10))
df.withColumn("map", map(lit("key1"), lit(1), lit("key2"), lit(2)))

To provide names for structs use either alias on each field:

df.withColumn(
    "some_struct",
    struct(lit("foo").alias("x"), lit(1).alias("y"), lit(0.3).alias("z"))
 )

or cast on the whole object

df.withColumn(
    "some_struct", 
    struct(lit("foo"), lit(1), lit(0.3)).cast("struct<x: string, y: integer, z: double>")
 )

It is also possible, although slower, to use an UDF.

Note:

The same constructs can be used to pass constant arguments to UDFs or SQL functions.

How to convert a datetime to string in T-SQL

You can use the convert statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:

SELECT convert(varchar(20), getdate(), 120)

The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS in 24 hour clock.

You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.

How to drop a PostgreSQL database if there are active connections to it?

In PostgreSQL 9.2 and above, to disconnect everything except your session from the database you are connected to:

SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database()
  AND pid <> pg_backend_pid();

In older versions it's the same, just change pid to procpid. To disconnect from a different database just change current_database() to the name of the database you want to disconnect users from.

You may want to REVOKE the CONNECT right from users of the database before disconnecting users, otherwise users will just keep on reconnecting and you'll never get the chance to drop the DB. See this comment and the question it's associated with, How do I detach all other users from the database.

If you just want to disconnect idle users, see this question.

How to fetch data from local JSON file on react native?

Since React Native 0.4.3 you can read your local JSON file like this:

const customData = require('./customData.json');

and then access customData like a normal JS object.

Location of sqlite database on the device

You can find your database file :

Context.getDatabasePath(getDatabaseName())

getDatabaseName from class SQLiteOpenHelper

How to build a query string for a URL in C#?

Same as accepted solution, but transfred to "dot" LINQ syntax...

private string ToQueryString(NameValueCollection nvc)
{
    if (nvc == null) return String.Empty;
    var queryParams = 
          string.Join("&", nvc.AllKeys.Select(key => 
              string.Join("&", nvc.GetValues(key).Select(v => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(v))))));
    return "?" + queryParams;
}

Fastest way to convert string to integer in PHP

More ad-hoc benchmark results:

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = (integer) "-11";}'     

real    2m10.397s
user    2m10.220s
sys     0m0.025s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i += "-11";}'              

real    2m1.724s
user    2m1.635s
sys     0m0.009s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = + "-11";}'             

real    1m21.000s
user    1m20.964s
sys     0m0.007s

How do you overcome the svn 'out of date' error?

Like @Alexander-Klyubin suggests, do the move in the repository. It's also going to be much faster, especially if you have a large amount of data to move, because you won't have to transfer all that data over the network again.

svn mv https://username@server/svn/old/ https://username@server/svn/new/

should work just fine

Passing struct to function

Instead of:

void addStudent(person)
{
    return;
}

try this:

void addStudent(student person)
{
    return;
}

Since you have already declared a structure called 'student' you don't necessarily have to specify so in the function implementation as in:

void addStudent(struct student person)
{
    return;
}

How to make an Asynchronous Method return a value?

Use a BackgroundWorker. It will allow you to get callbacks on completion and allow you to track progress. You can set the Result value on the event arguments to the resulting value.

    public void UseBackgroundWorker()
    {
        var worker = new BackgroundWorker();
        worker.DoWork += DoWork;
        worker.RunWorkerCompleted += WorkDone;
        worker.RunWorkerAsync("input");
    }

    public void DoWork(object sender, DoWorkEventArgs e)
    {
        e.Result = e.Argument.Equals("input");
        Thread.Sleep(1000);
    }

    public void WorkDone(object sender, RunWorkerCompletedEventArgs e)
    {
        var result = (bool) e.Result;
    }

Stop an input field in a form from being submitted

Handle the form's submit in a function via onSubmit() and perform something like below to remove the form element: Use getElementById() of the DOM, then using [object].parentNode.removeChild([object])

suppose your field in question has an id attribute "my_removable_field" code:

var remEl = document.getElementById("my_removable_field");
if ( remEl.parentNode && remEl.parentNode.removeChild ) {
remEl.parentNode.removeChild(remEl);
}

This will get you exactly what you are looking for.

How to create Drawable from resource

If you are trying to get the drawable from the view where the image is set as,

ivshowing.setBackgroundResource(R.drawable.one);

then the drawable will return only null value with the following code...

   Drawable drawable = (Drawable) ivshowing.getDrawable();

So, it's better to set the image with the following code, if you wanna retrieve the drawable from a particular view.

 ivshowing.setImageResource(R.drawable.one);

only then the drawable will we converted exactly.

Abort a Git Merge

Truth be told there are many, many resources explaining how to do this already out on the web:

Git: how to reverse-merge a commit?

Git: how to reverse-merge a commit?

Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)

So I guess I'll just summarize some of these:

  1. git revert <merge commit hash>
    This creates an extra "revert" commit saying you undid a merge

  2. git reset --hard <commit hash *before* the merge>
    This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick them on to afterwards.

But honestly this guide here is better than anything I can explain, with diagrams! :)

what is right way to do API call in react js?

This part from React v16 documentation will answer your question, read on about componentDidMount():

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

As you see, componentDidMount is considered the best place and cycle to do the api call, also access the node, means by this time it's safe to do the call, update the view or whatever you could do when document is ready, if you are using jQuery, it should somehow remind you document.ready() function, where you could make sure everything is ready for whatever you want to do in your code...

EditText underline below text property

You have to use a different background image, not color, for each state of the EditText (focus, enabled, activated).

http://android-holo-colors.com/

In the site above, you can get images from a lot of components in the Holo theme. Just select "EditText" and the color you want. You can see a preview at the bottom of the page.

Download the .zip file, and copy paste the resources in your project (images and the XML).

if your XML is named: apptheme_edit_text_holo_light.xml (or something similar):

  1. Go to your XML "styles.xml" and add the custom EditText style:

    <style name="EditTextCustomHolo" parent="android:Widget.EditText">
       <item name="android:background">@drawable/apptheme_edit_text_holo_light</item>
       <item name="android:textColor">#ffffff</item>
    </style>
    
  2. Just do this in your EditText:

    <EditText
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       style="@style/EditTextCustomHolo"/>
    

And that's it, I hope it helps you.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

I strongly prefer to keep my JavaScript out of my HTML markup as much as possible. If I'm using <a> as click event handlers then I'd recommend using <a class="trigger" href="#">Click me!</a>.

$('.trigger').click(function (e) {
    e.preventDefault();
    // Do stuff...
});

It's very important to note that many developers out there believe that using anchor tags for click-event handlers isn't good. They'd prefer you to use a <span> or <div> with some CSS that adds cursor: pointer; to it. This is a matter if much debate.

Wrap text in <td> tag

I believe you've encountered the catch 22 of tables. Tables are great for wrapping up content in a tabular structure and they do a wonderful job of "stretching" to meet the needs of the content they contain.

By default the table cells will stretch to fit content... thus your text just makes it wider.

There's a few solutions.

1.) You can try setting a max-width on the TD.

<td style="max-width:150px;">

2.) You can try putting your text in a wrapping element (e.g. a span) and set constraints on it.

<td><span style="max-width:150px;">Hello World...</span></td>

Be aware though that older versions of IE don't support min/max-width.

Since IE doesn't support max-width natively you'll need to add a hack if you want to force it to. There's several ways to add a hack, this is just one.

On page load, for IE6 only, get the rendered width of the table (in pixels) then get 15% of that and apply that as the width to the first TD in that column (or TH if you have headers) again, in pixels.

How to set image to fit width of the page using jsPDF?

The API changed since this commit, using version 1.4.1 it's now

var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();

Delete an element from a dictionary

    species = {'HI': {'1': (1215.671, 0.41600000000000004),
  '10': (919.351, 0.0012),
  '1025': (1025.722, 0.0791),
  '11': (918.129, 0.0009199999999999999),
  '12': (917.181, 0.000723),
  '1215': (1215.671, 0.41600000000000004),
  '13': (916.429, 0.0005769999999999999),
  '14': (915.824, 0.000468),
  '15': (915.329, 0.00038500000000000003),
 'CII': {'1036': (1036.3367, 0.11900000000000001), '1334': (1334.532, 0.129)}}

The following code will make a copy of dict species and delete items which are not in trans_HI

trans_HI=['1025','1215']
for transition in species['HI'].copy().keys():
    if transition not in trans_HI:
        species['HI'].pop(transition)

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

In my case, the solution was to make every directory in the directory path readable and accessible by mysql (chmod a+rx). The directory was still specified by its relative path in the command line.

chmod a+rx /tmp
chmod a+rx /tmp/migration
etc.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

You can try adding action="#{yourBean.function1}" on each button (changing of course the method function2, function3, or whatever you need). If that does not work, you can try the same with the onclick event.

Anyway, it would be easier to help you if you tell us what kind of buttons are you trying to use, a4j:commandButton or whatever you are using.

Prevent a webpage from navigating away using JavaScript

If you are catching a browser back/forward button and don't want to navigate away, you can use:

window.addEventListener('popstate', function() {
    if (window.location.origin !== 'http://example.com') {
        // Do something if not your domain
    } else if (window.location.href === 'http://example.com/sign-in/step-1') {
        window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
    } else if (window.location.href === 'http://example.com/sign-in/step-2') {
        window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
    } else {
        // Let it do its thing
    }
});

Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.

Understanding the main method of python

If you import the module (.py) file you are creating now from another python script it will not execute the code within

if __name__ == '__main__':
    ...

If you run the script directly from the console, it will be executed.

Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.

This is expanded upon a little more at python.berkely.edu

What is the behavior difference between return-path, reply-to and from?

I had to add a Return-Path header in emails send by a Redmine instance. I agree with greatwolf only the sender can determine a correct (non default) Return-Path. The case is the following : E-mails are send with the default email address : [email protected] But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ). We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.

Adding/removing items from a JavaScript object with jQuery

Splice is good, everyone explain splice so I didn't explain it. You can also use delete keyword in JavaScript, it's good. You can use $.grep also to manipulate this using jQuery.

The jQuery Way :

data.items = jQuery.grep(
                data.items, 
                function (item,index) { 
                  return item.id !=  "1"; 
                });

DELETE Way:

delete data.items[0]

For Adding PUSH is better the splice, because splice is heavy weighted function. Splice create a new array , if you have a huge size of array then it may be troublesome. delete is sometime useful, after delete if you look for the length of the array then there is no change in length there. So use it wisely.

How can I see the specific value of the sql_mode?

It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:

mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
|            |
+------------+
1 row in set (0.00 sec)

mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode                                                                                                           |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Closing Applications

What role do they play when exiting an application in C#?

The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.

But what is the difference?

One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.

What is the difference between bottom-up and top-down?

rev4: A very eloquent comment by user Sammaron has noted that, perhaps, this answer previously confused top-down and bottom-up. While originally this answer (rev3) and other answers said that "bottom-up is memoization" ("assume the subproblems"), it may be the inverse (that is, "top-down" may be "assume the subproblems" and "bottom-up" may be "compose the subproblems"). Previously, I have read on memoization being a different kind of dynamic programming as opposed to a subtype of dynamic programming. I was quoting that viewpoint despite not subscribing to it. I have rewritten this answer to be agnostic of the terminology until proper references can be found in the literature. I have also converted this answer to a community wiki. Please prefer academic sources. List of references: {Web: 1,2} {Literature: 5}

Recap

Dynamic programming is all about ordering your computations in a way that avoids recalculating duplicate work. You have a main problem (the root of your tree of subproblems), and subproblems (subtrees). The subproblems typically repeat and overlap.

For example, consider your favorite example of Fibonnaci. This is the full tree of subproblems, if we did a naive recursive call:

TOP of the tree
fib(4)
 fib(3)...................... + fib(2)
  fib(2)......... + fib(1)       fib(1)........... + fib(0)
   fib(1) + fib(0)   fib(1)       fib(1)              fib(0)
    fib(1)   fib(0)
BOTTOM of the tree

(In some other rare problems, this tree could be infinite in some branches, representing non-termination, and thus the bottom of the tree may be infinitely large. Furthermore, in some problems you might not know what the full tree looks like ahead of time. Thus, you might need a strategy/algorithm to decide which subproblems to reveal.)


Memoization, Tabulation

There are at least two main techniques of dynamic programming which are not mutually exclusive:

  • Memoization - This is a laissez-faire approach: You assume that you have already computed all subproblems and that you have no idea what the optimal evaluation order is. Typically, you would perform a recursive call (or some iterative equivalent) from the root, and either hope you will get close to the optimal evaluation order, or obtain a proof that you will help you arrive at the optimal evaluation order. You would ensure that the recursive call never recomputes a subproblem because you cache the results, and thus duplicate sub-trees are not recomputed.

    • example: If you are calculating the Fibonacci sequence fib(100), you would just call this, and it would call fib(100)=fib(99)+fib(98), which would call fib(99)=fib(98)+fib(97), ...etc..., which would call fib(2)=fib(1)+fib(0)=1+0=1. Then it would finally resolve fib(3)=fib(2)+fib(1), but it doesn't need to recalculate fib(2), because we cached it.
    • This starts at the top of the tree and evaluates the subproblems from the leaves/subtrees back up towards the root.
  • Tabulation - You can also think of dynamic programming as a "table-filling" algorithm (though usually multidimensional, this 'table' may have non-Euclidean geometry in very rare cases*). This is like memoization but more active, and involves one additional step: You must pick, ahead of time, the exact order in which you will do your computations. This should not imply that the order must be static, but that you have much more flexibility than memoization.

    • example: If you are performing fibonacci, you might choose to calculate the numbers in this order: fib(2),fib(3),fib(4)... caching every value so you can compute the next ones more easily. You can also think of it as filling up a table (another form of caching).
    • I personally do not hear the word 'tabulation' a lot, but it's a very decent term. Some people consider this "dynamic programming".
    • Before running the algorithm, the programmer considers the whole tree, then writes an algorithm to evaluate the subproblems in a particular order towards the root, generally filling in a table.
    • *footnote: Sometimes the 'table' is not a rectangular table with grid-like connectivity, per se. Rather, it may have a more complicated structure, such as a tree, or a structure specific to the problem domain (e.g. cities within flying distance on a map), or even a trellis diagram, which, while grid-like, does not have a up-down-left-right connectivity structure, etc. For example, user3290797 linked a dynamic programming example of finding the maximum independent set in a tree, which corresponds to filling in the blanks in a tree.

(At it's most general, in a "dynamic programming" paradigm, I would say the programmer considers the whole tree, then writes an algorithm that implements a strategy for evaluating subproblems which can optimize whatever properties you want (usually a combination of time-complexity and space-complexity). Your strategy must start somewhere, with some particular subproblem, and perhaps may adapt itself based on the results of those evaluations. In the general sense of "dynamic programming", you might try to cache these subproblems, and more generally, try avoid revisiting subproblems with a subtle distinction perhaps being the case of graphs in various data structures. Very often, these data structures are at their core like arrays or tables. Solutions to subproblems can be thrown away if we don't need them anymore.)

[Previously, this answer made a statement about the top-down vs bottom-up terminology; there are clearly two main approaches called Memoization and Tabulation that may be in bijection with those terms (though not entirely). The general term most people use is still "Dynamic Programming" and some people say "Memoization" to refer to that particular subtype of "Dynamic Programming." This answer declines to say which is top-down and bottom-up until the community can find proper references in academic papers. Ultimately, it is important to understand the distinction rather than the terminology.]


Pros and cons

Ease of coding

Memoization is very easy to code (you can generally* write a "memoizer" annotation or wrapper function that automatically does it for you), and should be your first line of approach. The downside of tabulation is that you have to come up with an ordering.

*(this is actually only easy if you are writing the function yourself, and/or coding in an impure/non-functional programming language... for example if someone already wrote a precompiled fib function, it necessarily makes recursive calls to itself, and you can't magically memoize the function without ensuring those recursive calls call your new memoized function (and not the original unmemoized function))

Recursiveness

Note that both top-down and bottom-up can be implemented with recursion or iterative table-filling, though it may not be natural.

Practical concerns

With memoization, if the tree is very deep (e.g. fib(10^6)), you will run out of stack space, because each delayed computation must be put on the stack, and you will have 10^6 of them.

Optimality

Either approach may not be time-optimal if the order you happen (or try to) visit subproblems is not optimal, specifically if there is more than one way to calculate a subproblem (normally caching would resolve this, but it's theoretically possible that caching might not in some exotic cases). Memoization will usually add on your time-complexity to your space-complexity (e.g. with tabulation you have more liberty to throw away calculations, like using tabulation with Fib lets you use O(1) space, but memoization with Fib uses O(N) stack space).

Advanced optimizations

If you are also doing a extremely complicated problems, you might have no choice but to do tabulation (or at least take a more active role in steering the memoization where you want it to go). Also if you are in a situation where optimization is absolutely critical and you must optimize, tabulation will allow you to do optimizations which memoization would not otherwise let you do in a sane way. In my humble opinion, in normal software engineering, neither of these two cases ever come up, so I would just use memoization ("a function which caches its answers") unless something (such as stack space) makes tabulation necessary... though technically to avoid a stack blowout you can 1) increase the stack size limit in languages which allow it, or 2) eat a constant factor of extra work to virtualize your stack (ick), or 3) program in continuation-passing style, which in effect also virtualizes your stack (not sure the complexity of this, but basically you will effectively take the deferred call chain from the stack of size N and de-facto stick it in N successively nested thunk functions... though in some languages without tail-call optimization you may have to trampoline things to avoid a stack blowout).


More complicated examples

Here we list examples of particular interest, that are not just general DP problems, but interestingly distinguish memoization and tabulation. For example, one formulation might be much easier than the other, or there may be an optimization which basically requires tabulation:

  • the algorithm to calculate edit-distance[4], interesting as a non-trivial example of a two-dimensional table-filling algorithm

Difference between matches() and find() in Java Regex

matches() will only return true if the full string is matched. find() will try to find the next occurrence within the substring that matches the regex. Note the emphasis on "the next". That means, the result of calling find() multiple times might not be the same. In addition, by using find() you can call start() to return the position the substring was matched.

final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + subMatcher.matches());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find());
System.out.println("Found: " + subMatcher.find());
System.out.println("Matched: " + subMatcher.matches());

System.out.println("-----------");
final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());

Will output:

Found: false
Found: true - position 4
Found: true - position 17
Found: true - position 20
Found: false
Found: false
Matched: false
-----------
Found: true - position 0
Found: false
Found: false
Matched: true
Matched: true
Matched: true
Matched: true

So, be careful when calling find() multiple times if the Matcher object was not reset, even when the regex is surrounded with ^ and $ to match the full string.

Iterate through a C array

I think you should store the size somewhere.

The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.

Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.

P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.

Search an Oracle database for tables with specific column names?

Here is one that we have saved off to findcol.sql so we can run it easily from within SQLPlus

set verify off
clear break
accept colnam prompt 'Enter Column Name (or part of): '
set wrap off
select distinct table_name, 
                column_name, 
                data_type || ' (' || 
                decode(data_type,'LONG',null,'LONG RAW',null,
                       'BLOB',null,'CLOB',null,'NUMBER',
                       decode(data_precision,null,to_char(data_length),
                              data_precision||','||data_scale
                             ), data_length
                      ) || ')' data_type
  from all_tab_columns
 where column_name like ('%' || upper('&colnam') || '%');
set verify on

Soft keyboard open and close listener in an activity in Android

Jaap's answer won't work for AppCompatActivity. Instead get the height of the Status Bar and Navigation bar etc and compare to your app's window size.

Like so:

    private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        // navigation bar height
        int navigationBarHeight = 0;
        int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            navigationBarHeight = getResources().getDimensionPixelSize(resourceId);
        }

        // status bar height
        int statusBarHeight = 0;
        resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }

        // display window size for the app layout
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

        // screen height - (user app height + status + nav) ..... if non-zero, then there is a soft keyboard
        int keyboardHeight = rootLayout.getRootView().getHeight() - (statusBarHeight + navigationBarHeight + rect.height());

        if (keyboardHeight <= 0) {
            onHideKeyboard();
        } else {
            onShowKeyboard(keyboardHeight);
        }
    }
};

Position an element relative to its container

I know I am late but hope this helps.

Following are the values for the position property.

  • static
  • fixed
  • relative
  • absolute

position : static

This is default. It means the element will occur at a position that it normally would.

#myelem {
    position : static;
}

position : fixed

This will set the position of an element with respect to the browser window (viewport). A fixed positioned element will remain in its position even when the page scrolls.

(Ideal if you want scroll-to-top button at the bottom right corner of the page).

#myelem {
    position : fixed;
    bottom : 30px;
    right : 30px;
}

position : relative

To place an element at a new location relative to its original position.

#myelem {
    position : relative;
    left : 30px;
    top : 30px;
}

The above CSS will move the #myelem element 30px to the left and 30px from the top of its actual location.

position : absolute

If we want an element to be placed at an exact position in the page.

#myelem {
    position : absolute;
    top : 30px;
    left : 300px;
}

The above CSS will position #myelem element at a position 30px from top and 300px from the left in the page and it will scroll with the page.

And finally...

position relative + absolute

We can set the position property of a parent element to relative and then set the position property of the child element to absolute. This way we can position the child relative to the parent at an absolute position.

#container {
    position : relative;
}

#div-2 {
    position : absolute;
    top : 0;
    right : 0;
}

Absolute position of a child element w.r.t. a Relative positioned parent element.

We can see in the above image the #div-2 element is positioned at the top-right corner inside the #container element.

GitHub: You can find the HTML of the above image here and CSS here.

Hope this tutorial helps.

How to destroy a DOM element with jQuery?

If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...

console.log($target);   // jQuery object
$target.remove();       // remove target from the DOM
console.log($target);   // $target still exists

Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)

$target = $();
console.log($target);   // empty jQuery object

Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)

delete $target;
console.log($target);   // error: $target is not defined

More reading: info about empty jQuery object, and info about delete

how to find my angular version in my project?

There are several ways you can do that:

  1. Go into node_modules/@angular/core/package.json and check version field.
  2. If you need to use it in your code, you can import it from the @angular/core:

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

  3. Inspect the rendered DOM - Angular adds the version to the main component element:

    <my-app ng-version="4.1.3">

Why doesn't the Scanner class have a nextChar method?

According to the javadoc a Scanner does not seem to be intended for reading single characters. You attach a Scanner to an InputStream (or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

_x000D_
_x000D_
.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

_x000D_
_x000D_
div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
_x000D_
_x000D_

(Or JSFiddle)

HTML CSS Invisible Button

You can use CSS to hide the button.

button {
  visibility: hidden;
}

If your <button> is just a clickable area on the image, why bother make it a button? You can use <map> element instead.

What exactly does an #if 0 ..... #endif block do?

Not only does it not get executed, it doesn't even get compiled.

#if is a preprocessor command, which gets evaluated before the actual compilation step. The code inside that block doesn't appear in the compiled binary.

It's often used for temporarily removing segments of code with the intention of turning them back on later.

Why is document.body null in my javascript?

Your script is being executed before the body element has even loaded.

There are a couple ways to workaround this.

  • Wrap your code in a DOM Load callback:

    Wrap your logic in an event listener for DOMContentLoaded.

    In doing so, the callback will be executed when the body element has loaded.

    document.addEventListener('DOMContentLoaded', function () {
        // ...
        // Place code here.
        // ...
    });
    

    Depending on your needs, you can alternatively attach a load event listener to the window object:

    window.addEventListener('load', function () {
        // ...
        // Place code here.
        // ...
    });
    

    For the difference between between the DOMContentLoaded and load events, see this question.

  • Move the position of your <script> element, and load JavaScript last:

    Right now, your <script> element is being loaded in the <head> element of your document. This means that it will be executed before the body has loaded. Google developers recommends moving the <script> tags to the end of your page so that all the HTML content is rendered before the JavaScript is processed.

    <!DOCTYPE html>
    <html>
    <head></head>
    <body>
      <p>Some paragraph</p>
      <!-- End of HTML content in the body tag -->
    
      <script>
        <!-- Place your script tags here. -->
      </script>
    </body>
    </html>
    

How to write character & in android strings.xml

To avoid the error, use extract string:

<string name="travels_tours_pvt_ltd"><![CDATA[Travels & Tours (Pvt) Ltd.]]></string>

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

I had a lecturer who once suggested generating a random array, checking if it was sorted and then checking if the data was the same as the array to be sorted.

Best case O(N) (first time baby!) Worst case O(Never)

Call a function after previous function is complete

If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :

function function1 (someVariable) {
    var date = Date.now ();
    while (Date.now () - date < 2000);      // function1 takes some time to complete
    console.log (someVariable);
}
function function2 (someVariable) {
    console.log (someVariable);
}
function onClick () {
    window.setTimeout (() => { function1 ("This is function1"); }, 0);
    window.setTimeout (() => { function2 ("This is function2"); }, 0);
    console.log ("Click handled");  // To show that the function will return before both functions are executed
}
onClick ();

The output will be :

Click handled

...and after 2 seconds :

This is function 1
This is function 2

This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.

Notice that this as funny as it may the code difficult to understand...

Base64 String throwing invalid character error

You say

The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything).

In fact, it does do something (it causes your code to throw a FormatException:"Invalid character in a Base-64 string") because the Convert.FromBase64String does not consider "\0" to be a valid Base64 character.

  byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
  byte[] data2 = Convert.FromBase64String("AAAA");   // Works

Solution: Get rid of the zero termination. (Maybe call .Trim("\0"))

Notes:

The MSDN docs for Convert.FromBase64String say it will throw a FormatException when

The length of s, ignoring white space characters, is not zero or a multiple of 4.

-or-

The format of s is invalid. s contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.

and that

The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'.

npm install private github repositories by dependency in package.json

Here is a more detailed version of how to use the Github token without publishing in the package.json file.

  1. Create personal github access token
  2. Setup url rewrite in ~/.gitconfig
git config --global url."https://<TOKEN HERE>:[email protected]/".insteadOf https://[email protected]/
  1. Install private repository. Verbose log level for debugging access errors.
npm install --loglevel verbose --save git+https://[email protected]/<USERNAME HERE>/<REPOSITORY HERE>.git#v0.1.27

In case access to Github fails, try running the git ls-remote ... command that the npm install will print

Open a facebook link by native Facebook app on iOS

I did this in MonoTouch in the following method, I'm sure a pure Obj-C based approach wouldn't be too different. I used this inside a class which had changing URLs at times which is why I just didn't put it in a if/elseif statement.

NSString *myUrls = @"fb://profile/100000369031300|http://www.facebook.com/ytn3rd";
NSArray *urls = [myUrls componentsSeparatedByString:@"|"];
for (NSString *url in urls){
    NSURL *nsurl = [NSURL URLWithString:url];
    if ([[UIApplication sharedApplication] canOpenURL:nsurl]){
        [[UIApplication sharedApplication] openURL:nsurl];
        break;
    }
}

The break is not always called before your app changes to Safari/Facebook. I assume your program will halt there and call it when you come back to it.

Tensorflow: Using Adam optimizer

FailedPreconditionError: Attempting to use uninitialized value is one of the most frequent errors related to tensorflow. From official documentation, FailedPreconditionError

This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.

In your case the error even explains what variable was not initialized: Attempting to use uninitialized value Variable_1. One of the TF tutorials explains a lot about variables, their creation/initialization/saving/loading

Basically to initialize the variable you have 3 options:

I almost always use the first approach. Remember you should put it inside a session run. So you will get something like this:

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

If your are curious about more information about variables, read this documentation to know how to report_uninitialized_variables and check is_variable_initialized.

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

Typically, I store a TimeSpan as a bigint populated with ticks from the TimeSpan.Ticks property as previously suggested. You can also store a TimeSpan as a varchar(26) populated with the output of TimeSpan.ToString(). The four scalar functions (ConvertFromTimeSpanString, ConvertToTimeSpanString, DateAddTicks, DateDiffTicks) that I wrote are helpful for handling TimeSpan on the SQL side and avoid the hacks that would produce artificially bounded ranges. If you can store the interval in a .NET TimeSpan at all it should work with these functions also. Additionally, the functions allow you to work with TimeSpans and 100-nanosecond ticks even when using technologies that don't include the .NET Framework.

DROP FUNCTION [dbo].[DateDiffTicks]
GO

DROP FUNCTION [dbo].[DateAddTicks]
GO

DROP FUNCTION [dbo].[ConvertToTimeSpanString]
GO

DROP FUNCTION [dbo].[ConvertFromTimeSpanString]
GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

-- =============================================
-- Author:      James Coe
-- Create date: 2011-05-23
-- Description: Converts from a varchar(26) TimeSpan string to a bigint containing the number of 100 nanosecond ticks.
-- =============================================
/*
    [-][d.]hh:mm:ss[.fffffff] 

    "-" 
     A minus sign, which indicates a negative time interval. No sign is included for a positive time span.

    "d" 
     The number of days in the time interval. This element is omitted if the time interval is less than one day. 

    "hh" 
     The number of hours in the time interval, ranging from 0 to 23. 

    "mm" 
     The number of minutes in the time interval, ranging from 0 to 59. 

    "ss" 
     The number of seconds in the time interval, ranging from 0 to 59. 

    "fffffff" 
     Fractional seconds in the time interval. This element is omitted if the time interval does not include 
     fractional seconds. If present, fractional seconds are always expressed using seven decimal digits.
    */
CREATE FUNCTION [dbo].[ConvertFromTimeSpanString] (@timeSpan varchar(26))
RETURNS bigint
AS
BEGIN
    DECLARE @hourStart int
    DECLARE @minuteStart int
    DECLARE @secondStart int
    DECLARE @ticks bigint
    DECLARE @hours bigint
    DECLARE @minutes bigint
    DECLARE @seconds DECIMAL(9, 7)

    SET @hourStart = CHARINDEX('.', @timeSpan) + 1
    SET @minuteStart = CHARINDEX(':', @timeSpan) + 1
    SET @secondStart = CHARINDEX(':', @timespan, @minuteStart) + 1
    SET @ticks = 0

    IF (@hourStart > 1 AND @hourStart < @minuteStart)
    BEGIN
        SET @ticks = CONVERT(bigint, LEFT(@timespan, @hourstart - 2)) * 864000000000
    END
    ELSE
    BEGIN
        SET @hourStart = 1
    END

    SET @hours = CONVERT(bigint, SUBSTRING(@timespan, @hourStart, @minuteStart - @hourStart - 1))
    SET @minutes = CONVERT(bigint, SUBSTRING(@timespan, @minuteStart, @secondStart - @minuteStart - 1))
    SET @seconds = CONVERT(DECIMAL(9, 7), SUBSTRING(@timespan, @secondStart, LEN(@timeSpan) - @secondStart + 1))

    IF (@ticks < 0)
    BEGIN
        SET @ticks = @ticks - @hours * 36000000000
    END
    ELSE
    BEGIN
        SET @ticks = @ticks + @hours * 36000000000
    END

    IF (@ticks < 0)
    BEGIN
        SET @ticks = @ticks - @minutes * 600000000
    END
    ELSE
    BEGIN
        SET @ticks = @ticks + @minutes * 600000000
    END

    IF (@ticks < 0)
    BEGIN
        SET @ticks = @ticks - @seconds * 10000000.0
    END
    ELSE
    BEGIN
        SET @ticks = @ticks + @seconds * 10000000.0
    END

    RETURN @ticks
END
GO

-- =============================================
-- Author:      James Coe
-- Create date: 2011-05-23
-- Description: Converts from a bigint containing the number of 100 nanosecond ticks to a varchar(26) TimeSpan string.
-- =============================================
/*
[-][d.]hh:mm:ss[.fffffff] 

"-" 
 A minus sign, which indicates a negative time interval. No sign is included for a positive time span.

"d" 
 The number of days in the time interval. This element is omitted if the time interval is less than one day. 

"hh" 
 The number of hours in the time interval, ranging from 0 to 23. 

"mm" 
 The number of minutes in the time interval, ranging from 0 to 59. 

"ss" 
 The number of seconds in the time interval, ranging from 0 to 59. 

"fffffff" 
 Fractional seconds in the time interval. This element is omitted if the time interval does not include 
 fractional seconds. If present, fractional seconds are always expressed using seven decimal digits.
*/
CREATE FUNCTION [dbo].[ConvertToTimeSpanString] (@ticks bigint)
RETURNS varchar(26)
AS
BEGIN
    DECLARE @timeSpanString varchar(26)

    IF (@ticks < 0)
    BEGIN
        SET @timeSpanString = '-'
    END
    ELSE
    BEGIN
        SET @timeSpanString = ''
    END

    -- Days
    DECLARE @days bigint

    SET @days = FLOOR(ABS(@ticks / 864000000000.0))

    IF (@days > 0)
    BEGIN
        SET @timeSpanString = @timeSpanString + CONVERT(varchar(26), @days) + '.'
    END

    SET @ticks = ABS(@ticks % 864000000000)
    -- Hours
    SET @timeSpanString = @timeSpanString + RIGHT('0' + CONVERT(varchar(26), FLOOR(@ticks / 36000000000.0)), 2) + ':'
    SET @ticks = @ticks % 36000000000
    -- Minutes
    SET @timeSpanString = @timeSpanString + RIGHT('0' + CONVERT(varchar(26), FLOOR(@ticks / 600000000.0)), 2) + ':'
    SET @ticks = @ticks % 600000000
    -- Seconds
    SET @timeSpanString = @timeSpanString + RIGHT('0' + CONVERT(varchar(26), FLOOR(@ticks / 10000000.0)), 2)
    SET @ticks = @ticks % 10000000

    -- Fractional Seconds
    IF (@ticks > 0)
    BEGIN
        SET @timeSpanString = @timeSpanString + '.' + LEFT(CONVERT(varchar(26), @ticks) + '0000000', 7)
    END

    RETURN @timeSpanString
END
GO

-- =============================================
-- Author:      James Coe
-- Create date: 2011-05-23
-- Description: Adds the specified number of 100 nanosecond ticks to a date.
-- =============================================
CREATE FUNCTION [dbo].[DateAddTicks] (
    @ticks bigint
    , @starting_date datetimeoffset
    )
RETURNS datetimeoffset
AS
BEGIN
    DECLARE @dateTimeResult datetimeoffset

    IF (@ticks < 0)
    BEGIN
        -- Hours
        SET @dateTimeResult = DATEADD(HOUR, CEILING(@ticks / 36000000000.0), @starting_date)
        SET @ticks = @ticks % 36000000000
        -- Seconds
        SET @dateTimeResult = DATEADD(SECOND, CEILING(@ticks / 10000000.0), @dateTimeResult)
        SET @ticks = @ticks % 10000000
        -- Nanoseconds
        SET @dateTimeResult = DATEADD(NANOSECOND, @ticks * 100, @dateTimeResult)
    END
    ELSE
    BEGIN
        -- Hours
        SET @dateTimeResult = DATEADD(HOUR, FLOOR(@ticks / 36000000000.0), @starting_date)
        SET @ticks = @ticks % 36000000000
        -- Seconds
        SET @dateTimeResult = DATEADD(SECOND, FLOOR(@ticks / 10000000.0), @dateTimeResult)
        SET @ticks = @ticks % 10000000
        -- Nanoseconds
        SET @dateTimeResult = DATEADD(NANOSECOND, @ticks * 100, @dateTimeResult)
    END

    RETURN @dateTimeResult
END
GO

-- =============================================
-- Author:      James Coe
-- Create date: 2011-05-23
-- Description:  Gets the difference between two dates in 100 nanosecond ticks.
-- =============================================
CREATE FUNCTION [dbo].[DateDiffTicks] (
    @starting_date datetimeoffset
    , @ending_date datetimeoffset
    )
RETURNS bigint
AS
BEGIN
    DECLARE @ticks bigint
    DECLARE @days bigint
    DECLARE @hours bigint
    DECLARE @minutes bigint
    DECLARE @seconds bigint

    SET @hours = DATEDIFF(HOUR, @starting_date, @ending_date)
    SET @starting_date = DATEADD(HOUR, @hours, @starting_date)
    SET @ticks = @hours * 36000000000
    SET @seconds = DATEDIFF(SECOND, @starting_date, @ending_date)
    SET @starting_date = DATEADD(SECOND, @seconds, @starting_date)
    SET @ticks = @ticks + @seconds * 10000000
    SET @ticks = @ticks + CONVERT(bigint, DATEDIFF(NANOSECOND, @starting_date, @ending_date)) / 100

    RETURN @ticks
END
GO

--- BEGIN Test Harness ---
SET NOCOUNT ON

DECLARE @dateTimeOffsetMinValue datetimeoffset
DECLARE @dateTimeOffsetMaxValue datetimeoffset
DECLARE @timeSpanMinValueString varchar(26)
DECLARE @timeSpanZeroString varchar(26)
DECLARE @timeSpanMaxValueString varchar(26)
DECLARE @timeSpanMinValueTicks bigint
DECLARE @timeSpanZeroTicks bigint
DECLARE @timeSpanMaxValueTicks bigint
DECLARE @dateTimeOffsetMinMaxDiffTicks bigint
DECLARE @dateTimeOffsetMaxMinDiffTicks bigint

SET @dateTimeOffsetMinValue = '0001-01-01T00:00:00.0000000+00:00'
SET @dateTimeOffsetMaxValue = '9999-12-31T23:59:59.9999999+00:00'
SET @timeSpanMinValueString = '-10675199.02:48:05.4775808'
SET @timeSpanZeroString = '00:00:00'
SET @timeSpanMaxValueString = '10675199.02:48:05.4775807'
SET @timeSpanMinValueTicks = -9223372036854775808
SET @timeSpanZeroTicks = 0
SET @timeSpanMaxValueTicks = 9223372036854775807
SET @dateTimeOffsetMinMaxDiffTicks = 3155378975999999999
SET @dateTimeOffsetMaxMinDiffTicks = -3155378975999999999

-- TimeSpan Conversion Tests
PRINT 'Testing TimeSpan conversions...'

DECLARE @convertToTimeSpanStringMinTicksResult varchar(26)
DECLARE @convertFromTimeSpanStringMinTimeSpanResult bigint
DECLARE @convertToTimeSpanStringZeroTicksResult varchar(26)
DECLARE @convertFromTimeSpanStringZeroTimeSpanResult bigint
DECLARE @convertToTimeSpanStringMaxTicksResult varchar(26)
DECLARE @convertFromTimeSpanStringMaxTimeSpanResult bigint

SET @convertToTimeSpanStringMinTicksResult = dbo.ConvertToTimeSpanString(@timeSpanMinValueTicks)
SET @convertFromTimeSpanStringMinTimeSpanResult = dbo.ConvertFromTimeSpanString(@timeSpanMinValueString)
SET @convertToTimeSpanStringZeroTicksResult = dbo.ConvertToTimeSpanString(@timeSpanZeroTicks)
SET @convertFromTimeSpanStringZeroTimeSpanResult = dbo.ConvertFromTimeSpanString(@timeSpanZeroString)
SET @convertToTimeSpanStringMaxTicksResult = dbo.ConvertToTimeSpanString(@timeSpanMaxValueTicks)
SET @convertFromTimeSpanStringMaxTimeSpanResult = dbo.ConvertFromTimeSpanString(@timeSpanMaxValueString)

-- Test Results
SELECT 'Convert to TimeSpan String from Ticks (Minimum)' AS Test
    , CASE 
        WHEN @convertToTimeSpanStringMinTicksResult = @timeSpanMinValueString
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @timeSpanMinValueTicks AS [Ticks]
    , CONVERT(varchar(26), NULL) AS [TimeSpan String]
    , CONVERT(varchar(26), @convertToTimeSpanStringMinTicksResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanMinValueString) AS [Expected Result]
UNION ALL
SELECT 'Convert from TimeSpan String to Ticks (Minimum)' AS Test
    , CASE 
        WHEN @convertFromTimeSpanStringMinTimeSpanResult = @timeSpanMinValueTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , NULL AS [Ticks]
    , @timeSpanMinValueString AS [TimeSpan String]
    , CONVERT(varchar(26), @convertFromTimeSpanStringMinTimeSpanResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanMinValueTicks) AS [Expected Result]
UNION ALL
SELECT 'Convert to TimeSpan String from Ticks (Zero)' AS Test
    , CASE 
        WHEN @convertToTimeSpanStringZeroTicksResult = @timeSpanZeroString
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @timeSpanZeroTicks AS [Ticks]
    , CONVERT(varchar(26), NULL) AS [TimeSpan String]
    , CONVERT(varchar(26), @convertToTimeSpanStringZeroTicksResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanZeroString) AS [Expected Result]
UNION ALL
SELECT 'Convert from TimeSpan String to Ticks (Zero)' AS Test
    , CASE 
        WHEN @convertFromTimeSpanStringZeroTimeSpanResult = @timeSpanZeroTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , NULL AS [Ticks]
    , @timeSpanZeroString AS [TimeSpan String]
    , CONVERT(varchar(26), @convertFromTimeSpanStringZeroTimeSpanResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanZeroTicks) AS [Expected Result]
UNION ALL
SELECT 'Convert to TimeSpan String from Ticks (Maximum)' AS Test
    , CASE 
        WHEN @convertToTimeSpanStringMaxTicksResult = @timeSpanMaxValueString
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @timeSpanMaxValueTicks AS [Ticks]
    , CONVERT(varchar(26), NULL) AS [TimeSpan String]
    , CONVERT(varchar(26), @convertToTimeSpanStringMaxTicksResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanMaxValueString) AS [Expected Result]
UNION ALL
SELECT 'Convert from TimeSpan String to Ticks (Maximum)' AS Test
    , CASE 
        WHEN @convertFromTimeSpanStringMaxTimeSpanResult = @timeSpanMaxValueTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , NULL AS [Ticks]
    , @timeSpanMaxValueString AS [TimeSpan String]
    , CONVERT(varchar(26), @convertFromTimeSpanStringMaxTimeSpanResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanMaxValueTicks) AS [Expected Result]

-- Ticks Date Add Test
PRINT 'Testing DateAddTicks...'

DECLARE @DateAddTicksPositiveTicksResult datetimeoffset
DECLARE @DateAddTicksZeroTicksResult datetimeoffset
DECLARE @DateAddTicksNegativeTicksResult datetimeoffset

SET @DateAddTicksPositiveTicksResult = dbo.DateAddTicks(@dateTimeOffsetMinMaxDiffTicks, @dateTimeOffsetMinValue)
SET @DateAddTicksZeroTicksResult = dbo.DateAddTicks(@timeSpanZeroTicks, @dateTimeOffsetMinValue)
SET @DateAddTicksNegativeTicksResult = dbo.DateAddTicks(@dateTimeOffsetMaxMinDiffTicks, @dateTimeOffsetMaxValue)

-- Test Results
SELECT 'Date Add with Ticks Test (Positive)' AS Test
    , CASE 
        WHEN @DateAddTicksPositiveTicksResult = @dateTimeOffsetMaxValue
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @dateTimeOffsetMinMaxDiffTicks AS [Ticks]
    , @dateTimeOffsetMinValue AS [Starting Date]
    , @DateAddTicksPositiveTicksResult AS [Actual Result]
    , @dateTimeOffsetMaxValue AS [Expected Result]
UNION ALL
SELECT 'Date Add with Ticks Test (Zero)' AS Test
    , CASE 
        WHEN @DateAddTicksZeroTicksResult = @dateTimeOffsetMinValue
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @timeSpanZeroTicks AS [Ticks]
    , @dateTimeOffsetMinValue AS [Starting Date]
    , @DateAddTicksZeroTicksResult AS [Actual Result]
    , @dateTimeOffsetMinValue AS [Expected Result]
UNION ALL
SELECT 'Date Add with Ticks Test (Negative)' AS Test
    , CASE 
        WHEN @DateAddTicksNegativeTicksResult = @dateTimeOffsetMinValue
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @dateTimeOffsetMaxMinDiffTicks AS [Ticks]
    , @dateTimeOffsetMaxValue AS [Starting Date]
    , @DateAddTicksNegativeTicksResult AS [Actual Result]
    , @dateTimeOffsetMinValue AS [Expected Result]

-- Ticks Date Diff Test
PRINT 'Testing Date Diff Ticks...'

DECLARE @dateDiffTicksMinMaxResult bigint
DECLARE @dateDiffTicksMaxMinResult bigint

SET @dateDiffTicksMinMaxResult = dbo.DateDiffTicks(@dateTimeOffsetMinValue, @dateTimeOffsetMaxValue)
SET @dateDiffTicksMaxMinResult = dbo.DateDiffTicks(@dateTimeOffsetMaxValue, @dateTimeOffsetMinValue)

-- Test Results
SELECT 'Date Difference in Ticks Test (Min, Max)' AS Test
    , CASE 
        WHEN @dateDiffTicksMinMaxResult = @dateTimeOffsetMinMaxDiffTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @dateTimeOffsetMinValue AS [Starting Date]
    , @dateTimeOffsetMaxValue AS [Ending Date]
    , @dateDiffTicksMinMaxResult AS [Actual Result]
    , @dateTimeOffsetMinMaxDiffTicks AS [Expected Result]
UNION ALL
SELECT 'Date Difference in Ticks Test (Max, Min)' AS Test
    , CASE 
        WHEN @dateDiffTicksMaxMinResult = @dateTimeOffsetMaxMinDiffTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @dateTimeOffsetMaxValue AS [Starting Date]
    , @dateTimeOffsetMinValue AS [Ending Date]
    , @dateDiffTicksMaxMinResult AS [Actual Result]
    , @dateTimeOffsetMaxMinDiffTicks AS [Expected Result]

PRINT 'Tests Complete.'
GO
--- END Test Harness ---

Is it possible to animate scrollTop with jQuery?

Nick's answer works great. Be careful when specifying a complete() function inside the animate() call because it will get executed twice since you have two selectors declared (html and body).

$("html, body").animate(
    { scrollTop: "300px" },
    {
        complete : function(){
            alert('this alert will popup twice');
        }
    }
);

Here's how you can avoid the double callback.

var completeCalled = false;
$("html, body").animate(
    { scrollTop: "300px" },
    {
        complete : function(){
            if(!completeCalled){
                completeCalled = true;
                alert('this alert will popup once');
            }
        }
    }
);

Selecting the first "n" items with jQuery

.slice() isn't always better. In my case, with jQuery 1.7 in Chrome 36, .slice(0, 20) failed with error:

RangeError: Maximum call stack size exceeded

I found that :lt(20) worked without error in this case. I had probably tens of thousands of matching elements.

Which type of folder structure should be used with Angular 2?

Here's mine

app
|
|-- shared (for html shared between modules)
|   |
|   |-- layouts
|   |   |
|   |   |-- default
|   |   |   |-- default.component.ts|html|scss|spec.ts
|   |   |   |-- default.module.ts
|   |   |
|   |   |-- fullwidth
|   |       |-- fullwidth.component.ts|html|scss|spec.ts
|   |       |-- fullwidth.module.ts
|   |
|   |-- components
|   |   |-- footer
|   |   |   |-- footer.component.ts|html|scss|spec.ts
|   |   |-- header
|   |   |   |-- header.component.ts|html|scss|spec.ts
|   |   |-- sidebar
|   |   |   |-- sidebar.component.ts|html|scss|spec.ts
|   |
|   |-- widgets
|   |   |-- card
|   |   |-- chart
|   |   |-- table
|   |
|   |-- shared.module.ts
|
|-- core (for code shared between modules)
|   |
|   |-- services
|   |-- guards
|   |-- helpers
|   |-- models
|   |-- pipes
|   |-- core.module.ts
|
|-- modules (each module contains its own set)
|   |
|   |-- dashboard
|   |-- users
|   |-- books
|       |-- components -> folders
|       |-- models
|       |-- guards
|       |-- books.service.ts
|       |-- books.module.ts
|
|-- material
|   |-- material.module.ts

Pure CSS multi-level drop-down menu

<div class="example" align="center">
    <div class="menuholder">
        <ul class="menu slide">
            <li><a href="index.php?id=1" class="blue">Home</a></li>
        <li><a href="index.php?id=14" class="blue">About Us</a></li>
            <li><a href="index.php?id=4" class="blue">Mens</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=15">Coats & Jackets</a></dd>
                        <dd><a href="index.php?id=22">Chinos</a></dd>
                        <dd><a href="index.php?id=23">Jeans</a></dd>
                        <dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
                        <dd><a href="index.php?id=25">Linen</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=26">Polo Shirts</a></dd>
                        <dd><a href="index.php?id=16">Shirts Casual</a></dd>
                        <dd><a href="index.php?id=27">Shirts Formal</a></dd>
                        <dd><a href="index.php?id=28">Shorts</a></dd>
                        <dd><a href="index.php?id=18">Sportswear</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
                        <dd><a href="index.php?id=20">Trousers Casual</a></dd>
                        <dd><a href="index.php?id=29">Trousers Formal</a></dd>
                        <dd><a href="index.php?id=30">Nightwear</a></dd>
                        <dd><a href="index.php?id=17">Socks</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=21">Underwear</a></dd>
                        <dd><a href="index.php?id=31">Swimwear</a></dd>
                    </dl>
                </div>
            </li>
            <!--menu-->
                        <li><a href="index.php?id=5" class="blue">Ladie's</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=32">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=33">Dresses</a></dd>
                          <dd><a href="index.php?id=34">Jeans</a></dd>
                          <dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=36">Jumpsuits</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
                          <dd><a href="index.php?id=38">Linen</a></dd>
                          <dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
                          <dd><a href="index.php?id=40">Maternity Wear</a></dd>
                          <dd><a href="index.php?id=41">Nightwear</a></dd>
                    </dl>
                    <dl>
                     <dd><a href="index.php?id=42">Shorts</a></dd>
                          <dd><a href="index.php?id=43">Skirts</a></dd>
                          <dd><a href="index.php?id=44">Sportswear</a></dd>
                          <dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
                          <dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=47">Thermals</a></dd>
                          <dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
                          <dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
                          <dd><a href="index.php?id=50">Socks</a></dd>
                    </dl>
                </div>
            </li><!--menu end-->
                        <!--menu-->
                        <li><a href="index.php?id=7" class="blue">Girls</a>
                <div class="subs">
                    <dl>
                            <dd><a href="index.php?id=51">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=52">Dresses</a></dd>
                          <dd><a href="index.php?id=53">Jeans</a></dd>
                          <dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
                    </dl>
                    <dl>
                                <dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
                              <dd><a href="index.php?id=57">Leggings</a></dd>
                              <dd><a href="index.php?id=58">Nightwear</a></dd>
                              <dd><a href="index.php?id=59">Shorts</a></dd>
                              <dd><a href="index.php?id=60">Skirts</a></dd>
                    </dl>
                    <dl>
                              <dd><a href="index.php?id=61">Swimwear</a></dd>
                              <dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
                              <dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
                              <dd><a href="index.php?id=64">Socks</a></dd>
                              <dd><a href="index.php?id=65">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
                            <!--menu-->
                        <li><a href="index.php?id=8" class="blue">Boys</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=66">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=67">Jeans</a></dd>
                          <dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=70">Nightwear</a></dd>
                    </dl>
                    <dl>
                            <dd><a href="index.php?id=71">Shirts</a></dd>
                          <dd><a href="index.php?id=72">Shorts</a></dd>
                          <dd><a href="index.php?id=73">Sportswear</a></dd>
                          <dd><a href="index.php?id=74">Swimwear</a></dd>
                          <dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
                          <dd><a href="index.php?id=77">Socks</a></dd>
                          <dd><a href="index.php?id=78">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=9" class="blue">Toddlers</a>
                <div class="subs">
                    <dl>
                      <dd><a href="index.php?id=79">Newborn</a></dd>
                      <dd><a href="index.php?id=80">0-2 Years</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=10" class="blue">Accessories</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=81">Shoes</a></dd>
                          <dd><a href="index.php?id=82">Ties</a></dd>
                          <dd><a href="index.php?id=83">Caps</a></dd>
                          <dd><a href="index.php?id=84">Belts</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <li><a href="index.php?id=13" class="blue">Contact Us</a></li>
        </ul>
        <div class="back"></div>
        <div class="shadow"></div>
    </div>
    <div style="clear:both"></div>
</div>

CSS 3 Coding- Copy and Paste

<style>

body{margin:0px;}
.example {
    width:980px;
    height:40px;
    margin:0px auto;
 position:absolute;
 margin-bottom:60px;
 top:95px;
}

.menuholder {
    float:left;
    font:normal bold 11px/35px verdana, sans-serif;
    overflow:hidden;
    position:relative;
}
.menuholder .shadow {
    -moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    background:#888;
    box-shadow:0 0 20px rgba(0, 0, 0, 1);
    height:10px;
    left:5%;
    position:absolute;
    top:-9px;
    width:100%;
    z-index:100;
}
.menuholder .back {
    -moz-transition-duration:.4s;
    -o-transition-duration:.4s;
    -webkit-transition-duration:.4s;
    background-color:rgba(0, 0, 0, 0.88);
    height:0;
    width:980px; /*100%*/
}
.menuholder:hover div.back {
    height:280px;
}
ul.menu {
    display:block;
    float:left;
    list-style:none;
    margin:0;
    padding:0 125px;
    position:relative;
}
ul.menu li {
    float:left;
    margin:0 10px 0 0;
}
ul.menu li > a {
    -moz-border-radius:0 0 10px 10px;
    -moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -moz-transition:all 0.3s ease-in-out;
    -o-border-radius:0 0 10px 10px;
    -o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -o-transition:all 0.3s ease-in-out;
    -webkit-border-bottom-left-radius:10px;
    -webkit-border-bottom-right-radius:10px;
    -webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -webkit-transition:all 0.3s ease-in-out;
    border-radius:0 0 10px 10px;
    box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    color:#eee;
    display:block;
    padding:0 10px;
    text-decoration:none;
    transition:all 0.3s ease-in-out;
}
ul.menu li a.red {
    background:#a00;
}
ul.menu li a.orange {
    background:#da0;
}
ul.menu li a.yellow {
    background:#aa0;
}
ul.menu li a.green {
    background:#060;
}
ul.menu li a.blue {
    background:#073263;
}
ul.menu li a.violet {
    background:#682bc2;
}
.menu li div.subs {
    left:0;
    overflow:hidden;
    position:absolute;
    top:35px;
    width:0;
}
.menu li div.subs dl {
    -moz-transition-duration:.2s;
    -o-transition-duration:.2s;
    -webkit-transition-duration:.2s;
    float:left;
    margin:0 130px 0 0;
    overflow:hidden;
    padding:40px 0 5% 2%;
    width:0;
}
.menu dt {
    color:#fc0;
    font-family:arial, sans-serif;
    font-size:12px;
    font-weight:700;
    height:20px;
    line-height:20px;
    margin:0;
    padding:0 0 0 10px;
    white-space:nowrap;
}
.menu dd {
    margin:0;
    padding:0;
    text-align:left;
}
.menu dd a {
    background:transparent;
    color:#fff;
    font-size:12px;
    height:20px;
    line-height:20px;
    padding:0 0 0 10px;
    text-align:left;
    white-space:nowrap;
    width:80px;
}
.menu dd a:hover {
    color:#fc0;
}
.menu li:hover div.subs dl {
    -moz-transition-delay:0.2s;
    -o-transition-delay:0.2s;
    -webkit-transition-delay:0.2s;
    margin-right:2%;
    width:21%;
}
ul.menu li:hover > a,ul.menu li > a:hover {
    background:#aaa;
    color:#fff;
    padding:10px 10px 0;
}
ul.menu li a.red:hover,ul.menu li:hover a.red {
    background:#c00;
}
ul.menu li a.orange:hover,ul.menu li:hover a.orange {
    background:#fc0;
}
ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
    background:#cc0;
}
ul.menu li a.green:hover,ul.menu li:hover a.green {
    background:#080;
}
ul.menu li a.blue:hover,ul.menu li:hover a.blue {
    background:#00c;
}
ul.menu li a.violet:hover,ul.menu li:hover a.violet {
background:#8a2be2;
}
.menu li:hover div.subs,.menu li a:hover div.subs {
    width:100%;
}

Python function pointer

Easiest

eval(myvar)(parameter1, parameter2)

You don't have a function "pointer". You have a function "name".

While this works well, you will have a large number of folks telling you it's "insecure" or a "security risk".

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Found a likely answer in /jstillwell's posts here: https://github.com/stefanocudini/leaflet-gps/issues/15 basically this feature will not be supported (in Chrome only?) in the future, but only for HTTP sites. HTTPS will still be ok, and there are no plans to create an equivalent replacement for HTTP use.

Facebook development in localhost

Of course you can, just add the url localhost (without "http") in your app_domain and then add in your site_url http://localhost (with http)

Update

Facebook change the things a little now, just go to the app settings and in the site url just add http: //localhost and leave the App Domain empty

JavaScript adding decimal numbers issue

Testing this Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixed works very well.

How to add rows dynamically into table layout

Solution 1. Set your TableLayout tl as class member variable, only call TableLayout tl=(TableLayout)findViewById(R.id.maintable); when you initiate the class. When button clicked use tl directly, eg. tl.addView(row), don't call FindViewById anymore. So the next new row wouldn't replace the previous new row.

Solution 2. Everytime after button click save your updated data into an array, and then re-render your whole table layout by loop through the array.

SQL Server query to find all permissions/access for all users in a database

I just added the following to Jeremy's answer because I had a role assigned to the database db_datareader which wasn't showing the permissions that role had. I tried going through all of the answers in everyone's posts but couldn't find anything that would do this so I added my own query.

    SELECT 
    UserType='Role', 
    DatabaseUserName = '{Role Members}',
    LoginName = DP2.name,
    Role = DP1.name,
    'SELECT' AS [PermissionType] ,
    [PermissionState]  = 'GRANT',
    [ObjectType] = 'Table',
    [Schema] = 'dbo',
    [ObjectName] = 'All Tables',
    [ColumnName] = NULL
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'
AND DP2.name IS NOT NULL

Access XAMPP Localhost from Internet

you have to open a port of the service in you router then try you puplic ip out of your all network cause if you try it from your network , the puplic ip will always redirect you to your router but from the outside it will redirect to the server you have

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

angularjs getting previous route path

You'll need to couple the event listener to $rootScope in Angular 1.x, but you should probably future proof your code a bit by not storing the value of the previous location on $rootScope. A better place to store the value would be a service:

var app = angular.module('myApp', [])
.service('locationHistoryService', function(){
    return {
        previousLocation: null,

        store: function(location){
            this.previousLocation = location;
        },

        get: function(){
            return this.previousLocation;
        }
})
.run(['$rootScope', 'locationHistoryService', function($location, locationHistoryService){
    $rootScope.$on('$locationChangeSuccess', function(e, newLocation, oldLocation){
        locationHistoryService.store(oldLocation);
    });
}]);

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

Chances are you need to install .NET 4 (Which will also create a new AppPool for you)

First make sure you have IIS installed then perform the following steps:

  1. Open your command prompt (Windows + R) and type cmd and press ENTER
    You may need to start this as an administrator if you have UAC enabled.
    To do so, locate the exe (usually you can start typing with Start Menu open), right click and select "Run as Administrator"
  2. Type cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\ and press ENTER.
  3. Type aspnet_regiis.exe -ir and press ENTER again.
    • If this is a fresh version of IIS (no other sites running on it) or you're not worried about the hosted sites breaking with a framework change you can use -i instead of -ir. This will change their AppPools for you and steps 5-on shouldn't be necessary.
    • at this point you will see it begin working on installing .NET's framework in to IIS for you
  4. Close the DOS prompt, re-open your start menu and right click Computer and select Manage
  5. Expand the left-hand side (Services and Applications) and select Internet Information Services
    • You'll now have a new applet within the content window exclusively for IIS.
  6. Expand out your computer and locate the Application Pools node, and select it. (You should now see ASP.NET v4.0 listed)
  7. Expand out your Sites node and locate the site you want to modify (select it)
  8. To the right you'll notice Basic Settings... just below the Edit Site text. Click this, and a new window should appear
  9. Select the .NET 4 AppPool using the Select... button and click ok.
  10. Restart the site, and you should be good-to-go.

(You can repeat steps 7-on for every site you want to apply .NET 4 on as well).


Additional References:

  1. .NET 4 Framework
    The framework for those that don't already have it.
  2. How do I run a command with elevated privileges?
    Directions on how to run the command prompt with Administrator rights.
  3. aspnet_regiis.exe options
    For those that might want to know what -ir or -i does (or the difference between them) or what other options are available. (I typically use -ir to prevent any older sites currently running from breaking on a framework change but that's up to you.)

Using If else in SQL Select statement

SELECT CASE WHEN IDParent < 1 
            THEN ID 
            ELSE IDParent 
       END AS colname 
FROM yourtable

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

Get the IP address of the machine

Further to what Steve Baker has said, you can find a description of the SIOCGIFCONF ioctl in the netdevice(7) man page.

Once you have the list of all the IP addresses on the host, you will have to use application specific logic to filter out the addresses you do not want and hope you have one IP address left.

What's the difference between event.stopPropagation and event.preventDefault?

return false;


return false; does 3 separate things when you call it:

  1. event.preventDefault() – It stops the browsers default behaviour.
  2. event.stopPropagation() – It prevents the event from propagating (or “bubbling up”) the DOM.
  3. Stops callback execution and returns immediately when called.

Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

preventDefault();


preventDefault(); does one thing: It stops the browsers default behaviour.

When to use them?


We know what they do but when to use them? Simply it depends on what you want to accomplish. Use preventDefault(); if you want to “just” prevent the default browser behaviour. Use return false; when you want to prevent the default browser behaviour and prevent the event from propagating the DOM. In most situations where you would use return false; what you really want is preventDefault().

Examples:


Let’s try to understand with examples:

We will see pure JAVASCRIPT example

Example 1:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked and immediately you will be redirected to stackoverflow.com.

Example 2:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.preventDefault();_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is due > to event.preventDefault() method we used to prevent the default click action to be triggered.

Example 3:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.stopPropagation();_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

This time if you click on Link the function executeParent() will not be called and you will not get the javascript alert div Clicked this time. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event is going to be executed‘ and immediately you will be redirected to stackoverflow.com. This is because we haven’t prevented the default click action from triggering this time using event.preventDefault() method.

Example 4:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('Div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

If you click on the Link, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.

Example 5:

For return false I have three examples and all appear to be doing the exact same thing (just returning false), but in reality the results are quite different. Here's what actually happens in each of the above.

cases:

  1. Returning false from an inline event handler prevents the browser from navigating to the link address, but it doesn't stop the event from propagating through the DOM.
  2. Returning false from a jQuery event handler prevents the browser from navigating to the link address and it stops the event from propagating through the DOM.
  3. Returning false from a regular DOM event handler does absolutely nothing.

Will see all three example.

  1. Inline return false.

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='return false'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  var link = document.querySelector('a');_x000D_
_x000D_
  link.addEventListener('click', function() {_x000D_
    event.currentTarget.innerHTML = 'Click event prevented using inline html'_x000D_
    alert('Link Clicked');_x000D_
  });_x000D_
_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('Div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

  1. Returning false from a jQuery event handler.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
  <a href='https://stackoverflow.com'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  $('a').click(function(event) {_x000D_
    alert('Link Clicked');_x000D_
    $('a').text('Click event prevented using return FALSE');_x000D_
    $('a').contents().unwrap();_x000D_
    return false;_x000D_
  });_x000D_
  $('div').click(function(event) {_x000D_
    alert('Div clicked');_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

  1. Returning false from a regular DOM event handler.

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
    return false_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('Div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Hope these examples are clear. Try executing all these examples in a html file to see how they work.

"unrecognized import path" with go get

I had the same issue after having upgraded go1.2 to go1.4.

I renamed src to _src in my GOPATH then did a go get -v

It worked then I deleted _src.

Hope it helps.

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

More importantly, the 2013 versions of Visual Studio Express have all the languages that comes with the commercial versions. You can use the Windows desktop versions not only to program using Windows Forms, it is possible to write those windowed applications with any language that comes with the software, may it be C++ using the windows.h header if you want to actually learn how to create windows applications from scratch, or use Windows form to create windows in C# or visual Basic.

In the past, you had to download one version for each language or type of content. Or just download an all-in-one that still installed separate versions of the software for different languages. Now with 2013 you get all the languages needed in each content oriented version of the 2013 express.

You pick what matters the most to you.

Besides, it might be a good way to learn using notepad and the command line to write and compile, but I find that a bit tedious to use. While using an IDE might be overwhelming at first, you start small, learning how to create a project, write code, compile your code. They have gone way over their heads to ease up your day when you take it for the first time.

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

Please try this line

getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_arrow);

Access denied for root user in MySQL command-line

Gain access to a MariaDB 10 database server

After stopping the database server, the next step is to gain access to the server through a backdoor by starting the database server and skipping networking and permission tables. This can be done by running the commands below.

sudo mysqld_safe --skip-grant-tables --skip-networking &

Reset MariaDB root Password

Now that the database server is started in safe mode, run the commands below to logon as root without password prompt. To do that, run the commands below

sudo mysql -u root

Then run the commands below to use the mysql database.

use mysql;

Finally, run the commands below to reset the root password.

update user set password=PASSWORD("new_password_here") where User='root';

Replace new_password _here with the new password you want to create for the root account, then press Enter.

After that, run the commands below to update the permissions and save your changes to disk.

flush privileges;

Exit (CTRL + D) and you’re done.

Next start MariaDB normally and test the new password you just created.

sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service

Logon to the database by running the commands below.

sudo mysql -u root -p

source: https://websiteforstudents.com/reset-mariadb-root-password-ubuntu-17-04-17-10/

How to cast List<Object> to List<MyClass>

As others have pointed out, you cannot savely cast them, since a List<Object> isn't a List<Customer>. What you could do, is to define a view on the list that does in-place type checking. Using Google Collections that would be:

return Lists.transform(list, new Function<Object, Customer>() {
  public Customer apply(Object from) {
    if (from instanceof Customer) {
      return (Customer)from;
    }
    return null; // or throw an exception, or do something else that makes sense.
  }
});

How to call getResources() from a class which has no context?

The normal solution to this is to pass an instance of the context to the class as you create it, or after it is first created but before you need to use the context.

Another solution is to create an Application object with a static method to access the application context although that couples the Droid object fairly tightly into the code.

Edit, examples added

Either modify the Droid class to be something like this

 public Droid(Context context,int x, int y) {
    this.bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.birdpic);
    this.x = x;
    this.y = y;
    }   

Or create an Application something like this:

public class App extends android.app.Application
{
    private static App mApp = null;
    /* (non-Javadoc)
     * @see android.app.Application#onCreate()
     */
    @Override
    public void onCreate()
    {
        super.onCreate();
        mApp = this;
    }
    public static Context context()
    {
        return mApp.getApplicationContext();
    }
}

And call App.context() wherever you need a context - note however that not all functions are available on an application context, some are only available on an activity context but it will certainly do with your need for getResources().

Please note that you'll need to add android:name to your application definition in your manifest, something like this:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name=".App" >

npm install error from the terminal

First download json package file from https://github.com/npm/read-package-json and then run npm install from terminal.

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.

MasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');

            alert(a.value);

        }

    </script>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);

        }
    }
}

Web API Put Request generates an Http 405 Method Not Allowed error

Your client application and server application must be under same domain, for example :

client - localhost

server - localhost

and not :

client - localhost:21234

server - localhost

What is /var/www/html?

/var/www/html is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf file (usually located in /etc/apache/conf) and changing the DocumentRoot attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)

Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.

How to send a "multipart/form-data" with requests in python?

Here is the python snippet you need to upload one large single file as multipart formdata. With NodeJs Multer middleware running on the server side.

import requests
latest_file = 'path/to/file'
url = "http://httpbin.org/apiToUpload"
files = {'fieldName': open(latest_file, 'rb')}
r = requests.put(url, files=files)

For the server side please check the multer documentation at: https://github.com/expressjs/multer here the field single('fieldName') is used to accept one single file, as in:

var upload = multer().single('fieldName');

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

Here is a Powershell alternative to @UuDdLrLrSs answer.

Get-Service workstation | Restart-Service -Force

keytool error Keystore was tampered with, or password was incorrect

keytool error: java.io.IOException: Keystore was tampered with, or password was incorrect

I solved my problem when I changed keystore path C:\MyWorks\mykeystore to C:\MyWorks\mykeystore.keystore.

JavaScript Nested function

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
}_x000D_
bar();
_x000D_
_x000D_
_x000D_
Will throw an error. Since bar is defined inside foo, bar will only be accessible inside foo.
To use bar you need to run it inside foo.

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
  bar();_x000D_
}
_x000D_
_x000D_
_x000D_

How to add a new line in textarea element?

Try this one:

_x000D_
_x000D_
    <textarea cols='60' rows='8'>This is my statement one.&#13;&#10;This is my statement2</textarea>
_x000D_
_x000D_
_x000D_

&#10; Line Feed and &#13; Carriage Return are HTML entitieswikipedia. This way you are actually parsing the new line ("\n") rather than displaying it as text.

Execute function after Ajax call is complete

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

Maximum size of an Array in Javascript

I have shamelessly pulled some pretty big datasets in memory, and altough it did get sluggish it took maybe 15 Mo of data upwards with pretty intense calculations on the dataset. I doubt you will run into problems with memory unless you have intense calculations on the data and many many rows. Profiling and benchmarking with different mock resultsets will be your best bet to evaluate performance.

Disposing WPF User Controls

My scenario is little different, but the intent is same i would like to know when the parent window hosting my user control is closing/closed as The view(i.e my usercontrol) should invoke the presenters oncloseView to execute some functionality and perform clean up. ( well we are implementing a MVP pattern on a WPF PRISM application).

I just figured that in the Loaded event of the usercontrol, i can hook up my ParentWindowClosing method to the Parent windows Closing event. This way my Usercontrol can be aware when the Parent window is being closed and act accordingly!

Using GPU from a docker container?

Ok i finally managed to do it without using the --privileged mode.

I'm running on ubuntu server 14.04 and i'm using the latest cuda (6.0.37 for linux 13.04 64 bits).


Preparation

Install nvidia driver and cuda on your host. (it can be a little tricky so i will suggest you follow this guide https://askubuntu.com/questions/451672/installing-and-testing-cuda-in-ubuntu-14-04)

ATTENTION : It's really important that you keep the files you used for the host cuda installation


Get the Docker Daemon to run using lxc

We need to run docker daemon using lxc driver to be able to modify the configuration and give the container access to the device.

One time utilization :

sudo service docker stop
sudo docker -d -e lxc

Permanent configuration Modify your docker configuration file located in /etc/default/docker Change the line DOCKER_OPTS by adding '-e lxc' Here is my line after modification

DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4 -e lxc"

Then restart the daemon using

sudo service docker restart

How to check if the daemon effectively use lxc driver ?

docker info

The Execution Driver line should look like that :

Execution Driver: lxc-1.0.5

Build your image with the NVIDIA and CUDA driver.

Here is a basic Dockerfile to build a CUDA compatible image.

FROM ubuntu:14.04
MAINTAINER Regan <http://stackoverflow.com/questions/25185405/using-gpu-from-a-docker-container>

RUN apt-get update && apt-get install -y build-essential
RUN apt-get --purge remove -y nvidia*

ADD ./Downloads/nvidia_installers /tmp/nvidia                             > Get the install files you used to install CUDA and the NVIDIA drivers on your host
RUN /tmp/nvidia/NVIDIA-Linux-x86_64-331.62.run -s -N --no-kernel-module   > Install the driver.
RUN rm -rf /tmp/selfgz7                                                   > For some reason the driver installer left temp files when used during a docker build (i don't have any explanation why) and the CUDA installer will fail if there still there so we delete them.
RUN /tmp/nvidia/cuda-linux64-rel-6.0.37-18176142.run -noprompt            > CUDA driver installer.
RUN /tmp/nvidia/cuda-samples-linux-6.0.37-18176142.run -noprompt -cudaprefix=/usr/local/cuda-6.0   > CUDA samples comment if you don't want them.
RUN export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64         > Add CUDA library into your PATH
RUN touch /etc/ld.so.conf.d/cuda.conf                                     > Update the ld.so.conf.d directory
RUN rm -rf /temp/*  > Delete installer files.

Run your image.

First you need to identify your the major number associated with your device. Easiest way is to do the following command :

ls -la /dev | grep nvidia

If the result is blank, use launching one of the samples on the host should do the trick. The result should look like that enter image description here As you can see there is a set of 2 numbers between the group and the date. These 2 numbers are called major and minor numbers (wrote in that order) and design a device. We will just use the major numbers for convenience.

Why do we activated lxc driver? To use the lxc conf option that allow us to permit our container to access those devices. The option is : (i recommend using * for the minor number cause it reduce the length of the run command)

--lxc-conf='lxc.cgroup.devices.allow = c [major number]:[minor number or *] rwm'

So if i want to launch a container (Supposing your image name is cuda).

docker run -ti --lxc-conf='lxc.cgroup.devices.allow = c 195:* rwm' --lxc-conf='lxc.cgroup.devices.allow = c 243:* rwm' cuda

How to replace comma with a dot in the number (or any replacement)

From the function's definition (http://www.w3schools.com/jsref/jsref_replace.asp):

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

This method does not change the original string.

Hence, the line: tt.replace(/,/g, '.') does not change the value of tt; it just returns the new value.

You need to replace this line with: tt = tt.replace(/,/g, '.')

Sending HTML email using Python

Here's sample code. This is inspired from code found on the Python Cookbook site (can't find the exact link)

def createhtmlmail (html, text, subject, fromEmail):
    """Create a mime-message that will render HTML in popular
    MUAs, text in better ones"""
    import MimeWriter
    import mimetools
    import cStringIO

    out = cStringIO.StringIO() # output buffer for our message 
    htmlin = cStringIO.StringIO(html)
    txtin = cStringIO.StringIO(text)

    writer = MimeWriter.MimeWriter(out)
    #
    # set up some basic headers... we put subject here
    # because smtplib.sendmail expects it to be in the
    # message body
    #
    writer.addheader("From", fromEmail)
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    #
    # start the multipart section of the message
    # multipart/alternative seems to work better
    # on some MUAs than multipart/mixed
    #
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    #
    # the plain text section
    #
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
    mimetools.encode(txtin, pout, 'quoted-printable')
    txtin.close()
    #
    # start the html subpart of the message
    #
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    #
    # returns us a file-ish object we can write to
    #
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    #
    # Now that we're done, close our writer and
    # return the message body
    #
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    print msg
    return msg

if __name__=="__main__":
    import smtplib
    html = 'html version'
    text = 'TEST VERSION'
    subject = "BACKUP REPORT"
    message = createhtmlmail(html, text, subject, 'From Host <[email protected]>')
    server = smtplib.SMTP("smtp_server_address","smtp_port")
    server.login('username', 'password')
    server.sendmail('[email protected]', '[email protected]', message)
    server.quit()

How to retrieve inserted id after inserting row in SQLite using Python?

You could use cursor.lastrowid (see "Optional DB API Extensions"):

connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('test','test'))
print(cursor.lastrowid)
# 1

If two people are inserting at the same time, as long as they are using different cursors, cursor.lastrowid will return the id for the last row that cursor inserted:

cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

print(cursor2.lastrowid)        
# 3
print(cursor.lastrowid)
# 2

cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
               (100,'blah','blah'))
print(cursor.lastrowid)
# 100

Note that lastrowid returns None when you insert more than one row at a time with executemany:

cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
               (('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None

Function to get yesterday's date in Javascript in format DD/MM/YYYY

You override $today in the if statement.

if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;

It is then not a Date() object anymore - hence the error.

JavaScript alert not working in Android WebView

As others indicated, setting the WebChromeClient is needed to get alert() to work. It's sufficient to just set the default WebChromeClient():

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient());

Thanks for all the comments below. Including John Smith's who indicated that you needed to enable JavaScript.

How can I set the aspect ratio in matplotlib?

Third times the charm. My guess is that this is a bug and Zhenya's answer suggests it's fixed in the latest version. I have version 0.99.1.1 and I've created the following solution:

import matplotlib.pyplot as plt
import numpy as np

def forceAspect(ax,aspect=1):
    im = ax.get_images()
    extent =  im[0].get_extent()
    ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)

data = np.random.rand(10,20)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_xlabel('xlabel')
ax.set_aspect(2)
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')
forceAspect(ax,aspect=1)
fig.savefig('force.png')

This is 'force.png': enter image description here

Below are my unsuccessful, yet hopefully informative attempts.

Second Answer:

My 'original answer' below is overkill, as it does something similar to axes.set_aspect(). I think you want to use axes.set_aspect('auto'). I don't understand why this is the case, but it produces a square image plot for me, for example this script:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10,20)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_aspect('equal')
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')

Produces an image plot with 'equal' aspect ratio: enter image description here and one with 'auto' aspect ratio: enter image description here

The code provided below in the 'original answer' provides a starting off point for an explicitly controlled aspect ratio, but it seems to be ignored once an imshow is called.

Original Answer:

Here's an example of a routine that will adjust the subplot parameters so that you get the desired aspect ratio:

import matplotlib.pyplot as plt

def adjustFigAspect(fig,aspect=1):
    '''
    Adjust the subplot parameters so that the figure has the correct
    aspect ratio.
    '''
    xsize,ysize = fig.get_size_inches()
    minsize = min(xsize,ysize)
    xlim = .4*minsize/xsize
    ylim = .4*minsize/ysize
    if aspect < 1:
        xlim *= aspect
    else:
        ylim /= aspect
    fig.subplots_adjust(left=.5-xlim,
                        right=.5+xlim,
                        bottom=.5-ylim,
                        top=.5+ylim)

fig = plt.figure()
adjustFigAspect(fig,aspect=.5)
ax = fig.add_subplot(111)
ax.plot(range(10),range(10))

fig.savefig('axAspect.png')

This produces a figure like so: enter image description here

I can imagine if your having multiple subplots within the figure, you would want to include the number of y and x subplots as keyword parameters (defaulting to 1 each) to the routine provided. Then using those numbers and the hspace and wspace keywords, you can make all the subplots have the correct aspect ratio.

"R cannot be resolved to a variable"?

For me somehow the Project properties; Android; Project Build Target was not set. I chose a Android version there (e.g. 4.2) and it fixed it.

Adding a custom header to HTTP request using angular.js

And what's the answer from the server? It should reply a 204 and then really send the GET you are requesting.

In the OPTIONS the client is checking if the server allows CORS requests. If it gives you something different than a 204 then you should configure your server to send the correct Allow-Origin headers.

The way you are adding headers is the right way to do it.

Run an exe from C# code

Example:

Process process = Process.Start(@"Data\myApp.exe");
int id = process.Id;
Process tempProc = Process.GetProcessById(id);
this.Visible = false;
tempProc.WaitForExit();
this.Visible = true;

ES6 exporting/importing in index file

Also, bear in mind that if you need to export multiple functions at once, like actions you can use

export * from './XThingActions';

What is the T-SQL syntax to connect to another SQL Server?

Whenever we are trying to retrieve any data from another server we need two steps.

First step:

-- Server one scalar variable
DECLARE @SERVER VARCHAR(MAX)
--Oracle is the server to which we want to connect
EXEC SP_ADDLINKEDSERVER @SERVER='ORACLE'

Second step:

--DBO is the owner name to know table owner name execute (SP_HELP TABLENAME)    
SELECT * INTO DESTINATION_TABLE_NAME 
FROM ORACLE.SOURCE_DATABASENAME.DBO.SOURCE_TABLE

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I had the same error, but in my case it was caused by the DEBUG mode in Intellij IDE. The debug slowed down the library and then server ended communication at handshake phase. The standard "RUN" worked perfectly.

How to revert initial git commit?

I wonder why "amend" is not suggest and have been crossed out by @damkrat, as amend appears to me as just the right way to resolve the most efficiently the underlying problem of fixing the wrong commit since there is no purpose of having no initial commit. As some stressed out you should only modify "public" branch like master if no one has clone your repo...

git add <your different stuff>
git commit --amend --author="author name <[email protected]>"-m "new message"

CSS rule to apply only if element has BOTH classes

div.abc.xyz {
    /* rules go here */
}

... or simply:

.abc.xyz {
    /* rules go here */
}

Getting a union of two arrays in JavaScript

Just wrote before for the same reason (works with any amount of arrays):

/**
 * Returns with the union of the given arrays.
 *
 * @param Any amount of arrays to be united.
 * @returns {array} The union array.
 */
function uniteArrays()
{
    var union = [];
    for (var argumentIndex = 0; argumentIndex < arguments.length; argumentIndex++)
    {
        eachArgument = arguments[argumentIndex];
        if (typeof eachArgument !== 'array')
        {
            eachArray = eachArgument;
            for (var index = 0; index < eachArray.length; index++)
            {
                eachValue = eachArray[index];
                if (arrayHasValue(union, eachValue) == false)
                union.push(eachValue);
            }
        }
    }

    return union;
}    

function arrayHasValue(array, value)
{ return array.indexOf(value) != -1; }

How can I use Google's Roboto font on a website?

Did you read the How_To_Use_Webfonts.html that's in that zip file?

After reading that, it seems that each font subfolder has an already created .css in there that you can use by including this:

<link rel="stylesheet" href="stylesheet.css" type="text/css" charset="utf-8" />

Want to upgrade project from Angular v5 to Angular v6

There are few steps to upgrade 2/4/5 to Angular 6.

npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install

To fix the issue related to "angular.json" :-

ng update @angular/cli --migrate-only --from=1.7.4

Store MIGRATION
https://github.com/ngrx/platform/blob/master/MIGRATION.md#ngrxstore

RXJS MIGRATION
https://www.academind.com/learn/javascript/rxjs-6-what-changed/

Hoping this will help you :)

how to destroy an object in java?

Set to null. Then there are no references anymore and the object will become eligible for Garbage Collection. GC will automatically remove the object from the heap.

add item to dropdown list in html using javascript

Try to use appendChild method:

select.appendChild(option);

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

SQL Server: Cannot insert an explicit value into a timestamp column

create table demo ( id int, ts timestamp )

insert into demo(id,ts) values (1, DEFAULT)

Parsing JSON from XmlHttpRequest.responseJSON

Note: I've only tested this in Chrome.

it adds a prototype function to the XMLHttpRequest .. XHR2,

in XHR 1 you probably just need to replace this.response with this.responseText

Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
 return JSON.parse(this.response);
},writable:false,enumerable:false});

to return the json in xhr2

xhr.onload=function(){
 console.log(this.responseJSON());
}

EDIT

If you plan to use XHR with arraybuffer or other response types then you have to check if the response is a string.

in any case you have to add more checks e.g. if it's not able to parse the json.

Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
 return (typeof this.response==='string'?JSON.parse(this.response):this.response);
},writable:false,enumerable:false});

Is SMTP based on TCP or UDP?

Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

Unable to launch the IIS Express Web server

Well none of the above mentioned steps worked for me. In my case my applicationhost.config file was somehow missing the following two line of code

 <add name="rules-64-ISAPI-2.0" path="*.rules" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" />
    <add name="xoml-64-ISAPI-2.0" path="*.xoml" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" />

Hope this can help some one.

CSS3 opacity gradient?

We can do it by css like.

body {
  background: #000;
  background-image: linear-gradient(90deg, rgba(255, 255, 255, .3) 0%, rgba(231, 231, 231, .3) 22.39%, rgba(209, 209, 209,  .3) 42.6%, rgba(182, 182, 182, .3) 79.19%, rgba(156, 156, 156, .3) 104.86%);
  
}

How To Get Selected Value From UIPickerView

You can access the selected row for a given component using the following method:

- (NSInteger)selectedRowInComponent:(NSInteger)component

Otherwise, implementing the delegate function is the only other option.

Refresh a page using JavaScript or HTML

window.location.reload()

should work however there are many different options like:

window.location.href=window.location.href

What is the use of rt.jar file in java?

Your question is already answered here :

Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file

Also, a good link on what happens if we try to include our class file in rt.jar.

How to get first character of a string in SQL?

If you search the first char of string in Sql string

SELECT CHARINDEX('char', 'my char')

=> return 4

Spring: @Component versus @Bean

@Component and @Bean do two quite different things, and shouldn't be confused.

@Component (and @Service and @Repository) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.

@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.

To answer your question...

would it have been possible to re-use the @Component annotation instead of introducing @Bean annotation?

Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.

git - remote add origin vs remote set-url origin

below is used to a add a new remote:

git remote add origin [email protected]:User/UserRepo.git

below is used to change the url of an existing remote repository:

git remote set-url origin [email protected]:User/UserRepo.git

below will push your code to the master branch of the remote repository defined with origin and -u let you point your current local branch to the remote master branch:

git push -u origin master

Documentation

XML Serialize generic list of serializable objects

knowTypeList parameter let serialize with DataContractSerializer several known types:

private static void WriteObject(
        string fileName, IEnumerable<Vehichle> reflectedInstances, List<Type> knownTypeList)
    {
        using (FileStream writer = new FileStream(fileName, FileMode.Append))
        {
            foreach (var item in reflectedInstances)
            {
                var serializer = new DataContractSerializer(typeof(Vehichle), knownTypeList);
                serializer.WriteObject(writer, item);
            }
        }
    }

pythonic way to do something N times without an index variable?

A slightly faster approach than looping on xrange(N) is:

import itertools

for _ in itertools.repeat(None, N):
    do_something()

What is the mouse down selector in CSS?

I recently found out that :active:focus does the same thing in css as :active:hover if you need to override a custom css library, they might use both.

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

Update React component every second

i myself like setTimeout more that setInterval but didn't find a solution in class based component .you could use sth like this in class based components:

class based component and setInterval:

_x000D_
_x000D_
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date()
    };
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      this.state.date.toLocaleTimeString()
    );
  }
}

ReactDOM.render( 
  <Clock / > ,
  document.getElementById('app')
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app" />
_x000D_
_x000D_
_x000D_

function based component and setInterval:

https://codesandbox.io/s/sweet-diffie-wsu1t?file=/src/index.js

function based component and setTimeout:

https://codesandbox.io/s/youthful-lovelace-xw46p

Interpreting segfault messages

Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.

"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.

"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.

Get the cell value of a GridView row

I had the same problem as yours. I found that when i use the BoundField tag in GridView to show my data. The row.Cells[1].Text is working in:

GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = "Cell Value" + row.Cells[1].Text + "";

But when i use TemplateField tag to show data like this:

 <asp:TemplateField HeaderText="??">
    <ItemTemplate>
    <asp:Label ID="Part_No" runat="server" Text='<%# Eval("Part_No")%>' ></asp:Label>
    </ItemTemplate>
    <HeaderStyle CssClass="bhead" />
    <ItemStyle CssClass="bbody" />
    </asp:TemplateField>

The row.Cells[1].Text just return null. I got stuck in this problem for a long time. I figur out recently and i want to share with someone who have the same problem my solution. Please feel free to edit this post and/or correct me.

My Solution:

Label lbCod = GridView1.Rows["AnyValidIndex"].Cells["AnyValidIndex"].Controls["AnyValidIndex"] as Label;

I use Controls attribute to find the Label control which i use to show data, and you can find yours. When you find it and convert to the correct type object than you can extract text and so on. Ex:

string showText = lbCod.Text;

Reference: reference

how to convert rgb color to int in java

If you are developing for Android, Color's method for this is rgb(int, int, int)

So you would do something like

myPaint.setColor(Color.rgb(int, int, int)); 

For retrieving the individual color values you can use the methods for doing so:

Color.red(int color) 
Color.blue(int color) 
Color.green(int color) 

Refer to this document for more info

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

^M gives unwanted line breaks. To handle this we can use the sed command as follows:

sed 's/\r//g'

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

The 'export' keyword is the way to separate out template implementation from template declaration. This was introduced in C++ standard without an existing implementation. In due course only a couple of compilers actually implemented it. Read in depth information at Inform IT article on export

Why would one mark local variables and method parameters as "final" in Java?

We do it here for the local variables if we think they will not be reassigned or should not be reassigned.

The parameters are not final since we have a Checkstyle-Check which checks for reassigning parameters. Of course nobody would ever want to reassign a parameter variable.

How to "test" NoneType in python?

It can also be done with isinstance as per Alex Hall's answer :

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

isinstance is also intuitive but there is the complication that it requires the line

NoneType = type(None)

which isn't needed for types like int and float.

"’" showing on page instead of " ' "

If someone gets this error on WordPress website, you need to change wp-config db charset:

define('DB_CHARSET', 'utf8mb4_unicode_ci');

instead of:

define('DB_CHARSET', 'utf8mb4');

How to create a HTML Table from a PHP array?

It would be better to just fetch the data into array like this:

<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
               array("title"=>"daisy", "price"=>0.75 , "number"=>25),
               array("title"=>"orchid", "price"=>1.15 , "number"=>7) 
             ); 
?>

And then do something like this, which should work well even when you add more columns to your table in the database later.

<?php if (count($shop) > 0): ?>
<table>
  <thead>
    <tr>
      <th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
    </tr>
  </thead>
  <tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
    <tr>
      <td><?php echo implode('</td><td>', $row); ?></td>
    </tr>
<?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>

How to capture no file for fs.readFileSync()?

I prefer this way of handling this. You can check if the file exists synchronously:

var file = 'info.json';
var content = '';

// Check that the file exists locally
if(!fs.existsSync(file)) {
  console.log("File not found");
}

// The file *does* exist
else {
  // Read the file and do anything you want
  content = fs.readFileSync(file, 'utf-8');
}

Note: if your program also deletes files, this has a race condition as noted in the comments. If however you only write or overwrite files, without deleting them, then this is totally fine.

Algorithm to calculate the number of divisors of a given number

Dmitriy is right that you'll want the Sieve of Atkin to generate the prime list but I don't believe that takes care of the whole issue. Now that you have a list of primes you'll need to see how many of those primes act as a divisor (and how often).

Here's some python for the algo Look here and search for "Subject: math - need divisors algorithm". Just count the number of items in the list instead of returning them however.

Here's a Dr. Math that explains what exactly it is you need to do mathematically.

Essentially it boils down to if your number n is:
n = a^x * b^y * c^z
(where a, b, and c are n's prime divisors and x, y, and z are the number of times that divisor is repeated) then the total count for all of the divisors is:
(x + 1) * (y + 1) * (z + 1).

Edit: BTW, to find a,b,c,etc you'll want to do what amounts to a greedy algo if I'm understanding this correctly. Start with your largest prime divisor and multiply it by itself until a further multiplication would exceed the number n. Then move to the next lowest factor and times the previous prime ^ number of times it was multiplied by the current prime and keep multiplying by the prime until the next will exceed n... etc. Keep track of the number of times you multiply the divisors together and apply those numbers into the formula above.

Not 100% sure about my algo description but if that isn't it it's something similar .

Can a relative sitemap url be used in a robots.txt?

According to the official documentation on sitemaps.org it needs to be a full URL:

You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:

Sitemap: http://www.example.com/sitemap.xml