Programs & Examples On #Css position

The "position" property in CSS allows you to control the location of an element on the page by setting its value to static (the default setting), relative, absolute, fixed, or sticky.

Iframe positioning

Try adding the css style property

position:relative;

to the div tag , it works ,

How to remove Left property when position: absolute?

In the future one would use left: unset; for unsetting the value of left.

As of today 4 nov 2014 unset is only supported in Firefox.

Read more about unset in MDN.

My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.

Have a fixed position div that needs to scroll if content overflows

The problem with using height:100% is that it will be 100% of the page instead of 100% of the window (as you would probably expect it to be). This will cause the problem that you're seeing, because the non-fixed content is long enough to include the fixed content with 100% height without requiring a scroll bar. The browser doesn't know/care that you can't actually scroll that bar down to see it

You can use fixed to accomplish what you're trying to do.

.fixed-content {
    top: 0;
    bottom:0;
    position:fixed;
    overflow-y:scroll;
    overflow-x:hidden;
}

This fork of your fiddle shows my fix: http://jsfiddle.net/strider820/84AsW/1/

Relative div height

The div take the height of its parent, but since it has no content (expecpt for your divs) it will only be as height as its content.

You need to set the height of the body and html:

HTML:

<div class="block12">
    <div class="block1">1</div>
    <div class="block2">2</div>
</div>
<div class="block3">3</div>

CSS:

body, html {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.block12 {
    width: 100%;
    height: 50%;
    background: yellow;
    overflow: auto;
}
.block1, .block2 {
    width: 50%;
    height: 100%;
    display: inline-block;
    margin-right: -4px;
    background: lightgreen;
}
.block2 { background: lightgray }
.block3 {
    width: 100%;
    height: 50%;
    background: lightblue;
}

And a JSFiddle

How to center a "position: absolute" element

_x000D_
_x000D_
html, body, ul, li, img {_x000D_
  box-sizing: border-box;_x000D_
  margin: 0px;  _x000D_
  padding: 0px;  _x000D_
}_x000D_
_x000D_
#slideshowWrapper {_x000D_
  width: 25rem;_x000D_
  height: auto;_x000D_
  position: relative;_x000D_
  _x000D_
  margin-top: 50px;_x000D_
  border: 3px solid black;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
  border: 3px solid blue;  _x000D_
}_x000D_
_x000D_
li {_x000D_
  /* center horizontal */_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  top: 50%;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
  font-size: 18px;_x000D_
  /* center horizontal */_x000D_
  _x000D_
  border: 3px solid red; _x000D_
}_x000D_
_x000D_
img {_x000D_
  border: 1px solid #ccc;_x000D_
  padding: 4px;_x000D_
  //width: 200px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<body>_x000D_
  <div id="slideshowWrapper">_x000D_
    <ul id="slideshow">_x000D_
      <li><img src="http://via.placeholder.com/350x150" alt="Dummy 1" /></li>_x000D_
      <li><img src="http://via.placeholder.com/140x100" alt="Dummy 2" /></li>_x000D_
      <li><img src="http://via.placeholder.com/200x100" alt="Dummy 3" /></li>      _x000D_
    </ul>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to position the Button exactly in CSS

So, the trick here is to use absolute positioning calc like this:

top: calc(50% - XYpx);
left: calc(50% - XYpx);

where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

Use: https://github.com/mkoryak/floatThead

Docs: http://mkoryak.github.io/floatThead/examples/bootstrap3/

$(document).ready(function(){
  $(".sticky-header").floatThead({top:50});
});

DEMO with 2 Tables and Fixed Header: http://jsbin.com/zuzuqe/1/

http://jsbin.com/zuzuqe/1/edit


HTML

<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Project name</a>
    </div>
    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#about">About</a></li>
        <li><a href="#contact">Contact</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li class="divider"></li>
            <li class="dropdown-header">Nav header</li>
            <li><a href="#">Separated link</a></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>
    </div>
    <!--/.nav-collapse -->
  </div>
</div>

<!-- Begin page content -->
<div class="container">
  <div class="page-header">
    <h1>Sticky footer with fixed navbar</h1>
  </div>
  <p class="lead">Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS. A fixed navbar has been added within <code>#wrap</code> with <code>padding-top: 60px;</code> on the <code>.container</code>.</p>
  <table class="table table-striped sticky-header">
    <thead>
      <tr>
        <th>#</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Username</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
    </tbody>
  </table>

  <h3>Table 2</h3>

  <table class="table table-striped sticky-header">
    <thead>
      <tr>
        <th>#</th>
        <th>New Table</th>
        <th>Last Name</th>
        <th>Username</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
    </tbody>
  </table>
</div>

CSS

body{
  padding-top:50px;
}
table.floatThead-table {
  border-top: none;
  border-bottom: none;
  background-color: #fff;
}

Difference between style = "position:absolute" and style = "position:relative"

With CSS positioning, you can place an element exactly where you want it on your page.

When you are going to use CSS positioning, the first thing you need to do is use the CSS property position to tell the browser if you're going to use absolute or relative positioning.

Both Positions are having different features. In CSS Once you set Position then you can able to use top, right, bottom, left attributes.

Absolute Position

An absolute position element is positioned relative to the first parent element that has a position other than static.

Relative Position

A relative positioned element is positioned relative to its normal position.

To position an element relatively, the property position is set as relative. The difference between absolute and relative positioning is how the position is being calculated.

More :Postion Relative vs Absolute

How to make div fixed after you scroll to that div?

jquery function is most important

<script>
$(function(){
    var stickyHeaderTop = $('#stickytypeheader').offset().top;

    $(window).scroll(function(){
            if( $(window).scrollTop() > stickyHeaderTop ) {
                    $('#stickytypeheader').css({position: 'fixed', top: '0px'});
                    $('#sticky').css('display', 'block');
            } else {
                    $('#stickytypeheader').css({position: 'static', top: '0px'});
                    $('#sticky').css('display', 'none');
            }
    });
});
</script>

Then use JQuery Lib...

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

Now use HTML

<div id="header">
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
 </div>

<div id="stickytypeheader">
 <table width="100%">
  <tr>
    <td><a href="http://growthpages.com/">Growth pages</a></td>

    <td><a href="http://google.com/">Google</a></td>

    <td><a href="http://yahoo.com/">Yahoo</a></td>

    <td><a href="http://www.bing.com/">Bing</a></td>

    <td><a href="#">Visitor</a></td>
  </tr>
 </table>
</div>

<div id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
</div>

Check DEMO HERE

center aligning a fixed position div

This works if you want the element to span across the page like another navigation bar.

width: calc (width: 100% - width whatever else is off centering it)

For example if your side navigation bar is 200px:

width: calc(100% - 200px);

CSS div 100% height

try setting the body style to:

body { position:relative;}

it worked for me

CSS z-index not working (position absolute)

I was struggling to figure it out how to put a div over an image like this: z-index working

No matter how I configured z-index in both divs (the image wrapper) and the section I was getting this:

z-index Not working

Turns out I hadn't set up the background of the section to be background: white;

so basically it's like this:

<div class="img-wrp">
  <img src="myimage.svg"/>
</div>
<section>
 <other content>
</section>

section{
  position: relative;
  background: white; /* THIS IS THE IMPORTANT PART NOT TO FORGET */
}
.img-wrp{
  position: absolute;
  z-index: -1; /* also worked with 0 but just to be sure */
}

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

To set the position relative to the parent you need to set the position:relative of parent and position:absolute of the element

$("#mydiv").parent().css({position: 'relative'});
$("#mydiv").css({top: 200, left: 200, position:'absolute'});

This works because position: absolute; positions relatively to the closest positioned parent (i.e., the closest parent with any position property other than the default static).

Make div stay at bottom of page's content all the time even when there are scrollbars

This is precisely what position: fixed was designed for:

#footer {
    position: fixed;
    bottom: 0;
    width: 100%;
}

Here's the fiddle: http://jsfiddle.net/uw8f9/

Fixed position but relative to container

The answer is yes, as long as you don't set left: 0 or right: 0 after you set the div position to fixed.

http://jsfiddle.net/T2PL5/85/

Checkout the sidebar div. It is fixed, but related to the parent, not to the window view point.

_x000D_
_x000D_
body {
  background: #ccc;
}

.wrapper {
  margin: 0 auto;
  height: 1400px;
  width: 650px;
  background: green;
}

.sidebar {
  background-color: #ddd;
  float: left;
  width: 300px;
  height: 100px;
  position: fixed;
}

.main {
  float: right;
  background-color: yellow;
  width: 300px;
  height: 1400px;
}
_x000D_
<div class="wrapper">wrapper
  <div class="sidebar">sidebar</div>
  <div class="main">main</div>
</div>
_x000D_
_x000D_
_x000D_

Absolute positioning ignoring padding of parent

Could have easily done using an extra level of Div.

<div style="background-color: blue; padding: 10px; position: relative; height: 100px;">
  <div style="position: absolute; left: 0px; right: 0px; bottom: 10px; padding:0px 10px;">
    <div style="background-color: gray;">css sux</div>
  </div>
</div>

Demo: https://jsfiddle.net/soxv3vr0/

Center a position:fixed element

I used vw (viewport width) and vh (viewport height). viewport is your entire screen. 100vw is your screens total width and 100vh is total height.

.class_name{
    width: 50vw;
    height: 50vh;
    border: 1px solid red;
    position: fixed;
    left: 25vw;top: 25vh;   
}

Center an item with position: relative

Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:

#parent {
    -webkit-box-align:center;
    -webkit-box-pack:center;
    display:-webkit-box;
}

How to position a Bootstrap popover?

Popover's Viewport (Bootstrap v3)

The best solution that will work for you in all occassions, especially if your website has a fluid width, is to use the viewport option of the Bootstrap Popover.

This will make the popover take width inside a selector you have assigned. So if the trigger button is on the right of that container, the bootstrap arrow will also appear on the right while the popover is inside that area. See jsfiddle.net

You can also use padding if you want some space from the edge of container. If you want no padding just use viewport: '.container'

$('#popoverButton').popover({
   container: 'body',
   placement: "bottom",
   html: true,   
   viewport: { selector: '.container', padding: 5 },
   content: '<strong>Hello Wooooooooooooooooooooooorld</strong>'
 });

in the following html example:

<div class="container">
   <button type="button" id="popoverButton">Click Me!</button>
</div>

and with CSS:

.container {
  text-align:right;
  width: 100px;
  padding: 20px;
  background: blue;
}

Popover's Boundary (Bootstrap v4)

Similar to viewport, in Bootstrap version 4, popover introduced the new option boundary

https://getbootstrap.com/docs/4.1/components/popovers/#options

How can I make a menubar fixed on the top while scrolling

The postition:absolute; tag positions the element relative to it's immediate parent. I noticed that even in the examples, there isn't room for scrolling, and when i tried it out, it didn't work. Therefore, to pull off the facebook floating menu, the position:fixed; tag should be used instead. It displaces/keeps the element at the given/specified location, and the rest of the page can scroll smoothly - even with the responsive ones.

Please see CSS postion attribute documentation when you can :)

How does the "position: sticky;" property work?

I know it's too late. But I found a solution even if you are using overflow or display:flex in parent elements sticky will work.

steps:

  1. Create a parent element for the element you want to set sticky (Get sure that the created element is relative to body or to full-width & full-height parent).

  2. Add the following styles to the parent element:

    { position: absolute; height: 100vmax; }

  3. For the sticky element, get sure to add z-index that is higher than all elements in the page.

That's it! Now it must work. Regards

How to make div's percentage width relative to parent div and not viewport

Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

For your purpose, you can just use

position: absolute;
top: 0%;

and it still be resizable, scrollable and responsive.

How to make fixed header table inside scrollable div?

Some of these answers seem unnecessarily complex. Make your tbody:

display: block; height: 300px; overflow-y: auto

Then manually set the widths of each column so that the thead and tbody columns are the same width. Setting the table's style="table-layout: fixed" may also be necessary.

Set Google Maps Container DIV width and height 100%

This Work for me.

    <!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css"> 

#cont{
    position: relative;
    width: 300px;
    height: 300px;
}
#map_canvas{
    overflow: hidden;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
</style> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=APIKEY"></script>
<script type="text/javascript">
function initialize() {
    console.log("Initializing...");
  var latlng = new google.maps.LatLng(LAT, LNG);
    var myOptions = {
      zoom: 10,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
}
</script>
</head>

<body onload="initialize()">
<div id="cont">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</div>
</body>
</html>

How to place a div on the right side with absolute position

I'm assuming that your container element is probably position:relative;. This is will mean that the dialog box will be positioned accordingly to the container, not the page.

Can you change the markup to this?

<html>
<body>
    <!-- Need to place this div at the top right of the page-->
        <div class="ajax-message">
            <div class="row">
                <div class="span9">
                    <div class="alert">
                        <a class="close icon icon-remove"></a>
                        <div class="message-content">
                            Some message goes here
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <div class="container">
        <!-- Page contents starts here. These are dynamic-->
        <div class="row">
            <div class="span12 inner-col">
                <h2>Documents</h2>
            </div>
        </div>
    </div>
</body>
</html>

With the dialog box outside the main container then you can use absolute positioning relative to the page.

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

A trick that works is to position box #2 with position: absolute instead of position: relative. We usually put a position: relative on an outer box (here box #2) when we want an inner box (here box #3) with position: absolute to be positioned relative to the outer box. But remember: for box #3 to be positioned relative to box #2, box #2 just need to be positioned. With this change, we get:

And here is the full code with this change:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <style type="text/css">

            /* Positioning */
            #box1 { overflow: hidden }
            #box2 { position: absolute }
            #box3 { position: absolute; top: 10px }

            /* Styling */
            #box1 { background: #efe; padding: 5px; width: 125px }
            #box2 { background: #fee; padding: 2px; width: 100px; height: 100px }
            #box3 { background: #eef; padding: 2px; width: 75px; height: 150px }

        </style>
    </head>
    <body>
        <br/><br/><br/>
        <div id="box1">
            <div id="box2">
                <div id="box3"/>
            </div>
        </div>
    </body>
</html>

Position one element relative to another in CSS

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">
  <div class="top left"></div>
  <div class="top right"></div>
  <div class="bottom left"></div>
  <div class="bottom right"></div>
</div>

And this CSS should work:

#container {
  position: relative;
}

#container > * {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

...

Center an element with "absolute" position and undefined width in CSS?

Absolute Centre

HTML:

<div class="parent">
  <div class="child">
    <!-- content -->
  </div>
</div>

CSS:

.parent {
  position: relative;
}

.child {
  position: absolute;
  
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  margin: auto;
}

Demo: http://jsbin.com/rexuk/2/

It was tested in Google Chrome, Firefox, and Internet Explorer 8.

