Programs & Examples On #Width

The property which determines the size of an object on the X-axis. The most common form of this measurement is in pixels or millimeters.

C# ListView Column Width Auto

This solution will first resize the columns based on column data, if the resized width is smaller than header size, it will resize columns to at least fit the header. This is a pretty ugly solution, but it works.

lstContacts.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
colFirstName.Width = (colFirstName.Width < 60 ? 60 : colFirstName.Width);
colLastName.Width = (colLastName.Width < 61 ? 61 : colLastName.Width);
colPhoneNumber.Width = (colPhoneNumber.Width < 81 ? 81 : colPhoneNumber.Width);
colEmail.Width = (colEmail.Width < 40 ? 40 : colEmail.Width);

lstContacts is the ListView. colFirstName is a column, where 60 is the width required to fit the title. Etc.

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

How to Determine the Screen Height and Width in Flutter

MediaQuery.of(context).size.width and MediaQuery.of(context).size.height works great, but every time need to write expressions like width/20 to set specific height width.

I've created a new application on flutter, and I've had problems with the screen sizes when switching between different devices.

Yes, flutter_screenutil plugin available for adapting screen and font size. Let your UI display a reasonable layout on different screen sizes!

Usage:

Add dependency:

Please check the latest version before installation.

dependencies:
  flutter:
    sdk: flutter
  # add flutter_ScreenUtil
  flutter_screenutil: ^0.4.2

Add the following imports to your Dart code:

import 'package:flutter_screenutil/flutter_screenutil.dart';

Initialize and set the fit size and font size to scale according to the system's "font size" accessibility option

//fill in the screen size of the device in the design

//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.instance = ScreenUtil()..init(context);

//If the design is based on the size of the iPhone6 ??(iPhone6 ??750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

//If you wang to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);

Use:

//for example:
//rectangle
Container(
           width: ScreenUtil().setWidth(375),
           height: ScreenUtil().setHeight(200),
           ...
            ),

////If you want to display a square:
Container(
           width: ScreenUtil().setWidth(300),
           height: ScreenUtil().setWidth(300),
            ),

Please refer updated documentation for more details

Note: I tested and using this plugin, which really works great with all devices including iPad

Hope this will helps someone

How to set up fixed width for <td>?

Use d-flex instead of row for "tr" in Bootstrap 4

The thing is that "row" class takes more width then the parent container, which introduces issues.

_x000D_
_x000D_
<table class="table">_x000D_
  <tbody>_x000D_
    <tr class="d-flex">_x000D_
      <td class="col-sm-8">Hello</td>_x000D_
      <td class="col-sm-4">World</td>_x000D_
    </tr>_x000D_
    <tr class="d-flex">_x000D_
      <td class="col-sm-8">8 columns</td>_x000D_
      <td class="col-sm-4">4 columns</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Change div width live with jQuery

It is indeed possible to change a div elements' width in jQuery:

$("#div").css("width", "300px");

However, what you're describing can be better and more effectively achieved in CSS by setting a width as a percentage:

#div {
    width: 75%;
    /* You can also specify min/max widths */
    min-width: 300px;
    max-width: 960px;
}

This div will then always be 75% the width of the screen, unless the screen width means the div will be smaller than 300px, or bigger than 960px.

How to get screen width without (minus) scrollbar?

I experienced a similar problem and doing width:100%; solved it for me. I came to this solution after trying an answer in this question and realizing that the very nature of an <iframe> will make these javascript measurement tools inaccurate without using some complex function. Doing 100% is a simple way to take care of it in an iframe. I don't know about your issue since I'm not sure of what HTML elements you are manipulating.

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Note that if the problem is being caused by appearing scrollbars, putting

body {
  overflow: hidden;
}

in your CSS might be an easy fix (if you don't need the page to scroll).

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

demo - http://jsfiddle.net/victor_007/ywevz8ra/

added border for better view (testing)

more info about white-space

table{
    width:100%;
}
table td{
    white-space: nowrap;  /** added **/
}
table td:last-child{
    width:100%;
}

_x000D_
_x000D_
    table {_x000D_
      width: 100%;_x000D_
    }_x000D_
    table td {_x000D_
      white-space: nowrap;_x000D_
    }_x000D_
    table td:last-child {_x000D_
      width: 100%;_x000D_
    }
_x000D_
<table border="1">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

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.

standard size for html newsletter template

Bdizzle,

I would recommend that you read this link

You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.

Be happy, Julian

css 100% width div not taking up full width of parent

The problem is caused by your #grid having a width:1140px.

You need to set a min-width:1140px on the body.

This will stop the body from getting smaller than the #grid. Remove width:100% as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/

html, body{
    margin:0;
    padding:0;
    min-width: 1140px; /* this is the important part*/
}
#grid-container{
    background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
    width:1140px;
    margin:0px auto;
}

How to set the initial zoom/width for a webview

in Kotlin You can use,

webView.isScrollbarFadingEnabled = true
webView.setInitialScale(100)

Android set height and width of Custom view programmatically

This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout.

someView.layoutParams = LinearLayout.LayoutParams(100, 200)

This allows to set the width and height (100 and 200) in a single line.

Change New Google Recaptcha (v2) Width

No, currently you can not. It was only possible with the old recaptcha, but I'm sure you will be able to do that in the future.

I have no solution but a suggestion. I had the same problem, so I centered the recaptcha div (margin: 0 auto;display: table), I think it looks much better than a left-aligned div.

Get width height of remote image from url

The w and h variables in img.onload function are not in the same scope with those in the getMeta() function. One way to do it, is as follows:

Fiddle: http://jsfiddle.net/ppanagi/28UES/2/

function getMeta(varA, varB) {
    if (typeof varB !== 'undefined') {
       alert(varA + ' width ' + varB + ' height');
    } else {
       var img = new Image();
       img.src = varA;
       img.onload = getMeta(this.width, this.height);
    }
}


getMeta("http://snook.ca/files/mootools_83_snookca.png");

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Div width 100% minus fixed amount of pixels

Maybe I'm being dumb, but isn't table the obvious solution here?

<div class="parent">
    <div class="fixed">
    <div class="stretchToFit">
</div>

.parent{ display: table; width 100%; }
.fixed { display: table-cell; width: 150px; }
.stretchToFit{ display: table-cell; vertical-align: top}

Another way that I've figured out in chrome is even simpler, but man is it a hack!

.fixed{ 
   float: left
}
.stretchToFit{
   display: table-cell;
   width: 1%;
}

This alone should fill the rest of the line horizontally, as table-cells do. However, you get some strange issues with it going over 100% of its parent, setting the width to a percent value fixes it though.

Width of input type=text element

input width is 10 + 2 times 1 px for border

Does height and width not apply to span?

Span takes width and height only when we make it block element.

span {display:block;}

CSS: 100% width or height while keeping aspect ratio?

I use this for a rectangular container with height and width fixed, but with images of different sizes.

img {
  max-width: 95%;
  max-height: 15em;
  width: auto !important;
}

How can I make a div not larger than its contents?

_x000D_
_x000D_
div{
width:fit-content;
}
_x000D_
<div>
    <table>
    </table>
</div>
_x000D_
_x000D_
_x000D_

Setting width as a percentage using jQuery

Hemnath

If your variable is the percentage:

var myWidth = 70;
$('div#somediv').width(myWidth + '%');

If your variable is in pixels, and you want the percentage it take up of the parent:

var myWidth = 140;
var myPercentage = (myWidth / $('div#somediv').parent().width()) * 100;
$('div#somediv').width(myPercentage + '%');

CSS – why doesn’t percentage height work?

A percentage value in a height property has a little complication, and the width and height properties actually behave differently to each other. Let me take you on a tour through the specs.

height property:

Let's have a look at what CSS Snapshot 2010 spec says about height:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'. A percentage height on the root element is relative to the initial containing block. Note: For absolutely positioned elements whose containing block is based on a block-level element, the percentage is calculated with respect to the height of the padding box of that element.

OK, let's take that apart step by step:

The percentage is calculated with respect to the height of the generated box's containing block.

What's a containing block? It's a bit complicated, but for a normal element in the default static position, it's:

the nearest block container ancestor box

or in English, its parent box. (It's well worth knowing what it would be for fixed and absolute positions as well, but I'm ignoring that to keep this answer short.)

So take these two examples:

_x000D_
_x000D_
<div   id="a"  style="width: 100px; height: 200px; background-color: orange">_x000D_
  <div id="aa" style="width: 100px; height: 50%;   background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<div   id="b"  style="width: 100px;              background-color: orange">_x000D_
  <div id="bb" style="width: 100px; height: 50%; background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In this example, the containing block of #aa is #a, and so on for #b and #bb. So far, so good.

The next sentence of the spec for height is the complication I mentioned in the introduction to this answer:

If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

Aha! Whether the height of the containing block has been specified explicitly matters!

  • 50% of height:200px is 100px in the case of #aa
  • But 50% of height:auto is auto, which is 0px in the case of #bb since there is no content for auto to expand to

As the spec says, it also matters whether the containing block has been absolutely positioned or not, but let's move on to width.

width property:

So does it work the same way for width? Let's take a look at the spec:

The percentage is calculated with respect to the width of the generated box's containing block.

Take a look at these familiar examples, tweaked from the previous to vary width instead of height:

_x000D_
_x000D_
<div   id="c"  style="width: 200px; height: 100px; background-color: orange">_x000D_
  <div id="cc" style="width: 50%;   height: 100px; background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<div   id="d"  style="            height: 100px; background-color: orange">_x000D_
  <div id="dd" style="width: 50%; height: 100px; background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • 50% of width:200px is 100px in the case of #cc
  • 50% of width:auto is 50% of whatever width:auto ends up being, unlike height, there is no special rule that treats this case differently.

Now, here's the tricky bit: auto means different things, depending partly on whether its been specified for width or height! For height, it just meant the height needed to fit the contents*, but for width, auto is actually more complicated. You can see from the code snippet that's in this case it ended up being the width of the viewport.

What does the spec say about the auto value for width?

The width depends on the values of other properties. See the sections below.

Wahey, that's not helpful. To save you the trouble, I've found you the relevant section to our use-case, titled "calculating widths and margins", subtitled "block-level, non-replaced elements in normal flow":

The following constraints must hold among the used values of the other properties:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

OK, so width plus the relevant margin, border and padding borders must all add up to the width of the containing block (not descendents the way height works). Just one more spec sentence:

If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.

Aha! So in this case, 50% of width:auto is 50% of the viewport. Hopefully everything finally makes sense now!


Footnotes

* At least, as far it matters in this case. spec All right, everything only kind of makes sense now.

How to make a div with no content have a width?

Use CSS to add a zero-width-space to your div. The content of the div will take no room but will force the div to display

.test1::before{
   content: "\200B";
}

Bootstrap Element 100% Width

QUICK ANSWER

  1. Use multiple NOT NESTED .containers
  2. Wrap those .containers you want to have a full-width background in a div
  3. Add a CSS background to the wrapping div

Fiddles: Simple: https://jsfiddle.net/vLhc35k4/ , Container borders: https://jsfiddle.net/vLhc35k4/1/
HTML:

<div class="container">
  <h2>Section 1</h2>
</div>
<div class="specialBackground">
  <div class="container">
    <h2>Section 2</h2>
  </div>
</div>

CSS: .specialBackground{ background-color: gold; /*replace with own background settings*/ }

FURTHER INFO

DON'T USE NESTED CONTAINERS

Many people will (wrongly) suggest, that you should use nested containers.
Well, you should NOT.
They are not ment to be nested. (See to "Containers" section in the docs)

HOW IT WORKS

div is a block element, which by default spans to the full width of a document body - there is the full-width feature. It also has a height of it's content (if you don't specify otherwise).

The bootstrap containers are not required to be direct children of a body, they are just containers with some padding and possibly some screen-width-variable fixed widths.

If a basic grid .container has some fixed width it is also auto-centered horizontally.
So there is no difference whether you put it as a:

  1. Direct child of a body
  2. Direct child of a basic div that is a direct child of a body.

By "basic" div I mean div that does not have a CSS altering his border, padding, dimensions, position or content size. Really just a HTML element with display: block; CSS and possibly background.
But of course setting vertical-like CSS (height, padding-top, ...) should not break the bootstrap grid :-)

Bootstrap itself is using the same approach

...All over it's own website and in it's "JUMBOTRON" example:
http://getbootstrap.com/examples/jumbotron/

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

Do you want the input fields to be centered? A trick to center elements: specify the width of the element and set the margin to auto, eg:

margin : 0px auto;
width:300px

A link to your updated fiddle:

http://jsfiddle.net/4x2KP/5/

CSS Layout - Dynamic width DIV

try

<div style="width:100%;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>

or

<div style="width:100%; border:2px solid #dadada;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>    
</div>

Width equal to content

set width attribute as: width: fit-content

demo: http://jsfiddle.net/rvrjp7/pyq3C/114

Is it really impossible to make a div fit its size to its content?

You can use:

width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;

EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/

ALSO: http://dev.w3.org/csswg/css-box-3/

jQuery - Get Width of Element when Not Visible (Display: None)

The biggest issue being missed by most solutions here is that an element's width is often changed by CSS based on where it is scoped in html.

If I was to determine offsetWidth of an element by appending a clone of it to body when it has styles that only apply in its current scope I would get the wrong width.

for example:

//css

.module-container .my-elem{ border: 60px solid black; }

now when I try to determine my-elem's width in context of body it will be out by 120px. You could clone the module container instead, but your JS shouldn't have to know these details.

I haven't tested it but essentially Soul_Master's solution appears to be the only one that could work properly. But unfortunately looking at the implementation it will likely be costly to use and bad for performance (as most of the solutions presented here are as well.)

If at all possible then use visibility: hidden instead. This will still render the element, allowing you to calculate width without all the fuss.

CSS to make table 100% of max-width

I had the same issue it was due to that I had the bootstrap class "hidden-lg" on the table which caused it to stupidly become display: block !important;

I wonder how Bootstrap never considered to just instead do this:

@media (min-width: 1200px) {
    .hidden-lg {
         display: none;
    }
}

And then just leave the element whatever display it had before for other screensizes.. Perhaps it is too advanced for them to figure out..

Anyway so:

table {
    display: table; /* check so these really applies */
    width: 100%;
}

should work

How to get Linux console window width in Python

Not sure why it is in the module shutil, but it landed there in Python 3.3, Querying the size of the output terminal:

>>> import shutil
>>> shutil.get_terminal_size((80, 20))  # pass fallback
os.terminal_size(columns=87, lines=23)  # returns a named-tuple

A low-level implementation is in the os module. Also works in Windows.

A backport is now available for Python 3.2 and below:

Make an image width 100% of parent div, but not bigger than its own width

Just specify max-width: 100% alone, that should do it.

Expand div to max width when float:left is set

this usage may solve your problem.

width: calc(100% - 100px);

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8" />_x000D_
  <title>Content with Menu</title>_x000D_
  <style>_x000D_
    .content .left {_x000D_
      float: left;_x000D_
      width: 100px;_x000D_
      background-color: green;_x000D_
    }_x000D_
    _x000D_
    .content .right {_x000D_
      float: left;_x000D_
      width: calc(100% - 100px);_x000D_
      background-color: red;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="content">_x000D_
    <div class="left">_x000D_
      <p>Hi, Flo!</p>_x000D_
    </div>_x000D_
    <div class="right">_x000D_
      <p>is</p>_x000D_
      <p>this</p>_x000D_
      <p>what</p>_x000D_
      <p>you are looking for?</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

How to make a div fill a remaining horizontal space?

I had a similar problem and I found the solution here: https://stackoverflow.com/a/16909141/3934886

The solution is for a fixed center div and liquid side columns.

.center{
    background:#ddd;
    width: 500px;
    float:left;
}

.left{
    background:#999;
    width: calc(50% - 250px);
    float:left;
}

.right{
    background:#999;
    width: calc(50% - 250px);
    float:right;
}

If you want a fixed left column, just change the formula accordingly.

How to get the width and height of an android.widget.ImageView?

my friend by this u are not getting height of image stored in db.but you are getting view height.for getting height of image u have to create bitmap from db,s image.and than u can fetch height and width of imageview

Override and reset CSS style: auto or none don't work

Well, display: none; will not display the table at all, try display: inline-block; with the width and min-width declarations remaining 'auto'.

td widths, not working?

You can try the "table-layout: fixed;" to your table

table-layout: fixed;
width: 150px;

150px or your desired width.

Reference: https://css-tricks.com/fixing-tables-long-strings/

Full width image with fixed height

Set the height of the parent element, and give that the width. Then use a background image with the rule "background-size: cover"

    .parent {
       background-image: url(../img/team/bgteam.jpg);
       background-repeat: no-repeat;
       background-position: center center;
       -webkit-background-size: cover;
       background-size: cover;
    }

How to make an element width: 100% minus padding?

Move the input box' padding to a wrapper element.

<style>
div.outer{ background: red; padding: 10px; }
div.inner { border: 1px solid #888; padding: 5px 10px; background: white; }
input { width: 100%; border: none }
</style>

<div class="outer">
    <div class="inner">
       <input/>
    </div>
</div>

See example here: http://jsfiddle.net/L7wYD/1/

IE 8: background-size fix

I use the filter solution above, for ie8. However.. In order to solve the freezing links problem , do also the following:

background: no-repeat center center fixed\0/; /* IE8 HACK */

This has solved the frozen links problem for me.

HTML input textbox with a width of 100% overflows table cells

You could use the CSS3 box-sizing property to include the external padding and border:

input[type="text"] {
     width: 100%; 
     box-sizing: border-box;
     -webkit-box-sizing:border-box;
     -moz-box-sizing: border-box;
}

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

Using Image control in WPF to display System.Drawing.Bitmap

I wrote a program with wpf and used Database for showing images and this is my code:

SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
                                      Initial Catalog=Payam;
                                      Integrated Security=True");

SqlDataAdapter da = new SqlDataAdapter("select * from news", con);

DataTable dt = new DataTable();
da.Fill(dt);

string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;

Calculating Time Difference

You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try

import time
time.time()

which gives you the seconds since the start of the epoch.

You can then get the intermediate time with something like

timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)

What is the Eclipse shortcut for "public static void main(String args[])"?

Just type ma and press Ctrl + Space, you will get an option for it.

Bootstrap dropdown not working

you have to import this files into the <head></head> of your html.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

Convert timestamp to date in MySQL query

I did it with the 'date' function as described in here :

(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)

Is Safari on iOS 6 caching $.ajax results?

It worked with ASP.NET only after adding the pragma:no-cache header in IIS. Cache-Control: no-cache was not enough.

Count the number occurrences of a character in a string

No more than this IMHO - you can add the upper or lower methods

def count_letter_in_str(string,letter):
    return string.count(letter)

how to add value to a tuple?

As other people have answered, tuples in python are immutable and the only way to 'modify' one is to create a new one with the appended elements included.

But the best solution is a list. When whatever function or method that requires a tuple needs to be called, create a tuple by using tuple(list).

Using Switch Statement to Handle Button Clicks

I have found that the simplest way to do this is to set onClick for each button in the xml

<Button
android:id="@+id/vrHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_menu_help"
android:onClick="helpB" />

and then you can do a switch case like this

  public void helpB(View v) {
    Button clickedButton = (Button) v;
    switch (clickedButton.getId()) {
      case R.id.vrHelp:
        dosomething...
        break;

      case R.id.coHelp:
        dosomething...
        break;

      case R.id.ksHelp:
        dosomething...
        break;

      case R.id.uHelp:
        dosomething...
        break;

      case R.id.pHelp:
        dosomething...
        break;
    }
  }

Getting realtime output using subprocess

Complete solution:

import contextlib
import subprocess

# Unix, Windows and old Macintosh end-of-line
newlines = ['\n', '\r\n', '\r']
def unbuffered(proc, stream='stdout'):
    stream = getattr(proc, stream)
    with contextlib.closing(stream):
        while True:
            out = []
            last = stream.read(1)
            # Don't loop forever
            if last == '' and proc.poll() is not None:
                break
            while last not in newlines:
                # Don't loop forever
                if last == '' and proc.poll() is not None:
                    break
                out.append(last)
                last = stream.read(1)
            out = ''.join(out)
            yield out

def example():
    cmd = ['ls', '-l', '/']
    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        # Make all end-of-lines '\n'
        universal_newlines=True,
    )
    for line in unbuffered(proc):
        print line

example()

Check if a string is a palindrome

    public static bool IsPalindrome(string str)
    {
        int i = 0;
        int a = 0;

        char[] chr = str.ToCharArray();
        foreach (char cr in chr)
        {
            Array.Reverse(chr);
            if (chr[i] == cr)
            {
                if (a == str.Length)
                {
                    return true;
                }
                a++;
                i++;
            }
            else
            {
                return false;
            }
        }
        return true;
    }

How can I get the SQL of a PreparedStatement?

If you're using MySQL you can log the queries using MySQL's query log. I don't know if other vendors provide this feature, but chances are they do.

Is it possible to access an SQLite database from JavaScript?

One of the most interesting features in HTML5 is the ability to store data locally and to allow the application to run offline. There are three different APIs that deal with these features and choosing one depends on what exactly you want to do with the data you're planning to store locally:

  1. Web storage: For basic local storage with key/value pairs
  2. Offline storage: Uses a manifest to cache entire files for offline use
  3. Web database: For relational database storage

For more reference see Introducing the HTML5 storage APIs

And how to use

http://cookbooks.adobe.com/post_Store_data_in_the_HTML5_SQLite_database-19115.html

How to get anchor text/href on click using jQuery?

Updated code

$('a','div.res').click(function(){
  var currentAnchor = $(this);
  alert(currentAnchor.text());
  alert(currentAnchor.attr('href'));
});

SQL Server date format yyyymmdd

SELECT YEAR(getdate()) * 10000 + MONTH(getdate()) * 100 + DAY(getdate())

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I had this problem but didn't have a version conflict in my package.json.

My package-lock.json was somehow out of sync with package json though. Deleting and regenerating it worked for me.

Stretch and scale a CSS image in the background - with CSS only

The following CSS part should stretch the image with all browsers.

I do this dynamically for each page. Therefore I use PHP to generate its own HTML tag for each page. All the pictures are in the 'image' folder and end with 'Bg.jpg'.

<html style="
      background: url(images/'.$pic.'Bg.jpg) no-repeat center center fixed;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
      filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/'.$pic.'Bg.jpg\',     sizingMethod=\'scale\');
      -ms-filter: \"progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/'.$pic.'Bg.jpg\', sizingMethod=\'scale\')\
";>

If you have only one background picture for all pages then you may remove the $pic variable, remove escaping back-slashes, adjust paths and place this code in your CSS file.

html{
    background: url(images/homeBg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg.jpg',     sizingMethod='scale');
    -ms-filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg', sizingMethod='scale');
}

This was tested with Internet Explorer 9, Chrome 21, and Firefox 14.

Using scanner.nextLine()

Rather than placing an extra scanner.nextLine() each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)

import java.util.Scanner;

class ScannerTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\\n");

        System.out.print("Enter an index: ");
        int index = scanner.nextInt();

        System.out.print("Enter a sentence: ");
        String sentence = scanner.next();

        System.out.println("\nYour sentence: " + sentence);
        System.out.println("Your index: " + index);
    }
}

Thus, to read a line of input, you only need scanner.next() that has the same behavior delimiter-wise of next{Int, Double, ...}

The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3, 3<space> and 3<space>whatever while the former only accepts 3 on a line on its own

Safest way to run BAT file from Powershell script

@Rynant 's solution worked for me. I had a couple of additional requirements though:

  1. Don't PAUSE if encountered in bat file
  2. Optionally, append bat file output to log file

Here's what I got working (finally):

[PS script code]

& runner.bat bat_to_run.bat logfile.txt

[runner.bat]

@echo OFF

REM This script can be executed from within a powershell script so that the bat file
REM passed as %1 will not cause execution to halt if PAUSE is encountered.
REM If {logfile} is included, bat file output will be appended to logfile.
REM
REM Usage:
REM runner.bat [path of bat script to execute] {logfile}

if not [%2] == [] GOTO APPEND_OUTPUT
@echo | call %1
GOTO EXIT

:APPEND_OUTPUT
@echo | call %1  1> %2 2>&1

:EXIT

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

In my case I just needed to remove Homebrew's executable using:

sudo rm -f `which brew`

Then reinstall Homebrew:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:

-lavcodec

Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.


For a detailed reference on GCC's linker option, please read here.

Video 100% width and height

This is a great way to make the video fit a banner, you might need to tweak this a little for full screen but should be ok. 100% CSS.

_x000D_
_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    z-index: 1;_x000D_
    min-width: 100%;_x000D_
    min-height: 100%;_x000D_
    width: auto;_x000D_
    height: auto;_x000D_
    transform: translate(-50%, -50%);
_x000D_
_x000D_
_x000D_

Dependent DLL is not getting copied to the build output folder in Visual Studio

TLDR; Visual Studio 2019 may simply need a restart.

I encountered this situation using projects based on Microsoft.NET.Sdk project.

<Project Sdk="Microsoft.NET.Sdk">

Specifically:

  • Project1: targets .netstandard2.1
    • references Microsoft.Extensions.Logging.Console via Nuget
  • Project2: targets .netstandard2.1
    • references Project1 via a Project reference
  • Project2Tests: targets .netcoreapp3.1
    • references Project2 via a Project reference

At test execution, I received the error messaging indicating that Microsoft.Extensions.Logging.Console could not be found, and it was indeed not in the output directory.

I decided to work around the issue by adding Microsoft.Extensions.Logging.Console to Project2, only to discover that Visual Studio's Nuget Manager did not list Microsoft.Extensions.Logging.Console as installed in Project1, despite it's presence in the Project1.csproj file.

A simple shut down and restart of Visual Studio resolved the problem without the need to add an extra reference. Perhaps this will save someone 45 minutes of lost productivity :-)

Iterate through string array in Java

    String[] nameArray= {"John", "Paul", "Ringo", "George"};
    int numberOfItems = nameArray.length;
    for (int i=0; i<numberOfItems; i++)
    {
        String name = nameArray[i];
        System.out.println("Hello " + name);
    }

to_string is not a member of std, says g++ (mingw)