node.js http 'get' request with query string parameters

If you don't want use external package , Just add the following function in your utilities :

var params=function(req){
  let q=req.url.split('?'),result={};
  if(q.length>=2){
      q[1].split('&').forEach((item)=>{
           try {
             result[item.split('=')[0]]=item.split('=')[1];
           } catch (e) {
             result[item.split('=')[0]]='';
           }
      })
  }
  return result;
}

Then , in createServer call back , add attribute params to request object :

 http.createServer(function(req,res){
     req.params=params(req); // call the function above ;
      /**
       * http://mysite/add?name=Ahmed
       */
     console.log(req.params.name) ; // display : "Ahmed"

})

How to get the value of an input field using ReactJS?

You should use constructor under the class MyComponent extends React.Component

constructor(props){
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

Then you will get the result of title

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

Word-wrap in an HTML table

Change your code

word-wrap: break-word;

to

word-break:break-all;

Example

_x000D_
_x000D_
<table style="width: 100%;">_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div style="word-break:break-all;">longtextwithoutspacelongtextwithoutspace Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content</div>_x000D_
    </td>_x000D_
    <td><span style="display: inline;">Short Content</span>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Installing NumPy via Anaconda in Windows

I had the same problem, getting the message "ImportError: No module named numpy".

I'm also using anaconda and found out that I needed to add numpy to the ENV I was using. You can check the packages you have in your environment with the command:

conda list

So, when I used that command, numpy was not displayed. If that is your case, you just have to add it, with the command:

conda install numpy

After I did that, the error with the import numpy was gone

Subset dataframe by multiple logical conditions of rows to remove

my.df <- read.table(textConnection("
v1 v2 v3 v4
a  v  d  c
a  v  d  d
b  n  p  g
b  d  d  h    
c  k  d  c    
c  r  p  g
d  v  d  x
d  v  d  c
e  v  d  b
e  v  d  c"), header = TRUE)

my.df[which(my.df$v1 != "b" & my.df$v1 != "d" & my.df$v1 != "e" ), ]

  v1 v2 v3 v4
1  a  v  d  c
2  a  v  d  d
5  c  k  d  c
6  c  r  p  g

anaconda/conda - install a specific package version

There is no version 1.3.0 for rope. 1.3.0 refers to the package cached-property. The highest available version of rope is 0.9.4.

You can install different versions with conda install package=version. But in this case there is only one version of rope so you don't need that.

The reason you see the cached-property in this listing is because it contains the string "rope": "cached-p rope erty"

py35_0 means that you need python version 3.5 for this specific version. If you only have python3.4 and the package is only for version 3.5 you cannot install it with conda.

I am not quite sure on the defaults either. It should be an indication that this package is inside the default conda channel.

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

Execute PHP function with onclick

In javascript, make an ajax function,

function myAjax() {
      $.ajax({
           type: "POST",
           url: 'your_url/ajax.php',
           data:{action:'call_this'},
           success:function(html) {
             alert(html);
           }

      });
 }

Then call from html,

<a href="" onclick="myAjax()" class="deletebtn">Delete</a>

And in your ajax.php,

if($_POST['action'] == 'call_this') {
  // call removeday() here
}

How do you list volumes in docker containers?

Show names and mount point destinations of volumes used by a container:

docker container inspect \
 -f '{{ range .Mounts }}{{ .Name }}:{{ .Destination }} {{ end }}' \
 CONTAINER_ID_OR_NAME

This is compatible with Docker 1.13.

How to convert string to integer in PowerShell

You can specify the type of a variable before it to force its type. It's called (dynamic) casting (more information is here):

$string = "1654"
$integer = [int]$string

$string + 1
# Outputs 16541

$integer + 1
# Outputs 1655

As an example, the following snippet adds, to each object in $fileList, an IntVal property with the integer value of the Name property, then sorts $fileList on this new property (the default is ascending), takes the last (highest IntVal) object's IntVal value, increments it and finally creates a folder named after it:

# For testing purposes
#$fileList = @([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })
# OR
#$fileList = New-Object -TypeName System.Collections.ArrayList
#$fileList.AddRange(@([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })) | Out-Null

$highest = $fileList |
    Select-Object *, @{ n = "IntVal"; e = { [int]($_.Name) } } |
    Sort-Object IntVal |
    Select-Object -Last 1

$newName = $highest.IntVal + 1

New-Item $newName -ItemType Directory

Sort-Object IntVal is not needed so you can remove it if you prefer.

[int]::MaxValue = 2147483647 so you need to use the [long] type beyond this value ([long]::MaxValue = 9223372036854775807).

key_load_public: invalid format

So, after update I had the same issue. I was using PEM key_file without extension and simply adding .pem fixed my issue. Now the file is key_file.pem.

CSS content property: is it possible to insert HTML instead of Text?

In CSS3 paged media this is possible using position: running() and content: element().

Example from the CSS Generated Content for Paged Media Module draft:

@top-center {
  content: element(heading); 
}

.runner { 
  position: running(heading);
}

.runner can be any element and heading is an arbitrary name for the slot.

EDIT: to clarify, there is basically no browser support so this was mostly meant to be for future reference/in addition to the 'practical answers' given already.

conditional Updating a list using LINQ

cleaner way to do this is using foreach

foreach(var item in li.Where(w => w.name =="di"))
{
   item.age=10;
}

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

browser sessionStorage. share between tabs?

Using sessionStorage for this is not possible.

From the MDN Docs

Opening a page in a new tab or window will cause a new session to be initiated.

That means that you can't share between tabs, for this you should use localStorage

Multiline string literal in C#

One other gotcha to watch for is the use of string literals in string.Format. In that case you need to escape curly braces/brackets '{' and '}'.

// this would give a format exception
string.Format(@"<script> function test(x) 
      { return x * {0} } </script>", aMagicValue)
// this contrived example would work
string.Format(@"<script> function test(x) 
      {{ return x * {0} }} </script>", aMagicValue)

Use custom build output folder when using create-react-app

Quick compatibility build script (also works on Windows):

"build": "react-scripts build && rm -rf docs && mv build docs"

Copying text to the clipboard using Java

This works for me and is quite simple:

Import these:

import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;

And then put this snippet of code wherever you'd like to alter the clipboard:

String myString = "This text will be copied into clipboard";
StringSelection stringSelection = new StringSelection(myString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);

Where is NuGet.Config file located in Visual Studio project?

In addition to the accepted answer, I would like to add one info, that NuGet packages in Visual Studio 2017 are located in the project file itself. I.e., right click on the project -> edit, to find all package reference entries.

How to change an application icon programmatically in Android?

AndroidManifest.xml example:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name="com.pritesh.resourceidentifierexample.MainActivity"
                  android:label="@string/app_name"
                  android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <!--<category android:name="android.intent.category.LAUNCHER"/>-->
            </intent-filter>
        </activity>

        <activity-alias android:label="RED"
                        android:icon="@drawable/ic_android_red"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Red"
                        android:enabled="true"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

        <activity-alias android:label="GREEN"
                        android:icon="@drawable/ic_android_green"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Green"
                        android:enabled="false"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

        <activity-alias android:label="BLUE"
                        android:icon="@drawable/ic_android_blue"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Blue"
                        android:enabled="false"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

    </application>

Then follow below given code in MainActivity:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
            int imageResourceId;
            String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
            int hours = new Time(System.currentTimeMillis()).getHours();
            Log.d("DATE", "onCreate: "  + hours);

            getPackageManager().setComponentEnabledSetting(
                    getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

            if(hours == 13)
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_red", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Red"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
            }else if(hours == 14)
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_green", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Green"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

            }else
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_blue", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Blue"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

            }

            imageView.setImageResource(imageResourceId);

How to see full absolute path of a symlink

unix flavors -> ll symLinkName

OSX -> readlink symLinkName

Difference is 1st way would display the sym link path in a blinking way and 2nd way would just echo it out on the console.

How to solve '...is a 'type', which is not valid in the given context'? (C#)

You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();

What is the difference between Cygwin and MinGW?

Cygwin uses a compatibility layer, while MinGW is native. That is one of the main differences.

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Each individual Web App under an IIS Web Site can use a different App Pool.

Verify the App Pool assigned to your app (not just the root site per your pictures) is .NET 4.0 compatible:

  1. Expand Default Web Site
  2. Right click on ProjectPALS, choose 'Manage Application' then 'Advanced...'
  3. Observe the 'Application Pool' your app is running as under the site
  4. Change to another App Pool if neccessary

How to set cursor position in EditText?

I want to set cursor position in edittext which contains no data

There is only one position in an empty EditText, it's setSelection(0).

Or did you mean you want to get focus to your EditText when your activity opens? In that case its requestFocus()

Effective swapping of elements of an array in Java

If you want to swap string. it's already the efficient way to do that.

However, if you want to swap integer, you can use XOR to swap two integers more efficiently like this:

int a = 1; int b = 2; a ^= b; b ^= a; a ^= b;

enable or disable checkbox in html

In jsp you can do it like this:

<%
boolean checkboxDisabled = true; //do your logic here
String checkboxState = checkboxDisabled ? "disabled" : "";
%>
<input type="checkbox" <%=checkboxState%>>

Draw line in UIView

The easiest way in your case (horizontal line) is to add a subview with black background color and frame [0, 200, 320, 1].

Code sample (I hope there are no errors - I wrote it without Xcode):

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 1)];
lineView.backgroundColor = [UIColor blackColor];
[self.view addSubview:lineView];
[lineView release];
// You might also keep a reference to this view 
// if you are about to change its coordinates.
// Just create a member and a property for this...

Another way is to create a class that will draw a line in its drawRect method (you can see my code sample for this here).

Android: Background Image Size (in Pixel) which Support All Devices

My understanding is that if you use a View object (as supposed to eg. android:windowBackground) Android will automatically scale your image to the correct size. The problem is that too much scaling can result in artifacts (both during up and down scaling) and blurring. Due to various resolutions and aspects ratios on the market, it's impossible to create "perfect" fits for every screen, but you can do your best to make sure only a little bit of scaling has to be done, and thus mitigate the unwanted side effects. So what I would do is:

  • Keep to the 3:4:6:8:12:16 scaling ratio between the six generalized densities (ldpi, mdpi, hdpi, etc).
  • You should not include xxxhdpi elements for your UI elements, this resolution is meant for upscaling launcher icons only (so mipmap folder only) ... You should not use the xxxhdpi qualifier for UI elements other than the launcher icon. ... although eg. on the Samsung edge 7 calling getDisplayMetrics().density returns 4 (xxxhdpi), so perhaps this info is outdated.
  • Then look at the new phone models on the market, and find the representative ones. Assumming the new google pixel is a good representation of an android phone: It has a 1080 x 1920 resolution at 441 dpi, and a screen size of 4.4 x 2.5 inches. Then from the the android developer docs:

    • ldpi (low) ~120dpi
    • mdpi (medium) ~160dpi
    • hdpi (high) ~240dpi
    • xhdpi (extra-high) ~320dpi
    • xxhdpi (extra-extra-high) ~480dpi
    • xxxhdpi (extra-extra-extra-high) ~640dpi

    This corresponds to an xxhdpi screen. From here I could scale these 1080 x 1920 down by the (3:4:6:8:12) ratios above.

  • I could also acknowledge that downsampling is generally an easy way to scale and thus I might want slightly oversized bitmaps bundled in my apk (Note: higher memory consumption). Once more assuming that the width and height of the pixel screen is represetative, I would scale up the 1080x1920 by a factor of 480/441, leaving my maximum resolution background image at approx. 1200x2100, which should then be scaled by the 3:4:6:8:12.
  • Remember, you only need to provide density-specific drawables for bitmap files (.png, .jpg, or .gif) and Nine-Patch files (.9.png). If you use XML files to define drawable resources (eg. shapes), just put one copy in the default drawable directory.
  • If you ever have to accomodate really large or odd aspect ratios, create specific folders for these as well, using the flags for this, eg. sw, long, large, etc.
  • And no need to draw the background twice. Therefore set a style with <item name="android:windowBackground">@null</item>

Do copyright dates need to be updated?

Your OCD is to blame :)

You do not have to put anything about copyright on your page - copyright automatically applies until you explicitly license it otherwise. Copyright also applies for a preset number of years as determined by international treaties. I do not know what the exact number of years is, but it is a lot, so there is absolutely no point in updating the year in your copyright notice.

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

Change status bar color with AppCompat ActionBarActivity

Applying

    <item name="android:statusBarColor">@color/color_primary_dark</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>

in Theme.AppCompat.Light.DarkActionBar didn't worked for me. What did the trick is , giving colorPrimaryDark as usual along with android:colorPrimary in styles.xml

<item name="android:colorAccent">@color/color_primary</item>
<item name="android:colorPrimary">@color/color_primary</item>
<item name="android:colorPrimaryDark">@color/color_primary_dark</item>

and in setting

if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    Window window = this.Window;
                    Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
                }

didn't had to set statusbar color in code .

Accessing attributes from an AngularJS directive

See section Attributes from documentation on directives.

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

HttpContext.Current.User.Identity.Name is Empty

As @PaulTheCyclist says, If using IISExpress anonymous authentication is enabled by default, windows authentication is disabled.

This can be changed in what I'm sure used to be called PropertyPages (NOT right-click -> properties). Select the web project

Custom circle button

Use xml drawable like this:

Save the following contents as round_button.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="oval">
            <solid android:color="#fa09ad"/>
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape android:shape="oval">
            <solid android:color="#c20586"/>
        </shape>
    </item>
</selector>

Android Material Effect: Although FloatingActionButton is a better option, If you want to do it using xml selector, create a folder drawable-v21 in res and save another round_button.xml there with following xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#c20586">
    <item>
        <shape android:shape="oval">
            <solid android:color="#fa09ad"/>
        </shape>
    </item>
</ripple>

And set it as background of Button in xml like this:

<Button
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/round_button"
android:gravity="center_vertical|center_horizontal"
android:text="hello"
android:textColor="#fff" />

Important:

  1. If you want it to show all these states (enabled, disabled, highlighted etc), you will use selector as described here.
  2. You've to keep both files in order to make the drawable backward-compatible. Otherwise, you'll face weird exceptions in previous android version.

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

How do I add a placeholder on a CharField in Django?

class FormClass(forms.ModelForm):
    class Meta:
        model = Book
        fields = '__all__'
        widgets = {
            'field_name': forms.TextInput(attrs={'placeholder': 'Type placeholder text here..'}),
        }

Asynchronously wait for Task<T> to complete with timeout

Using Stephen Cleary's excellent AsyncEx library, you can do:

TimeSpan timeout = TimeSpan.FromSeconds(10);

using (var cts = new CancellationTokenSource(timeout))
{
    await myTask.WaitAsync(cts.Token);
}