The fact is that libstdc++ actually supported std::to_string in *-w64-mingw32 targets since 4.8.0. However, this does not include support for MinGW.org, Cygwin and variants (e.g. *-pc-msys from MSYS2). See also https://cygwin.com/ml/cygwin/2015-01/msg00245.html.

I have implemented a workaround before the bug resolved for MinGW-w64. Being different to code in other answers, this is a mimic to libstdc++ (as possible). It does not require string stream construction but depends on libstdc++ extensions. Even now I am using mingw-w64 targets on Windows, it still works well for multiple other targets (as long as long double functions not being used).

Relative imports in Python 3

To obviate this problem, I devised a solution with the repackage package, which has worked for me for some time. It adds the upper directory to the lib path:

import repackage
repackage.up()
from mypackage.mymodule import myfunction

Repackage can make relative imports that work in a wide range of cases, using an intelligent strategy (inspecting the call stack).

How to retrieve data from sqlite database in android and display it in TextView

First cast your Edit text like this:

TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);

And after that close the DB not befor this line...

 myDataBaseHelper.close(); 

How to hide keyboard in swift on pressing return key?

@RSC

for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()

 self.input.delegate = self;

Tried getting it to work with the return key for hours till I found your post, RSC. Thank you!

Also, if you want to hide the keyboard if you touch anywhere else on the screen:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true);
    }

Angular ng-click with call to a controller function not working

I'm going to guess you aren't getting errors or you would've mentioned them. If that's the case, try removing the href attribute value so the page doesn't navigate away before your code is executed. In Angular it's perfectly acceptable to leave href attributes blank.

<a href="" data-router="article" ng-click="changeListName('metro')">

Also I don't know what data-router is doing but if you still aren't getting the proper result, that could be why.

How to convert List<string> to List<int>?

I know it's old post, but I thought this is a good addition: You can use List<T>.ConvertAll<TOutput>

List<int> integers = strings.ConvertAll(s => Int32.Parse(s));

Is there 'byte' data type in C++?

There's also byte_lite, compatible with C++98, C++11 and later.

VB.Net Properties - Public Get, Private Set

Yes, quite straight forward:

Private _name As String

Public Property Name() As String
    Get
        Return _name
    End Get
    Private Set(ByVal value As String)
        _name = value
    End Set
End Property

Ruby on Rails - Import Data from a CSV file

I know it's old question but it still in first 10 links in google.

It is not very efficient to save rows one-by-one because it cause database call in the loop and you better avoid that, especially when you need to insert huge portions of data.

It's better (and significantly faster) to use batch insert.

INSERT INTO `mouldings` (suppliers_code, name, cost)
VALUES
    ('s1', 'supplier1', 1.111), 
    ('s2', 'supplier2', '2.222')

You can build such a query manually and than do Model.connection.execute(RAW SQL STRING) (not recomended) or use gem activerecord-import (it was first released on 11 Aug 2010) in this case just put data in array rows and call Model.import rows

refer to gem docs for details

What's the difference between a Future and a Promise?

For client code, Promise is for observing or attaching callback when a result is available, whereas Future is to wait for result and then continue. Theoretically anything which is possible to do with futures what can done with promises, but due to the style difference, the resultant API for promises in different languages make chaining easier.

CALL command vs. START with /WAIT option

This is what I found while running batch files in parallel (multiple instances of the same bat file at the same time with different input parameters) :

Lets say that you have an exe file that performs a long task called LongRunningTask.exe

If you call the exe directly from the bat file, only the first call to the LongRunningTask will succed, while the rest will get an OS error "File is already in use by the process"

If you use this command:

start /B /WAIT "" "LongRunningTask.exe" "parameters"

You will be able to run multiple instances of the bat and exe, while still waiting for the task to finish before the bat continues executing the remaining commands. The /B option is to avoid creating another window, the empty quotes are needed in order to the command to work, see the reference below.

Note that if you don´t use the /WAIT in the start, the LongRunningTask will be executed at the same time than the remaining commands in the batch file, so it might create problems if one of these commands requires the output of the LongRunningTask

Resuming :

This can´t run in parallel :

  • call LongRunningTask.exe

This will run in parallel and will be ok as far as there are no data dependencies between the output of the command and the rest of the bat file :

  • start /B "" "LongRunningTask.exe" "parameters"

This will run in parallel and wait for the task to finish, so you can use the output :

  • start /B /WAIT "" "LongRunningTask.exe" "parameters"

Reference for the start command : How can I run a program from a batch file without leaving the console open after the program start?

Virtualhost For Wildcard Subdomain and Static Subdomain

Wildcards can only be used in the ServerAlias rather than the ServerName. Something which had me stumped.

For your use case, the following should suffice

<VirtualHost *:80>
    ServerAlias *.example.com
    VirtualDocumentRoot /var/www/%1/
</VirtualHost>

MAX(DATE) - SQL ORACLE

Try with:

select TO_CHAR(dates,'dd/MM/yyy hh24:mi') from (  SELECT min  (TO_DATE(a.PAYM_DATE)) as dates from user_payment a )

Should we pass a shared_ptr by reference or by value?

This question has been discussed and answered by Scott, Andrei and Herb during Ask Us Anything session at C++ and Beyond 2011. Watch from 4:34 on shared_ptr performance and correctness.

Shortly, there is no reason to pass by value, unless the goal is to share ownership of an object (eg. between different data structures, or between different threads).

Unless you can move-optimise it as explained by Scott Meyers in the talk video linked above, but that is related to actual version of C++ you can use.

A major update to this discussion has happened during GoingNative 2012 conference's Interactive Panel: Ask Us Anything! which is worth watching, especially from 22:50.

Node JS Error: ENOENT

change

"/tmp/test.jpg".

to

"./tmp/test.jpg"

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

Form/JavaScript not working on IE 11 with error DOM7011

Go to

Tools > Compatibility View settings > Uncheck the option "Display intranet sites in Compatibility View".

Click on Close. It may re-launch the page and then your problem would be resolved.

Bootstrap footer at the bottom of the page

Use this stylesheet:

_x000D_
_x000D_
/* Sticky footer styles_x000D_
-------------------------------------------------- */_x000D_
html {_x000D_
  position: relative;_x000D_
  min-height: 100%;_x000D_
}_x000D_
body {_x000D_
  /* Margin bottom by footer height */_x000D_
  margin-bottom: 60px;_x000D_
}_x000D_
.footer {_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 100%;_x000D_
  /* Set the fixed height of the footer here */_x000D_
  height: 60px;_x000D_
  line-height: 60px; /* Vertically center the text there */_x000D_
  background-color: #f5f5f5;_x000D_
}_x000D_
_x000D_
_x000D_
/* Custom page CSS_x000D_
-------------------------------------------------- */_x000D_
/* Not required for template or sticky footer method. */_x000D_
_x000D_
body > .container {_x000D_
  padding: 60px 15px 0;_x000D_
}_x000D_
_x000D_
.footer > .container {_x000D_
  padding-right: 15px;_x000D_
  padding-left: 15px;_x000D_
}_x000D_
_x000D_
code {_x000D_
  font-size: 80%;_x000D_
}
_x000D_
_x000D_
_x000D_

What is the meaning of "Failed building wheel for X" in pip install?

Try this:

sudo apt-get install libpcap-dev libpq-dev

It has worked for me when I have installed these two.

See the link here for more information

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Font awesome is not showing icon

my issue was the one having most of the votes

*{
font-family: xxxxx
}

changing it to this solved the problem

body{
font-family: xxxx
}

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

Windows service start failure: Cannot start service from the command line or debugger

To install your service manually

To install or uninstall windows service manually (which was created using .NET Framework) use utility InstallUtil.exe. This tool can be found in the following path (use appropriate framework version number).

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe

To install

installutil yourproject.exe

To uninstall

installutil /u yourproject.exe

See: How to: Install and Uninstall Services (Microsoft)

Install service programmatically

To install service programmatically using C# see the following class ServiceInstaller (c-sharpcorner).

How do I get the difference between two Dates in JavaScript?

If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.

moment(endDate).diff(moment(beginDate), 'days');

Additional details can be found in the moment.js page

Cheers, Miguel

How to fix 'Microsoft Excel cannot open or save any more documents'

After giving necessary permissions in DCOM configurations I also needed to change the identity of my application in the IIS to a custom account

Alter a MySQL column to be AUTO_INCREMENT

You must specify the type of the column before the auto_increment directive, i.e. ALTER TABLE document MODIFY COLUMN document_id INT AUTO_INCREMENT.

Image convert to Base64

_x000D_
_x000D_
function readFile() {_x000D_
  _x000D_
  if (this.files && this.files[0]) {_x000D_
    _x000D_
    var FR= new FileReader();_x000D_
    _x000D_
    FR.addEventListener("load", function(e) {_x000D_
      document.getElementById("img").src       = e.target.result;_x000D_
      document.getElementById("b64").innerHTML = e.target.result;_x000D_
    }); _x000D_
    _x000D_
    FR.readAsDataURL( this.files[0] );_x000D_
  }_x000D_
  _x000D_
}_x000D_
_x000D_
document.getElementById("inp").addEventListener("change", readFile);
_x000D_
<input id="inp" type='file'>_x000D_
<p id="b64"></p>_x000D_
<img id="img" height="150">
_x000D_
_x000D_
_x000D_

(P.S: A base64 encoded image (String) 4/3 the size of the original image data)

Check this answer for multiple images upload.

Browser support: http://caniuse.com/#search=file%20api
More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

I came across this issue as well. What I did was force kill the app on my device, then I opened up another console and ran

react-native start

and then I opened the app again from my device and it started working again.

EDIT: If you are using an android device via USB and have unplugged it or your computer went to sleep, you may have to first run

adb reverse tcp:8081 tcp:8081

Error "package android.support.v7.app does not exist"

For AndroidX implement following lib in gridle

implementation 'androidx.palette:palette:1.0.0'

and import following class in activity -

import androidx.palette.graphics.Palette;

for more info see class and mapping for AndroidX https://developer.android.com/jetpack/androidx/migrate/artifact-mappings https://developer.android.com/jetpack/androidx/migrate/class-mappings

How do I compile a .cpp file on Linux?

The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.

Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.

Get value of a string after last slash in JavaScript

Try;

var str = "foo/bar/test.html";
var tmp = str.split("/");
alert(tmp.pop());

How to increase the execution timeout in php?

You need to change some setting in your php.ini:

upload_max_filesize = 2M 
;or whatever size you want

max_execution_time = 60
; also, higher if you must - sets the maximum time in seconds

Were your PHP.ini is located depends on your environment, more information: http://php.net/manual/en/ini.list.php

How do I integrate Ajax with Django applications?

When we use Django:

Server ===> Client(Browser)   
      Send a page

When you click button and send the form,
----------------------------
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      Send a page after doing sth with these data
----------------------------

If you want to keep old data, you can do it without Ajax. (Page will be refreshed)

Server ===> Client(Browser)   
      Send a page
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      1. Send a page after doing sth with data
      2. Insert data into form and make it like before. 
      After these thing, server will send a html page to client. It means that server do more work, however, the way to work is same.

Or you can do with Ajax (Page will be not refreshed)

--------------------------
<Initialization> 
Server ===> Client(Browser) [from URL1]    
      Give a page                      
--------------------------  
<Communication>
Server <=== Client(Browser)     
      Give data struct back but not to refresh the page.
Server ===> Client(Browser) [from URL2] 
      Give a data struct(such as JSON)
---------------------------------

If you use Ajax, you must do these:

  1. Initial a HTML page using URL1 (we usually initial page by Django template). And then server send client a html page.
  2. Use Ajax to communicate with server using URL2. And then server send client a data struct.

Django is different from Ajax. The reason for this is as follows:

  • The thing return to client is different. The case of Django is HTML page. The case of Ajax is data struct.
  • Django is good at creating something, but it only can create once, it cannot change anything. Django is like anime, consist of many picture. By contrast, Ajax is not good at creating sth but good at change sth in exist html page.

In my opinion, if you would like to use ajax everywhere. when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template.

If you don't think Ajax is the best practice. you can use Django template to do everything, like anime.

(My English is not good)

Converting a String to a List of Words?

Well, you could use

import re
list = re.sub(r'[.!,;?]', ' ', string).split()

Note that both string and list are names of builtin types, so you probably don't want to use those as your variable names.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Swift: Convert enum value to String?

Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:

enum Audience : String {
    case public
    case friends
    case private
}

let audience = Audience.public.rawValue // "public"

When strings are used for raw values, the implicit value for each case is the text of that case’s name.

[...]

enum CompassPoint : String {
    case north, south, east, west
}

In the example above, CompassPoint.south has an implicit raw value of "south", and so on.

You access the raw value of an enumeration case with its rawValue property:

let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

Source.

How can I get the list of files in a directory using C or C++?

This works for me. I'm sorry if I cannot remember the source. It is probably from a man page.

#include <ftw.h>

int AnalizeDirectoryElement (const char *fpath, 
                            const struct stat *sb,
                            int tflag, 
                            struct FTW *ftwbuf) {

  if (tflag == FTW_F) {
    std::string strFileName(fpath);

    DoSomethingWith(strFileName);
  }
  return 0; 
}

void WalkDirectoryTree (const char * pchFileName) {

  int nFlags = 0;

  if (nftw(pchFileName, AnalizeDirectoryElement, 20, nFlags) == -1) {
    perror("nftw");
  }
}

int main() {
  WalkDirectoryTree("some_dir/");
}

Is there a way to define a min and max value for EditText in Android?

here's the way I've used, it's working for negative number

First, create MinMaxFIlter.java class with the following code :

import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;

/**
* Created by 21 on 4/5/2016.
*/
public class MinMaxFilter implements InputFilter {

private double mIntMin, mIntMax;

public MinMaxFilter(double minValue, double maxValue) {
    this.mIntMin = minValue;
    this.mIntMax = maxValue;
}

public MinMaxFilter(String minValue, String maxValue) {
    this.mIntMin = Double.parseDouble(minValue);
    this.mIntMax = Double.parseDouble(maxValue);
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    try {
        Boolean isNeg = false;
        String provi = dest.toString() + source.toString();
        if("-".equals(provi.substring(0,1))){
            if(provi.length()>1) {
                provi = provi.substring(1, provi.length());
                isNeg = true;
            }
            else{
                if("".equals(source)){
                    return null;
                }
                return "-";
            }
        }

        double input = Double.parseDouble(provi); 
        if(isNeg){input = input * (-1);}

        if (isInRange(mIntMin, mIntMax, input)) {
            return null;
        }
    } catch (Exception nfe) {}
    return "";
}

private boolean isInRange(double a, double b, double c) {
    if((c>=a && c<=b)){
        return true;
    }
    else{
        return false;
    }
}
}

Then, create and set your filter to your edittext like this :

EditText edittext = new EditText(context);
editext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
eInt.setFilters(new InputFilter[]{new MinMaxFilter(min, max)});

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Here is My Code

protected void btnExcel_Click(object sender, ImageClickEventArgs e)
    {
        if (gvDetail.Rows.Count > 0)
        {
            System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
            gvDetail.RenderControl(htmlWrite1);

            gvDetail.AllowPaging = false;
            Search();
            sh.ExportToExcel(gvDetail, "Report");
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

Multithreading in Bash

You can run several copies of your script in parallel, each copy for different input data, e.g. to process all *.cfg files on 4 cores:

    ls *.cfg | xargs -P 4 -n 1 read_cfg.sh

The read_cfg.sh script takes just one parameters (as enforced by -n)

Unstage a deleted file in git

From manual page,

git-reset - Reset current HEAD to the specified state
git reset [-q] [<tree-ish>] [--] <paths>...
In the first and second form, copy entries from <tree-ish> to the index.

for example, when we use git reset HEAD~1 it reset our current HEAD to HEAD~1

so when we use git reset 'some-deleted-file-path'

git assume 'some-deleted-file-path' as some commit point and try to reset out current HEAD to there.

And it ends up fail

fatal: ambiguous argument 'some-deleted-file-path': unknown revision or path not in the working tree.

Function that creates a timestamp in c#

You can also use

Stopwatch.GetTimestamp().ToString();

Open file dialog box in JavaScript

May use

$('<input type="file" />').click()

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

This is what did it for me in .htaccess (it could be that you had a directive making all files load as MIME type text/html):

In .htaccess

AddType text/css .css

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Vava's answer is on the mark. If you use jQuery, then the $.each() function takes care of this, hence it is safer to use.

$.each(evtListeners, function(index, elem) {
    // your code
});

Python - Convert a bytes array into JSON format

Python 3.5 + Use io module

import json
import io

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

fix_bytes_value = my_bytes_value.replace(b"'", b'"')

my_json = json.load(io.BytesIO(fix_bytes_value))  

Iptables setting multiple multiports in one rule

enable_boxi_poorten

}

enable_boxi_poorten() {
SRV="boxi_poorten"
boxi_ports="427 5666 6001 6002 6003 6004 6005 6400 6410 8080 9321 15191 16447 17284 17723 17736 21306 25146 26632 27657 27683 28925 41583 45637 47648 49633 52551 53166 56392 56599 56911 59115 59898 60163 63512 6352 25834"


case "$1" in
  "LOCAL")
         for port in $boxi_ports; do $IPT -A tcp_inbound -p TCP -s $LOC_SUB --dport $port -j ACCEPT -m comment --comment "boxi specifieke poorten";done
     # multiports gaat maar tot 15 maximaal :((
     # daarom maar for loop maken
     # $IPT -A tcp_inbound -p TCP -s $LOC_SUB -m state --state NEW -m multiport --dports $MULTIPORTS -j ACCEPT -m comment --comment "boxi specifieke poorten"
     echo "${GREEN}Allowing $SRV for local hosts.....${NORMAL}"
    ;;
  "WEB")
     for port in $boxi_ports; do $IPT -A tcp_inbound -p TCP -s 0/0 --dport $port -j ACCEPT -m comment --comment "boxi specifieke poorten";done
     echo "${RED}Allowing $SRV for all hosts.....${NORMAL}"
    ;;
  *)
     for port in $boxi_ports; do $IPT -A tcp_inbound -p TCP -s $LOC_SUB --dport $port -j ACCEPT -m comment --comment "boxi specifieke poorten";done
     echo "${GREEN}Allowing $SRV for local hosts.....${NORMAL}"
    ;;
 esac

}

reCAPTCHA ERROR: Invalid domain for site key

I had the same problems I solved it. I went to https://www.google.com/recaptcha/admin and clicked on the domain and then went to key settings at the bottom.

There I disabled the the option below Domain Name Validation Verify the origin of reCAPTCHA solution

clicked on save and captcha started working.

I think this has to do with way the server is setup. I am on a shared hosting and just was transferred without notice from Liquidweb to Deluxehosting(as the former sold their share hosting to the latter) and have been having such problems with many issues. I think in this case google is checking the server but it is identifying as shared server name and not my domain. When i uncheck the "verify origin" it starts working. Hope this helps solve the problem for the time being.

Javascript array value is undefined ... how do I test for that

You are checking it the array index contains a string "undefined", you should either use the typeof operator:

typeof predQuery[preId] == 'undefined'

Or use the undefined global property:

predQuery[preId] === undefined

The first way is safer, because the undefined global property is writable, and it can be changed to any other value.

What are the differences between B trees and B+ trees?

Define "much faster". Asymptotically they're about the same. The differences lie in how they make use of secondary storage. The Wikipedia articles on B-trees and B+trees look pretty trustworthy.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Add CSS or JavaScript files to layout head from views or partial views

I had a similar problem, and ended up applying Kalman's excellent answer with the code below (not quite as neat, but arguably more expansible):

namespace MvcHtmlHelpers
{
    //http://stackoverflow.com/questions/5110028/add-css-or-js-files-to-layout-head-from-views-or-partial-views#5148224
    public static partial class HtmlExtensions
    {
        public static AssetsHelper Assets(this HtmlHelper htmlHelper)
        {
            return AssetsHelper.GetInstance(htmlHelper);
        }
    }
    public enum BrowserType { Ie6=1,Ie7=2,Ie8=4,IeLegacy=7,W3cCompliant=8,All=15}
    public class AssetsHelper
    {
        public static AssetsHelper GetInstance(HtmlHelper htmlHelper)
        {
            var instanceKey = "AssetsHelperInstance";
            var context = htmlHelper.ViewContext.HttpContext;
            if (context == null) {return null;}
            var assetsHelper = (AssetsHelper)context.Items[instanceKey];
            if (assetsHelper == null){context.Items.Add(instanceKey, assetsHelper = new AssetsHelper(htmlHelper));}
            return assetsHelper;
        }
        private readonly List<string> _styleRefs = new List<string>();
        public AssetsHelper AddStyle(string stylesheet)
        {
            _styleRefs.Add(stylesheet);
            return this;
        }
        private readonly List<string> _scriptRefs = new List<string>();
        public AssetsHelper AddScript(string scriptfile)
        {
            _scriptRefs.Add(scriptfile);
            return this;
        }
        public IHtmlString RenderStyles()
        {
            ItemRegistrar styles = new ItemRegistrar(ItemRegistrarFormatters.StyleFormat,_urlHelper);
            styles.Add(Libraries.UsedStyles());
            styles.Add(_styleRefs);
            return styles.Render();
        }
        public IHtmlString RenderScripts()
        {
            ItemRegistrar scripts = new ItemRegistrar(ItemRegistrarFormatters.ScriptFormat, _urlHelper);
            scripts.Add(Libraries.UsedScripts());
            scripts.Add(_scriptRefs);
            return scripts.Render();
        }
        public LibraryRegistrar Libraries { get; private set; }
        private UrlHelper _urlHelper;
        public AssetsHelper(HtmlHelper htmlHelper)
        {
            _urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            Libraries = new LibraryRegistrar();
        }
    }
    public class LibraryRegistrar
    {
        public class Component
        {
            internal class HtmlReference
            {
                internal string Url { get; set; }
                internal BrowserType ServeTo { get; set; }
            }
            internal List<HtmlReference> Styles { get; private set; }
            internal List<HtmlReference> Scripts { get; private set; }
            internal List<string> RequiredLibraries { get; private set; }

            public Component()
            {
                Styles = new List<HtmlReference>();
                Scripts = new List<HtmlReference>();
                RequiredLibraries = new List<string>();
            }
            public Component Requires(params string[] libraryNames)
            {
                foreach (var lib in libraryNames)
                {
                    if (!RequiredLibraries.Contains(lib))
                        { RequiredLibraries.Add(lib); }
                }
                return this;
            }
            public Component AddStyle(string url, BrowserType serveTo = BrowserType.All)
            {
                Styles.Add(new HtmlReference { Url = url, ServeTo=serveTo });
                return this;
            }
            public Component AddScript(string url, BrowserType serveTo = BrowserType.All)
            {
                Scripts.Add(new HtmlReference { Url = url, ServeTo = serveTo });
                return this;
            }
        }
        private readonly Dictionary<string, Component> _allLibraries = new Dictionary<string, Component>();
        private List<string> _usedLibraries = new List<string>();
        internal IEnumerable<string> UsedScripts()
        {
            SetOrder();
            var returnVal = new List<string>();
            foreach (var key in _usedLibraries)
            {
                returnVal.AddRange(from s in _allLibraries[key].Scripts
                                   where IncludesCurrentBrowser(s.ServeTo)
                                   select s.Url);
            }
            return returnVal;
        }
        internal IEnumerable<string> UsedStyles()
        {
            SetOrder();
            var returnVal = new List<string>();
            foreach (var key in _usedLibraries)
            {
                returnVal.AddRange(from s in _allLibraries[key].Styles
                                   where IncludesCurrentBrowser(s.ServeTo)
                                   select s.Url);
            }
            return returnVal;
        }
        public void Uses(params string[] libraryNames)
        {
            foreach (var name in libraryNames)
            {
                if (!_usedLibraries.Contains(name)){_usedLibraries.Add(name);}
            }
        }
        public bool IsUsing(string libraryName)
        {
            SetOrder();
            return _usedLibraries.Contains(libraryName);
        }
        private List<string> WalkLibraryTree(List<string> libraryNames)
        {
            var returnList = new List<string>(libraryNames);
            int counter = 0;
            foreach (string libraryName in libraryNames)
            {
                WalkLibraryTree(libraryName, ref returnList, ref counter);
            }
            return returnList;
        }
        private void WalkLibraryTree(string libraryName, ref List<string> libBuild, ref int counter)
        {
            if (counter++ > 1000) { throw new System.Exception("Dependancy library appears to be in infinate loop - please check for circular reference"); }
            Component library;
            if (!_allLibraries.TryGetValue(libraryName, out library))
                { throw new KeyNotFoundException("Cannot find a definition for the required style/script library named: " + libraryName); }
            foreach (var childLibraryName in library.RequiredLibraries)
            {
                int childIndex = libBuild.IndexOf(childLibraryName);
                if (childIndex!=-1)
                {
                    //child already exists, so move parent to position before child if it isn't before already
                    int parentIndex = libBuild.LastIndexOf(libraryName);
                    if (parentIndex>childIndex)
                    {
                        libBuild.RemoveAt(parentIndex);
                        libBuild.Insert(childIndex, libraryName);
                    }
                }
                else
                {
                    libBuild.Add(childLibraryName);
                    WalkLibraryTree(childLibraryName, ref libBuild, ref counter);
                }
            }
            return;
        }
        private bool _dependenciesExpanded;
        private void SetOrder()
        {
            if (_dependenciesExpanded){return;}
            _usedLibraries = WalkLibraryTree(_usedLibraries);
            _usedLibraries.Reverse();
            _dependenciesExpanded = true;
        }
        public Component this[string index]
        {
            get
            {
                if (_allLibraries.ContainsKey(index))
                    { return _allLibraries[index]; }
                var newComponent = new Component();
                _allLibraries.Add(index, newComponent);
                return newComponent;
            }
        }
        private BrowserType _requestingBrowser;
        private BrowserType RequestingBrowser
        {
            get
            {
                if (_requestingBrowser == 0)
                {
                    var browser = HttpContext.Current.Request.Browser.Type;
                    if (browser.Length > 2 && browser.Substring(0, 2) == "IE")
                    {
                        switch (browser[2])
                        {
                            case '6':
                                _requestingBrowser = BrowserType.Ie6;
                                break;
                            case '7':
                                _requestingBrowser = BrowserType.Ie7;
                                break;
                            case '8':
                                _requestingBrowser = BrowserType.Ie8;
                                break;
                            default:
                                _requestingBrowser = BrowserType.W3cCompliant;
                                break;
                        }
                    }
                    else
                    {
                        _requestingBrowser = BrowserType.W3cCompliant;
                    }
                }
                return _requestingBrowser;
            }
        }
        private bool IncludesCurrentBrowser(BrowserType browserType)
        {
            if (browserType == BrowserType.All) { return true; }
            return (browserType & RequestingBrowser) != 0;
        }
    }
    public class ItemRegistrar
    {
        private readonly string _format;
        private readonly List<string> _items;
        private readonly UrlHelper _urlHelper;