TaskCanceledException will be thrown in the event of a timeout.

What is Hash and Range Primary Key?

"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:

Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.

This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.


Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.

This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:

Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false

I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.

How can query string parameters be forwarded through a proxy_pass with nginx?

you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3

S3 Static Website Hosting Route All Paths to Index.html

adopted to your needs would be something like

location /service/ {
    rewrite ^\/service\/(.*) /$1 break;
    proxy_pass http://apache;
}

if you want to end up in http://127.0.0.1:8080/query/params/

if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like

location /service/ {
    rewrite ^\/(.*) /$1 break;
    proxy_pass http://apache;
}

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

Just in case...
If you are using SoapUI Mock Service (as the Server), calling it from a C# WCF:

WCF --> SoapUI MockService

And in this case you are getting the same error:

The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8).

Edit your Mock Response at SoapUI and add a Header to it: enter image description here

In my scenario, this fix the problem.

Create a new TextView programmatically then display it below another TextView

You're not assigning any id to the text view, but you're using tv.getId() to pass it to the addRule method as a parameter. Try to set a unique id via tv.setId(int).

You could also use the LinearLayout with vertical orientation, that might be easier actually. I prefer LinearLayout over RelativeLayouts if not necessary otherwise.

FULL OUTER JOIN vs. FULL JOIN

Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:

  • LEFT OUTER JOIN or LEFT JOIN

  • RIGHT OUTER JOIN or RIGHT JOIN

  • FULL OUTER JOIN or FULL JOIN

From MSDN

The full outer join or full join returns all rows from both tables, matching up the rows wherever a match can be made and placing NULLs in the places where no matching row exists.

Vertical Alignment of text in a table cell

Try

_x000D_
_x000D_
td.description {_x000D_
  line-height: 15px_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
_x000D_
_x000D_

Set the line-height value to the desired value.

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

<div class="col d-none d-sm-block">
    <span class="vcard">
        …
    </span>
</div>
<div class="col d-none d-xl-block">
    <div class="d-none d-md-block">
                …
    </div>
    <div class="d-none d-sm-block">
                …
    </div>
</div>

class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

<span class="d-none d-sm-inline">hidden-xs</span>

<span class="d-none d-sm-inline-block">hidden-xs</span>

An example of Bootstrap 4 responsive utilities:

<div class="d-none d-sm-block"> hidden-xs           
  <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
    <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
      <div class="d-none d-xl-block"> visible-xl </div>
    </div>
  </div>
</div>

<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>

<div class="d-xl-none"> hidden-xl (visible-lg and down)         
  <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
    <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
      <div class="d-sm-none"> visible-xs </div>
    </div>
  </div>
</div>

Documentation

JNI converting jstring to char *

Here's a a couple of useful link that I found when I started with JNI

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}

Correct way to create rounded corners in Twitter Bootstrap

Bootstrap is just a big, useful, yet simple CSS file - not a framework or anything you can't override. I say this because I've noticed many developers got stick with BS classes and became lazy "I-can't-write-CSS-code-anymore" coders [this not being your case of course!].

If it features something you need, go with Bootstrap classes - if not, go write your additional code in good ol' style.css.

To have best of both worlds, you may write your own declarations in LESS and recompile the whole thing upon your needs, minimizing server request as a bonus.

How do I set multipart in axios with react?

If you are sending alphanumeric data try changing

'Content-Type': 'multipart/form-data'

to

'Content-Type': 'application/x-www-form-urlencoded'

If you are sending non-alphanumeric data try to remove 'Content-Type' at all.

If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

You may also get this error if you have a name clash of a view and a module. I've got the error when i distribute my view files under views folder, /views/view1.py, /views/view2.py and imported some model named table.py in view2.py which happened to be a name of a view in view1.py. So naming the view functions as v_table(request,id) helped.

How to launch jQuery Fancybox on page load?

why isn't this one of the answers yet?:

$("#manual2").click(function() {
    $.fancybox([
        'http://farm5.static.flickr.com/4044/4286199901_33844563eb.jpg',
        'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
        {
            'href'  : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
            'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
        }
    ], {
        'padding'           : 0,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none',
        'type'              : 'image',
        'changeFade'        : 0
    });
});

now just trigger your link!!

got this from the Fancybox homepage

Android: Scale a Drawable or background image?

To keep the aspect ratio you have to use android:scaleType=fitCenter or fitStart etc. Using fitXY will not keep the original aspect ratio of the image!

Note this works only for images with a src attribute, not for the background image.

How to add a TextView to a LinearLayout dynamically in Android?

LayoutParams lparams = new LayoutParams(
   LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);

You can change lparams according to your needs

Is there a better way to refresh WebView?

Yes for some reason WebView.reload() causes a crash if it failed to load before (something to do with the way it handles history). This is the code I use to refresh my webview. I store the current url in self.url

# 1: Pause timeout and page loading

self.timeout.pause()
sleep(1)

# 2: Check for internet connection (Really lazy way)

while self.page().networkAccessManager().networkAccessible() == QNetworkAccessManager.NotAccessible: sleep(2)

# 3:Try again

if self.url == self.page().mainFrame().url():
    self.page().action(QWebPage.Reload)
    self.timeout.resume(60)

else:
    self.page().action(QWebPage.Stop)
    self.page().mainFrame().load(self.url)
    self.timeout.resume(30)

return False

Loading existing .html file with android WebView

paste your .html file in assets folder of your project folder. and create an xml file in layout folder with the fol code: my.xml:

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/webview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
    />

add fol code in activity

setContentView(R.layout.my);
    WebView mWebView = null;
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl("file:///android_asset/new.html"); //new.html is html file name.

jQuery select by attribute using AND and OR operators

AND operation

a=$('[myc="blue"][myid="1"][myid="3"]');

OR operation, use commas

a=$('[myc="blue"],[myid="1"],[myid="3"]');

As @Vega commented:

a=$('[myc="blue"][myid="1"],[myc="blue"][myid="3"]');

How to start mongodb shell?

Try this:

mongod --fork --logpath /var/log/mongodb.log

You may need to create the db-folder:

mkdir -p /data/db

If you get any 'Permission denied'-error, I'ld recommend changing the permissions of the particular files instead of running mongod as root.

While variable is not defined - wait

I have upvoted @dnuttle's answer, but ended up using the following strategy:

// On doc ready for modern browsers
document.addEventListener('DOMContentLoaded', (e) => {
  // Scope all logic related to what you want to achieve by using a function
  const waitForMyFunction = () => {
    // Use a timeout id to identify your process and purge it when it's no longer needed
    let timeoutID;
    // Check if your function is defined, in this case by checking its type
    if (typeof myFunction === 'function') {
      // We no longer need to wait, purge the timeout id
      window.clearTimeout(timeoutID);
      // 'myFunction' is defined, invoke it with parameters, if any
      myFunction('param1', 'param2');
    } else {
      // 'myFunction' is undefined, try again in 0.25 secs
      timeoutID = window.setTimeout(waitForMyFunction, 250);
    }
  };
  // Initialize
  waitForMyFunction();
});

It is tested and working! ;)

Gist: https://gist.github.com/dreamyguy/f319f0b2bffb1f812cf8b7cae4abb47c

VBA for clear value in specific range of cell and protected cell from being wash away formula

Try this

Sheets("your sheetname").range("A5:X50").Value = ""

You can also use

ActiveSheet.range

python selenium click on button

I had the same problem using Phantomjs as browser, so I solved in the following way:

driver.find_element_by_css_selector('div.button.c_button.s_button').click()

Essentially I have added the name of the DIV tag into the quote.

How to pass command-line arguments to a PowerShell ps1 file

Maybe you can wrap the PowerShell invocation in a .bat file like so:

rem ps.bat
@echo off
powershell.exe -command "%*"

If you then placed this file under a folder in your PATH, you could call PowerShell scripts like this:

ps foo 1 2 3

Quoting can get a little messy, though:

ps write-host """hello from cmd!""" -foregroundcolor green

Removing u in list

arr = [str(r) for r in arr]

This basically converts all your elements in string. Hence removes the encoding. Hence the u which represents encoding gets removed Will do the work easily and efficiently

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

How do I get the height of a div's full content with jQuery?

Element.scrollHeight is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow and height to auto, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.

How can I get a file's size in C++?

Using standard library:

Assuming that your implementation meaningfully supports SEEK_END:

fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file

Linux/POSIX:

You can use stat (if you know the filename), or fstat (if you have the file descriptor).

Here is an example for stat:

#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;

Win32:

You can use GetFileSize or GetFileSizeEx.

Does Typescript support the ?. operator? (And, what's it called?)

This is defined in the ECMAScript Optional Chaining specification, so we should probably refer to optional chaining when we discuss this. Likely implementation:

const result = a?.b?.c;

The long and short of this one is that the TypeScript team are waiting for the ECMAScript specification to get tightened up, so their implementation can be non-breaking in the future. If they implemented something now, it would end up needing major changes if ECMAScript redefine their specification.

See Optional Chaining Specification

Where something is never going to be standard JavaScript, the TypeScript team can implement as they see fit, but for future ECMAScript additions, they want to preserve semantics even if they give early access, as they have for so many other features.

Short Cuts

So all of JavaScripts funky operators are available, including the type conversions such as...

var n: number = +myString; // convert to number
var b: bool = !!myString; // convert to bool

Manual Solution

But back to the question. I have an obtuse example of how you can do a similar thing in JavaScript (and therefore TypeScript) although I'm definitely not suggesting it is a graceful as the feature you are really after.

(foo||{}).bar;

So if foo is undefined the result is undefined and if foo is defined and has a property named bar that has a value, the result is that value.

I put an example on JSFiddle.

This looks quite sketchy for longer examples.

var postCode = ((person||{}).address||{}).postcode;

Chain Function

If you are desperate for a shorter version while the specification is still up in the air, I use this method in some cases. It evaluates the expression and returns a default if the chain can't be satisfied or ends up null/undefined (note the != is important here, we don't want to use !== as we want a bit of positive juggling here).

function chain<T>(exp: () => T, d: T) {
    try {
        let val = exp();
        if (val != null) {
            return val;
        }
    } catch { }
    return d;
}

let obj1: { a?: { b?: string }} = {
    a: {
        b: 'c'
    }
};

// 'c'
console.log(chain(() => obj1.a.b, 'Nothing'));

obj1 = {
    a: {}
};

// 'Nothing'
console.log(chain(() => obj1.a.b, 'Nothing'));

obj1 = {};

// 'Nothing'
console.log(chain(() => obj1.a.b, 'Nothing'));

obj1 = null;

// 'Nothing'
console.log(chain(() => obj1.a.b, 'Nothing'));

Installing tkinter on ubuntu 14.04

In Ubuntu 14.04.2 LTS:

  1. Go to Software Center and remove "IDLE(using Python-2.7)".

  2. Install "IDLE(using Python-3.4)".

Try again. This step worked for me.

How to pass a file path which is in assets folder to File(String path)?

Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.

You'll need to unpack the file or use it directly.

If you have a Context, you can use context.getAssets().open("myfoldername/myfilename"); to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).

how does array[100] = {0} set the entire array to 0?

Implementation is up to compiler developers.

If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.

How to use Collections.sort() in Java?

The answer given by NINCOMPOOP can be made simpler using Lambda Expressions:

Collections.sort(recipes, (Recipe r1, Recipe r2) ->
r1.getID().compareTo(r2.getID()));

Also introduced after Java 8 is the comparator construction methods in the Comparator interface. Using these, one can further reduce this to 1:

recipes.sort(comparingInt(Recipe::getId));

1 Bloch, J. Effective Java (3rd Edition). 2018. Item 42, p. 194.

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

Be sure to configure the 'default' key in app/config/database.php

For postgres, this would be 'default' => 'postgres',

If you are receiving a [PDOException] could not find driver error, check to see if you have the correct PHP extensions installed. You need pdo_pgsql.so and pgsql.so installed and enabled. Instructions on how to do this vary between operating systems.

For Windows, the pgsql extensions should come pre-downloaded with the official PHP distribution. Just edit your php.ini and uncomment the lines extension=pdo_pgsql.so and extension=pgsql.so

Also, in php.ini, make sure extension_dir is set to the proper directory. It should be a folder called extensions or ext or similar inside your PHP install directory.

Finally, copy libpq.dll from C:\wamp\bin\php\php5.*\ into C:\wamp\bin\apache*\bin and restart all services through the WampServer interface.

If you still get the exception, you may need to add the postgres \bin directory to your PATH:

  1. System Properties -> Advanced tab -> Environment Variables
  2. In 'System variables' group on lower half of window, scroll through and find the PATH entry.
  3. Select it and click Edit
  4. At the end of the existing entry, put the full path to your postgres bin directory. The bin folder should be located in the root of your postgres installation directory.
  5. Restart any open command prompts, or to be certain, restart your computer.

This should hopefully resolve any problems. For more information see:

Converting milliseconds to a date (jQuery/JavaScript)

_x000D_
_x000D_
var time = new Date().getTime(); // get your number
var date = new Date(time); // create Date object

console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
_x000D_
_x000D_
_x000D_

"Warning: iPhone apps should include an armv6 architecture" even with build config set

In addition to Nick's answer about Xcode 4.2, you may also need to review your info.plist file. It seems as if new projects started in Xcode 4.2 by default specify 'armv7' in the 'Required Device Capabilities'. You'll need to remove this if wanting to support devices that run armv6 (e.g. the iPhone 3G).

enter image description here

Delete armv7 from the 'Required device capabilities' in yourProjectName-Info.plist

Save results to csv file with Python

Use csv.writer:

import csv

with open('thefile.csv', 'rb') as f:
  data = list(csv.reader(f))

import collections
counter = collections.defaultdict(int)
for row in data:
    counter[row[0]] += 1


writer = csv.writer(open("/path/to/my/csv/file", 'w'))
for row in data:
    if counter[row[0]] >= 4:
        writer.writerow(row)

NodeJS / Express: what is "app.use"?

app.use() used to Mounts the middleware function or mount to a specified path,the middleware function is executed when the base path matches.

For example: if you are using app.use() in indexRouter.js , like this:

//indexRouter.js

var adsRouter = require('./adsRouter.js');

module.exports = function(app) {
    app.use('/ads', adsRouter);
}

In the above code app.use() mount the path on '/ads' to adsRouter.js.

Now in adsRouter.js

// adsRouter.js

var router = require('express').Router();
var controllerIndex = require('../controller/index');
router.post('/show', controllerIndex.ads.showAd);
module.exports = router;

in adsRouter.js, the path will be like this for ads- '/ads/show', and then it will work according to controllerIndex.ads.showAd().

app.use([path],callback,[callback]) : we can add a callback on the same.

app.use('/test', function(req, res, next) {

  // write your callback code here.

    });

Remote JMX connection