        public ItemRegistrar(string format, UrlHelper urlHelper)
        {
            _format = format;
            _items = new List<string>();
            _urlHelper = urlHelper;
        }
        internal void Add(IEnumerable<string> urls)
        {
            foreach (string url in urls)
            {
                Add(url);
            }
        }
        public ItemRegistrar Add(string url)
        {
            url = _urlHelper.Content(url);
            if (!_items.Contains(url))
                { _items.Add( url); }
            return this;
        }
        public IHtmlString Render()
        {
            var sb = new StringBuilder();
            foreach (var item in _items)
            {
                var fmt = string.Format(_format, item);
                sb.AppendLine(fmt);
            }
            return new HtmlString(sb.ToString());
        }
    }
    public class ItemRegistrarFormatters
    {
        public const string StyleFormat = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
        public const string ScriptFormat = "<script src=\"{0}\" type=\"text/javascript\"></script>";
    }
}

The project contains a static AssignAllResources method:

assets.Libraries["jQuery"]
        .AddScript("~/Scripts/jquery-1.10.0.min.js", BrowserType.IeLegacy)
        .AddScript("~/Scripts//jquery-2.0.1.min.js",BrowserType.W3cCompliant);
        /* NOT HOSTED YET - CHECK SOON 
        .AddScript("//ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js",BrowserType.W3cCompliant);
        */
    assets.Libraries["jQueryUI"].Requires("jQuery")
        .AddScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js",BrowserType.Ie6)
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/eggplant/jquery-ui.css",BrowserType.Ie6)
        .AddScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js", ~BrowserType.Ie6)
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/eggplant/jquery-ui.css", ~BrowserType.Ie6);
    assets.Libraries["TimePicker"].Requires("jQueryUI")
        .AddScript("~/Scripts/jquery-ui-sliderAccess.min.js")
        .AddScript("~/Scripts/jquery-ui-timepicker-addon-1.3.min.js")
        .AddStyle("~/Content/jQueryUI/jquery-ui-timepicker-addon.css");
    assets.Libraries["Validation"].Requires("jQuery")
        .AddScript("//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js")
        .AddScript("~/Scripts/jquery.validate.unobtrusive.min.js")
        .AddScript("~/Scripts/mvcfoolproof.unobtrusive.min.js")
        .AddScript("~/Scripts/CustomClientValidation-1.0.0.min.js");
    assets.Libraries["MyUtilityScripts"].Requires("jQuery")
        .AddScript("~/Scripts/GeneralOnLoad-1.0.0.min.js");
    assets.Libraries["FormTools"].Requires("Validation", "MyUtilityScripts");
    assets.Libraries["AjaxFormTools"].Requires("FormTools", "jQueryUI")
        .AddScript("~/Scripts/jquery.unobtrusive-ajax.min.js");
    assets.Libraries["DataTables"].Requires("MyUtilityScripts")
        .AddScript("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js")
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css")
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables_themeroller.css");
    assets.Libraries["MvcDataTables"].Requires("DataTables", "jQueryUI")
        .AddScript("~/Scripts/jquery.dataTables.columnFilter.min.js");
    assets.Libraries["DummyData"].Requires("MyUtilityScripts")
        .AddScript("~/Scripts/DummyData.js")
        .AddStyle("~/Content/DummyData.css");     

in the _layout page

@{
    var assets = Html.Assets();
    CurrentResources.AssignAllResources(assets);
    Html.Assets().RenderStyles()
}
</head>
...
    @Html.Assets().RenderScripts()
</body>

and in the partial(s) and views

Html.Assets().Libraries.Uses("DataTables");
Html.Assets().AddScript("~/Scripts/emailGridUtilities.js");

How to format a string as a telephone number in C#

You'll need to break it into substrings. While you could do that without any extra variables, it wouldn't be particularly nice. Here's one potential solution:

string phone = i["MyPhone"].ToString();
string area = phone.Substring(0, 3);
string major = phone.Substring(3, 3);
string minor = phone.Substring(6);
string formatted = string.Format("{0}-{1}-{2}", area, major, minor);

Can I make a <button> not submit a form?

Just use good old HTML:

<input type="button" value="Submit" />

Wrap it as the subject of a link, if you so desire:

<a href="http://somewhere.com"><input type="button" value="Submit" /></a>

Or if you decide you want javascript to provide some other functionality:

<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

Uncomment this line (in /conf/logging.properties)

org.apache.jasper.compiler.TldLocationsCache.level = FINE

Work's for me in tomcat 7.0.53!

Creating a list of objects in Python

To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.

instancelist = [ MyClass() for i in range(29)]

and then access the instances through the index of the list.

instancelist[5].attr1 = 'whamma'

Prepend text to beginning of string

Another option would be to use join

var mystr = "Matayoshi";
mystr = ["Mariano", mystr].join(' ');

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

Java Web Service client basic authentication

If you are using a JAX-WS implementation for your client, such as Metro Web Services, the following code shows how to pass username and password in the HTTP headers:

 MyService port = new MyService();
 MyServiceWS service = port.getMyServicePort();

 Map<String, List<String>> credentials = new HashMap<String,List<String>>();

 credentials.put("username", Collections.singletonList("username"));
 credentials.put("password", Collections.singletonList("password"));

 ((BindingProvider)service).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, credentials);

Then subsequent calls to the service will be authenticated. Beware that the password is only encoded using Base64, so I encourage you to use other additional mechanism like client certificates to increase security.

Use a JSON array with objects with javascript

Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:

if you have the JSON string as above then you'd just need to do this

var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');

then you can access these vars with something like jsonObj[0].id etc

Let me know if that's not what you were getting at and I'll try to help.

M

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

I find that the "solution" of just increasing the timeouts obscures what's really going on here, which is either

  1. Your code and/or network calls are way too slow (should be sub 100 ms for a good user experience)
  2. The assertions (tests) are failing and something is swallowing the errors before Mocha is able to act on them.

You usually encounter #2 when Mocha doesn't receive assertion errors from a callback. This is caused by some other code swallowing the exception further up the stack. The right way of dealing with this is to fix the code and not swallow the error.

When external code swallows your errors

In case it's a library function that you are unable to modify, you need to catch the assertion error and pass it onto Mocha yourself. You do this by wrapping your assertion callback in a try/catch block and pass any exceptions to the done handler.

it('should not fail', function (done) { // Pass reference here!

  i_swallow_errors(function (err, result) {
    try { // boilerplate to be able to get the assert failures
      assert.ok(true);
      assert.equal(result, 'bar');
      done();
    } catch (error) {
      done(error);
    }
  });
});

This boilerplate can of course be extracted into some utility function to make the test a little more pleasing to the eye:

it('should not fail', function (done) { // Pass reference here!
    i_swallow_errors(handleError(done, function (err, result) {
        assert.equal(result, 'bar');
    }));
});

// reusable boilerplate to be able to get the assert failures
function handleError(done, fn) {
    try { 
        fn();
        done();
    } catch (error) {
        done(error);
    }
}

Speeding up network tests

Other than that I suggest you pick up the advice on starting to use test stubs for network calls to make tests pass without having to rely on a functioning network. Using Mocha, Chai and Sinon the tests might look something like this

describe('api tests normally involving network calls', function() {

    beforeEach: function () {
        this.xhr = sinon.useFakeXMLHttpRequest();
        var requests = this.requests = [];

        this.xhr.onCreate = function (xhr) {
            requests.push(xhr);
        };
    },

    afterEach: function () {
        this.xhr.restore();
    }


    it("should fetch comments from server", function () {
        var callback = sinon.spy();
        myLib.getCommentsFor("/some/article", callback);
        assertEquals(1, this.requests.length);

        this.requests[0].respond(200, { "Content-Type": "application/json" },
                                 '[{ "id": 12, "comment": "Hey there" }]');
        expect(callback.calledWith([{ id: 12, comment: "Hey there" }])).to.be.true;
    });

});

See Sinon's nise docs for more info.

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Working Soap client example

The response of acdcjunior it was awesome, I just expand his explanation with the next code, where you can see how iterate over the XML elements.

public class SOAPClientSAAJ {

public static void main(String args[]) throws Exception {
    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
    SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);



    SOAPPart soapPart=soapResponse.getSOAPPart();
    // SOAP Envelope
    SOAPEnvelope envelope=soapPart.getEnvelope();
    SOAPBody soapBody = envelope.getBody();

    @SuppressWarnings("unchecked")
    Iterator<Node> itr=soapBody.getChildElements();
    while (itr.hasNext()) {

        Node node=(Node)itr.next();
        if (node.getNodeType()==Node.ELEMENT_NODE) {
            System.out.println("reading Node.ELEMENT_NODE");
            Element ele=(Element)node;
            System.out.println("Body childs : "+ele.getLocalName());

            switch (ele.getNodeName()) {

          case "VerifyEmailResponse":
             NodeList statusNodeList = ele.getChildNodes();

             for(int i=0;i<statusNodeList.getLength();i++){
               Element emailResult = (Element) statusNodeList.item(i);
               System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName());
                switch (emailResult.getNodeName()) {

                case "VerifyEmailResult":
                    NodeList emailResultList = emailResult.getChildNodes();

                    for(int j=0;j<emailResultList.getLength();j++){
                      Element emailResponse = (Element) emailResultList.item(j);
                      System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName());
                       switch (emailResponse.getNodeName()) {
                       case "ResponseText":
                           System.out.println(emailResponse.getTextContent());
                           break;
                        case "ResponseCode":
                          System.out.println(emailResponse.getTextContent());
                           break;
                        case "LastMailServer":
                          System.out.println(emailResponse.getTextContent());
                          break;
                        case "GoodEmail":
                          System.out.println(emailResponse.getTextContent());
                       default:
                          break;
                       }
                    }
                    break;
                default:
                   break;
                }
             }


             break;


          default:
             break;
          }

        } else if (node.getNodeType()==Node.TEXT_NODE) {
            System.out.println("reading Node.TEXT_NODE");
            //do nothing here most likely, as the response nearly never has mixed content type
            //this is just for your reference
        }
    }
    // print SOAP Response
    System.out.println("Response SOAP Message:");
    soapResponse.writeTo(System.out);

    soapConnection.close();
}

private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("[email protected]");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.println("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println("");
    System.out.println("------");

    return soapMessage;
}

}

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

And so I see from other answers that there are several ways of dealing with it. But I don't believe this. It has to be reduced into one way. I love IDE but, but if I follow the IDE steps provided from different answers I know this is not the fundamental algebra. My error looked like:

* What went wrong:
Execution failed for task ':compileJava'.
> Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'.

And the way to solve it scientifically is:

vi build.gradle

To change from:

java {
    sourceCompatibility = JavaVersion.toVersion('11')
    targetCompatibility = JavaVersion.toVersion('11')
}

to become:

java {
    sourceCompatibility = JavaVersion.toVersion('8')
    targetCompatibility = JavaVersion.toVersion('8')
}

The scientific method is that method that is open for argumentation and deals on common denominators.

"Could not find a version that satisfies the requirement opencv-python"

It happened with me on Windows, pip was not able to install opencv-python==3.4.0.12.

Later found out that it was due to the Python version, Python 3.7 has some issue with not getting linked to https://github.com/skvark/opencv-python.

Downgraded to Python 3.6 and it worked with:

pip3 install opencv-python

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

I used the code of @Spajus and wrote a more extended jQuery plugin.

I wrote these four jQuery functions:

  • upperFirstAll() to capitalize ALL words in an inputfield
  • upperFirst() to capitalize only the FIRST word
  • upperCase() to convert the hole text to upper case
  • lowerCase() to convert the hole text to lower case

You can use and chain them like any other jQuery function:
$('#firstname').upperFirstAll()

My complete jQuery plugin:

(function ($) {
    $.fn.extend({

    // With every keystroke capitalize first letter of ALL words in the text
    upperFirstAll: function() {
        $(this).keyup(function(event) {
            var box = event.target;
            var txt = $(this).val();
            var start = box.selectionStart;
            var end = box.selectionEnd;

            $(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)(.)/g,
            function(c) {
                return c.toUpperCase();
            }));
            box.setSelectionRange(start, end);
        });
        return this;
    },

    // With every keystroke capitalize first letter of the FIRST word in the text
    upperFirst: function() {
        $(this).keyup(function(event) {
            var box = event.target;
            var txt = $(this).val();
            var start = box.selectionStart;
            var end = box.selectionEnd;

            $(this).val(txt.toLowerCase().replace(/^(.)/g,
            function(c) {
                return c.toUpperCase();
            }));
            box.setSelectionRange(start, end);
        });
        return this;
    },

    // Converts with every keystroke the hole text to lowercase
    lowerCase: function() {
        $(this).keyup(function(event) {
            var box = event.target;
            var txt = $(this).val();
            var start = box.selectionStart;
            var end = box.selectionEnd;

            $(this).val(txt.toLowerCase());
            box.setSelectionRange(start, end);
        });
        return this;
    },

    // Converts with every keystroke the hole text to uppercase
    upperCase: function() {
        $(this).keyup(function(event) {
            var box = event.target;
            var txt = $(this).val();
            var start = box.selectionStart;
            var end = box.selectionEnd;

            $(this).val(txt.toUpperCase());
            box.setSelectionRange(start, end);
        });
        return this;
    }

    });
}(jQuery));

Groetjes :)

Check if a Windows service exists and delete in PowerShell

For single PC:

if (Get-Service "service_name" -ErrorAction 'SilentlyContinue'){(Get-WmiObject -Class Win32_Service -filter "Name='service_name'").delete()}

else{write-host "No service found."}

Macro for list of PCs:

$name = "service_name"

$list = get-content list.txt

foreach ($server in $list) {

if (Get-Service "service_name" -computername $server -ErrorAction 'SilentlyContinue'){
(Get-WmiObject -Class Win32_Service -filter "Name='service_name'" -ComputerName $server).delete()}

else{write-host "No service $name found on $server."}

}

printf formatting (%d versus %u)

%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.

How to get a value of an element by name instead of ID

What element is used for the part with a green background? Just type the name of the element without "<" and ">" characters. For example type P, not <P> if the answer is the <P> element.

Create text file and fill it using bash

Creating a text file in unix can be done through a text editor (vim, emacs, gedit, etc). But what you want might be something like this

echo "insert text here" > myfile.txt

That will put the text 'insert text here' into a file myfile.txt. To verify that this worked use the command 'cat'.

cat myfile.txt

If you want to append to a file use this

echo "append this text" >> myfile.txt

Uncaught TypeError: Cannot read property 'value' of undefined

First, you should make sure that document.getElementsByName("username")[0] actually returns an object and not "undefined". You can simply check like

if (typeof document.getElementsByName("username")[0] != 'undefined')

Similarly for the other element password.

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

its even easier:

fileList.Where(item => filterList.Contains(item))

in case you want to filter not for an exact match but for a "contains" you can use this expression:

var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));

Regex for Comma delimited list

This one will reject extraneous commas at the start or end of the line, if that's important to you.

((, )?(^)?(possible|value|patterns))*

Replace possible|value|patterns with a regex that matches your allowed values.

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

If you don't have the msi and you need the upgrade code, rather than the product code then the answer is here: How can I find the upgrade code for an installed application in C#?

Iterating through all nodes in XML file

This is what I quickly wrote for myself:

public static class XmlDocumentExtensions
{
    public static void IterateThroughAllNodes(
        this XmlDocument doc, 
        Action<XmlNode> elementVisitor)
    {
        if (doc != null && elementVisitor != null)
        {
            foreach (XmlNode node in doc.ChildNodes)
            {
                doIterateNode(node, elementVisitor);
            }
        }
    }

    private static void doIterateNode(
        XmlNode node, 
        Action<XmlNode> elementVisitor)
    {
        elementVisitor(node);

        foreach (XmlNode childNode in node.ChildNodes)
        {
            doIterateNode(childNode, elementVisitor);
        }
    }
}

To use it, I've used something like:

var doc = new XmlDocument();
doc.Load(somePath);

doc.IterateThroughAllNodes(
    delegate(XmlNode node)
    {
        // ...Do something with the node...
    });

Maybe it helps someone out there.

Submitting a multidimensional array via POST with php

I made a function which handles arrays as well as single GET or POST values

function subVal($varName, $default=NULL,$isArray=FALSE ){ // $isArray toggles between (multi)array or single mode

    $retVal = "";
    $retArray = array();

    if($isArray) {
        if(isset($_POST[$varName])) {
            foreach ( $_POST[$varName] as $var ) {  // multidimensional POST array elements
                $retArray[]=$var;
            }
        }
        $retVal=$retArray;
    }

    elseif (isset($_POST[$varName]) )  {  // simple POST array element
        $retVal = $_POST[$varName];
    }

    else {
        if (isset($_GET[$varName]) ) {
            $retVal = $_GET[$varName];    // simple GET array element
        }
        else {
            $retVal = $default;
        }
    }

    return $retVal;

}

Examples:

$curr_topdiameter = subVal("topdiameter","",TRUE)[3];
$user_name = subVal("user_name","");

Creating instance list of different objects

You could create a list of Object like List<Object> list = new ArrayList<Object>(). As all classes implementation extends implicit or explicit from java.lang.Object class, this list can hold any object, including instances of Employee, Integer, String etc.

When you retrieve an element from this list, you will be retrieving an Object and no longer an Employee, meaning you need to perform a explicit cast in this case as follows:

List<Object> list = new ArrayList<Object>();
list.add("String");
list.add(Integer.valueOf(1));
list.add(new Employee());

Object retrievedObject = list.get(2);
Employee employee = (Employee)list.get(2); // explicit cast

[Ljava.lang.Object; cannot be cast to

You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.

How to exclude 0 from MIN formula Excel

Try this formula

=SMALL((A1,C1,E1),INDEX(FREQUENCY((A1,C1,E1),0),1)+1)

Both SMALL and FREQUENCY functions accept "unions" as arguments, i.e. single cell references separated by commas and enclosed in brackets like (A1,C1,E1).

So the formula uses FREQUENCY and INDEX to find the number of zeroes in a range and if you add 1 to that you get the k value such that the kth smallest is always the minimum value excluding zero.

I'm assuming you don't have negative numbers.....

How to get Database Name from Connection String using SqlConnectionStringBuilder

You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);

string server = builder.DataSource;
string database = builder.InitialCatalog;

or

System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();

builder.ConnectionString = connectionString;

string server = builder["Data Source"] as string;
string database = builder["Initial Catalog"] as string;

Text blinking jQuery

based on alex idea

$('#selector').blink();

$.fn.blink = function(options) {    
    options = $.extend({}, {'speed' : 800}, options);

    var elem = this;
    setInterval(function() {
        if (!elem.is(':visible')) {
            elem.show();
        } else {
            elem.hide();
        }    
    }, options.speed);      
}   

Don't understand why UnboundLocalError occurs (closure)

To modify a global variable inside a function, you must use the global keyword.

When you try to do this without the line

global counter

inside of the definition of increment, a local variable named counter is created so as to keep you from mucking up the counter variable that the whole program may depend on.

Note that you only need to use global when you are modifying the variable; you could read counter from within increment without the need for the global statement.

Can RDP clients launch remote applications and not desktops

"alternate shell" doesn't seem to work anymore in recent versions of Windows, RemoteApp is the way to go.

remoteapplicationmode:i:1
remoteapplicationname:s:Purpose of the app shown to user...
remoteapplicationprogram:s:C:\...\some.exe
remoteapplicationcmdline:s:

To get this to work under e.g. Windows 10 Professional, one needs to enable some policy:

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services]
"fAllowUnlistedRemotePrograms"=dword:00000001

How to check a radio button with jQuery?

In case you don't want to include a big library like jQuery for something this simple, here's an alternative solution using built-in DOM methods:

_x000D_
_x000D_
// Check checkbox by id:_x000D_
document.querySelector('#radio_1').checked = true;_x000D_
_x000D_
// Check checkbox by value:_x000D_
document.querySelector('#type > [value="1"]').checked = true;_x000D_
_x000D_
// If this is the only input with a value of 1 on the page, you can leave out the #type >_x000D_
document.querySelector('[value="1"]').checked = true;
_x000D_
<form>_x000D_
    <div id='type'>_x000D_
        <input type='radio' id='radio_1' name='type' value='1' />_x000D_
        <input type='radio' id='radio_2' name='type' value='2' />_x000D_
        <input type='radio' id='radio_3' name='type' value='3' /> _x000D_
    </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>

How does one Display a Hyperlink in React Native App?

Use React Native Hyperlink (Native <A> tag):

Install:

npm i react-native-a

import:

import A from 'react-native-a'

Usage:

  1. <A>Example.com</A>
  2. <A href="example.com">Example</A>
  3. <A href="https://example.com">Example</A>
  4. <A href="example.com" style={{fontWeight: 'bold'}}>Example</A>

remove item from array using its name / value

it worked for me..

countries.results= $.grep(countries.results, function (e) { 
      if(e.id!= currentID) {
       return true; 
      }
     });

Removing Data From ElasticSearch

The documentation (or The Definitive Guide) says, that you can also use the next query to delete all indices:

curl -XDELETE 'http://localhost:9200/*'

And there's an important note:

For some, the ability to delete all your data with a single command is a very scary prospect. If you want to eliminate the possibility of an accidental mass-deletion, you can set the following to true in your elasticsearch.yml:

action.destructive_requires_name: true

How to add footnotes to GitHub-flavoured Markdown?

For short notes, providing an anchor element with a title attribute creates a "tooltip".

<a title="Note text goes here."><sup>n</sup></a>

Otherwise, for more involved notes, it looks like your best bet is maintaining named links manually.

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

In my case, I had copied some code from another project that was using Automapper - took me ages to work that one out. Just had to add automapper nuget package to project.

How to correct TypeError: Unicode-objects must be encoded before hashing?

To store the password (PY3):

import hashlib, os
password_salt = os.urandom(32).hex()
password = '12345'

hash = hashlib.sha512()
hash.update(('%s%s' % (password_salt, password)).encode('utf-8'))
password_hash = hash.hexdigest()

Running the new Intel emulator for Android

Small Note for Windows 8 user, Intel HAX will not work if Hyper-V feature is enable. Hyper-V (like most of the virtualization tech) will exclusively lock the VT extension witch will prevent HAX to work properly. A workaround if you “need” Hyper-V too might be to stop manually the Hyper-V services when you need HAX (haven’t tested it yet through).

Is it possible to use 'else' in a list comprehension?

To use the else in list comprehensions in python programming you can try out the below snippet. This would resolve your problem, the snippet is tested on python 2.7 and python 3.5.

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]

What does $1 mean in Perl?

In general, questions regarding "magic" variables in Perl can be answered by looking in the Perl predefined variables documentation a la:

perldoc perlvar

However, when you search this documentation for $1, etc., you'll find references in a number of places except the section on these "digit" variables. You have to search for

$<digits>

I would have added this to Brian's answer either by commenting or editing, but I don't have enough rep. If someone adds this I'll remove this answer.

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

Two comments:

  • Use and and or for logical operations in Python.
  • Use 4 spaces to indent instead of 2. You will thank yourself later because your code will look pretty much the same as everyone else's code. See PEP 8 for more details.

OSError: [Errno 2] No such file or directory while using python subprocess in Django

No such file or directory can be also raised if you are trying to put a file argument to Popen with double-quotes.

For example:

call_args = ['mv', '"path/to/file with spaces.txt"', 'somewhere']

In this case, you need to remove double-quotes.

call_args = ['mv', 'path/to/file with spaces.txt', 'somewhere']

How do I determine if a checkbox is checked?

<!DOCTYPE html>
<html>
<body>
    <input type="checkbox" id="isSelected"/>
    <div id="myDiv" style="display:none">Is Checked</div>
</body>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
        $('#isSelected').click(function() {
            $("#myDiv").toggle(this.checked);
        });
    </script>
</html>

Plotting of 1-dimensional Gaussian distribution function

The correct form, based on the original syntax, and correctly normalized is:

def gaussian(x, mu, sig):
    return 1./(np.sqrt(2.*np.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2)

WordPress asking for my FTP credentials to install plugins

From the first hit on Google:

WordPress asks for your FTP credentials when it can't access the files directly. This is usually caused by PHP running as the apache user (mod_php or CGI) rather than the user that owns your WordPress files.

This is rather normal in most shared hosting environments - the files are stored as the user, and Apache runs as user apache or httpd. This is actually a good security precaution so exploits and hacks cannot modify hosted files. You could circumvent this by setting all WP files to 777 security, but that means no security, so I would highly advise against that. Just use FTP, it's the automatically advised workaround with good reason.

Dynamically creating keys in a JavaScript associative array

In response to MK_Dev, one is able to iterate, but not consecutively (for that, obviously an array is needed).

A quick Google search brings up hash tables in JavaScript.

Example code for looping over values in a hash (from the aforementioned link):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

What are carriage return, linefeed, and form feed?

\r is carriage return and moves the cursor back like if i will do-

printf("stackoverflow\rnine")
ninekoverflow

means it has shifted the cursor to the beginning of "stackoverflow" and overwrites the starting four characters since "nine" is four character long.

\n is new line character which changes the line and takes the cursor to the beginning of a new line like-

printf("stackoverflow\nnine")
stackoverflow
nine

\f is form feed, its use has become obsolete but it is used for giving indentation like

printf("stackoverflow\fnine")
stackoverflow
             nine

if i will write like-

printf("stackoverflow\fnine\fgreat")
stackoverflow
             nine
                 great

sqlite3.OperationalError: unable to open database file

I had this problem serving with Apache and found that using the absolute path to the sqlite3 db in my .env //// as opposed to using the relative path /// fixed the problem. All of the permissions and ownership mentioned above are necessary as well.

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

I have fixed a few things here, the "DB_HOST" defined here should be also DB_HOST down there, and the "DB_USER" is called "DB_USER" down there too, check the code always that those are the same.

<?php
    define("DB_HOST", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "");
    define("DB_DATABASE", "");

    $db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
?>

@Autowired - No qualifying bean of type found for dependency

Spent much of my time with this! My bad! Later found that the class on which I declared the annotation Service or Component was of type abstract. Had enabled debug logs on Springframework but no hint was received. Please check if the class if of abstract type. If then, the basic rule applied, can't instantiate an abstract class.

What is the Windows equivalent of the diff command?

Well, on Windows I happily run diff and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.

So, my answer is that the Windows equivalent of diff, is none other than diff itself!

PostgreSQL "DESCRIBE TABLE"

/dt is the commad which lists you all the tables present in a database. using
/d command and /d+ we can get the details of a table. The sysntax will be like
* /d table_name (or) \d+ table_name

jQuery scroll() detect when user stops scrolling

function scrolled() {
    //do by scroll start
    $(this).off('scroll')[0].setTimeout(function(){
        //do by scroll end
        $(this).on('scroll',scrolled);
    }, 500)
}
$(window).on('scroll',scrolled);

very small Version with start and end ability

JSON Structure for List of Objects

As others mentioned, Justin's answer was close, but not quite right. I tested this using Visual Studio's "Paste JSON as C# Classes"

{
    "foos" : [
        {
            "prop1":"value1",
            "prop2":"value2"
        },
        {
            "prop1":"value3", 
            "prop2":"value4"
        }
    ]
}

Append an object to a list in R in amortized constant time, O(1)?

> LL<-list(1:4)

> LL

[[1]]
[1] 1 2 3 4

> LL<-list(c(unlist(LL),5:9))

> LL

[[1]]
 [1] 1 2 3 4 5 6 7 8 9

What is the difference between docker-compose ports vs expose

ports:

  1. Activates the container to listen for specified port(s) from the world outside of the docker(can be same host machine or a different machine) AND also accessible world inside docker.
  2. More than one port can be specified (that's is why ports not port)

enter image description here

expose:

  1. Activates container to listen for a specific port only from the world inside of docker AND not accessible world outside of the docker.
  2. More than one port can be specified

enter image description here

Styling of Select2 dropdown select boxes

Here is a working example of above. http://jsfiddle.net/z7L6m2sc/ Now select2 has been updated the classes have change may be why you cannot get it to work. Here is the css....

.select2-dropdown.select2-dropdown--below{
    width: 148px !important;
}

.select2-container--default .select2-selection--single{
    padding:6px;
    height: 37px;
    width: 148px; 
    font-size: 1.2em;  
    position: relative;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
    height: 27px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
}

Set Google Chrome as the debugging browser in Visual Studio

For MVC developers,

  • click on a folder in Solution Explorer (say, Controllers)
  • Select Browse With...
  • Select desired browser
  • (Optionally click ) set as Default

Bootstrap modal appearing under background

I got it to work by giving a high z-index value to the modal window AFTER opening it. E.g.:

$("#myModal").modal("show");
$("#myModal").css("z-index", "1500");

How to check heap usage of a running JVM from the command line?

For Java 8 you can use the following command line to get the heap space utilization in kB:

jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'

The command basically sums up:

  • S0U: Survivor space 0 utilization (kB).
  • S1U: Survivor space 1 utilization (kB).
  • EU: Eden space utilization (kB).
  • OU: Old space utilization (kB).

You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

cost = Select Supplier_Item.Price from Supplier_Item,orderdetails,Supplier 
   where Supplier_Item.SKU=OrderDetails.Sku and 
      Supplier_Item.SupplierId=Supplier.SupplierID

This subquery returns multiple values, SQL is complaining because it can't assign multiple values to cost in a single record.

Some ideas:

  1. Fix the data such that the existing subquery returns only 1 record
  2. Fix the subquery such that it only returns one record
  3. Add a top 1 and order by to the subquery (nasty solution that DBAs hate - but it "works")
  4. Use a user defined function to concatenate the results of the subquery into a single string

Text file in VBA: Open/Find Replace/SaveAs/Close File

I have had the same problem and came acrosse this site.

the solution to just set another "filename" in the

... for output as ... command was very simple and useful.

in addition (beyond the Application.GetSaveAsFilename() Dialog)

it is very simple to set a** new filename** just using

the replace command, so you may change the filename/extension

eg. (as from the first post)

sFileName = "C:\filelocation"
iFileNum = FreeFile

Open sFileName For Input As iFileNum
content = (...edit the content) 

Close iFileNum

now just set:

newFilename = replace(sFilename, ".txt", ".csv") to change the extension

or

newFilename = replace(sFilename, ".", "_edit.") for a differrent filename

and then just as before

iFileNum = FreeFile
Open newFileName For Output As iFileNum

Print #iFileNum, content
Close iFileNum 

I surfed over an hour to find out how to rename a txt-file,

with many different solutions, but it could be sooo easy :)

Automate scp file transfer using a shell script

rsync is a program that behaves in much the same way that rcp does, but has many more options and uses the rsync remote-update protocol to greatly speed up file transfers when the destination file is being updated.

The rsync remote-update protocol allows rsync to transfer just the differences between two sets of files across the network connection, using an efficient checksum-search algorithm described in the technical report that accompanies this package.


Copying folder from one location to another

   #!/usr/bin/expect -f   
   spawn rsync -a -e ssh [email protected]:/cool/cool1/* /tmp/cool/   
   expect "password:"   
   send "cool\r"   
   expect "*\r"   
   expect "\r"  

SQL how to make null values come last when sorting ascending

USE NVL function

  select * from MyTable order by NVL(MyDate, to_date('1-1-1','DD-MM-YYYY'))

Here's the alternative of NVL in most famous DBMS

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

A workaround is to add the domain names you use as "subjectAltName" (X509v3 Subject Alternative Name). This can be done by changing your OpenSSL configuration (/etc/ssl/openssl.cnf on Linux) and modify the v3_req section to look like this:

[ v3_req ]

# Extensions to add to a certificate request

basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = myserver.net
DNS.2 = sub1.myserver.net

With this in place, not forget to use the -extensions v3_req switch when generating your new certificate. (see also How can I generate a self-signed certificate with SubjectAltName using OpenSSL?)

An URL to a Windows shared folder

This depend on how you want to incorporate it. The scenario 1. click on a link 2. explorer window popped up

<a href="\\server\folder\path" target="_blank">click</a>

If there is a need in a fancy UI - then it will barely serve as a solution.

How to use the 'og' (Open Graph) meta tag for Facebook share

I built a tool for meta generation. It pre-configures entries for Facebook, Google+ and Twitter, and you can use it free here: http://www.groovymeta.com

To answer the question a bit more, OG tags (Open Graph) tags work similarly to meta tags, and should be placed in the HEAD section of your HTML file. See Facebook's best practises for more information on how to use OG tags effectively.

curl_exec() always returns false

Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error() and curl_errno() will contain further information in case of failure:

try {
    $ch = curl_init();

    // Check if initialization had gone wrong*    
    if ($ch === false) {
        throw new Exception('failed to initialize');
    }

    curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt(/* ... */);

    $content = curl_exec($ch);

    // Check the return value of curl_exec(), too
    if ($content === false) {
        throw new Exception(curl_error($ch), curl_errno($ch));
    }

    /* Process $content here */

    // Close curl handle
    curl_close($ch);
} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);

}

* The curl_init() manual states:

Returns a cURL handle on success, FALSE on errors.

I've observed the function to return FALSE when you're using its $url parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.

xxxxxx.exe is not a valid Win32 application

I had the same issue on Windows XP when running an application built with a static version of Qt 5.7.0 (MSVC 2013).

Adding the following line to the project's .pro file solved it:

QMAKE_LFLAGS_WINDOWS = /SUBSYSTEM:WINDOWS,5.01

How can I let a table's body scroll but keep its head fixed in place?

I do this with javascript (no library) and CSS - the table body scrolls with the page, and the table does not have to be fixed width or height, although each column must have a width. You can also keep sorting functionality.

Basically:

  1. In HTML, create container divs to position the table header row and the table body, also create a "mask" div to hide the table body as it scrolls past the header

  2. In CSS, convert the table parts to blocks

  3. In Javascript, get the table width and match the mask's width... get the height of the page content... measure scroll position... manipulate CSS to set the table header row position and the mask height

Here's the javascript and a jsFiddle DEMO.

// get table width and match the mask width

function setMaskWidth() { 
  if (document.getElementById('mask') !==null) {
    var tableWidth = document.getElementById('theTable').offsetWidth;

    // match elements to the table width
    document.getElementById('mask').style.width = tableWidth + "px";
   }
}

function fixTop() {

  // get height of page content 
  function getScrollY() {
      var y = 0;
      if( typeof ( window.pageYOffset ) == 'number' ) {
        y = window.pageYOffset;
      } else if ( document.body && ( document.body.scrollTop) ) {
        y = document.body.scrollTop;
      } else if ( document.documentElement && ( document.documentElement.scrollTop) ) {
        y = document.documentElement.scrollTop;
      }
      return [y];
  }  

  var y = getScrollY();
  var y = y[0];

  if (document.getElementById('mask') !==null) {
      document.getElementById('mask').style.height = y + "px" ;

      if (document.all && document.querySelector && !document.addEventListener) {
        document.styleSheets[1].rules[0].style.top = y + "px" ;
      } else {
        document.styleSheets[1].cssRules[0].style.top = y + "px" ;
      }
  }

}

window.onscroll = function() {
  setMaskWidth();
  fixTop();
}

How to send a correct authorization header for basic authentication

If you are in a browser environment you can also use btoa.

btoa is a function which takes a string as argument and produces a Base64 encoded ASCII string. Its supported by 97% of browsers.

Example:

> "Basic " + btoa("billy"+":"+"secretpassword")
< "Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ="

You can then add Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ= to the authorization header.

Note that the usual caveats about HTTP BASIC auth apply, most importantly if you do not send your traffic over https an eavesdropped can simply decode the Base64 encoded string thus obtaining your password.

This security.stackexchange.com answer gives a good overview of some of the downsides.

How to show an alert box in PHP?

When I just run this as a page

<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
exit;

it works fine.

What version of PHP are you running?

Could you try echoing something else after: $testObject->split_for_sms($Chat);

Maybe it doesn't get to that part of the code? You could also try these with the other function calls to check where your program stops/is getting to.

Hope you get a bit further with this.

Asp.net Validation of viewstate MAC failed

I have faced the similar issue on my website hosted on IIS. This issue generally because of IIS Application pool settings. As application pool recycle after some time that caused the issue for me.

Following steps help me to fix the issue:

  1. Open App pool of you website on IIS.
  2. Go to Advance settings on right hand pane.
  3. Scroll down to Process Model
  4. Change Idle Time-out minutes to 20 or number of minutes you don't want to recycle your App pool.

enter image description here

Then try again . It will solve your issue.

How to autowire RestTemplate using annotations

@Autowired
private RestOperations restTemplate;

You can only autowire interfaces with implementations.

What does cmd /C mean?

The part you should be interested in is the /? part, which should solve most other questions you have with the tool.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>cmd /?
Starts a new instance of the Windows XP command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.

allowing only alphabets in text box using java script

:::::HTML:::::

<input type="text" onkeypress="return lettersValidate(event)" />

Only letters no spaces

::::JS::::::::

// ===================== Allow - Only Letters ===============================================================

function lettersValidate(key) {
    var keycode = (key.which) ? key.which : key.keyCode;

    if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))  
    {     
           return true;    
    }
    else
    {
        return false;
    }
         
}
 

MS Access: how to compact current database in VBA

Check out this solution VBA Compact Current Database.

Basically it says this should work

Public Sub CompactDB() 
    CommandBars("Menu Bar").Controls("Tools").Controls ("Database utilities"). _
    Controls("Compact and repair database...").accDoDefaultAction 
End Sub 

What's the difference between integer class and numeric class in R

To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:

> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct

Example of Integer:

> x<- 2L
> print(x)

Example of Numeric (kind of like double/float from other programming languages)

> x<-3.4
> print(x)

What are all the escape characters?

These are escape characters which are used to manipulate string.

\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a form feed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

Read more about them from here.

http://docs.oracle.com/javase/tutorial/java/data/characters.html

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

I used another repository for oracle java.

sudo add-apt-repository ppa:linuxuprising/java
sudo apt-get update

sudo apt install  oracle-java11-installer

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Assuming RestTemplate is configured to use HttpClient 4.x, you can read up on HttpClient's logging documentation here. The loggers are different than those specified in the other answers.

The logging configuration for HttpClient 3.x is available here.

How to close the current fragment by using Button like the back button?

Try this:

public void removeFragment(Fragment fragment){
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.remove(fragment);
    fragmentTransaction.commit();
}

SQL DROP TABLE foreign key constraint