To enable JMX remote, pass below VM parameters along with JAVA Command.

    -Dcom.sun.management.jmxremote 
    -Dcom.sun.management.jmxremote.port=453
    -Dcom.sun.management.jmxremote.authenticate=false                               
    -Dcom.sun.management.jmxremote.ssl=false 
    -Djava.rmi.server.hostname=myDomain.in

Creating a UITableView Programmatically

You might be do that its works 100% .

- (void)viewDidLoad
{
    [super viewDidLoad];
    // init table view
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

    // must set delegate & dataSource, otherwise the the table will be empty and not responsive
    tableView.delegate = self;
    tableView.dataSource = self;

    tableView.backgroundColor = [UIColor cyanColor];

    // add to canvas
    [self.view addSubview:tableView];
}

#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
    return 1;
}

// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    // Similar to UITableViewCell, but 
    JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    // Just want to test, so I hardcode the data
    cell.descriptionLabel.text = @"Testing";

    return cell;
}

#pragma mark - UITableViewDelegate
// when user tap the row, what action you want to perform
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected %d row", indexPath.row);
}

@end

Refresh a page using PHP

You sure can refresh a page periodically using PHP:

<?php
    header("refresh: 3;");
?>

This will refresh the page every three seconds.

How to get substring of NSString?

Here is a little combination of @Regexident Option 1 and @Garett answers, to get a powerful string cutter between a prefix and suffix, with MORE...ANDMORE words on it.

NSString *haystack = @"MOREvalue:hello World:valueANDMORE";
NSString *prefix = @"value:";
NSString *suffix = @":value";
NSRange prefixRange = [haystack rangeOfString:prefix];
NSRange suffixRange = [[haystack substringFromIndex:prefixRange.location+prefixRange.length] rangeOfString:suffix];
NSRange needleRange = NSMakeRange(prefixRange.location+prefix.length, suffixRange.location);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle);

Creating a system overlay window (always on top)

Found a library that does just that: https://github.com/recruit-lifestyle/FloatingView

There's a sample project in the root folder. I ran it and it works as required. The background is clickable - even if it's another app.

enter image description here

How to replace text of a cell based on condition in excel

You can use the IF statement in a new cell to replace text, such as:

=IF(A4="C", "Other", A4)

This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.

EDIT

Assuming that the Employee_Count values are in B1-B10, you can use this:

=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)

This function doesn't even require the data to be sorted; the LARGE function will find the 10th largest number in the series, and then the rest of the formula will compare against that.

VBA using ubound on a multidimensional array

You need to deal with the optional Rank parameter of UBound.

Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1)  '? returns 4
Debug.Print UBound(arr, 2)  '? returns 3

More at: UBound Function (Visual Basic)

Loop timer in JavaScript

You should try something like this:

 function update(){
    i++;
    document.getElementById('tekst').innerHTML = i;
    setInterval(update(),1000);
    }

This means that you have to create a function in which you do the stuff you need to do, and make sure it will call itself with an interval you like. In your body onload call the function for the first time like this:

<body onload="update()">

Swift 3 - Comparing Date objects

Look this http://iswift.org/cookbook/compare-2-dates

Get Dates:

// Get current date
let dateA = NSDate()

// Get a later date (after a couple of milliseconds)
let dateB = NSDate()

Using SWITCH Statement

// Compare them
switch dateA.compare(dateB) {
    case .OrderedAscending     :   print("Date A is earlier than date B")
    case .OrderedDescending    :   print("Date A is later than date B")
    case .OrderedSame          :   print("The two dates are the same")
}

using IF Statement

 if dateA.compare(dateB) == .orderedAscending {
     datePickerTo.date = datePicker.date
 }

 //OR

 if case .orderedAcending = dateA.compare(dateB) {

 }

how to add key value pair in the JSON object already declared

you can do try lodash

Example code for json object:

_x000D_
_x000D_
    var user = {'user':'barney','age':36};
    user["newKey"] = true;
    console.log(user);
_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>
<script src="lodash.js"></script>
_x000D_
_x000D_
_x000D_

for json array elements

Example code:

_x000D_
_x000D_
var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

users.map(i=>{i["newKey"] = true});

console.log(users);
_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>
<script src="lodash.js"></script>
_x000D_
_x000D_
_x000D_

Find the nth occurrence of substring in a string

I'd probably do something like this, using the find function that takes an index parameter:

def find_nth(s, x, n):
    i = -1
    for _ in range(n):
        i = s.find(x, i + len(x))
        if i == -1:
            break
    return i

print find_nth('bananabanana', 'an', 3)

It's not particularly Pythonic I guess, but it's simple. You could do it using recursion instead:

def find_nth(s, x, n, i = 0):
    i = s.find(x, i)
    if n == 1 or i == -1:
        return i 
    else:
        return find_nth(s, x, n - 1, i + len(x))

print find_nth('bananabanana', 'an', 3)

It's a functional way to solve it, but I don't know if that makes it more Pythonic.

python JSON only get keys in first level

A good way to check whether a python object is an instance of a type is to use isinstance() which is Python's 'built-in' function. For Python 3.6:

dct = {
       "1": "a", 
       "3": "b", 
       "8": {
            "12": "c", 
            "25": "d"
           }
      }

for key in dct.keys():
    if isinstance(dct[key], dict)== False:
       print(key, dct[key])
#shows:
# 1 a
# 3 b

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

this worked for me on iis8 together with some of the other answers. My error was a 404.6 specifically

<system.webServer>
  <security>
  <requestFiltering>
    <verbs applyToWebDAV="false">
       <add verb="DELETE" allowed="true" />
    </verbs>
  </requestFiltering>
  </security>
</system.webServer>

Swift: Reload a View Controller

In Swift 4:

self.view.layoutIfNeeded()

PostgreSQL - query from bash script as database user 'postgres'

To ans to @Jason 's question, in my bash script, I've dome something like this (for my purpose):

dbPass='xxxxxxxx'
.....
## Connect to the DB
PGPASSWORD=${dbPass} psql -h ${dbHost} -U ${myUsr} -d ${myRdb} -P pager=on --set AUTOCOMMIT=off

The another way of doing it is:

psql --set AUTOCOMMIT=off --set ON_ERROR_STOP=on -P pager=on \
     postgresql://${myUsr}:${dbPass}@${dbHost}/${myRdb}

but you have to be very careful about the password: I couldn't make a password with a ' and/or a : to work in that way. So gave up in the end.

-S

PDO get the last ID inserted

lastInsertId() only work after the INSERT query.

Correct:

$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                              VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0

How do you make sure email you send programmatically is not automatically marked as spam?

First of all, you need to ensure the required email authentication mechanisms like SPF and DKIM are in place. These two are prominent ways of proving that you were the actual sender of an email and it's not really spoofed. This reduces the chances of emails getting filtered as spam.

Second thing is, you can check the reverse DNS output of your domain name against different DNSBLs. Use below simple command on terminal:

  **dig a +short (domain-name).(blacklist-domain-name)**

  ie.  dig a +short example.com.dsn.rfc-clueless.org
  > 127.0.0.2

In the above examples, this means your domain "example.com" is listed in blacklist but due to Domain Setting Compliance(rfc-clueless.org list domain which has compliance issue )

note: I prefer multivalley and pepipost tool for checking the domain listings.

The from address/reply-to-id should be proper, always use visible unsubscribe button within your email body (this will help your users to sign out from your email-list without killing your domain reputation)

Android Gradle Apache HttpClient does not exist?

This is what I did, and it works for me.

step 1: add this in the build.grade(module: app)

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

step 2: sync the project and done.

Temporarily switch working copy to a specific Git commit

In addition to the other answers here showing you how to git checkout <the-hash-you-want> it's worth knowing you can switch back to where you were using:

git checkout @{-1}

This is often more convenient than:

git checkout what-was-that-original-branch-called-again-question-mark

As you might anticipate, git checkout @{-2} will take you back to the branch you were at two git checkouts ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.


Sadly for productivity, git checkout @{1} does not take you to the branch you will be on in future, which is a shame.

How to find the index of an element in an array in Java?

Very Heavily Edited. I think either you want this:

class CharStorage {
    /** set offset to 1 if you want b=1, o=2, y=3 instead of b=0... */
    private final int offset=0;
    private int array[]=new int[26];

    /** Call this with up to 26 characters to initialize the array.  For 
      * instance, if you pass "boy" it will init to b=0,o=1,y=2.
      */
    void init(String s) {
        for(int i=0;i<s.length;i++)
            store(s.charAt(i)-'a' + offset,i); 
    }

    void store(char ch, int value) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        array[ch-'a']=value;
    }

    int get(char ch) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        return array[ch-'a'];
    }
}

(Note that you may have to adjust the init method if you want to use 1-26 instead of 0-25)

or you want this:

int getLetterPossitionInAlphabet(char c) {
    return c - 'a' + 1
}

The second is if you always want a=1, z=26. The first will let you put in a string like "qwerty" and assign q=0, w=1, e=2, r=3...

Get the current time in C

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

void main()
{
    time_t t;
    time(&t);
    clrscr();

    printf("Today's date and time : %s",ctime(&t));
    getch();
}

load jquery after the page is fully loaded

You can either use .onload function. It runs a function when the page is fully loaded including graphics.

window.onload=function(){
      // Run code
    };

Or another way is : Include scripts at the bottom of your page.

How do I query between two dates using MySQL?

Might be a problem with date configuration on server side or on client side. I've found this to be a common problem on multiple databases when the host is configured in spanish, french or whatever... that could affect the format dd/mm/yyyy or mm/dd/yyyy.

What is the difference between a hash join and a merge join (Oracle RDBMS )?

A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.

A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.

(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).

The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:

  1. The size of each hash table is reduced, hence reducing the maximum amount of memory required and potentially removing the need for the operation to require temporary disk space.
  2. For parallel query operations the amount of inter-process messaging is vastly reduced, reducing CPU usage and improving performance, as each hash join can be performed by one pair of PQ processes.
  3. For non-parallel query operations the memory requirement is reduced by a factor of n, and the first rows are projected from the query earlier.

You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.

In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.

This topic is very well covered in the documentation.

http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523

12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm

Phone mask with jQuery and Masked Input Plugin

You can use the phone alias with Inputmask v3

$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });

_x000D_
_x000D_
$(function() {_x000D_
  $('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });_x000D_
});
_x000D_
<label for="phone">Phone</label>_x000D_
    <input name="phone" type="tel">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.numeric.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.date.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.phone.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/jquery.inputmask.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/phone-codes/phone.js"></script>
_x000D_
_x000D_
_x000D_

https://github.com/RobinHerbots/Inputmask#aliases

Returning http status code from Web Api controller

In MVC 5, things got easier:

return new StatusCodeResult(HttpStatusCode.NotModified, this);

MySQL: Quick breakdown of the types of joins

Based on your comment, simple definitions of each is best found at W3Schools The first line of each type gives a brief explanation of the join type

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

END EDIT

In a nutshell, the comma separated example you gave of

SELECT * FROM a, b WHERE b.id = a.beeId AND ...

is selecting every record from tables a and b with the commas separating the tables, this can be used also in columns like

SELECT a.beeName,b.* FROM a, b WHERE b.id = a.beeId AND ...

It is then getting the instructed information in the row where the b.id column and a.beeId column have a match in your example. So in your example it will get all information from tables a and b where the b.id equals a.beeId. In my example it will get all of the information from the b table and only information from the a.beeName column when the b.id equals the a.beeId. Note that there is an AND clause also, this will help to refine your results.

For some simple tutorials and explanations on mySQL joins and left joins have a look at Tizag's mySQL tutorials. You can also check out Keith J. Brown's website for more information on joins that is quite good also.

I hope this helps you

How do you get the current project directory from C# code when creating a custom MSBuild task?

This works on VS2017 w/ SDK Core MSBuild configurations.

You need to NuGet in the EnvDTE / EnvDTE80 packages.

Do not use COM or interop. anything.... garbage!!

 internal class Program {
    private static readonly DTE2 _dte2;

    // Static Constructor
    static Program() {
      _dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.15.0");
    }


    private static void FindProjectsIn(ProjectItem item, List<Project> results) {
      if (item.Object is Project) {
        var proj = (Project) item.Object;
        if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
          results.Add((Project) item.Object);
        else
          foreach (ProjectItem innerItem in proj.ProjectItems)
            FindProjectsIn(innerItem, results);
      }

      if (item.ProjectItems != null)
        foreach (ProjectItem innerItem in item.ProjectItems)
          FindProjectsIn(innerItem, results);
    }


    private static void FindProjectsIn(UIHierarchyItem item, List<Project> results) {
      if (item.Object is Project) {
        var proj = (Project) item.Object;
        if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
          results.Add((Project) item.Object);
        else
          foreach (ProjectItem innerItem in proj.ProjectItems)
            FindProjectsIn(innerItem, results);
      }

      foreach (UIHierarchyItem innerItem in item.UIHierarchyItems)
        FindProjectsIn(innerItem, results);
    }


    private static IEnumerable<Project> GetEnvDTEProjectsInSolution() {
      var ret = new List<Project>();
      var hierarchy = _dte2.ToolWindows.SolutionExplorer;
      foreach (UIHierarchyItem innerItem in hierarchy.UIHierarchyItems)
        FindProjectsIn(innerItem, ret);
      return ret;
    }


    private static void Main() {
      var projects = GetEnvDTEProjectsInSolution();
      var solutiondir = Path.GetDirectoryName(_dte2.Solution.FullName);

      // TODO
      ...

      var project = projects.FirstOrDefault(p => p.Name == <current project>);
      Console.WriteLine(project.FullName);
    }
  }

Validating IPv4 addresses with regexp

Following is the regex expression to validate the IP-Address.

^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

Django - Static file not found

TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')

STATICFILES_DIRS=[STATIC_DIR]

Ruby on Rails generates model field:type - what are the options for field:type?

There are lots of data types you can mention while creating model, some examples are:

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references

syntax:

field_type:data_type

Append text to file from command line without using io redirection

You can use the --append feature of tee:

cat file01.txt | tee --append bothFiles.txt 
cat file02.txt | tee --append bothFiles.txt 

Or shorter,

cat file01.txt file02.txt | tee --append bothFiles.txt 

I assume the request for no redirection (>>) comes from the need to use this in xargs or similar. So if that doesn't count, you can mute the output with >/dev/null.

RunAs A different user when debugging in Visual Studio

I'm using Visual Studio 2015 and attempting to debug a website with different credentials.

(I'm currently testing a website on a development network that has a copy of the live active directory; I can "hijack" user accounts to test permissions in a safe way)

  1. Begin debugging with your normal user, ensure you can get to http://localhost:8080 as normal etc
  2. Give the other user "Full Control" access to your normal user's home directory, ie, C:\Users\Colin
  3. Make the other user an administrator on your machine. Right click Computer > Manage > Add other user to Administrator group
  4. Run Internet Explorer as the other user (Shift + Right Click Internet Explorer, Run as different user)
  5. Go to your localhost URL in that IE window

Really convenient to do some quick testing. The Full Control access is probably overkill but I develop on an isolated network. If anyone adds notes about more specific settings I'll gladly edit this post in future.

How to build and use Google TensorFlow C++ api

If you don't mind using CMake, there is also tensorflow_cc project that builds and installs TF C++ API for you, along with convenient CMake targets you can link against. The project README contains an example and Dockerfiles you can easily follow.

how to change color of TextinputLayout's label and edittext underline android

With the Material Components Library you can use the com.google.android.material.textfield.TextInputLayout.

You can apply a custom style to change the colors.

To change the hint color you have to use these attributes:
hintTextColor and android:textColorHint.

<style name="Custom_textinputlayout_filledbox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
    <!-- The color of the label when it is collapsed and the text field is active -->
    <item name="hintTextColor">?attr/colorPrimary</item>

    <!-- The color of the label in all other text field states (such as resting and disabled) -->
    <item name="android:textColorHint">@color/selector_hint_text_color</item>
</style>

You should use a selector for the android:textColorHint. Something like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:alpha="0.38" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
  <item android:alpha="0.6" android:color="?attr/colorOnSurface"/>
</selector>

To change the bottom line color you have to use the attribute: boxStrokeColor.

<style name="Custom_textinputlayout_filledbox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
    ....
    <item name="boxStrokeColor">@color/selector_stroke_color</item>
</style>

Also in this case you should use a selector. Something like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="?attr/colorPrimary" android:state_focused="true"/>
  <item android:alpha="0.87" android:color="?attr/colorOnSurface" android:state_hovered="true"/>
  <item android:alpha="0.12" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
  <item android:alpha="0.38" android:color="?attr/colorOnSurface"/>
</selector>

enter image description here enter image description here

You can also apply these attributes in your layout:

<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"
    app:boxStrokeColor="@color/selector_stroke_color"
    app:hintTextColor="?attr/colorPrimary"
    android:textColorHint="@color/selector_hint_text_color"
    ...>

Passing just a type as a parameter in C#

foo.GetColumnValues(dm.mainColumn, typeof(string))

Alternatively, you could use a generic method:

public void GetColumnValues<T>(object mainColumn)
{
    GetColumnValues(mainColumn, typeof(T));
}

and you could then use it like:

foo.GetColumnValues<string>(dm.mainColumn);

How do you sort an array on multiple columns?

Sourced from GitHub

_x000D_
_x000D_
function sortMethodAsc(a, b) {_x000D_
    return a == b ? 0 : a > b ? 1 : -1;_x000D_
}_x000D_
_x000D_
function sortMethodWithDirection(direction) { _x000D_
    if (direction === undefined || direction == "asc") {_x000D_
        return sortMethodAsc;_x000D_
    } else {_x000D_
        return function(a, b) {_x000D_
            return -sortMethodAsc(a, b);_x000D_
        } _x000D_
    }_x000D_
}_x000D_
_x000D_
function sortMethodWithDirectionByColumn(columnName, direction){   _x000D_
    const sortMethod = sortMethodWithDirection(direction)_x000D_
    return function(a, b){_x000D_
        return sortMethod(a[columnName], b[columnName]);_x000D_
    } _x000D_
}_x000D_
_x000D_
function sortMethodWithDirectionMultiColumn(sortArray) {_x000D_
    //sample of sortArray_x000D_
    // sortArray = [_x000D_
    //     { column: "column5", direction: "asc" },_x000D_
    //     { column: "column3", direction: "desc" }_x000D_
    // ]_x000D_
    const sortMethodsForColumn = (sortArray || []).map( item => sortMethodWithDirectionByColumn(item.column, item.direction) );_x000D_
    return function(a,b) {_x000D_
        let sorted = 0;_x000D_
        let index = 0;_x000D_
        while (sorted === 0 && index < sortMethodsForColumn.length) {_x000D_
            sorted = sortMethodsForColumn[index++](a,b);_x000D_
        }_x000D_
        return sorted;_x000D_
    }_x000D_
} _x000D_
_x000D_
//=============================================_x000D_
//=============================================_x000D_
//=============================================_x000D_
//test_x000D_
_x000D_
var data = [_x000D_
    {"CountryName":"Aruba","CountryCode":"ABW","GNI":280},{_x000D_
        "CountryName":"Afghanistan","CountryCode":"ABW","GNI":280},{"CountryName":"Angola","CountryCode":"AGO","GNI":280},{"CountryName":"Albania","CountryCode":"ALB","GNI":4320},_x000D_
        {"CountryName":"Arab World","CountryCode":"ARB","GNI":280},{"CountryName":"United Arab Emirates","CountryCode":"ARE","GNI":39130},_x000D_
        {"CountryName":"Argentina","CountryCode":"ARG","GNI":13030},{"CountryName":"Armenia","CountryCode":"ARM","GNI":3990},{"CountryName":"American Samoa","CountryCode":"ASM","GNI":280},_x000D_
        {"CountryName":"Antigua and Barbuda","CountryCode":"ATG","GNI":13810},{"CountryName":"Australia","CountryCode":"AUS","GNI":51360},_x000D_
        {"CountryName":"Austria","CountryCode":"AUT","GNI":45440},{"CountryName":"Azerbaijan","CountryCode":"AZE","GNI":4080},{"CountryName":"Burundi","CountryCode":"BDI","GNI":280},_x000D_
        {"CountryName":"Belgium","CountryCode":"BEL","GNI":41790},{"CountryName":"Benin","CountryCode":"BEN","GNI":800},{"CountryName":"Burkina Faso","CountryCode":"BFA","GNI":590},_x000D_
        {"CountryName":"Bangladesh","CountryCode":"BGD","GNI":1470},{"CountryName":"Bulgaria","CountryCode":"BGR","GNI":7860},{"CountryName":"Bahrain","CountryCode":"BHR","GNI":21150},_x000D_
        {"CountryName":"Bosnia and Herzegovina","CountryCode":"BIH","GNI":4910},{"CountryName":"Belarus","CountryCode":"BLR","GNI":5280},_x000D_
        {"CountryName":"Belize","CountryCode":"BLZ","GNI":4390},{"CountryName":"Bolivia","CountryCode":"BOL","GNI":3130},{"CountryName":"Brazil","CountryCode":"BRA","GNI":8600},_x000D_
        {"CountryName":"Barbados","CountryCode":"BRB","GNI":15270},{"CountryName":"Brunei Darussalam","CountryCode":"BRN","GNI":29600},_x000D_
        {"CountryName":"Bhutan","CountryCode":"BTN","GNI":2660},{"CountryName":"Botswana","CountryCode":"BWA","GNI":6730},_x000D_
        {"CountryName":"Central African Republic","CountryCode":"CAF","GNI":390},{"CountryName":"Canada","CountryCode":"CAN","GNI":42870},_x000D_
        {"CountryName":"Central Europe and the Baltics","CountryCode":"CEB","GNI":13009},{"CountryName":"Switzerland","CountryCode":"CHE","GNI":80560},_x000D_
        {"CountryName":"Chile","CountryCode":"CHL","GNI":13610},{"CountryName":"China","CountryCode":"CHN","GNI":8690},{"CountryName":"Cote d'Ivoire","CountryCode":"CIV","GNI":1580},_x000D_
        {"CountryName":"Cameroon","CountryCode":"CMR","GNI":1370},{"CountryName":"Colombia","CountryCode":"COL","GNI":5890},{"CountryName":"Comoros","CountryCode":"COM","GNI":1280},_x000D_
        {"CountryName":"Cabo Verde","CountryCode":"CPV","GNI":3030},{"CountryName":"Costa Rica","CountryCode":"CRI","GNI":11120},_x000D_
        {"CountryName":"Caribbean small states","CountryCode":"CSS","GNI":8909},{"CountryName":"Cyprus","CountryCode":"CYP","GNI":23720},_x000D_
        {"CountryName":"Czech Republic","CountryCode":"CZE","GNI":18160},{"CountryName":"Germany","CountryCode":"DEU","GNI":43490},_x000D_
        {"CountryName":"Djibouti","CountryCode":"DJI","GNI":1880},{"CountryName":"Dominica","CountryCode":"DMA","GNI":6590},{"CountryName":"Denmark","CountryCode":"DNK","GNI":55220},_x000D_
        {"CountryName":"Dominican Republic","CountryCode":"DOM","GNI":6630},{"CountryName":"Algeria","CountryCode":"DZA","GNI":3940},_x000D_
        {"CountryName":"East Asia & Pacific (excluding high income)","CountryCode":"EAP","GNI":6987},{"CountryName":"Early-demographic dividend","CountryCode":"EAR","GNI":3352},_x000D_
        {"CountryName":"East Asia & Pacific","CountryCode":"EAS","GNI":10171},{"CountryName":"Europe & Central Asia (excluding high income)","CountryCode":"ECA","GNI":7375},_x000D_
        {"CountryName":"Europe & Central Asia","CountryCode":"ECS","GNI":22656},{"CountryName":"Ecuador","CountryCode":"ECU","GNI":5920},_x000D_
        {"CountryName":"Euro area","CountryCode":"EMU","GNI":35645},{"CountryName":"Spain","CountryCode":"ESP","GNI":27180},{"CountryName":"Estonia","CountryCode":"EST","GNI":18190},_x000D_
        {"CountryName":"Ethiopia","CountryCode":"ETH","GNI":740},{"CountryName":"European Union","CountryCode":"EUU","GNI":32784},_x000D_
        {"CountryName":"Fragile and conflict affected situations","CountryCode":"FCS","GNI":1510},{"CountryName":"Finland","CountryCode":"FIN","GNI":44580},_x000D_
        {"CountryName":"Fiji","CountryCode":"FJI","GNI":4970},{"CountryName":"France","CountryCode":"FRA","GNI":37970},{"CountryName":"Gabon","CountryCode":"GAB","GNI":6650},_x000D_
        {"CountryName":"United Kingdom","CountryCode":"GBR","GNI":40530},{"CountryName":"Georgia","CountryCode":"GEO","GNI":3780},{"CountryName":"Ghana","CountryCode":"GHA","GNI":1880},_x000D_
        {"CountryName":"Guinea","CountryCode":"GIN","GNI":790},{"CountryName":"Guinea-Bissau","CountryCode":"GNB","GNI":660},_x000D_
        {"CountryName":"Equatorial Guinea","CountryCode":"GNQ","GNI":7050},{"CountryName":"Greece","CountryCode":"GRC","GNI":18090},_x000D_
        {"CountryName":"Grenada","CountryCode":"GRD","GNI":9180},{"CountryName":"Guatemala","CountryCode":"GTM","GNI":4060},{"CountryName":"Guyana","CountryCode":"GUY","GNI":4500},_x000D_
        {"CountryName":"High income","CountryCode":"HIC","GNI":40142},{"CountryName":"Honduras","CountryCode":"HND","GNI":2250},{"CountryName":"Heavily indebted poor countries (HIPC)","CountryCode":"HPC","GNI":904},{"CountryName":"Croatia","CountryCode":"HRV","GNI":12570},{"CountryName":"Haiti","CountryCode":"HTI","GNI":760},{"CountryName":"Hungary","CountryCode":"HUN","GNI":12870},{"CountryName":"IBRD only","CountryCode":"IBD","GNI":5745},{"CountryName":"IDA & IBRD total","CountryCode":"IBT","GNI":4620},{"CountryName":"IDA total","CountryCode":"IDA","GNI":1313},{"CountryName":"IDA blend","CountryCode":"IDB","GNI":1791},_x000D_
        {"CountryName":"Indonesia","CountryCode":"IDN","GNI":3540},{"CountryName":"IDA only","CountryCode":"IDX","GNI":1074},{"CountryName":"India","CountryCode":"IND","GNI":1800},{"CountryName":"Ireland","CountryCode":"IRL","GNI":55290},{"CountryName":"Iraq","CountryCode":"IRQ","GNI":4630},{"CountryName":"Iceland","CountryCode":"ISL","GNI":60830},{"CountryName":"Israel","CountryCode":"ISR","GNI":37270},{"CountryName":"Italy","CountryCode":"ITA","GNI":31020},{"CountryName":"Jamaica","CountryCode":"JAM","GNI":4760},{"CountryName":"Jordan","CountryCode":"JOR","GNI":3980},{"CountryName":"Japan","CountryCode":"JPN","GNI":38550},{"CountryName":"Kazakhstan","CountryCode":"KAZ","GNI":7970},{"CountryName":"Kenya","CountryCode":"KEN","GNI":1460},{"CountryName":"Kyrgyz Republic","CountryCode":"KGZ","GNI":1130},_x000D_
        {"CountryName":"Cambodia","CountryCode":"KHM","GNI":1230},{"CountryName":"Kiribati","CountryCode":"KIR","GNI":3010},{"CountryName":"St. Kitts and Nevis","CountryCode":"KNA","GNI":16240},{"CountryName":"Kuwait","CountryCode":"KWT","GNI":31430},{"CountryName":"Latin America & Caribbean (excluding high income)","CountryCode":"LAC","GNI":7470},{"CountryName":"Lao PDR","CountryCode":"LAO","GNI":2270},{"CountryName":"Lebanon","CountryCode":"LBN","GNI":8400},{"CountryName":"Liberia","CountryCode":"LBR","GNI":620},{"CountryName":"Libya","CountryCode":"LBY","GNI":5500},{"CountryName":"St. Lucia","CountryCode":"LCA","GNI":8830},{"CountryName":"Latin America & Caribbean","CountryCode":"LCN","GNI":8251},{"CountryName":"Least developed countries: UN classification","CountryCode":"LDC","GNI":1011},{"CountryName":"Low income","CountryCode":"LIC","GNI":774},{"CountryName":"Sri Lanka","CountryCode":"LKA","GNI":3850},{"CountryName":"Lower middle income","CountryCode":"LMC","GNI":2118},{"CountryName":"Low & middle income","CountryCode":"LMY","GNI":4455},{"CountryName":"Lesotho","CountryCode":"LSO","GNI":1210},{"CountryName":"Late-demographic dividend","CountryCode":"LTE","GNI":8518},{"CountryName":"Lithuania","CountryCode":"LTU","GNI":15200},{"CountryName":"Luxembourg","CountryCode":"LUX","GNI":70260},{"CountryName":"Latvia","CountryCode":"LVA","GNI":14740},{"CountryName":"Morocco","CountryCode":"MAR","GNI":2860},{"CountryName":"Moldova","CountryCode":"MDA","GNI":2200},{"CountryName":"Madagascar","CountryCode":"MDG","GNI":400},{"CountryName":"Maldives","CountryCode":"MDV","GNI":9760},_x000D_
        {"CountryName":"Middle East & North Africa","CountryCode":"MEA","GNI":7236},{"CountryName":"Mexico","CountryCode":"MEX","GNI":8610},{"CountryName":"Marshall Islands","CountryCode":"MHL","GNI":4840},{"CountryName":"Middle income","CountryCode":"MIC","GNI":4942},{"CountryName":"Mali","CountryCode":"MLI","GNI":770},_x000D_
        {"CountryName":"Malta","CountryCode":"MLT","GNI":24080},{"CountryName":"Myanmar","CountryCode":"MMR","GNI":1210},{"CountryName":"Middle East & North Africa (excluding high income)","CountryCode":"MNA","GNI":3832},{"CountryName":"Montenegro","CountryCode":"MNE","GNI":7400},{"CountryName":"Mongolia","CountryCode":"MNG","GNI":3270},{"CountryName":"Mozambique","CountryCode":"MOZ","GNI":420},{"CountryName":"Mauritania","CountryCode":"MRT","GNI":1100},{"CountryName":"Mauritius","CountryCode":"MUS","GNI":10130},{"CountryName":"Malawi","CountryCode":"MWI","GNI":320},{"CountryName":"Malaysia","CountryCode":"MYS","GNI":9650},{"CountryName":"North America","CountryCode":"NAC","GNI":56721},{"CountryName":"Namibia","CountryCode":"NAM","GNI":4570},{"CountryName":"Niger","CountryCode":"NER","GNI":360},{"CountryName":"Nigeria","CountryCode":"NGA","GNI":2100},_x000D_
        {"CountryName":"Nicaragua","CountryCode":"NIC","GNI":2130},{"CountryName":"Netherlands","CountryCode":"NLD","GNI":46180},{"CountryName":"Norway","CountryCode":"NOR","GNI":75990},{"CountryName":"Nepal","CountryCode":"NPL","GNI":800},{"CountryName":"Nauru","CountryCode":"NRU","GNI":10220},{"CountryName":"New Zealand","CountryCode":"NZL","GNI":38970},{"CountryName":"OECD members","CountryCode":"OED","GNI":37273},{"CountryName":"Oman","CountryCode":"OMN","GNI":14440},{"CountryName":"Other small states","CountryCode":"OSS","GNI":12199},{"CountryName":"Pakistan","CountryCode":"PAK","GNI":1580},{"CountryName":"Panama","CountryCode":"PAN","GNI":13280},{"CountryName":"Peru","CountryCode":"PER","GNI":5960},{"CountryName":"Philippines","CountryCode":"PHL","GNI":3660},{"CountryName":"Palau","CountryCode":"PLW","GNI":12700},{"CountryName":"Papua New Guinea","CountryCode":"PNG","GNI":2340},{"CountryName":"Poland","CountryCode":"POL","GNI":12730},{"CountryName":"Pre-demographic dividend","CountryCode":"PRE","GNI":1379},{"CountryName":"Portugal","CountryCode":"PRT","GNI":19820},{"CountryName":"Paraguay","CountryCode":"PRY","GNI":5470},{"CountryName":"West Bank and Gaza","CountryCode":"PSE","GNI":3180},{"CountryName":"Pacific island small states","CountryCode":"PSS","GNI":3793},{"CountryName":"Post-demographic dividend","CountryCode":"PST","GNI":41609},{"CountryName":"Qatar","CountryCode":"QAT","GNI":60510},{"CountryName":"Romania","CountryCode":"ROU","GNI":10000},{"CountryName":"Russian Federation","CountryCode":"RUS","GNI":9230},{"CountryName":"Rwanda","CountryCode":"RWA","GNI":720},{"CountryName":"South Asia","CountryCode":"SAS","GNI":1729},{"CountryName":"Saudi Arabia","CountryCode":"SAU","GNI":20090},{"CountryName":"Sudan","CountryCode":"SDN","GNI":2380},{"CountryName":"Senegal","CountryCode":"SEN","GNI":1240},{"CountryName":"Singapore","CountryCode":"SGP","GNI":54530},{"CountryName":"Solomon Islands","CountryCode":"SLB","GNI":1920},{"CountryName":"Sierra Leone","CountryCode":"SLE","GNI":510},{"CountryName":"El Salvador","CountryCode":"SLV","GNI":3560},{"CountryName":"Serbia","CountryCode":"SRB","GNI":5180},{"CountryName":"Sub-Saharan Africa (excluding high income)","CountryCode":"SSA","GNI":1485},{"CountryName":"Sub-Saharan Africa","CountryCode":"SSF","GNI":1486},{"CountryName":"Small states","CountryCode":"SST","GNI":11099},{"CountryName":"Sao Tome and Principe","CountryCode":"STP","GNI":1770},{"CountryName":"Suriname","CountryCode":"SUR","GNI":5150},{"CountryName":"Slovak Republic","CountryCode":"SVK","GNI":16610},{"CountryName":"Slovenia","CountryCode":"SVN","GNI":22000},{"CountryName":"Sweden","CountryCode":"SWE","GNI":52590},{"CountryName":"Eswatini","CountryCode":"SWZ","GNI":2950},{"CountryName":"Seychelles","CountryCode":"SYC","GNI":14170},{"CountryName":"Chad","CountryCode":"TCD","GNI":640},{"CountryName":"East Asia & Pacific (IDA & IBRD countries)","CountryCode":"TEA","GNI":7061},_x000D_
        {"CountryName":"Europe & Central Asia (IDA & IBRD countries)","CountryCode":"TEC","GNI":7866},{"CountryName":"Togo","CountryCode":"TGO","GNI":610},{"CountryName":"Thailand","CountryCode":"THA","GNI":5950},{"CountryName":"Tajikistan","CountryCode":"TJK","GNI":990},{"CountryName":"Turkmenistan","CountryCode":"TKM","GNI":6380},{"CountryName":"Latin America & the Caribbean (IDA & IBRD countries)","CountryCode":"TLA","GNI":8179},{"CountryName":"Timor-Leste","CountryCode":"TLS","GNI":1790},{"CountryName":"Middle East & North Africa (IDA & IBRD countries)","CountryCode":"TMN","GNI":3839},{"CountryName":"Tonga","CountryCode":"TON","GNI":4010},{"CountryName":"South Asia (IDA & IBRD)","CountryCode":"TSA","GNI":1729},_x000D_
        {"CountryName":"Sub-Saharan Africa (IDA & IBRD countries)","CountryCode":"TSS","GNI":1486},{"CountryName":"Trinidad and Tobago","CountryCode":"TTO","GNI":15340},{"CountryName":"Tunisia","CountryCode":"TUN","GNI":3490},{"CountryName":"Turkey","CountryCode":"TUR","GNI":10940},{"CountryName":"Tuvalu","CountryCode":"TUV","GNI":4970},{"CountryName":"Tanzania","CountryCode":"TZA","GNI":910},{"CountryName":"Uganda","CountryCode":"UGA","GNI":600},{"CountryName":"Ukraine","CountryCode":"UKR","GNI":2390},{"CountryName":"Upper middle income","CountryCode":"UMC","GNI":8197},{"CountryName":"Uruguay","CountryCode":"URY","GNI":15250},{"CountryName":"United States","CountryCode":"USA","GNI":58270},{"CountryName":"Uzbekistan","CountryCode":"UZB","GNI":2000},{"CountryName":"St. Vincent and the Grenadines","CountryCode":"VCT","GNI":7390},{"CountryName":"Vietnam","CountryCode":"VNM","GNI":2160},{"CountryName":"Vanuatu","CountryCode":"VUT","GNI":2920},{"CountryName":"World","CountryCode":"WLD","GNI":10371},{"CountryName":"Samoa","CountryCode":"WSM","GNI":4090},{"CountryName":"Kosovo","CountryCode":"XKX","GNI":3900},_x000D_
        {"CountryName":"South Africa","CountryCode":"ZAF","GNI":5430},{"CountryName":"Zambia","CountryCode":"ZMB","GNI":1290},{"CountryName":"Zimbabwe","CountryCode":"ZWE","GNI":1170},_x000D_
        {"CountryName":"Zimbabwe","CountryCode":"ZWE","GNI":1171}];_x000D_
_x000D_
    const sortMethod = sortMethodWithDirectionMultiColumn(_x000D_
        [_x000D_
            { column: "GNI", direction: "asc" },_x000D_
            { column: "CountryCode", direction: "desc" }_x000D_
        ]_x000D_
    );_x000D_
    let sortedData = data.sort(sortMethod);  _x000D_
    _x000D_
    _x000D_
    console.log("sorted by: 1)column:GNI-asc, 2)column:CountryCode-desc") _x000D_
    console.table(sortedData);_x000D_
    console.log(sortedData);_x000D_
    
_x000D_
_x000D_
_x000D_

Get last 30 day records from today date in SQL Server

You can use DateDiff for this. The where clause in your query would look like:

where DATEDIFF(day,pdate,GETDATE()) < 31

Including an anchor tag in an ASP.NET MVC Html.ActionLink

I would probably build the link manually, like this:

<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>

How to bring an activity to foreground (top of stack)?

You can try this FLAG_ACTIVITY_REORDER_TO_FRONT (the document describes exactly what you want to)

How to upload files in asp.net core?

 <form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">

     <div class="form-group">
        <input type="file" class="form-control" name="image" />
     </div>

     <div class="form-group">
        <button type="submit" class="btn btn-primary col-xs-12">Add</button>
     </div>
  </form>

My Action Is

        [HttpPost]
        public IActionResult AddNews(IFormFile image)
        {
            Tbl_News tbl_News = new Tbl_News();
            if (image!=null)
            {

                //Set Key Name
                string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);

                //Get url To Save
                string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);

                using(var stream=new FileStream(SavePath, FileMode.Create))
                {
                    image.CopyTo(stream);
                }
            }
            return View();
        }