If I want to delete all the tables in my database

Then it's a lot easier to drop the entire database:

DROP DATABASE WorkerPensions

How to delete a file or folder?

My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.

In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...

It also wraps shutil.rmtree:

$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib

# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)

# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)

you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

diff to output only the file names

From the diff man page:

-q   Report only whether the files differ, not the details of the differences.
-r   When comparing directories, recursively compare any subdirectories found.

Example command:

diff -qr dir1 dir2

Example output (depends on locale):

$ ls dir1 dir2
dir1:
same-file  different  only-1

dir2:
same-file  different  only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2

WPF global exception handler

You can trap unhandled exceptions at different levels:

  1. AppDomain.CurrentDomain.UnhandledException From all threads in the AppDomain.
  2. Dispatcher.UnhandledException From a single specific UI dispatcher thread.
  3. Application.Current.DispatcherUnhandledException From the main UI dispatcher thread in your WPF application.
  4. TaskScheduler.UnobservedTaskException from within each AppDomain that uses a task scheduler for asynchronous operations.

You should consider what level you need to trap unhandled exceptions at.

Deciding between #2 and #3 depends upon whether you're using more than one WPF thread. This is quite an exotic situation and if you're unsure whether you are or not, then it's most likely that you're not.

Check if a folder exist in a directory and create them using C#

if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
     System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}

SQL is null and = null

First is correct way of checking whether a field value is null while later won't work the way you expect it to because null is special value which does not equal anything, so you can't use equality comparison using = for it.

So when you need to check if a field value is null or not, use:

where x is null

instead of:

where x = null

Add 2 hours to current time in MySQL?

This will also work

SELECT NAME 
FROM GEO_LOCATION
WHERE MODIFY_ON BETWEEN SYSDATE() - INTERVAL 2 HOUR AND SYSDATE()

C Macro definition to determine big endian or little endian machine?

Code supporting arbitrary byte orders, ready to be put into a file called order32.h:

#ifndef ORDER32_H
#define ORDER32_H

#include <limits.h>
#include <stdint.h>

#if CHAR_BIT != 8
#error "unsupported char size"
#endif

enum
{
    O32_LITTLE_ENDIAN = 0x03020100ul,
    O32_BIG_ENDIAN = 0x00010203ul,
    O32_PDP_ENDIAN = 0x01000302ul,      /* DEC PDP-11 (aka ENDIAN_LITTLE_WORD) */
    O32_HONEYWELL_ENDIAN = 0x02030001ul /* Honeywell 316 (aka ENDIAN_BIG_WORD) */
};

static const union { unsigned char bytes[4]; uint32_t value; } o32_host_order =
    { { 0, 1, 2, 3 } };

#define O32_HOST_ORDER (o32_host_order.value)

#endif

You would check for little endian systems via

O32_HOST_ORDER == O32_LITTLE_ENDIAN

Uncompress tar.gz file

gunzip <filename>

then

tar -xvf <tar-file-name>

Check if record exists from controller in Rails

ActiveRecord#where will return an ActiveRecord::Relation object (which will never be nil). Try using .empty? on the relation to test if it will return any records.

How to get back to the latest commit after checking out a previous commit?

git reflog //find the hash of the commit that you want to checkout
git checkout <commit number>>

How to get the cell value by column name not by index in GridView in asp.net

For Lambda lovers

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var boundFields = e.Row.Cells.Cast<DataControlFieldCell>()
            .Select(cell => cell.ContainingField).Cast<BoundField>().ToList();

        int idx = boundFields.IndexOf(
            boundFields.FirstOrDefault(f => f.DataField == "ColName"));

        e.Row.Cells[idx].Text = modification;        
    }
}

.NET - How do I retrieve specific items out of a Dataset?

int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());

List all employee's names and their managers by manager name using an inner join

Add m.Ename to your SELECT query:

select distinct e.Ename as Employee, m.mgr as reports_to, m.Ename as Manager
from EMPLOYEES e
inner join Employees m on e.mgr = m.EmpID;

How to check command line parameter in ".bat" file?

The short answer - use square brackets:

if [%1]==[] goto :blank

or (when you need to handle quoted args, see the Edit below):

if [%~1]==[] goto :blank

Why? you might ask. Well, just as Jeremiah Willcock mentioned: http://ss64.com/nt/if.html - they use that! OK, but what's wrong with the quotes?

Again, short answer: they are "magical" - sometimes double (double) quotes get converted to a single (double) quote. And they need to match, for a start.

Consider this little script:

@rem argq.bat
@echo off

:loop 
if "%1"=="" goto :done
echo %1
shift
goto :loop

:done
echo Done.

Let's test it:

C:\> argq bla bla
bla
bla
Done.

Seems to work. But now, lets switch to second gear:

C:\> argq "bla bla"
bla""=="" was unexpected at this time.

Boom This didn't evaluate to true, neither did it evaluate to false. The script DIED. If you were supposed to turn off the reactor somewhere down the line, well - tough luck. You now will die like Harry Daghlian.

You may think - OK, the arguments can't contain quotes. If they do, this happens. Wrong Here's some consolation:

C:\> argq ""bla bla""
""bla
bla""
Done.

Oh yeah. Don't worry - sometimes this will work.

Let's try another script:

@rem args.bat
@echo off

:loop 
if [%1]==[] goto :done
echo %1
shift
goto :loop

:done
echo Done.

You can test yourself, that it works OK for the above cases. This is logical - quotes have nothing to do with brackets, so there's no magic here. But what about spicing the args up with brackets?

D:\>args ]bla bla[
]bla
bla[
Done.

D:\>args [bla bla]
[bla
bla]
Done.

No luck there. The brackets just can't choke cmd.exe's parser.

Let's go back to the evil quotes for a moment. The problem was there, when the argument ended with a quote:

D:\>argq "bla1 bla2"
bla2""=="" was unexpected at this time.

What if I pass just:

D:\>argq bla2"
The syntax of the command is incorrect.

The script won't run at all. Same for args.bat:

D:\>args bla2"
The syntax of the command is incorrect.

But what do I get, when the number of "-characters "matches" (i.e. - is even), in such a case:

D:\>args bla2" "bla3
bla2" "bla3
Done.

NICE - I hope you learned something about how .bat files split their command line arguments (HINT: *It's not exactly like in bash). The above argument contains a space. But the quotes are not stripped automatically.

And argq? How does it react to that? Predictably:

D:\>argq bla2" "bla3
"bla3"=="" was unexpected at this time.

So - think before you say: "Know what? Just use quotes. [Because, to me, this looks nicer]".

Edit

Recently, there were comments about this answer - well, sqare brackets "can't handle" passing quoted arguments and treating them just as if they weren't quoted.

The syntax:

if "%~1"=="" (...)

Is not some newly found virtue of the double quotes, but a display of a neat feature of stripping quotes from the argument variable, if the first and last character is a double quote.

This "technology" works just as well with square brackets:

if [%~1]==[] (...)

It was a useful thing to point this out, so I also upvote the new answer.

Finally, double quote fans, does an argument of the form "" exist in your book, or is it blank? Just askin' ;)

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

Reading file contents on the client-side in javascript in various browsers

In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file"> tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.

_x000D_
_x000D_
function onFileLoad(elementId, event) {_x000D_
    document.getElementById(elementId).innerText = event.target.result;_x000D_
}_x000D_
_x000D_
function onChooseFile(event, onLoadFileHandler) {_x000D_
    if (typeof window.FileReader !== 'function')_x000D_
        throw ("The file API isn't supported on this browser.");_x000D_
    let input = event.target;_x000D_
    if (!input)_x000D_
        throw ("The browser does not properly implement the event object");_x000D_
    if (!input.files)_x000D_
        throw ("This browser does not support the `files` property of the file input.");_x000D_
    if (!input.files[0])_x000D_
        return undefined;_x000D_
    let file = input.files[0];_x000D_
    let fr = new FileReader();_x000D_
    fr.onload = onLoadFileHandler;_x000D_
    fr.readAsText(file);_x000D_
}
_x000D_
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />_x000D_
<p id="contents"></p>
_x000D_
_x000D_
_x000D_

Remove first Item of the array (like popping from stack)

Plunker

$scope.remove = function(item) { 
    $scope.cards.splice(0, 1);     
  }

Made changes to .. now it will remove from the top

Bootstrap radio button "checked" flag

Use active class with label to make it auto select and use checked="" .

   <label class="btn btn-primary  active" value="regular"  style="width:47%">
   <input  type="radio" name="service" checked=""  > Regular </label>
   <label class="btn btn-primary " value="express" style="width:46%">
   <input type="radio" name="service"> Express </label>

how to convert 2d list to 2d numpy array?

Just pass the list to np.array:

a = np.array(a)

You can also take this opportunity to set the dtype if the default is not what you desire.

a = np.array(a, dtype=...)

Error 1053 the service did not respond to the start or control request in a timely fashion

I had same problem. Unchecking "Sing the ClickOnce manifest", "Sign the assembly" and "Enable ClickOnce security settings" in project properties helped

How to check a Long for null in java

As primitives(long) can't be null,It can be converted to wrapper class of that primitive type(ie.Long) and null check can be performed.

If you want to check whether long variable is null,you can convert that into Long and check,

long longValue=null;

if(Long.valueOf(longValue)==null)

How to align a div to the top of its parent but keeping its inline-block behaviour?

As others have said, vertical-align: top is your friend.

As a bonus here is a forked fiddle with added enhancements that make it work in Internet Explorer 6 and Internet Explorer 7 too ;)

Example: here

How to convert a table to a data frame

Short answer: using as.data.frame.matrix(mytable), as @Victor Van Hee suggested.

Long answer: as.data.frame(mytable) may not work on contingency tables generated by table() function, even if is.matrix(your_table) returns TRUE. It will still melt you table into the factor1 factor2 factori counts format.

Example:

> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)

> freq_t
   gear
cyl  3  4  5
  4  1  8  2
  6  2  4  1
  8 12  0  2

> is.matrix(freq_t)
[1] TRUE

> as.data.frame(freq_t)
  cyl gear Freq
1   4    3    1
2   6    3    2
3   8    3   12
4   4    4    8
5   6    4    4
6   8    4    0
7   4    5    2
8   6    5    1
9   8    5    2
> as.data.frame.matrix(freq_t)
   3 4 5
4  1 8 2
6  2 4 1
8 12 0 2

Autocompletion in Vim

There’s also clang_complete which uses the clang compiler to provide code completion for C++ projects. There’s another question with troubleshooting hints for this plugin.

The plugin seems to work fairly well as long as the project compiles, but is prohibitively slow for large projects (since it attempts a full compilation to generate the tags list).

How do I see what character set a MySQL database / table / column is?

For databases:

USE your_database_name;
show variables like "character_set_database";
-- or:
-- show variables like "collation_database";

Cf. this page. And check out the MySQL manual

How to perform runtime type checking in Dart?

Just to clarify a bit the difference between is and runtimeType. As someone said already (and this was tested with Dart V2+) the following code:

class Foo { 
  Type get runtimeType => String;
}
main() {
  var foo = new Foo();
  if (foo is Foo) {
    print("it's a foo!");
  }
  print("type is ${foo.runtimeType}");

}

will output:

it's a foo! 
type is String

Which is wrong. Now, I can't see the reason why one should do such a thing...

In which case do you use the JPA @JoinTable annotation?

It lets you handle Many to Many relationship. Example:

Table 1: post

post has following columns
____________________
|  ID     |  DATE   |
|_________|_________|
|         |         |
|_________|_________|

Table 2: user

user has the following columns:

____________________
|     ID  |NAME     |
|_________|_________|
|         |         |
|_________|_________|

Join Table lets you create a mapping using:

@JoinTable(
  name="USER_POST",
  joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
  inverseJoinColumns=@JoinColumn(name="POST_ID", referencedColumnName="ID"))

will create a table:

____________________
|  USER_ID| POST_ID |
|_________|_________|
|         |         |
|_________|_________|

Java - sending HTTP parameters via POST method easily

Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.

So the minimum required code is:

    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
    connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
    connection.connect();
    connection.getOutputStream().close(); 

You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.

You can also use NameValuePair apparently.

angularjs directive call function specified in attribute and pass an argument to it

Here's what worked for me.

Html using the directive

 <tr orderitemdirective remove="vm.removeOrderItem(orderItem)" order-item="orderitem"></tr>

Html of the directive: orderitem.directive.html

<md-button type="submit" ng-click="remove({orderItem:orderItem})">
       (...)
</md-button>

Directive's scope:

scope: {
    orderItem: '=',
    remove: "&",

Handling ExecuteScalar() when no results are returned

string VAR;    
if ((command.ExecuteScalar()).ToString() != string.Empty)

{VAR = (string)command.ExecuteScalar();} else{

How to completely DISABLE any MOUSE CLICK

something like:

    $('#doc').click(function(e){
       e.preventDefault()
       e.stopImmediatePropagation() //charles ma is right about that, but stopPropagation isn't also needed
});

should do the job you could also bind more mouse events with replacing for: edit: add this in the feezing part

    $('#doc').bind('click mousedown dblclick',function(e){
       e.preventDefault()
       e.stopImmediatePropagation()
});

and this in the unfreezing:

  $('#doc').unbind();