How to compare two floating point numbers in Bash?

beware when comparing numbers that are package versions, like checking if grep 2.20 is greater than version 2.6:

$ awk 'BEGIN { print (2.20 >= 2.6) ? "YES" : "NO" }'
NO

$ awk 'BEGIN { print (2.2 >= 2.6) ? "YES" : "NO" }'
NO

$ awk 'BEGIN { print (2.60 == 2.6) ? "YES" : "NO" }'
YES

I solved such problem with such shell/awk function:

# get version of GNU tool
toolversion() {
    local prog="$1" operator="$2" value="$3" version

    version=$($prog --version | awk '{print $NF; exit}')

    awk -vv1="$version" -vv2="$value" 'BEGIN {
        split(v1, a, /\./); split(v2, b, /\./);
        if (a[1] == b[1]) {
            exit (a[2] '$operator' b[2]) ? 0 : 1
        }
        else {
            exit (a[1] '$operator' b[1]) ? 0 : 1
        }
    }'
}

if toolversion grep '>=' 2.6; then
   # do something awesome
fi

How large is a DWORD with 32- and 64-bit code?

It is defined as:

typedef unsigned long       DWORD;

However, according to the MSDN:

On 32-bit platforms, long is synonymous with int.

Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:

typdef unsigned _int64 DWORD64;

Hope that helps.

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

I sorted this problem as verifying the json from JSONLint.com and then, correcting it. And this is code for the same.

String jsonStr = "[{\r\n" + "\"name\":\"New York\",\r\n" + "\"number\": \"732921\",\r\n"+ "\"center\": {\r\n" + "\"latitude\": 38.895111,\r\n"  + " \"longitude\": -77.036667\r\n" + "}\r\n" + "},\r\n" + " {\r\n"+ "\"name\": \"San Francisco\",\r\n" +\"number\":\"298732\",\r\n"+ "\"center\": {\r\n" + "    \"latitude\": 37.783333,\r\n"+ "\"longitude\": -122.416667\r\n" + "}\r\n" + "}\r\n" + "]";

ObjectMapper mapper = new ObjectMapper();
MyPojo[] jsonObj = mapper.readValue(jsonStr, MyPojo[].class);

for (MyPojo itr : jsonObj) {
    System.out.println("Val of name is: " + itr.getName());
    System.out.println("Val of number is: " + itr.getNumber());
    System.out.println("Val of latitude is: " + 
        itr.getCenter().getLatitude());
    System.out.println("Val of longitude is: " + 
        itr.getCenter().getLongitude() + "\n");
}

Note: MyPojo[].class is the class having getter and setter of json properties.

Result:

Val of name is: New York
Val of number is: 732921
Val of latitude is: 38.895111
Val of longitude is: -77.036667
Val of name is: San Francisco
Val of number is: 298732
Val of latitude is: 37.783333
Val of longitude is: -122.416667

Removing a model in rails (reverse of "rails g model Title...")

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
    
  2. To remove Model

    rails d model name  #name => Your model name
    

Get HTML code from website in C#

Try this solution. It works fine.

 try{
        String url = textBox1.Text;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(sr);
        var aTags = doc.DocumentNode.SelectNodes("//a");
        int counter = 1;
        if (aTags != null)
        {
            foreach (var aTag in aTags)
            {
                richTextBox1.Text +=  aTag.InnerHtml +  "\n" ;
                counter++;
            }
        }
        sr.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to retrieve related keywords." + ex);
        }

Excel - Combine multiple columns into one column

Function Concat(myRange As Range, Optional myDelimiter As String) As String 
  Dim r As Range 
  Application.Volatile 
  For Each r In myRange 
    If Len(r.Text) Then 
      Concat = Concat & IIf(Concat <> "", myDelimiter, "") & r.Text 
    End If 
  Next 
End Function

How to create an Explorer-like folder browser control?

It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.

How do I run a node.js app as a background service?

You can use Forever, A simple CLI tool for ensuring that a given node script runs continuously (i.e. forever): https://www.npmjs.org/package/forever

SQL Last 6 Months

For MS SQL Server, you can use:

where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)

How do I make an editable DIV look like a text field?

The problem with all these is they don't address if the lines of text are long and much wider that the div overflow:auto does not ad a scroll bar that works right. Here is the perfect solution I found:

Create two divs. An inner div that is wide enough to handle the widest line of text and then a smaller outer one which acts at the holder for the inner div:

<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:500px;">
    <div style="width:800px;">

     now really long text like this can be put in the text area and it will really <br/>
     look and act more like a real text area bla bla bla <br/>

    </div>
</div>

Bootstrap 3 Glyphicons are not working

If you're using a CDN for the bootstrap CSS files it may be the culprit, as the glyph files (e.g. glyphicons-halflings-regular.woff) are taken from the CDN as well.

In my case, I faced this issue using Microsoft's CDN, but switching to MaxCDN resolved it.

How to insert a new key value pair in array in php?

Try this:

foreach($array as $k => $obj) { 
    $obj->{'newKey'} = "value"; 
}

Could not find an implementation of the query pattern

You are missing an equality:

var query = (from p in tblPersoon where p.id == 5 select p).Single();

where clause must result in a boolean.

OR you should not be using where at all:

var query = (from p in tblPersoon select p).Single();

Double value to round up in Java

You could try defining a new DecimalFormat and using it as a Double result to a new double variable.

Example given to make you understand what I just said.

double decimalnumber = 100.2397;
DecimalFormat dnf = new DecimalFormat( "#,###,###,##0.00" );
double roundednumber = new Double(dnf.format(decimalnumber)).doubleValue();

How would I run an async Task<T> method synchronously?

    private int GetSync()
    {
        try
        {
            ManualResetEvent mre = new ManualResetEvent(false);
            int result = null;

            Parallel.Invoke(async () =>
            {
                result = await SomeCalcAsync(5+5);
                mre.Set();
            });

            mre.WaitOne();
            return result;
        }
        catch (Exception)
        {
            return null;
        }
    }

Java: how can I split an ArrayList in multiple small ArrayLists?

Just to be clear, This still have to be tested more...

public class Splitter {

public static <T> List<List<T>> splitList(List<T> listTobeSplit, int size) {
    List<List<T>> sublists= new LinkedList<>();
    if(listTobeSplit.size()>size) {
    int counter=0;
    boolean lastListadded=false;

    List<T> subList=new LinkedList<>();

    for(T t: listTobeSplit) {           
         if (counter==0) {               
             subList =new LinkedList<>();
             subList.add(t);
             counter++;
             lastListadded=false;
         }
         else if(counter>0 && counter<size-1) {
             subList.add(t);
             counter++;
         }
         else {
             lastListadded=true;
             subList.add(t);
             sublists.add(subList);
             counter=0;
         }              
    }
    if(lastListadded==false)
        sublists.add(subList);      
    }
    else {
        sublists.add(listTobeSplit);
    }
    log.debug("sublists: "+sublists);
    return sublists;
 }
}

How to set up tmux so that it starts up with specified windows opened?

I've create this script. It does not need tmuxinator, ruby or others. It is just a bash script, configurable:

A file named config should contains something like this:

combo=()
combo+=('logs' 'cd /var/log; clear; pwd')
combo+=('home' 'cd ~; clear; pwd')

and the bash code should be:

#!/bin/bash

if [ -r config ]; then
    echo ""
    echo "Loading custom file"
    . config
else
    . config.dist
fi

tmux start-server

window=0
windownumber=-1

for i in "${combo[@]}"; do

    if [ $((window%2)) == 0 ]; then
        name=${i}
        ((windownumber++))
    else
        command=${i}
    fi

    if [ ${combo[0]} == "${i}" ]; then
        tmux new-session -d -s StarTmux -n "${name}"
    else
        if [ $((window%2)) == 0 ]; then
            tmux new-window -tStarTmux:$windownumber -n "${name}"
        fi
    fi

    if [ $((window%2)) == 1 ]; then
        tmux send-keys -tStarTmux:$windownumber "${command}" C-m
    fi

    ((window++))
done

tmux select-window -tStarTmux:0
tmux attach-session -d -tStarTmux

Can you write virtual functions / methods in Java?

From wikipedia

In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.

jquery - Check for file extension before uploading

 $("#file-upload").change(function () {

    var validExtensions = ["jpg","pdf","jpeg","gif","png"]
    var file = $(this).val().split('.').pop();
    if (validExtensions.indexOf(file) == -1) {
        alert("Only formats are allowed : "+validExtensions.join(', '));
    }

});

jQuery - Add ID instead of Class

Im doing this in coffeescript

booking_module_time_clock_convert_id = () ->
  if $('.booking_module_time_clock').length
    idnumber = 1
    for a in $('.booking_module_time_clock')
      elementID = $(a).attr("id")
      $(a).attr( 'id', "#{elementID}_#{idnumber}" )
      idnumber++

Android: show/hide a view using an animation

ViewAnimator:

In XML:

  <ViewAnimator
    android:id="@+id/animator_message"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inAnimation="@anim/slide_down_text"
    android:outAnimation="@anim/slide_up_text">

    <TextView
        android:id="@+id/text_message_authentication"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="message_error_authentication" />

    <TextView
        android:id="@+id/text_message_authentication_connection"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="message_error_authentication_connection" />

    <TextView
        android:id="@+id/text_message_authentication_empty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="message_error_authentication_field_empty" />

</ViewAnimator>

Functions:

public void show(int viewId) {
    ViewAnimator animator = (ViewAnimator) findView(animatorId);
    View view = findViewById(viewId);

    if (animator.getDisplayedChild() != animator.indexOfChild(view)) {
        animator.setDisplayedChild(animator.indexOfChild(view));
     }
 }


 private void showAuthenticationConnectionFailureMessage() {
    show(R.id.text_message_authentication_connection);
}

How to redirect to Login page when Session is expired in Java web application?

Until the session timeout we get a normal request, after which we get an Ajax request. We can identify it the following way:

String ajaxRequestHeader = request.getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(ajaxRequestHeader)) {
    response.sendRedirect("/login.jsp");
}

Merging multiple PDFs using iTextSharp in c#.net

Merge byte arrays of multiple PDF files:

    public static byte[] MergePDFs(List<byte[]> pdfFiles)
    {  
        if (pdfFiles.Count > 1)
        {
            PdfReader finalPdf;
            Document pdfContainer;
            PdfWriter pdfCopy;
            MemoryStream msFinalPdf = new MemoryStream();

            finalPdf = new PdfReader(pdfFiles[0]);
            pdfContainer = new Document();
            pdfCopy = new PdfSmartCopy(pdfContainer, msFinalPdf);

            pdfContainer.Open();

            for (int k = 0; k < pdfFiles.Count; k++)
            {
                finalPdf = new PdfReader(pdfFiles[k]);
                for (int i = 1; i < finalPdf.NumberOfPages + 1; i++)
                {
                    ((PdfSmartCopy)pdfCopy).AddPage(pdfCopy.GetImportedPage(finalPdf, i));
                }
                pdfCopy.FreeReader(finalPdf);

            }
            finalPdf.Close();
            pdfCopy.Close();
            pdfContainer.Close();

            return msFinalPdf.ToArray();
        }
        else if (pdfFiles.Count == 1)
        {
            return pdfFiles[0];
        }
        return null;
    }

Modifying local variable from inside lambda

You can wrap it up to workaround the compiler but please remember that side effects in lambdas are discouraged.

To quote the javadoc

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement A small number of stream operations, such as forEach() and peek(), can operate only via side-effects; these should be used with care

Hidden TextArea

use

textarea{
  visibility:hidden;
}

Python socket connection timeout

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

how to fire event on file select

vanilla js using es6

document.querySelector('input[name="file"]').addEventListener('change', (e) => {
 const file = e.target.files[0];
  // todo: use file pointer
});

“tag already exists in the remote" error after recreating the git tag

The reason you are getting rejected is that your tag lost sync with the remote version. This is the same behaviour with branches.

sync with the tag from the remote via git pull --rebase <repo_url> +refs/tags/<TAG> and after you sync, you need to manage conflicts. If you have a diftool installed (ex. meld) git mergetool meld use it to sync remote and keep your changes.

The reason you're pulling with --rebase flag is that you want to put your work on top of the remote one so you could avoid other conflicts.

Also, what I don't understand is why would you delete the dev tag and re-create it??? Tags are used for specifying software versions or milestones. Example of git tags v0.1dev, v0.0.1alpha, v2.3-cr(cr - candidate release) and so on..


Another way you can solve this is issue a git reflog and go to the moment you pushed the dev tag on remote. Copy the commit id and git reset --mixed <commmit_id_from_reflog> this way you know your tag was in sync with the remote at the moment you pushed it and no conflicts will arise.

Decimal values in SQL for dividing results

just convert denominator to decimal before division e.g

select col1 / CONVERT(decimal(4,2), col2) from tbl1

How to change the blue highlight color of a UITableViewCell?

You can change the highlight color in several ways.

  1. Change the selectionStyle property of your cell. If you change it to UITableViewCellSelectionStyleGray, it will be gray.

  2. Change the selectedBackgroundView property. Actually what creates the blue gradient is a view. You can create a view and draw what ever you like, and use the view as the background of your table view cells.

WhatsApp API (java/python)

From my blog

courtesy

There is a secret pilot program which WhatsApp is working on with selected businesses

News coverage:

For some of my technical experiments, I was trying to figure out how beneficial and feasible it is to implement bots for different chat platforms in terms of market share and so possibilities of adaptation. Especially when you have bankruptly failed twice, it's important to validate ideas and fail more faster.

Popular chat platforms like Messenger, Slack, Skype etc. have happily (in the sense officially) provided APIs for bots to interact with, but WhatsApp has not yet provided any API.

However, since many years, a lot of activities has happened around this - struggle towards automated interaction with WhatsApp platform:

  1. Bots App Bots App is interesting because it shows that something is really tried and tested.

  2. Yowsup A project still actively developed to interact with WhatsApp platform.

  3. Yallagenie Yallagenie claim that there is a demo bot which can be interacted with at +971 56 112 6652

  4. Hubtype Hubtype is working towards having a bot platform for WhatsApp for business.

  5. Fred Fred's task was to automate WhatsApp conversations, however since it was not officially supported by WhatsApp - it was shut down.

  6. Oye Gennie A bot blocked by WhatsApp.

  7. App/Website to WhatsApp We can use custom URL schemes and Android intent system to interact with WhatsApp but still NOT WhatsApp API.

  8. Chat API daemon Probably created by inspecting the API calls in WhatsApp web version. NOT affiliated with WhatsApp.

  9. WhatsBot Deactivated WhatsApp bot. Created during a hackathon.

  10. No API claim WhatsApp co-founder clearly stated this in a conference that they did not had any plans for APIs for WhatsApp.

  11. Bot Ware They probably are expecting WhatsApp to release their APIs for chat bot platforms.

  12. Vixi They seems to be talking about how some platform which probably would work for WhatsApp. There is no clarity as such.

  13. Unofficial API This API can shut off any time.

    And the number goes on...

How to make a jquery function call after "X" seconds

If you could show the actual page, we, possibly, could help you better.

If you want to trigger the button only after the iframe is loaded, you might want to check if it has been loaded or use the iframe.onload:

<iframe .... onload='buttonWhatever(); '></iframe>


<script type="text/javascript">

    function buttonWhatever() {
        $("#<%=Button1.ClientID%>").click(function (event) {
            $('#<%=TextBox1.ClientID%>').change(function () {
                $('#various3').attr('href', $(this).val());
            });
            $("#<%=Button2.ClientID%>").click();
        });

        function showStickySuccessToast() {
            $().toastmessage('showToast', {
                text: 'Finished Processing!',
                sticky: false,
                position: 'middle-center',
                type: 'success',
                closeText: '',
                close: function () { }
            });
        }
    }

</script>

SQL statement to select all rows from previous day

subdate(now(),1) will return yesterdays timestamp The below code will select all rows with yesterday's timestamp

Select * FROM `login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)

How I can print to stderr in C?

#include<stdio.h>

int main ( ) {
    printf( "hello " );
    fprintf( stderr, "HELP!" );
    printf( " world\n" );
    return 0;
}

$ ./a.exe
HELP!hello  world
$ ./a.exe 2> tmp1
hello  world
$ ./a.exe 1> tmp1
HELP!$
  1. stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed. Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.

  2. Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.

filter out multiple criteria using excel vba

Here an option using a list written on some range, populating an array that will be fiiltered. The information will be erased then the columns sorted.

Sub Filter_Out_Values()

'Automation to remove some codes from the list
Dim ws, ws1 As Worksheet
Dim myArray() As Variant
Dim x, lastrow As Long
Dim cell As Range

Set ws = Worksheets("List")
Set ws1 = Worksheets(8)
lastrow = ws.Cells(Application.Rows.Count, 1).End(xlUp).Row

'Go through the list of codes to exclude
For Each cell In ws.Range("A2:A" & lastrow)

    If cell.Offset(0, 2).Value = "X" Then 'If the Code is associated with "X"
        ReDim Preserve myArray(x) 'Initiate array
        myArray(x) = CStr(cell.Value) 'Populate the array with the code
        x = x + 1 'Increase array capacity
        ReDim Preserve myArray(x) 'Redim array
    End If

Next cell

lastrow = ws1.Cells(Application.Rows.Count, 1).End(xlUp).Row
ws1.Range("C2:C" & lastrow).AutoFilter field:=3, Criteria1:=myArray, Operator:=xlFilterValues
ws1.Range("A2:Z" & lastrow).SpecialCells(xlCellTypeVisible).ClearContents
ws1.Range("A2:Z" & lastrow).AutoFilter field:=3

'Sort columns
lastrow = ws1.Cells(Application.Rows.Count, 1).End(xlUp).Row
'Sort with 2 criteria
With ws1.Range("A1:Z" & lastrow)
    .Resize(lastrow).Sort _
    key1:=ws1.Columns("B"), order1:=xlAscending, DataOption1:=xlSortNormal, _
    key2:=ws1.Columns("D"), order1:=xlAscending, DataOption1:=xlSortNormal, _
    Header:=xlYes, MatchCase:=False, Orientation:=xlTopToBottom, SortMethod:=xlPinYin
End With

End Sub

Pandas left outer join multiple dataframes on multiple columns

Merge them in two steps, df1 and df2 first, and then the result of that to df3.

In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

I dropped year from df3 since you don't need it for the last join.

In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                       how='left', on=['Week', 'Colour'])

In [40]: df
Out[40]: 
   Year Week Colour  Val1  Val2 Val3
0  2014    A    Red    50   NaN  NaN
1  2014    B    Red    60   NaN   60
2  2014    B  Black    70   100   10
3  2014    C    Red    10    20  NaN
4  2014    D  Green    20   NaN   20

[5 rows x 6 columns]

What's the difference between display:inline-flex and display:flex?

Display:flex apply flex layout to the flex items or children of the container only. So, the container itself stays a block level element and thus takes up the entire width of the screen.

This causes every flex container to move to a new line on the screen.

Display:inline-flex apply flex layout to the flex items or children as well as to the container itself. As a result the container behaves as an inline flex element just like the children do and thus takes up the width required by its items/children only and not the entire width of the screen.

This causes two or more flex containers one after another, displayed as inline-flex, align themselves side by side on the screen until the whole width of the screen is taken.

What is SOA "in plain english"?

from ittoolbox blogs.

The following outlines the similarities and differences to past design techniques:

• SOA versus Structured Programming o Similarities: Most similar to subroutine calls where parameters are passed and the operation of the function is abstracted from the caller - e.g. CICS link and execute and the COBOL CALL reserved word. Copybooks are used to define data structure which is typically defined as an XML schema for services. o Differences: SOA is loosely coupled implying changes to a service have less impact to the consumer (the "calling" program) and services are interoperable across languages and platforms.

• SOA versus OOA/OOD o Similarities: Encapsulation, Abstraction and Defined Interfaces o Differences: SOA is loosely coupled with no class hierarchy or inheritance, Low-level abstractions - class level versus business service

• SOA versus legacy Component Based Development (CBD) - e.g. CORBA, DCOM, EJB o Similarities: Reuse through assembling components, Interfaces, Remote calls o Differences: Wide adoption of standards, XML Schemas vs. Marshaled Objects, Service Orchestration, Designing for reuse is easier, services are business focused vs. IT focused, business services are course grained (broad in scope)

• SOA (for integration) versus Enterprise Application Integration (EAI) o Similarities: Best practices (well defined interfaces, standardized schemas, event driven architecture), reusable interfaces, common schemas o Differences: Standards, adoption, and improved tools

What's the best way to detect a 'touch screen' device using JavaScript?

Extent jQuery support object:

jQuery.support.touch = 'ontouchend' in document;

And now you can check it anywhere, like this:

if( jQuery.support.touch )
   // do touch stuff

How to convert java.sql.timestamp to LocalDate (java8) java.time?

You can do:

timeStamp.toLocalDateTime().toLocalDate();

Note that timestamp.toLocalDateTime() will use the Clock.systemDefaultZone() time zone to make the conversion. This may or may not be what you want.

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

This kind of logic could be implemented using EXISTS:

CREATE TABLE tab(a INT, b VARCHAR(10));
INSERT INTO tab(a,b) VALUES(1,'a'),(1, NULL),(NULL, 'a'),(2,'b');

Query:

DECLARE @a INT;

--SET @a = 1;    -- specific NOT NULL value
--SET @a = NULL; -- NULL value
--SET @a = -1;   -- all values

SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1');

db<>fiddle demo

It could be extended to contain multiple params:

SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1')
  AND EXISTS(SELECT t.b INTERSECT SELECT @b UNION SELECT @a WHERE @b = '-1');

How to make System.out.println() shorter

Use log4j or JDK logging so you can just create a static logger in the class and call it like this:

LOG.info("foo")

Python requests library how to pass Authorization header with single token

i founded here, its ok with me for linkedin: https://auth0.com/docs/flows/guides/auth-code/call-api-auth-code so my code with with linkedin login here:

ref = 'https://api.linkedin.com/v2/me'
headers = {"content-type": "application/json; charset=UTF-8",'Authorization':'Bearer {}'.format(access_token)}
Linkedin_user_info = requests.get(ref1, headers=headers).json()

How can I replace newline or \r\n with <br/>?

Try using this:

$description = preg_replace("/\r\n|\r|\n/", '<br/>', $description);

How to run crontab job every week on Sunday

Here is an explanation of the crontab format.

# 1. Entry: Minute when the process will be started [0-60]
# 2. Entry: Hour when the process will be started [0-23]
# 3. Entry: Day of the month when the process will be started [1-28/29/30/31]
# 4. Entry: Month of the year when the process will be started [1-12]
# 5. Entry: Weekday when the process will be started [0-6] [0 is Sunday]
#
# all x min = */x

So according to this your 5 8 * * 0 would run 8:05 every Sunday.

Bootstrap 3 scrollable div for table

You can use too

style="overflow-y: scroll; height:150px; width: auto;"

It's works for me

What are the proper permissions for an upload folder with PHP/Apache?

I would support the idea of creating a ftp group that will have the rights to upload. However, i don't think it is necessary to give 775 permission. 7 stands for read, write, execute. Normally you want to allow certain groups to read and write, but depending on the case, execute may not be necessary.

SQL - How do I get only the numbers after the decimal?

You can use FLOOR:

select x, ABS(x) - FLOOR(ABS(x))
from (
    select 2.938 as x
) a

Output:

x                                       
-------- ----------
2.938    0.938

Or you can use SUBSTRING:

select x, SUBSTRING(cast(x as varchar(max)), charindex(cast(x as varchar(max)), '.') + 3, len(cast(x as varchar(max))))
from (
    select 2.938 as x
) a

Spring-Security-Oauth2: Full authentication is required to access this resource

setting management.security.enabled=false in application.properties resolved the issue for me.

MySQL: When is Flush Privileges in MySQL really needed?

Privileges assigned through GRANT option do not need FLUSH PRIVILEGES to take effect - MySQL server will notice these changes and reload the grant tables immediately.

From MySQL documentation:

If you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE, your changes have no effect on privilege checking until you either restart the server or tell it to reload the tables. If you change the grant tables directly but forget to reload them, your changes have no effect until you restart the server. This may leave you wondering why your changes seem to make no difference!

To tell the server to reload the grant tables, perform a flush-privileges operation. This can be done by issuing a FLUSH PRIVILEGES statement or by executing a mysqladmin flush-privileges or mysqladmin reload command.

If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

Fatal Error :1:1: Content is not allowed in prolog

There are certainly some weird characters (e.g. BOM) or some whitespace before the XML preamble (<?xml ...?>)?

How to get HTML 5 input type="date" working in Firefox and/or IE 10

Here is the proper solution. You should use jquery datepicker everywhere

  <script>
  $( function() {
    $( ".simple_date" ).datepicker();
  } );
  </script>

Below is the link to get the complete code

https://tutorialvilla.com/how/how-to-solve-the-problem-of-html-date-picker

How to format strings in Java

I wrote this function it does just the right thing. Interpolate a word starting with $ with the value of the variable of the same name.

private static String interpol1(String x){
    Field[] ffield =  Main.class.getDeclaredFields();
    String[] test = x.split(" ") ;
    for (String v : test ) {
        for ( Field n: ffield ) {
            if(v.startsWith("$") && ( n.getName().equals(v.substring(1))  )){
                try {
                    x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
                }catch (Exception e){
                    System.out.println("");
                }
            }
        }
    }
    return x;
}

How to refresh token with Google API client?

Google has made some changes since this question was originally posted.

Here is my currently working example.

    public function update_token($token){

    try {

        $client = new Google_Client();
        $client->setAccessType("offline"); 
        $client->setAuthConfig(APPPATH . 'vendor' . DIRECTORY_SEPARATOR . 'google' . DIRECTORY_SEPARATOR . 'client_secrets.json');  
        $client->setIncludeGrantedScopes(true); 
        $client->addScope(Google_Service_Calendar::CALENDAR); 
        $client->setAccessToken($token);

        if ($client->isAccessTokenExpired()) {
            $refresh_token = $client->getRefreshToken();
            if(!empty($refresh_token)){
                $client->fetchAccessTokenWithRefreshToken($refresh_token);      
                $token = $client->getAccessToken();
                $token['refresh_token'] = json_decode($refresh_token);
                $token = json_encode($token);
            }
        }

        return $token;

    } catch (Exception $e) { 
        $error = json_decode($e->getMessage());
        if(isset($error->error->message)){
            log_message('error', $error->error->message);
        }
    }


}

PHP 7: Missing VCRUNTIME140.dll

Installing vc_redist.x86.exe works for me even though you have a 64-bit machine.

Removing html5 required attribute with jQuery

_x000D_
_x000D_
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

How to set full calendar to a specific start date when it's initialized for the 1st time?

If you don't want to load the calendar twice and you don't have a version where defaultDate is implemented, do the following:

Change the following method:

function Calendar(element, options, eventSources) { ... var date = new Date(); ... }

to:

function Calendar(element, options, eventSources) { ... var date = options.defaultDate ? options.defaultDate : new Date(); ... }

Regular expression for exact match of a string

A more straight forward way is to check for equality

if string1 == string2
  puts "match"
else
  puts "not match"
end

however, if you really want to stick to regular expression,

string1 =~ /^123456$/

Reading and writing binary file

You should pass length into fwrite instead of sizeof(buffer).

Error:java: invalid source release: 8 in Intellij. What does it mean?

I had the same issue when "downgrading" a project from Java 8 to Java 6. The reason was that it was not changed at all places in IntelliJ.

In IntelliJ 13.1.4 I had to change Java and SDK version on the following places not to get this error:

  • File -> Project Structure -> Project Settings
  • File -> Project Structure -> Module Settings -> Tab: Sources: Language Level
  • File -> Project Structure -> Module Settings -> Tab: Dependencies: Module SDK
  • File -> Settings -> Compiler -> Java Compiler -> Target bytecode version

screen shot of File > Project Structure > Project

screen shot of File > Project Structure > Modules > Sources

screen shot of File > Project Structure > Modules > Dependencies

screen shot of File > Settings/Preferences > Compiler > Java Compiler

The last bullet was the one that was not updated in my case. Once I changed this, the error disappeared.

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

For Nginx:

  1. openssl req -newkey rsa:2048 -nodes -keyout domain.com.key -out domain.com.csr

  2. SSL file domain_com.crt and domain_com.ca-bundle files, then copy new file in paste domain.com.chained.crt.

3: Add nginx files:

  1. ssl_certificate /home/user/domain_ssl/domain.com.chained.crt;
  2. ssl_certificate_key /home/user/domain_ssl/domain.com.key;

Lates restart Nginx.

Display fullscreen mode on Tkinter

This creates a fullscreen window. Pressing Escape resizes the window to '200x200+0+0' by default. If you move or resize the window, Escape toggles between the current geometry and the previous geometry.

import Tkinter as tk

class FullScreenApp(object):
    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)            
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

root=tk.Tk()
app=FullScreenApp(root)
root.mainloop()

Create Word Document using PHP in Linux

real Word documents

If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend Joel's article on this subject.

fake HTTP headers for tricking Word into opening raw HTML

A rather common (but unreliable) alternative is:

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=document_name.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>Fake word document</b>";
echo "</body>";
echo "</html>"

Make sure you don't use external stylesheets. Everything should be in the same file.

Note that this does not send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a .doc file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading Content-Type header along does not constitute a real file format conversion.

How to get item count from DynamoDB?

I used scan to get total count of the required tableName.Following is a Java code snippet for same

Long totalItemCount = 0;
do{
    ScanRequest req = new ScanRequest();
    req.setTableName(tableName);

    if(result != null){
        req.setExclusiveStartKey(result.getLastEvaluatedKey());
    }

    result = client.scan(req);

    totalItemCount += result.getItems().size();

} while(result.getLastEvaluatedKey() != null);

System.out.println("Result size: " + totalItemCount);

How can I get relative path of the folders in my android project?

Are you looking for the root folder of the application? Then I would use

 String path = getClass().getClassLoader().getResource(".").getPath();

to actually "find out where I am".

Where can I find the assembly System.Web.Extensions dll?

I had this issue when converting an older project to use a new version of Visual Studio. Upon conversion, the project target framework was set to 2.0

I was able to solve this issue by changing the target framework to be 3.5.

Difference between a View's Padding and Margin

Padding is within the view, margin is outside. Padding is available for all views. Depending on the view, there may or may not be a visual difference between padding and margin.

For buttons, for example, the characteristic button background image includes the padding, but not the margin. In other words, adding more padding makes the button look visually bigger, while adding more margin just makes the gap between the button and the next control wider.

For TextViews, on the other hand, the visual effect of padding and margin is identical.

Whether or not margin is available is determined by the container of the view, not by the view itself. In LinearLayout margin is supported, in AbsoluteLayout (considered obsolete now) - no.

Print the stack trace of an exception

See javadoc

out = some stream ...
try
{
}
catch ( Exception cause )
{
      cause . printStrackTrace ( new PrintStream ( out ) ) ;
}

How to convert jsonString to JSONObject in Java

I like to use google-gson for this, and it's precisely because I don't need to work with JSONObject directly.

In that case I'd have a class that will correspond to the properties of your JSON Object

class Phone {
 public String phonetype;
 public String cat;
}


...
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Gson gson = new Gson();
Phone fooFromJson = gson.fromJson(jsonString, Phone.class);
...

However, I think your question is more like, How do I endup with an actual JSONObject object from a JSON String.

I was looking at the google-json api and couldn't find anything as straight forward as org.json's api which is probably what you want to be using if you're so strongly in need of using a barebones JSONObject.

http://www.json.org/javadoc/org/json/JSONObject.html

With org.json.JSONObject (another completely different API) If you want to do something like...

JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
System.out.println(jsonObject.getString("phonetype"));

I think the beauty of google-gson is that you don't need to deal with JSONObject. You just grab json, pass the class to want to deserialize into, and your class attributes will be matched to the JSON, but then again, everyone has their own requirements, maybe you can't afford the luxury to have pre-mapped classes on the deserializing side because things might be too dynamic on the JSON Generating side. In that case just use json.org.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

It may happens because fake png files. You can use this command to check out fake pngs.

cd <YOUR_PROJECT/res/> && find . -name *.png | xargs pngcheck

And then,use ImageEditor(Ex, Pinta) to open fake pngs and re-save them to png.

Good luck.

How to access a mobile's camera from a web app?

well, there's a new HTML5 features for accessing the native device camera - "getUserMedia API"

NOTE: HTML5 can handle photo capture from a web page on Android devices (at least on the latest versions, run by the Honeycomb OS; but it can’t handle it on iPhones but iOS 6 ).

Use of Application.DoEvents()

Application.DoEvents can create problems, if something other than graphics processing is put in the message queue.

It can be useful for updating progress bars and notifying the user of progress in something like MainForm construction and loading, if that takes a while.

In a recent application I've made, I used DoEvents to update some labels on a Loading Screen every time a block of code is executed in the constructor of my MainForm. The UI thread was, in this case, occupied with sending an email on a SMTP server that didn't support SendAsync() calls. I could probably have created a different thread with Begin() and End() methods and called a Send() from their, but that method is error-prone and I would prefer the Main Form of my application not throwing exceptions during construction.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Set UITableView content inset permanently

After one hour of tests the only way that works 100% is this one:

-(void)hideSearchBar
{
    if([self.tableSearchBar.text length]<=0 && !self.tableSearchBar.isFirstResponder)
    {
        self.tableView.contentOffset = CGPointMake(0, self.tableSearchBar.bounds.size.height);
        self.edgesForExtendedLayout = UIRectEdgeBottom;
    }
}

-(void)viewDidLayoutSubviews
{
    [self hideSearchBar];
}

with this approach you can always hide the search bar if is empty

How to concatenate string and int in C?

Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).

Cannot use special principal dbo: Error 15405

To fix this, open the SQL Server Management Studio and click New Query. Then type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

How to check if a string contains only digits in Java

You must allow for more than a digit (the + sign) as in:

String regex = "[0-9]+"; 
String data = "23343453"; 
System.out.println(data.matches(regex));