Programs & Examples On #Efv4

The provider is not compatible with the version of Oracle client

I've been looking into this problem further, and you simply need to grab all the appropriate DLL's from the same downloaded version of ODP.Net and put them in the same folder as your Exe file, because ODP.Net is fussy about not mixing version numbers.

I've explained how to do this here: http://splinter.com.au/using-the-new-odpnet-to-access-oracle-from-c Here's the gist of it though:

  • Download ODP.Net
  • Unzip the file
  • Unzip all the JAR's in it
  • Grab these dll's that were just unzipped:
    • oci.dll (renamed from 'oci.dll.dbl')
    • Oracle.DataAccess.dll
    • oraociicus11.dll
    • OraOps11w.dll
    • orannzsbb11.dll
    • oraocci11.dll
    • ociw32.dll (renamed from 'ociw32.dll.dbl')
  • Put all the DLLs in the same folder as your C# Executable

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

How to get the current user in ASP.NET MVC

This page could be what you looking for:
Using Page.User.Identity.Name in MVC3

You just need User.Identity.Name.

How to get ASCII value of string in C#

string s = "9quali52ty3";
foreach(char c in s)
{
  Console.WriteLine((int)c);
}

Which regular expression operator means 'Don't' match this character?

^ used at the beginning of a character range, or negative lookahead/lookbehind assertions.

>>> re.match('[^f]', 'foo')
>>> re.match('[^f]', 'bar')
<_sre.SRE_Match object at 0x7f8b102ad6b0>
>>> re.match('(?!foo)...', 'foo')
>>> re.match('(?!foo)...', 'bar')
<_sre.SRE_Match object at 0x7f8b0fe70780>

How to add http:// if it doesn't exist in the URL

A modified version of @nickf code:

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

Recognizes ftp://, ftps://, http:// and https:// in a case insensitive way.

How to connect android emulator to the internet

I have Mac OS X 10.7.2, Eclipse Helios Service Release 2. I also work via Proxy and my IP settings are via DHCP. I solved this issue firstly using this article http://www.gitshah.com/2011/02/android-fixing-no-internet-connection.html, then I removed Emulator settings and just go to Run->Run Configurations->Target->Additional Emulator Command Line Options and type there -http-proxy xxx.xx.111.1:3128 . Also I would like to say that when I typed also a DNS like this: -dns-server xxx.xx.111.1 -http-proxy xxx.xx.111.1:3128 it did not work, but when I removed DNS it worked. Also I would like to note, that Additional Emulator Command Line Options are not visible without scrolling to the bottom of that window. I also want to note, that when you change emulator options, all apps will work. But If you write Additional Emulator Command Line Options, you need to write them every time for every app target in Run Configurations.

IE prompts to open or save json result from server

Have you tried to send your ajax request using POST method ? You could also try to set content type to 'text/x-json' while returning result from the server.

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Clean your maven cache and rerun:

mvn dependency:purge-local-repository

"unexpected token import" in Nodejs5 and babel?

  • install --> "npm i --save-dev babel-cli babel-preset-es2015 babel-preset-stage-0"

next in package.json file add in scripts "start": "babel-node server.js"

    {
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "lodash": "^4.17.4",
    "mongoose": "^5.0.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "babel-node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

and create file for babel , in root ".babelrc"

    {
    "presets":[
        "es2015",
        "stage-0"
    ]
}

and run npm start in terminal

Div show/hide media query

It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

http://www.w3schools.com/css/css_rwd_viewport.asp

Passing parameters to JavaScript files

Here is a very rushed proof of concept.

I'm sure there are at least 2 places where there can be improvements, and I'm also sure that this would not survive long in the wild. Any feedback to make it more presentable or usable is welcome.

The key is setting an id for your script element. The only catch is that this means you can only call the script once since it looks for that ID to pull the query string. This could be fixed if, instead, the script loops through all query elements to see if any of them point to it, and if so, uses the last instance of such an script element. Anyway, on with the code:

Script being called:

window.onload = function() {
//Notice that both possible parameters are pre-defined.
//Which is probably not required if using proper object notation
//in query string, or if variable-variables are possible in js.
var header;
var text;

//script gets the src attribute based on ID of page's script element:
var requestURL = document.getElementById("myScript").getAttribute("src");

//next use substring() to get querystring part of src
var queryString = requestURL.substring(requestURL.indexOf("?") + 1, requestURL.length);

//Next split the querystring into array
var params = queryString.split("&");

//Next loop through params
for(var i = 0; i < params.length; i++){
 var name  = params[i].substring(0,params[i].indexOf("="));
 var value = params[i].substring(params[i].indexOf("=") + 1, params[i].length);

    //Test if value is a number. If not, wrap value with quotes:
    if(isNaN(parseInt(value))) {
  params[i] = params[i].replace(value, "'" + value + "'");
 }

    // Finally, use eval to set values of pre-defined variables:
 eval(params[i]);
}

//Output to test that it worked:
document.getElementById("docTitle").innerHTML = header;
document.getElementById("docText").innerHTML = text;
};

Script called via following page:

<script id="myScript" type="text/javascript" 
        src="test.js?header=Test Page&text=This Works"></script>

<h1 id="docTitle"></h1>
<p id="docText"></p>

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

I got this error, but mine was coming from the Toasts, not a Dialog.

I have Activity and Fragments in my layout. Code for the Toast was in the Activity class. Fragments gets loaded before the Activity.

I think the Toast code was hit before the Context/Activity finished initializing. I think it was the getApplicationContext() in the command Toast.makeText(getApplicationContext(), "onMenutItemActionCollapse called", Toast.LENGTH_SHORT).show();

SharePoint 2013 get current user using JavaScript

U can use javascript to achive that like this:

function loadConstants() {

    this.clientContext = new SP.ClientContext.get_current();
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();  
    this.clientContext.load(currentUser);
      completefunc:this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));


}

//U must set a timeout to recivie the exactly user u want:

function onQuerySucceeded(sender, args) {

    window.setTimeout("ttt();",1000);
}
function onQueryFailed(sender, args) {

    console.log(args.get_message());
}

//By using a proper timeout, u can get current user :

function ttt(){ 

    var clientContext = new SP.ClientContext.get_current();
    var groupCollection = clientContext.get_web().get_siteGroups();
    visitorsGroup = groupCollection.getByName('OLAP Portal Members');

    t=this.currentUser .get_loginName().toLowerCase();

    console.log ('this.currentUser .get_loginName() : '+ t);      

}

Date difference in minutes in Python

In Other ways to get difference between date;

import dateutil.parser
import datetime

timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)

Thanks

How can I run a PHP script inside a HTML file?

You can't run PHP in an html page ending with .html. Unless the page is actually PHP and the extension was changed with .htaccess from .php to .html

What you mean is:

index.html
<html>
...
<?php echo "Hello world";?> //This is impossible


index.php //The file extension can be changed using htaccess, ex: its type stays php but will be visible to visitors as index.html

<?php echo "Hello world";?>

How to identify all stored procedures referring a particular table

SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%TableNameOrWhatever%'

BTW -- here is a handy resource for this type of question: Querying the SQL Server System Catalog FAQ

Centering in CSS Grid

This answer has two main sections:

  1. Understanding how alignment works in CSS Grid.
  2. Six methods for centering in CSS Grid.

If you're only interested in the solutions, skip the first section.


The Structure and Scope of Grid layout

To fully understand how centering works in a grid container, it's important to first understand the structure and scope of grid layout.

The HTML structure of a grid container has three levels:

  • the container
  • the item
  • the content

Each of these levels is independent from the others, in terms of applying grid properties.

The scope of a grid container is limited to a parent-child relationship.

This means that a grid container is always the parent and a grid item is always the child. Grid properties work only within this relationship.

Descendants of a grid container beyond the children are not part of grid layout and will not accept grid properties. (At least not until the subgrid feature has been implemented, which will allow descendants of grid items to respect the lines of the primary container.)

Here's an example of the structure and scope concepts described above.

Imagine a tic-tac-toe-like grid.

article {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
}

enter image description here

You want the X's and O's centered in each cell.

So you apply the centering at the container level:

article {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  justify-items: center;
}

But because of the structure and scope of grid layout, justify-items on the container centers the grid items, not the content (at least not directly).

enter image description here

_x000D_
_x000D_
article {_x000D_
  display: inline-grid;_x000D_
  grid-template-rows: 100px 100px 100px;_x000D_
  grid-template-columns: 100px 100px 100px;_x000D_
  grid-gap: 3px;_x000D_
  justify-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
    border: 2px solid black;_x000D_
    font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
</article>
_x000D_
_x000D_
_x000D_

Same problem with align-items: The content may be centered as a by-product, but you've lost the layout design.

article {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  justify-items: center;
  align-items: center;
}

enter image description here

_x000D_
_x000D_
article {_x000D_
  display: inline-grid;_x000D_
  grid-template-rows: 100px 100px 100px;_x000D_
  grid-template-columns: 100px 100px 100px;_x000D_
  grid-gap: 3px;_x000D_
  justify-items: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
    border: 2px solid black;_x000D_
    font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
    <section>O</section>_x000D_
    <section>X</section>_x000D_
</article>
_x000D_
_x000D_
_x000D_

To center the content you need to take a different approach. Referring again to the structure and scope of grid layout, you need to treat the grid item as the parent and the content as the child.

article {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
}

section {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px solid black;
  font-size: 3em;
}

enter image description here

_x000D_
_x000D_
article {_x000D_
  display: inline-grid;_x000D_
  grid-template-rows: 100px 100px 100px;_x000D_
  grid-template-columns: 100px 100px 100px;_x000D_
  grid-gap: 3px;_x000D_
}_x000D_
_x000D_
section {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  border: 2px solid black;_x000D_
  font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
  <section>X</section>_x000D_
  <section>O</section>_x000D_
  <section>X</section>_x000D_
  <section>O</section>_x000D_
  <section>X</section>_x000D_
  <section>O</section>_x000D_
  <section>X</section>_x000D_
  <section>O</section>_x000D_
  <section>X</section>_x000D_
</article>
_x000D_
_x000D_
_x000D_

jsFiddle demo


Six Methods for Centering in CSS Grid

There are multiple methods for centering grid items and their content.

Here's a basic 2x2 grid:

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

Flexbox

For a simple and easy way to center the content of grid items use flexbox.

More specifically, make the grid item into a flex container.

There is no conflict, spec violation or other problem with this method. It's clean and valid.

grid-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  display: flex;            /* new */_x000D_
  align-items: center;      /* new */_x000D_
  justify-content: center;  /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

See this post for a complete explanation:


Grid Layout

In the same way that a flex item can also be a flex container, a grid item can also be a grid container. This solution is similar to the flexbox solution above, except centering is done with grid, not flex, properties.

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  display: grid;            /* new */_x000D_
  align-items: center;      /* new */_x000D_
  justify-items: center;    /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_


auto margins

Use margin: auto to vertically and horizontally center grid items.

grid-item {
  margin: auto;
}

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

To center the content of grid items you need to make the item into a grid (or flex) container, wrap anonymous items in their own elements (since they cannot be directly targeted by CSS), and apply the margins to the new elements.

grid-item {
  display: flex;
}

span, img {
  margin: auto;
}

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
  margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item><span>this text should be centered</span></grid-item>_x000D_
  <grid-item><span>this text should be centered</span></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_


Box Alignment Properties

When considering using the following properties to align grid items, read the section on auto margins above.

  • align-items
  • justify-items
  • align-self
  • justify-self

https://www.w3.org/TR/css-align-3/#property-index


text-align: center

To center content horizontally in a grid item, you can use the text-align property.

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
  text-align: center;  /* new */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

Note that for vertical centering, vertical-align: middle will not work.

This is because the vertical-align property applies only to inline and table-cell containers.

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
  text-align: center;     /* <--- works */_x000D_
  vertical-align: middle; /* <--- fails */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item>this text should be centered</grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

One might say that display: inline-grid establishes an inline-level container, and that would be true. So why doesn't vertical-align work in grid items?

The reason is that in a grid formatting context, items are treated as block-level elements.

6.1. Grid Item Display

The display value of a grid item is blockified: if the specified display of an in-flow child of an element generating a grid container is an inline-level value, it computes to its block-level equivalent.

In a block formatting context, something the vertical-align property was originally designed for, the browser doesn't expect to find a block-level element in an inline-level container. That's invalid HTML.


CSS Positioning

Lastly, there's a general CSS centering solution that also works in Grid: absolute positioning

This is a good method for centering objects that need to be removed from the document flow. For example, if you want to:

Simply set position: absolute on the element to be centered, and position: relative on the ancestor that will serve as the containing block (it's usually the parent). Something like this:

grid-item {
  position: relative;
  text-align: center;
}

span {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

_x000D_
_x000D_
grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-auto-rows: 75px;_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  position: relative;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  top: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
_x000D_
grid-container {_x000D_
  background-color: lightyellow;_x000D_
  border: 1px solid #bbb;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
  background-color: lightgreen;_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
  <grid-item><span>this text should be centered</span></grid-item>_x000D_
  <grid-item><span>this text should be centered</span></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
  <grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
_x000D_
_x000D_

Here's a complete explanation for how this method works:

Here's the section on absolute positioning in the Grid spec:

Functions that return a function

Snippet one:

function a() {
  
    alert('A!');

    function b(){
        alert('B!'); 
    }

    return b(); //return nothing here as b not defined a return value
}

var s = a(); //s got nothing assigned as b() and thus a() return nothing.
alert('break');
s(); // s equals nothing so nothing will be executed, JavaScript interpreter will complain

the statement 'b()' means to execute the function named 'b' which shows a dialog box with text 'B!'

the statement 'return b();' means to execute a function named 'b' and then return what function 'b' return. but 'b' returns nothing, then this statement 'return b()' returns nothing either. If b() return a number, then ‘return b()’ is a number too.

Now ‘s’ is assigned the value of what 'a()' return, which returns 'b()', which is nothing, so 's' is nothing (in JavaScript it’s a thing actually, it's an 'undefined'. So when you ask JavaScript to interpret what data type the 's' is, JavaScript interpreter will tell you 's' is an undefined.) As 's' is an undefined, when you ask JavaScript to execute this statement 's()', you're asking JavaScript to execute a function named as 's', but 's' here is an 'undefined', not a function, so JavaScript will complain, "hey, s is not a function, I don't know how to do with this s", then a "Uncaught TypeError: s is not a function" error message will be shown by JavaScript (tested in Firefox and Chrome)


Snippet Two

function a() {
  
    alert('A!');

    function b(){
        alert('B!'); 
    }

    return b; //return pointer to function b here
}

var s = a();  //s get the value of pointer to b
alert('break');
s(); // b() function is executed

now, function 'a' returning a pointer/alias to a function named 'b'. so when execute 's=a()', 's' will get a value pointing to b, i.e. 's' is an alias of 'b' now, calling 's' equals calling 'b'. i.e. 's' is a function now. Execute 's()' means to run function 'b' (same as executing 'b()'), a dialog box showing 'B!' will appeared (i.e. running the 'alert('B!'); statement in the function 'b')

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

RoboSpice Vs. Volley

From https://groups.google.com/forum/#!topic/robospice/QwVCfY_glOQ

  • RoboSpice(RS) is service based and more respectful of Android philosophy than Volley. Volley is thread based and this is not the way background processing should take place on Android. Ultimately, you can dig down both libs and find that they are quite similar, but our way to do background processing is more Android oriented, it allow us, for instance, to tell users that RS is actually doing something in background, which would be hard for volley (actually it doesn't at all).
  • RoboSpice and volley both offer nice features like prioritization, retry policies, request cancellation. But RS offers more : a more advanced caching and that's a big one, with cache management, request aggregation, more features like repluging to a pending request, dealing with cache expiry without relying on server headers, etc.
  • RoboSpice does more outside of UI Thread : volley will deserialize your POJOs on the main thread, which is horrible to my mind. With RS your app will be more responsive.
  • In terms of speed, we definitely need metrics. RS has gotten super fast now, but still we don't have figure to put here. Volley should theoretically be a bit faster, but RS is now massively parallel... who knows ?
  • RoboSpice offers a large compatibility range with extensions. You can use it with okhttp, retrofit, ormlite (beta), jackson, jackson2, gson, xml serializer, google http client, spring android... Quite a lot. Volley can be used with ok http and uses gson. that's it.
  • Volley offers more UI sugar that RS. Volley provides NetworkImageView, RS does provide a spicelist adapter. In terms of feature it's not so far, but I believe Volley is more advanced on this topic.
  • More than 200 bugs have been solved in RoboSpice since its initial release. It's pretty robust and used heavily in production. Volley is less mature but its user base should be growing fast (Google effect).
  • RoboSpice is available on maven central. Volley is hard to find ;)

How to make a Qt Widget grow with the window size?

In Designer, activate the centralWidget and assign a layout, e.g. horizontal or vertical layout. Then your QFormLayout will automatically resize.

Image of Designer

Always make sure, that all widgets have a layout! Otherwise, automatic resizing will break with that widget!

See also

Controls insist on being too large, and won't resize, in QtDesigner

html select option SELECTED

This is simple example by using ternary operator to set selected=selected

<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
  <option value="<?php echo $key;?>" <?php echo ($key ==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>

Python: Select subset from list based on index set

You could just use list comprehension:

property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]

or

property_asel = [property_a[i] for i in good_indices]

The latter one is faster because there are fewer good_indices than the length of property_a, assuming good_indices are precomputed instead of generated on-the-fly.


Edit: The first option is equivalent to itertools.compress available since Python 2.7/3.1. See @Gary Kerr's answer.

property_asel = list(itertools.compress(property_a, good_objects))

How do you turn a Mongoose document into a plain object?

You can also stringify the object and then again parse to make the normal object. For example like:-

const obj = JSON.parse(JSON.stringify(mongoObj))

Sqlite or MySql? How to decide?

My few cents to previous excellent replies. the site www.sqlite.org works on a sqlite database. Here is the link when the author (Richard Hipp) replies to a similar question.

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

Adding the correct doctype declaration and avoiding the XML prolog should be enough to avoid quirks mode.

Error: 'int' object is not subscriptable - Python

You need to convert age1 into int first, so it can do the minus. After that turn the result back to string for display:

name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
twentyone = str(21 - int(age1))
print "Hi, " + name1+ " you will be 21 in: " + twentyone + " years."

Fitting a histogram with python

Here is an example that uses scipy.optimize to fit a non-linear functions like a Gaussian, even when the data is in a histogram that isn't well ranged, so that a simple mean estimate would fail. An offset constant also would cause simple normal statistics to fail ( just remove p[3] and c[3] for plain gaussian data).

from pylab import *
from numpy import loadtxt
from scipy.optimize import leastsq

fitfunc  = lambda p, x: p[0]*exp(-0.5*((x-p[1])/p[2])**2)+p[3]
errfunc  = lambda p, x, y: (y - fitfunc(p, x))

filename = "gaussdata.csv"
data     = loadtxt(filename,skiprows=1,delimiter=',')
xdata    = data[:,0]
ydata    = data[:,1]

init  = [1.0, 0.5, 0.5, 0.5]

out   = leastsq( errfunc, init, args=(xdata, ydata))
c = out[0]

print "A exp[-0.5((x-mu)/sigma)^2] + k "
print "Parent Coefficients:"
print "1.000, 0.200, 0.300, 0.625"
print "Fit Coefficients:"
print c[0],c[1],abs(c[2]),c[3]

plot(xdata, fitfunc(c, xdata))
plot(xdata, ydata)

title(r'$A = %.3f\  \mu = %.3f\  \sigma = %.3f\ k = %.3f $' %(c[0],c[1],abs(c[2]),c[3]));

show()

Output:

A exp[-0.5((x-mu)/sigma)^2] + k 
Parent Coefficients:
1.000, 0.200, 0.300, 0.625
Fit Coefficients:
0.961231625289 0.197254597618 0.293989275502 0.65370344131

gaussian plot with fit

Omitting the first line from any Linux command output

This is a quick hacky way: ls -lart | grep -v ^total.

Basically, remove any lines that start with "total", which in ls output should only be the first line.

A more general way (for anything):

ls -lart | sed "1 d"

sed "1 d" means only print everything but first line.

pandas unique values multiple columns

I have setup a DataFrame with a few simple strings in it's columns:

>>> df
   a  b
0  a  g
1  b  h
2  d  a
3  e  e

You can concatenate the columns you are interested in and call unique function:

>>> pandas.concat([df['a'], df['b']]).unique()
array(['a', 'b', 'd', 'e', 'g', 'h'], dtype=object)

twitter bootstrap navbar fixed top overlapping site

All the previous solutions hard-code 40 pixels specifically into the html or CSS in one fashion or another. What if the navbar contains a different font-size or an image? What if I have a good reason not to mess with the body padding in the first place? I have been searching for a solution to this problem, and here is what I came up with:

$(document).ready(function(){
    $('.contentwrap') .css({'margin-top': (($('.navbar-fixed-top').height()) + 1 )+'px'});
    $(window).resize(function(){
        $('.contentwrap') .css({'margin-top': (($('.navbar-fixed-top').height()) + 1 )+'px'});
});

You can move it up or down by adjusting the '1'. It seems to work for me regardless of the size of the content in the navbar, before and after resizing.

I am curious what others think about this: please share your thoughts. (It will be refactored as not to repeat, btw.) Besides using jQuery, are there any other reasons not to approach the problem this way? I've even got it working with a secondary navbar like this:

$('.contentwrap') .css({'margin-top': (($('.navbar-fixed-top').height())
        + $('.admin-nav').height() + 1 )+'px'});

PS: Above is on Bootstrap 2.3.2 - will it work in 3.x As long as the generic class names remain... in fact, it should work independent of bootstrap, right?

EDIT: Here is a complete jquery function that handles two stacked, responsive fixed navbars of dynamic size. It requires 3 html classes(or could use id's): user-top, admin-top, and contentwrap:

$(document).ready(function(){

    $('.admin-top').css({'margin-top':($('.user-top').height()+0)+'px'});
    $('.contentwrap') .css({'padding-top': (
        $('.user-top').height()
         + $('.admin-top').height()
         + 0 )+'px'
    });

    $(window).resize(function(){
        $('.admin-top').css({'margin-top':($('.user-top').height()+0)+'px'});
        $('.contentwrap') .css({'padding-top': (
            $('.user-top').height()
             + $('.admin-top').height()
             + 0 )+'px'
        });
});

Java generics - ArrayList initialization

The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

ArrayList<A> a = new ArrayList<A>();

Here a is a reference to an instance of a specific type - exactly an array list of As. More explicitly, a is a reference to an array list that will accept As and will produce As. new ArrayList<A>() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

ArrayList<Integer> a = new ArrayList<Number>(); 

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers. It cannot point to an array list of Numbers. That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

ArrayList<Number> a = new ArrayList<Integer>(); 

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers. It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

ArrayList<? extends Object> a= new ArrayList<Object>();

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object. (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

ArrayList<? super Integer> a = new ArrayList<Number>();

Again, a is a reference to a family of types (rather than a single specific type). Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer. However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

ArrayList<ArrayList<?>> a

An array list that holds references to any list that is a member of a family of array lists types.

= new ArrayList<ArrayList<?>>(); // correct

An instance of an array list that holds references to any list that is a member of a family of array lists types.

ArrayList<?> a

An reference to any array list (a member of the family of array list types).

= new ArrayList<?>()

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.


See also How can I add to List<? extends Number> data structures?

(13: Permission denied) while connecting to upstream:[nginx]

I’ve run into this problem too. Another solution is to toggle the SELinux boolean value for httpd network connect to on (Nginx uses the httpd label).

setsebool httpd_can_network_connect on

To make the change persist use the -P flag.

setsebool httpd_can_network_connect on -P

You can see a list of all available SELinux booleans for httpd using

getsebool -a | grep httpd

How to send HTML-formatted email?

Setting isBodyHtml to true allows you to use HTML tags in the message body:

msg = new MailMessage("[email protected]",
                "[email protected]", "Message from PSSP System",
                "This email sent by the PSSP system<br />" +
                "<b>this is bold text!</b>");

msg.IsBodyHtml = true;

read word by word from file in C++

I have edited the function for you,

void readFile()
{
    ifstream file;
    file.open ("program.txt");
    if (!file.is_open()) return;

    string word;
    while (file >> word)
    {
        cout<< word << '\n';
    }
}

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

A little late, but since I've run into the same problem, in your exact scenario, I figured I'd add my solution.

I have Windows 7 (64-bit) and Office 2010 (32-bit). I tried with the DSN-less connection string:

jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=I:/TeamForge/ORS/CTFORS.accdb

and I tried with the DSN connection, using both the System32 and SysWOW64 versions of the ODBC Admin, and none of that worked.

What finally worked, was to match the bit version of Java with the bit version of Office. Once I did that, I could use either the DSN or DSN less connection mode, without any fuss.

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Adding items in a Listbox with multiple columns

There is one more way to achieve it:-

Private Sub UserForm_Initialize()
Dim list As Object
Set list = UserForm1.Controls.Add("Forms.ListBox.1", "hello", True)
With list
    .Top = 30
    .Left = 30
    .Width = 200
    .Height = 340
    .ColumnHeads = True
    .ColumnCount = 2
    .ColumnWidths = "100;100"
    .MultiSelect = fmMultiSelectExtended
    .RowSource = "Sheet1!C4:D25"
End With End Sub

Here, I am using the range C4:D25 as source of data for the columns. It will result in both the columns populated with values.

The properties are self explanatory. You can explore other options by drawing ListBox in UserForm and using "Properties Window (F4)" to play with the option values.

WordPress asking for my FTP credentials to install plugins

We had the same problem as part of a bigger problem. The suggested solution of

define('FS_METHOD', 'direct');

hides that window but then we still had problems with loading themes and upgrades etc. It is related to permissions however in our case we fixed the problem by moving from php OS vendor mod_php to the more secure php OS vendor FastCGI application.

$('body').on('click', '.anything', function(){})

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

$(document).on('click','body *',function(){
    //  $(this) = your current element that clicked.
    // additional code
});

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

What is the difference between parseInt(string) and Number(string) in JavaScript?

parseInt(string) will convert a string containing non-numeric characters to a number, as long as the string begins with numeric characters

'10px' => 10

Number(string) will return NaN if the string contains any non-numeric characters

'10px' => NaN

C++ performance vs. Java/C#

I like Orion Adrian's answer, but there is another aspect to it.

The same question was posed decades ago about assembly language vs. "human" languages like FORTRAN. And part of the answer is similar.

Yes, a C++ program is capable of being faster than C# on any given (non-trivial?) algorithm, but the program in C# will often be as fast or faster than a "naive" implementation in C++, and an optimized version in C++ will take longer to develop, and might still beat the C# version by a very small margin. So, is it really worth it?

You'll have to answer that question on a one-by-one basis.

That said, I'm a long time fan of C++, and I think it's an incredibly expressive and powerful language -- sometimes underappreciated. But in many "real life" problems (to me personally, that means "the kind I get paid to solve"), C# will get the job done sooner and safer.

The biggest penalty you pay? Many .NET and Java programs are memory hogs. I have seen .NET and Java apps take "hundreds" of megabytes of memory, when C++ programs of similar complexity barely scratch the "tens" of MBs.

How do I use spaces in the Command Prompt?

I prefer to enclose the command in () which is valid batch which makes it a bit easier to read:

cmd /C ("C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*")

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

How to use Lambda in LINQ select statement

using LINQ query expression

 IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID };

 ViewBag.storeSelector = stores;

or using LINQ extension methods with lambda expressions

 IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(store => new SelectListItem { Value = store.Name, Text = store.ID });

 ViewBag.storeSelector = stores;

Sibling package imports

Here is another alternative that I insert at top of the Python files in tests folder:

# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))

Java, How to add library files in netbeans?

In Netbeans 8.2

1. Dowload the binaries from the web source. The Apache Commos are in: [http://commons.apache.org/components.html][1] In this case, you must select the "Logging" in the Components menu and follow the link to downloads in the Releases part. Direct URL: [http://commons.apache.org/proper/commons-logging/download_logging.cgi][2] For me, the correct download was the file: commons-logging-1.2-bin.zip from the Binaries.

2. Unzip downloaded content. Now, you can see several jar files inside the directory created from the zip file.

3. Add the library to the project. Right click in the project, select Properties and click in Libraries (in the left side). Click the button "Add Jar/Folder". Go to the previously unzipped contents and select the properly jar file. Clic in "Open" and click in"Ok". The library has been loaded!

Start an activity from a fragment

You may have to replace getActivity() with MainActivity.this for those that are having issues with this.

Adding blank spaces to layout

try this

in layout.xml :

<TextView
        android:id="@+id/xxx"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/empty_spaces" />

in strings.xml :

<string name="empty_spaces">\t\t</string>

it worked for me

How to create a delay in Swift?

this is the simplest

    delay(0.3, closure: {
        // put her any code you want to fire it with delay
        button.removeFromSuperview()   
    })

Getting the index of a particular item in array

You can use FindIndex

 var index = Array.FindIndex(myArray, row => row.Author == "xyz");

Edit: I see you have an array of string, you can use any code to match, here an example with a simple contains:

 var index = Array.FindIndex(myArray, row => row.Contains("Author='xyz'"));

Maybe you need to match using a regular expression?

How to find if a native DLL file is compiled as x64 or x86?

You can use DUMPBIN too. Use the /headers or /all flag and its the first file header listed.

dumpbin /headers cv210.dll

64-bit

Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file cv210.dll

PE signature found

File Type: DLL

FILE HEADER VALUES
            8664 machine (x64)
               6 number of sections
        4BBAB813 time date stamp Tue Apr 06 12:26:59 2010
               0 file pointer to symbol table
               0 number of symbols
              F0 size of optional header
            2022 characteristics
                   Executable
                   Application can handle large (>2GB) addresses
                   DLL

32-bit

Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file acrdlg.dll

PE signature found

File Type: DLL

FILE HEADER VALUES
             14C machine (x86)
               5 number of sections
        467AFDD2 time date stamp Fri Jun 22 06:38:10 2007
               0 file pointer to symbol table
               0 number of symbols
              E0 size of optional header
            2306 characteristics
                   Executable
                   Line numbers stripped
                   32 bit word machine
                   Debug information stripped
                   DLL

'find' can make life slightly easier:

dumpbin /headers cv210.dll |find "machine"
        8664 machine (x64)

How to solve npm error "npm ERR! code ELIFECYCLE"

Its weird but it works for me

Go to

control panel -->System and Security--> System --> Advanced System Security--> Environment Variables

In Environment Variable popup you will edit the user variable PATH and add "C:\Windows\System32" value as semicolon separated to the existing value.

Not but not least restart the Machine.

enter image description here

Java Generate Random Number Between Two Given Values

One can also try below:

public class RandomInt { 
    public static void main(String[] args) { 

        int n1 = Integer.parseInt(args[0]);
        int n2 = Integer.parseInt(args[1]);
        double Random;

        if (n1 != n2)
        {
            if (n1 > n2)
            {
                Random = n2 + (Math.random() * (n1 - n2));
                System.out.println("Your random number is: " + Random);
            }
            else
            {
                Random = n1 + (Math.random() * (n2 - n1));   
                System.out.println("Your random number is: " +Random);
            }
        } else {
            System.out.println("Please provide valid Range " +n1+ " " +n2+ " are equal numbers." );
        }                     
    }
}

C++ unordered_map using a custom class type as the key

I think, jogojapan gave an very good and exhaustive answer. You definitively should take a look at it before reading my post. However, I'd like to add the following:

  1. You can define a comparison function for an unordered_map separately, instead of using the equality comparison operator (operator==). This might be helpful, for example, if you want to use the latter for comparing all members of two Node objects to each other, but only some specific members as key of an unordered_map.
  2. You can also use lambda expressions instead of defining the hash and comparison functions.

All in all, for your Node class, the code could be written as follows:

using h = std::hash<int>;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);

Notes:

  • I just reused the hashing method at the end of jogojapan's answer, but you can find the idea for a more general solution here (if you don't want to use Boost).
  • My code is maybe a bit too minified. For a slightly more readable version, please see this code on Ideone.

Spring Boot REST API - request timeout?

A fresh answer for Spring Boot 2.2 is required as server.connection-timeout=5000 is deprecated. Each server behaves differently, so server specific properties are recommended instead.

SpringBoot embeds Tomcat by default, if you haven't reconfigured it with Jetty or something else. Use server specific application properties like server.tomcat.connection-timeout or server.jetty.idle-timeout.

How to apply a patch generated with git format-patch?

First you should take a note about difference between git am and git apply

When you are using git am you usually wanna to apply many patches. Thus should use:

git am *.patch

or just:

git am

Git will find patches automatically and apply them in order ;-)

UPD
Here you can find how to generate such patches

How does HTTP_USER_AGENT work?

http://www.useragentstring.com/

Visit that page, it'll give you a good explanation of each element of your user agent.

Mozilla:

MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore

Extract subset of key-value pairs from Python dictionary object?

Maybe:

subdict=dict([(x,bigdict[x]) for x in ['l', 'm', 'n']])

Python 3 even supports the following:

subdict={a:bigdict[a] for a in ['l','m','n']}

Note that you can check for existence in dictionary as follows:

subdict=dict([(x,bigdict[x]) for x in ['l', 'm', 'n'] if x in bigdict])

resp. for python 3

subdict={a:bigdict[a] for a in ['l','m','n'] if a in bigdict}

Catch checked change event of a checkbox

For JQuery 1.7+ use:

$('input[type=checkbox]').on('change', function() {
  ...
});

Connecting to remote URL which requires authentication using Java

There's a native and less intrusive alternative, which works only for your call.

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

There is no argument given that corresponds to the required formal parameter - .NET Error

I received this same error in the following Linq statement regarding DailyReport. The problem was that DailyReport had no default constructor. Apparently, it instantiates the object before populating the properties.

var sums = reports
    .GroupBy(r => r.CountryRegion)
    .Select(cr => new DailyReport
    {
        CountryRegion = cr.Key,
        ProvinceState = "All",
        RecordDate = cr.First().RecordDate,
        Confirmed = cr.Sum(c => c.Confirmed),
        Recovered = cr.Sum(c => c.Recovered),
        Deaths = cr.Sum(c => c.Deaths)
    });

How can a add a row to a data frame in R?

I like list instead of c because it handles mixed data types better. Adding an additional column to the original poster's question:

#Create an empty data frame
df <- data.frame(hello=character(), goodbye=character(), volume=double())
de <- list(hello="hi", goodbye="bye", volume=3.0)
df = rbind(df,de, stringsAsFactors=FALSE)
de <- list(hello="hola", goodbye="ciao", volume=13.1)
df = rbind(df,de, stringsAsFactors=FALSE)

Note that some additional control is required if the string/factor conversion is important.

Or using the original variables with the solution from MatheusAraujo/Ytsen de Boer:

df[nrow(df) + 1,] = list(hello="hallo",goodbye="auf wiedersehen", volume=20.2)

Note that this solution doesn't work well with the strings unless there is existing data in the dataframe.

How to format DateTime columns in DataGridView?

I used these code Hope it could help

dataGridView2.Rows[n].Cells[3].Value = item[2].ToString();
dataGridView2.Rows[n].Cells[3].Value = Convert.ToDateTime(item[2].ToString()).ToString("d");

how to increase sqlplus column output length?

What I use:

set long 50000
set linesize 130

col x format a80 word_wrapped;
select dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA') x from dual;

Or am I missing something?

Binding a list in @RequestParam

Change hidden field value with checkbox toggle like below...

HTML:

<input type='hidden' value='Unchecked' id="deleteAll" name='anyName'>
<input type="checkbox"  onclick="toggle(this)"/> Delete All

Script:

function toggle(obj) {`var $input = $(obj);
    if ($input.prop('checked')) {

    $('#deleteAll').attr( 'value','Checked');

    } else {

    $('#deleteAll').attr( 'value','Unchecked');

    }

}

Eliminating NAs from a ggplot

Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.

library(tidyverse) 

MyDate %>%
   filter(!is.na(the_variable)) %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 
        geom_bar(stat="bin") 

You should be able to remove the annoying NAs on your plot. Hope this works :)

CSS checkbox input styling

With CSS 2 you can do this:

input[type='checkbox'] { ... }

This should be pretty widely supported by now. See support for browsers

React img tag issue with url and class

var Hello = React.createClass({
    render: function() {
      return (
        <div className="divClass">
           <img src={this.props.url} alt={`${this.props.title}'s picture`}  className="img-responsive" />
           <span>Hello {this.props.name}</span>
        </div>
      );
    }
});

What does "collect2: error: ld returned 1 exit status" mean?

clrscr is not standard C function. According to internet, it used to be a thing in old Borland C.
Is clrscr(); a function in C++?

HTML character codes for this ? or this ?

Check this page http://www.alanwood.net/unicode/geometric_shapes.html, first is "9650 ? 25B2 BLACK UP-POINTING TRIANGLE (present in WGL4)" and 2nd "9660 ? 25BC BLACK DOWN-POINTING TRIANGLE (present in WGL4)".

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

I had the same problem. I found solution here http://jakob.engbloms.se/archives/1403

c:\msysgit\bin>rebase.exe -b 0x50000000 msys-1.0.dll

For me solution was slightly different. It was

C:\Program Files (x86)\Git\bin>rebase.exe -b 0x50000000 msys-1.0.dll

Before you rebase dlls, you should make sure it is not in use:

tasklist /m msys-1.0.dll

And make a backup:

copy msys-1.0.dll msys-1.0.dll.bak

If the rebase command fails with something like:

ReBaseImage (msys-1.0.dll) failed with last error = 6

You will need to perform the following steps in order:

  1. Copy the dll to another directory
  2. Rebase the copy using the commands above
  3. Replace the original dll with the copy.

If any issue run the commands as Administrator

Spark - load CSV file as DataFrame?

spark-csv is part of core Spark functionality and doesn't require a separate library. So you could just do for example

df = spark.read.format("csv").option("header", "true").load("csvfile.csv")

In scala,(this works for any format-in delimiter mention "," for csv, "\t" for tsv etc)

val df = sqlContext.read.format("com.databricks.spark.csv") .option("delimiter", ",") .load("csvfile.csv")

How can I list the scheduled jobs running in my database?

The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.

The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.

The privileges you need are defined in the Admin Guide. Find out more.

So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.

How to get exit code when using Python subprocess communicate method?

.poll() will update the return code.

Try

child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
returnCode = child.poll()

In addition, after .poll() is called the return code is available in the object as child.returncode.

How to set the UITableView Section title programmatically (iPhone/iPad)?

titleForHeaderInSection is a delegate method of UITableView so to apply header text of section write as follows,

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
              return @"Hello World";
}

Responsive Bootstrap Jumbotron Background Image

The simplest way is to set the background-size CSS property to cover:

.jumbotron {
  background-image: url("../img/jumbotron_bg.jpg");
  background-size: cover;
}

.autocomplete is not a function Error

If your page has a section for Scripts such as the following, then ensure you refer to your Jquery library from inside this section.

@section Scripts 
{ 
   <script src="~/Scripts/jquery-ui.js" type="text/javascript"></script>
} 

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

Visual Studio 2005

  1. Create a new console application project in Visual Studio
  2. Add a "Web Reference" to the Lists.asmx web service.
    • Your URL will probably look like: http://servername/sites/SiteCollection/SubSite/_vti_bin/Lists.asmx
    • I named my web reference: ListsWebService
  3. Write the code in program.cs (I have an Issues list here)

Here is the code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace WebServicesConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ListsWebService.Lists listsWebSvc = new WebServicesConsoleApp.ListsWebService.Lists();
                listsWebSvc.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                listsWebSvc.Url = "http://servername/sites/SiteCollection/SubSite/_vti_bin/Lists.asmx";
                XmlNode node = listsWebSvc.GetList("Issues");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

Visual Studio 2008

  1. Create a new console application project in Visual Studio
  2. Right click on References and Add Service Reference
  3. Put in the URL to the Lists.asmx service on your server
    • Ex: http://servername/sites/SiteCollection/SubSite/_vti_bin/Lists.asmx
  4. Click Go
  5. Click OK
  6. Make the following code changes:

Change your app.config file from:

<security mode="None">
    <transport clientCredentialType="None" proxyCredentialType="None"
        realm="" />
    <message clientCredentialType="UserName" algorithmSuite="Default" />
</security>

To:

<security mode="TransportCredentialOnly">
  <transport clientCredentialType="Ntlm"/>
</security>

Change your program.cs file and add the following code to your Main function:

ListsSoapClient client = new ListsSoapClient();
client.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
XmlElement listCollection = client.GetListCollection();

Add the using statements:

using [your app name].ServiceReference1;
using System.Xml;

Reference: http://sharepointmagazine.net/technical/development/writing-caml-queries-for-retrieving-list-items-from-a-sharepoint-list

How to loop through all but the last item of a list?

If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).

from itertools import tee, izip, chain

def pairwise(seq):
    a,b = tee(seq)
    b.next()
    return izip(a,b)

for current_item, next_item in pairwise(y):
    if compare(current_item, next_item):
        # do what you have to do

If you need to compare the last value to some special value, chain that value to the end

for current, next_item in pairwise(chain(y, [None])):

How to get all table names from a database?

You need to iterate over your ResultSet calling next().

This is an example from java2s.com:

DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
  System.out.println(rs.getString(3));
}

Column 3 is the TABLE_NAME (see documentation of DatabaseMetaData::getTables).

how do you view macro code in access?

EDIT: Per Michael Dillon's answer, SaveAsText does save the commands in a macro without having to go through converting to VBA. I don't know what happened when I tested that, but it didn't produce useful text in the resulting file.

So, I learned something new today!

ORIGINAL POST: To expand the question, I wondered if there was a way to retrieve the contents of a macro from code, and it doesn't appear that there is (at least not in A2003, which is what I'm running).

There are two collections through which you can access stored Macros:

  CurrentDB.Containers("Scripts").Documents
  CurrentProject.AllMacros

The properties that Intellisense identifies for the two collections are rather different, because the collections are of different types. The first (i.e., traditional, pre-A2000 way) is via a documents collection, and the methods/properties/members of all documents are the same, i.e., not specific to Macros.

Likewise, the All... collections of CurrentProject return collections where the individual items are of type Access Object. The result is that Intellisense gives you methods/properties/members that may not exist for the particular document/object.

So far as I can tell, there is no way to programatically retrieve the contents of a macro.

This would stand to reason, as macros aren't of much use to anyone who would have the capability of writing code to examine them programatically.

But if you just want to evaluate what the macros do, one alternative would be to convert them to VBA, which can be done programmatically thus:

  Dim varItem As Variant
  Dim strMacroName As String

  For Each varItem In CurrentProject.AllMacros
    strMacroName = varItem.Name
    'Debug.Print strMacroName
    DoCmd.SelectObject acMacro, strMacroName, True
    DoCmd.RunCommand acCmdConvertMacrosToVisualBasic
    Application.SaveAsText acModule, "Converted Macro- " & strMacroName, _
      CurrentProject.Path & "\" & "Converted Macro- " & strMacroName & ".txt"
  Next varItem

Then you could use the resulting text files for whatever you needed to do.

Note that this has to be run interactively in Access because it uses DoCmd.RunCommand, and you have to click OK for each macro -- tedious for databases with lots of macros, but not too onerous for a normal app, which shouldn't have more than a handful of macros.

When use getOne and findOne methods Spring Data JPA

TL;DR

T findOne(ID id) (name in the old API) / Optional<T> findById(ID id) (name in the new API) relies on EntityManager.find() that performs an entity eager loading.

T getOne(ID id) relies on EntityManager.getReference() that performs an entity lazy loading. So to ensure the effective loading of the entity, invoking a method on it is required.

findOne()/findById() is really more clear and simple to use than getOne().
So in the very most of cases, favor findOne()/findById() over getOne().


API Change

From at least, the 2.0 version, Spring-Data-Jpa modified findOne().
Previously, it was defined in the CrudRepository interface as :

T findOne(ID primaryKey);

Now, the single findOne() method that you will find in CrudRepository is which one defined in the QueryByExampleExecutor interface as :

<S extends T> Optional<S> findOne(Example<S> example);

That is implemented finally by SimpleJpaRepository, the default implementation of the CrudRepository interface.
This method is a query by example search and you don't want to that as replacement.

In fact, the method with the same behavior is still there in the new API but the method name has changed.
It was renamed from findOne() to findById() in the CrudRepository interface :

Optional<T> findById(ID id); 

Now it returns an Optional. Which is not so bad to prevent NullPointerException.

So, the actual choice is now between Optional<T> findById(ID id) and T getOne(ID id).


Two distinct methods that rely on two distinct JPA EntityManager retrieval methods

1) The Optional<T> findById(ID id) javadoc states that it :

Retrieves an entity by its id.

As we look into the implementation, we can see that it relies on EntityManager.find() to do the retrieval :

public Optional<T> findById(ID id) {

    Assert.notNull(id, ID_MUST_NOT_BE_NULL);

    Class<T> domainType = getDomainClass();

    if (metadata == null) {
        return Optional.ofNullable(em.find(domainType, id));
    }

    LockModeType type = metadata.getLockModeType();

    Map<String, Object> hints = getQueryHints().withFetchGraphs(em).asMap();

    return Optional.ofNullable(type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints));
}

And here em.find() is an EntityManager method declared as :

public <T> T find(Class<T> entityClass, Object primaryKey,
                  Map<String, Object> properties);

Its javadoc states :

Find by primary key, using the specified properties

So, retrieving a loaded entity seems expected.

2) While the T getOne(ID id) javadoc states (emphasis is mine) :

Returns a reference to the entity with the given identifier.

In fact, the reference terminology is really board and JPA API doesn't specify any getOne() method.
So the best thing to do to understand what the Spring wrapper does is looking into the implementation :

@Override
public T getOne(ID id) {
    Assert.notNull(id, ID_MUST_NOT_BE_NULL);
    return em.getReference(getDomainClass(), id);
}

Here em.getReference() is an EntityManager method declared as :

public <T> T getReference(Class<T> entityClass,
                              Object primaryKey);

And fortunately, the EntityManager javadoc defined better its intention (emphasis is mine) :

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

So, invoking getOne() may return a lazily fetched entity.
Here, the lazy fetching doesn't refer to relationships of the entity but the entity itself.

It means that if we invoke getOne() and then the Persistence context is closed, the entity may be never loaded and so the result is really unpredictable.
For example if the proxy object is serialized, you could get a null reference as serialized result or if a method is invoked on the proxy object, an exception such as LazyInitializationException is thrown.
So in this kind of situation, the throw of EntityNotFoundException that is the main reason to use getOne() to handle an instance that does not exist in the database as an error situation may be never performed while the entity is not existing.

In any case, to ensure its loading you have to manipulate the entity while the session is opened. You can do it by invoking any method on the entity.
Or a better alternative use findById(ID id) instead of.


Why a so unclear API ?

To finish, two questions for Spring-Data-JPA developers:

  • why not having a clearer documentation for getOne() ? Entity lazy loading is really not a detail.

  • why do you need to introduce getOne() to wrap EM.getReference() ?
    Why not simply stick to the wrapped method :getReference() ? This EM method is really very particular while getOne() conveys a so simple processing.

SpringApplication.run main method

You need to run Application.run() because this method starts whole Spring Framework. Code below integrates your main() with Spring Boot.

Application.java

@SpringBootApplication
public class Application {

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

ReconTool.java

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        main(args);
    }

    public static void main(String[] args) {
        // Recon Logic
    }
}

Why not SpringApplication.run(ReconTool.class, args)

Because this way spring is not fully configured (no component scan etc.). Only bean defined in run() is created (ReconTool).

Example project: https://github.com/mariuszs/spring-run-magic

HashMap to return default value for non-found keys?

/**
 * Extension of TreeMap to provide default value getter/creator.
 * 
 * NOTE: This class performs no null key or value checking.
 * 
 * @author N David Brown
 *
 * @param <K>   Key type
 * @param <V>   Value type
 */
public abstract class Hash<K, V> extends TreeMap<K, V> {

    private static final long serialVersionUID = 1905150272531272505L;

    /**
     * Same as {@link #get(Object)} but first stores result of
     * {@link #create(Object)} under given key if key doesn't exist.
     * 
     * @param k
     * @return
     */
    public V getOrCreate(final K k) {
        V v = get(k);
        if (v == null) {
            v = create(k);
            put(k, v);
        }
        return v;
    }

    /**
     * Same as {@link #get(Object)} but returns specified default value
     * if key doesn't exist. Note that default value isn't automatically
     * stored under the given key.
     * 
     * @param k
     * @param _default
     * @return
     */
    public V getDefault(final K k, final V _default) {
        V v = get(k);
        return v == null ? _default : v;
    }

    /**
     * Creates a default value for the specified key.
     * 
     * @param k
     * @return
     */
    abstract protected V create(final K k);
}

Example Usage:

protected class HashList extends Hash<String, ArrayList<String>> {
    private static final long serialVersionUID = 6658900478219817746L;

    @Override
        public ArrayList<Short> create(Short key) {
            return new ArrayList<Short>();
        }
}

final HashList haystack = new HashList();
final String needle = "hide and";
haystack.getOrCreate(needle).add("seek")
System.out.println(haystack.get(needle).get(0));

Measure execution time for a Java method

You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.

If you use Spring, take a look at their MethodInterceptor class.

Hex colors: Numeric representation for "transparent"?

The alpha channel defines the transparency value of a color, so any color is 100% transparent as long as the alpha value is 0. Typically this four-channel color type is known as RGBA.

You can specify RGBA in CSS like so:

div {
    background: rgba(200, 54, 54, 0.5); /* 50% transparent */
}

Note that not all browsers support RGBA, in which case you can specify a fallback:

div {
    background: rgb(200, 54, 54); /* fallback */
    background: rgba(200, 54, 54, 0.5); /* 50% transparent */
}

More information regarding browser support and workarounds can be found here.

Pass a simple string from controller to a view MVC3

@Steve Hobbs' answer is probably the best, but some of your other solutions could have worked. For example, @Html.Label(ViewBag.CurrentPath); will probably work with an explicit cast, like @Html.Label((string)ViewBag.CurrentPath);. Also, your reference to currentPath in @Html.Label(ViewData["CurrentPath"].ToString()); is capitalized, wherein your other code it is not, which is probably why you were getting null reference exceptions.

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki


Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.


gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

What file uses .md extension and how should I edit them?

BBEdit will also display MD on the mac.

and here is a quicklook plugin to display them when you preview them.

How to discard uncommitted changes in SourceTree?

Ok I just noticed that my question was already answered in the question title.

To unstage files use

git reset HEAD /file/name

And to undo the changes to a file

git checkout -- /file/name

If you have a batch of files inside a folder you can undo the whole folder

git checkout -- /folder/name

Note that all these commands are already displayed when you git status

Here I created a dummy repo and listed all 3 possibilities

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   test
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   test2
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       test3

Where to find Java JDK Source Code?

Sadly, as of this writing, DESPITE their own documentation readme, there is no src.zip in the JDK 7 or 8 install directories when you download the Windows version.

Note: perhaps this happens because many of us don't actually run the install .exe, but instead extract it. Many of us don't run the Java install (the full blown windows install) for security reasons....we just want the JDK put someplace out of the way where potential viruses cannot find it.

But their policy regarding the windows .exe (whatever it truly is) is indeed nuts, HOWEVER, the src.zip DOES exist in the linux install (a .tar.gz). There are multiple ways of extracting a .tar and a .gz, and I prefer the free "7Zip" utility.

  1. download the Linux 64 bit .tar.gz
  2. use 7zip to uncompress the .tar.gz to a .tar
  3. use 7zip to extract the .tar to the installation directory
  4. src.zip will be waiting for you in that installation directory.
  5. pull it out and place it where you like.

Oracle, this is really beyond stupid.

Simple working Example of json.net in VB.net

Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue".

So either create a class for that, e.g.:

Public Class Container
    Public Venue As JSON_result
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
End Class

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)

or change your JSON string to

{
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}

or use e.g. a ContractResolver to parse the JSON string.

Git list of staged files

The best way to do this is by running the command:

git diff --name-only --cached

When you check the manual you will likely find the following:

--name-only
    Show only names of changed files.

And on the example part of the manual:

git diff --cached
    Changes between the index and your current HEAD.

Combined together you get the changes between the index and your current HEAD and Show only names of changed files.

Update: --staged is also available as an alias for --cached above in more recent git versions.

Error: Cannot find module 'gulp-sass'

Just do npm update and then npm install gulp-sass --save-dev in your root folder, and then when you run you shouldn't have any issues.

Is Secure.ANDROID_ID unique for each device?

Check into this thread,. However you should be careful as it's documented as "can change upon factory reset". Use at your own risk, and it can be easily changed on a rooted phone. Also it appears as if some manufacturers have had issues with their phones having duplicate numbers thread. Depending on what your trying to do, I probably wouldnt use this as a UID.

Parsing Query String in node.js

node -v v9.10.1

If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

So I would suggest use JSON.stringify

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}

What does the "yield" keyword do?

For those who prefer a minimal working example, meditate on this interactive Python session:

>>> def f():
...   yield 1
...   yield 2
...   yield 3
... 
>>> g = f()
>>> for i in g:
...   print(i)
... 
1
2
3
>>> for i in g:
...   print(i)
... 
>>> # Note that this time nothing was printed

How Stuff and 'For Xml Path' work in SQL Server?

In for xml path, if we define any value like [ for xml path('ENVLOPE') ] then these tags will be added with each row:

<ENVLOPE>
</ENVLOPE>

MySQL DROP all tables, ignoring foreign keys

DB="your database name" \
    && mysql $DB < "SET FOREIGN_KEY_CHECKS=0" \
    && mysqldump --add-drop-table --no-data $DB | grep 'DROP TABLE' | grep -Ev "^$" | mysql $DB \
    && mysql $DB < "SET FOREIGN_KEY_CHECKS=1"

Array.push() if does not exist?

I know this is a very old question, but if you're using ES6 you can use a very small version:

[1,2,3].filter(f => f !== 3).concat([3])

Very easy, at first add a filter which removes the item - if it already exists, and then add it via a concat.

Here is a more realistic example:

const myArray = ['hello', 'world']
const newArrayItem

myArray.filter(f => f !== newArrayItem).concat([newArrayItem])

If you're array contains objects you could adapt the filter function like this:

someArray.filter(f => f.some(s => s.id === myId)).concat([{ id: myId }])

How to use a WSDL

In visual studio.

  • Create or open a project.
  • Right-click project from solution explorer.
  • Select "Add service refernce"
  • Paste the address with WSDL you received.
  • Click OK.

If no errors, you should be able to see the service reference in the object browser and all related methods.

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

Gulp doesn't offer any kind of util for that, but you can use one of the many command args parsers. I like yargs. Should be:

var argv = require('yargs').argv;

gulp.task('my-task', function() {
    return gulp.src(argv.a == 1 ? options.SCSS_SOURCE : options.OTHER_SOURCE)
        .pipe(sass({style:'nested'}))
        .pipe(autoprefixer('last 10 version'))
        .pipe(concat('style.css'))
        .pipe(gulp.dest(options.SCSS_DEST));
});

You can also combine it with gulp-if to conditionally pipe the stream, very useful for dev vs. prod building:

var argv = require('yargs').argv,
    gulpif = require('gulp-if'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify');

gulp.task('my-js-task', function() {
  gulp.src('src/**/*.js')
    .pipe(concat('out.js'))
    .pipe(gulpif(argv.production, uglify()))
    .pipe(gulpif(argv.production, rename({suffix: '.min'})))
    .pipe(gulp.dest('dist/'));
});

And call with gulp my-js-task or gulp my-js-task --production.

Angularjs: input[text] ngChange fires while the value is changing

This is about recent additions to AngularJS, to serve as future answer (also for another question).

Angular newer versions (now in 1.3 beta), AngularJS natively supports this option, using ngModelOptions, like

ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"

NgModelOptions docs

Example:

<input type="text" name="username"
       ng-model="user.name"
       ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0} }" />

Why is it not advisable to have the database and web server on the same machine?

It doesn't really matter (you can quite happily run your site with web/database on the same machine), it's just the easiest step in scaling..

It's exactly what StackOverflow did - starting with single machine running IIS/SQL Server, then when it started getting heavily loaded, a second server was bought and the SQL server was moved onto that.

If performance is not an issue, do not waste money buying/maintaining two servers.

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

How to set adaptive learning rate for GradientDescentOptimizer?

Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.

The key excerpt to look at is:

# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)

learning_rate = tf.train.exponential_decay(
  0.01,                # Base learning rate.
  batch * BATCH_SIZE,  # Current index into the dataset.
  train_size,          # Decay step.
  0.95,                # Decay rate.
  staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
                                     0.9).minimize(loss,
                                                   global_step=batch)

Note the global_step=batch parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.

Visual Studio Community 2015 expiration date

Here is a simple approach to sneak by that stupid blocker screen in Visual Studio after 30-days expires using Process Hacker:

VS2015 Trial

Details at: https://stackoverflow.com/a/34243422/3135511

It's more of a quick 'n dirty fix than a real solution. However, it may be quicker than doing all that official login/sign up, subscribe, whatever crap Microsoft wants you to do, in order to use Visual Studio Community Version for free.

Specifying number of decimal places in Python

You don't show the code for display_data, but here's what you need to do:

print "$%0.02f" %amount

This is a format specifier for the variable amount.

Since this is beginner topic, I won't get into floating point rounding error, but it's good to be aware that it exists.

How to convert number to words in java

I have used 2 dimensional array...

   import java.util.Scanner;


   public class numberEnglish {
   public static void main(String args[])
        {
    String[ ][ ] aryNumbers = new String[9][4];
    aryNumbers[0][0] = "one";
    aryNumbers[0][1] = "ten";
    aryNumbers[0][2] = "one hundred and";
    aryNumbers[0][3] = "one thousand";

    aryNumbers[1][0] = "two";
    aryNumbers[1][1] = "twenty";
    aryNumbers[1][2] = "two hundred and";
    aryNumbers[1][3] = "two thousand";

    aryNumbers[2][0] = "three";
    aryNumbers[2][1] = "thirty";
    aryNumbers[2][2] = "three hundred and";
    aryNumbers[2][3] = "three thousand";

    aryNumbers[3][0] = "four";
    aryNumbers[3][1] = "fourty";
    aryNumbers[3][2] = "four hundred and";
    aryNumbers[3][3] = "four thousand";

    aryNumbers[4][0] = "five";
    aryNumbers[4][1] = "fifty";
    aryNumbers[4][2] = "five hundred and";
    aryNumbers[4][3] = "five thousand";

    aryNumbers[5][0] = "six";
    aryNumbers[5][1] = "sixty";
    aryNumbers[5][2] = "six hundred and";
    aryNumbers[5][3] = "six thousand";

    aryNumbers[6][0] = "seven";
    aryNumbers[6][1] = "seventy";
    aryNumbers[6][2] = "seven hundred and";
    aryNumbers[6][3] = "seven thousand";

    aryNumbers[7][0] = "eight";
    aryNumbers[7][1] = "eighty";
    aryNumbers[7][2] = "eight hundred and";
    aryNumbers[7][3] = "eight thousand";

    aryNumbers[8][0] = "nine";
    aryNumbers[8][1] = "ninty";
    aryNumbers[8][2] = "nine hundred and";
    aryNumbers[8][3] = "nine thousand";


    //System.out.println(aryNumbers[0] + " "+aryNumbers[0] + " ");

    int number=0;
    Scanner sc = new Scanner(System.in);
    System.out.println(" Enter Number 4 digited number:: ");
    number = sc.nextInt();
    int temp = number;
    int count=1;
    String english="";
    String tenglish = "";
    if(number == 0)
    {
        System.out.println("*********");
        System.out.println("Zero");
        System.out.println("*********");
        sc.close();
        return;
    }
    while(temp !=0)
    {

        int r = temp%10;
        if(r==0)
        {
            tenglish = " zero ";
            count++;
        }
        else
        {

            int t1=r-1;
            int t2 = count-1;
            //System.out.println(t1 +" "+t2);
            count++;
            tenglish = aryNumbers[t1][t2];

            //System.out.println(aryNumbers[t1][t2]);
        }
        english = tenglish +" "+ english;
        temp = temp/10;

    }
    //System.out.println(aryNumbers[0][0]);
    english = english.replace("ten  zero", "ten");
    english = english.replace("twenty  zero", "twenty");
    english = english.replace("thirty  zero", "thirty");
    english = english.replace("fourty  zero", "fourty");
    english = english.replace("fifty  zero", "fifty");
    english = english.replace("sixty  zero", "sixty");
    english = english.replace("seventy  zero", "seventy");
    english = english.replace("eighty  zero", "eighty");
    english = english.replace("ninety  zero", "ninety");

    english = english.replace("ten one", "eleven");
    english = english.replace("ten two", "twelve");
    english = english.replace("ten three", "thirteen");
    english = english.replace("ten four", "fourteen");
    english = english.replace("ten five", "fifteen");
    english = english.replace("ten six", "sixteen");
    english = english.replace("ten seven", "seventeen");
    english = english.replace("ten eight", "eighteen");
    english = english.replace("ten nine", "nineteen");
    english = english.replace(" zero ", "");
    int length = english.length();
    String sub = english.substring(length-6,length-3);
    //System.out.println(length);
    //System.out.println(sub);
    if(sub.equals("and"))
    {
        //System.out.println("hello");
        english=english.substring(0,length-6);
    }
    System.out.println("********************************************");
    System.out.println(english);
    System.out.println("********************************************");
    sc.close();
}

}

Installing TensorFlow on Windows (Python 3.6.x)

After searching a lot and trying to install and reinstall Python, i found the solution was very simple

use the following for windows

python -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl

change to following on mac

python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl

for Anaconda use corresponding conda

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

How to get the full URL of a Drupal page?

Maybe what you want is just plain old predefined variables.

Consider trying

$_SERVER['REQUEST_URI'']

Or read more here.

JavaScript DOM: Find Element Index In Container

For just elements this can be used to find the index of an element amongst it's sibling elements:

function getElIndex(el) {
    for (var i = 0; el = el.previousElementSibling; i++);
    return i;
}

Note that previousElementSibling isn't supported in IE<9.

How to run Rake tasks from within Rake tasks?

task :invoke_another_task do
  # some code
  Rake::Task["another:task"].invoke
end

Invoke JSF managed bean action on page load

calling bean action from a will be a good idea,keep attribute autoRun="true" example below

<p:remoteCommand autoRun="true" name="myRemoteCommand" action="#{bean.action}" partialSubmit="true" update=":form" />

How to read until EOF from cin in C++

After researching KeithB's solution using std::istream_iterator, I discovered the std:istreambuf_iterator.

Test program to read all piped input into a string, then write it out again:

#include <iostream>
#include <iterator>
#include <string>

int main()
{
  std::istreambuf_iterator<char> begin(std::cin), end;
  std::string s(begin, end);
  std::cout << s;
}

How to recursively find the latest modified file in a directory?

Instead of sorting the results and keeping only the last modified ones, you could use awk to print only the one with greatest modification time (in unix time):

find . -type f -printf "%T@\0%p\0" | awk '
    {
        if ($0>max) {
            max=$0; 
            getline mostrecent
        } else 
            getline
    } 
    END{print mostrecent}' RS='\0'

This should be a faster way to solve your problem if the number of files is big enough.

I have used the NUL character (i.e. '\0') because, theoretically, a filename may contain any character (including space and newline) but that.

If you don't have such pathological filenames in your system you can use the newline character as well:

find . -type f -printf "%T@\n%p\n" | awk '
    {
        if ($0>max) {
            max=$0; 
            getline mostrecent
        } else 
            getline
    } 
    END{print mostrecent}' RS='\n'

In addition, this works in mawk too.

Ignoring directories in Git repositories on Windows

I had some issues creating a file in Windows Explorer with a . at the beginning.

A workaround was to go into the commandshell and create a new file using "edit".

How to move a file?

Based on the answer described here, using subprocess is another option.

Something like this:

subprocess.call("mv %s %s" % (source_files, destination_folder), shell=True)

I am curious to know the pro's and con's of this method compared to shutil. Since in my case I am already using subprocess for other reasons and it seems to work I am inclined to stick with it.

Is it system dependent maybe?

How can I nullify css property?

I had an issue that even when I did overwrite "height" to "unset" or "initial", it behaved differently from when I removed the previous setting.

It turned out I needed to remove the min-height property too!

height: unset;
min-height: none

Edit: I tested on IE 7 and it doesn't recognize "unset", so "auto" works better".

What does "TypeError 'xxx' object is not callable" means?

That error occurs when you try to call, with (), an object that is not callable.

A callable object can be a function or a class (that implements __call__ method). According to Python Docs:

object.__call__(self[, args...]): Called when the instance is “called” as a function

For example:

x = 1
print x()

x is not a callable object, but you are trying to call it as if it were it. This example produces the error:

TypeError: 'int' object is not callable

For better understaing of what is a callable object read this answer in another SO post.

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

Start up R in a fresh session and paste this in:

library(ggplot2)

df <- structure(list(year = c(1, 2, 3, 4), pollution = structure(c(346.82, 
134.308821199349, 130.430379885892, 88.275457392443), .Dim = 4L, .Dimnames = list(
    c("1999", "2002", "2005", "2008")))), .Names = c("year", 
"pollution"), row.names = c(NA, -4L), class = "data.frame")

df[] <- lapply(df, as.numeric) # make all columns numeric

ggplot(df, aes(year, pollution)) +
           geom_point() +
           geom_line() +
           labs(x = "Year", 
                y = "Particulate matter emissions (tons)", 
                title = "Motor vehicle emissions in Baltimore")

android - listview get item view by position

This is the Kotlin version of the function posted by VVB. I used it in the ListView Adapter to implement the "go to next row first EditText when Enter key is pressed on the last EditText of current row" feature in the getView().

In the ListViewAdapter class, fun getView(), add lastEditText.setOnKeyListner as below:

lastEditText.setOnKeyListener { v, keyCode, event ->
    var setOnKeyListener = false
    if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
        try {
            val nextRow = getViewByPosition(position + 1, parent as ListView) as LinearLayout
            val nextET = nextRow.findViewById(R.id.firstEditText) as EditText
            nextET.isFocusableInTouchMode = true
            nextET.requestFocus()
        } catch (e: Exception) {
            // do nothing
        }
        setOnKeyListener = true
    }
    setOnKeyListener
}

add the fun getViewByPosition() after fun getView() as below:

private fun getViewByPosition(pos: Int, listView: ListView): View? {
    val firstListItemPosition: Int = listView.firstVisiblePosition
    val lastListItemPosition: Int = firstListItemPosition + listView.childCount - 1
    return if (pos < firstListItemPosition || pos > lastListItemPosition) {
        listView.adapter.getView(pos, null, listView)
    } else {
        val childIndex = pos + listView.headerViewsCount - firstListItemPosition
        listView.getChildAt(childIndex)
    }
}

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

There actually IS a way to do this. Think about how you might use Newtonsoft JSON to deserialize an object from json. It will (or at least can) ignore missing elements and populate all the elements that it does know about.

So here's how I did it. A small code sample will follow my explanation.

  1. Create an instance of your object from the base class and populate it accordingly.

  2. Using the "jsonconvert" class of Newtonsoft json, serialize that object into a json string.

  3. Now create your sub class object by deserializing with the json string created in step 2. This will create an instance of your sub class with all the properties of the base class.

This works like a charm! So.. when is this useful? Some people asked when this would make sense and suggested changing the OP's schema to accommodate the fact that you can't natively do this with class inheritance (in .Net).

In my case, I have a settings class that contains all the "base" settings for a service. Specific services have more options and those come from a different DB table, so those classes inherit the base class. They all have a different set of options. So when retrieving the data for a service, it's much easier to FIRST populate the values using an instance of the base object. One method to do this with a single DB query. Right after that, I create the sub class object using the method outlined above. I then make a second query and populate all the dynamic values on the sub class object.

The final output is a derived class with all the options set. Repeating this for additional new sub classes takes just a few lines of code. It's simple, and it uses a very tried and tested package (Newtonsoft) to make the magic work.

This example code is vb.Net, but you can easily convert to c#.

' First, create the base settings object.
    Dim basePMSettngs As gtmaPayMethodSettings = gtmaPayments.getBasePayMethodSetting(payTypeId, account_id)
    Dim basePMSettingsJson As String = JsonConvert.SerializeObject(basePMSettngs, Formatting.Indented)

    ' Create a pmSettings object of this specific type of payment and inherit from the base class object
    Dim pmSettings As gtmaPayMethodAimACHSettings = JsonConvert.DeserializeObject(Of gtmaPayMethodAimACHSettings)(basePMSettingsJson)

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

Check Whether a User Exists

Below is the script to check the OS distribution and create User if not exists and do nothing if user exists.

#!/bin/bash

# Detecting OS Ditribution
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
elif type lsb_release >/dev/null 2>&1; then
OS=$(lsb_release -si)
elif [ -f /etc/lsb-release ]; then
    . /etc/lsb-release
    OS=$DISTRIB_ID
else
    OS=$(uname -s)
fi

 echo "$OS"

 user=$(cat /etc/passwd | egrep -e ansible | awk -F ":" '{ print $1}')

 #Adding User based on The OS Distribution
 if [[ $OS = *"Red Hat"* ]] || [[ $OS = *"Amazon Linux"* ]] || [[ $OS = *"CentOS"*  
]] && [[ "$user" != "ansible" ]];then
 sudo useradd ansible

elif [ "$OS" =  Ubuntu ] && [ "$user" != "ansible" ]; then
sudo adduser --disabled-password --gecos "" ansible
else
  echo "$user is already exist on $OS"
 exit
fi

How to set viewport meta for iPhone that handles rotation properly?

Was just trying to work this out myself, and the solution I came up with was:

<meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0" />

This seems to lock the device into 1.0 scale regardless of it's orientation. As a side effect, it does however completely disable user scaling (pinch zooming, etc).

SQL Server query to find all current database names

This forum suggests also:

SELECT CATALOG_NAME AS DataBaseName
FROM INFORMATION_SCHEMA.SCHEMATA

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Convert Text to Date?

To the OP... I also got a type mismatch error the first time I tried running your subroutine. In my case it was cause by non-date-like data in the first cell (i.e. a header). When I changed the contents of the header cell to date-style txt for testing, it ran just fine...

Hope this helps as well.

jQuery slide left and show

This feature is included as part of jquery ui http://docs.jquery.com/UI/Effects/Slide if you want to extend it with your own names you can use this.

jQuery.fn.extend({
  slideRightShow: function() {
    return this.each(function() {
        $(this).show('slide', {direction: 'right'}, 1000);
    });
  },
  slideLeftHide: function() {
    return this.each(function() {
      $(this).hide('slide', {direction: 'left'}, 1000);
    });
  },
  slideRightHide: function() {
    return this.each(function() {
      $(this).hide('slide', {direction: 'right'}, 1000);
    });
  },
  slideLeftShow: function() {
    return this.each(function() {
      $(this).show('slide', {direction: 'left'}, 1000);
    });
  }
});

you will need the following references

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/ui/jquery.effects.core.js"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/ui/jquery.effects.slide.js"></script>

How to add and get Header values in WebApi

For WEB API 2.0:

I had to use Request.Content.Headers instead of Request.Headers

and then i declared an extestion as below

  /// <summary>
    /// Returns an individual HTTP Header value
    /// </summary>
    /// <param name="headers"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetHeader(this HttpContentHeaders headers, string key, string defaultValue)
    {
        IEnumerable<string> keys = null;
        if (!headers.TryGetValues(key, out keys))
            return defaultValue;

        return keys.First();
    }

And then i invoked it by this way.

  var headerValue = Request.Content.Headers.GetHeader("custom-header-key", "default-value");

I hope it might be helpful

Check if an element is a child of a parent

If you are only interested in the direct parent, and not other ancestors, you can just use parent(), and give it the selector, as in target.parent('div#hello').

Example: http://jsfiddle.net/6BX9n/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parent('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

Or if you want to check to see if there are any ancestors that match, then use .parents().

Example: http://jsfiddle.net/6BX9n/1/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parents('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

Pure CSS animation visibility with delay

Unfortunately you can't animate the display property. For a full list of what you can animate, try this CSS animation list by w3 Schools.

If you want to retain it's visual position on the page, you should try animating either it's height (which will still affect the position of other elements), or opacity (how transparent it is). You could even try animating the z-index, which is the position on the z axis (depth), by putting an element over the top of it, and then rearranging what's on top. However, I'd suggest using opacity, as it retains the vertical space where the element is.

I've updated the fiddle to show an example.

Good luck!

OnClick in Excel VBA

SelectionChange is the event built into the Excel Object model for this. It should do exactly as you want, firing any time the user clicks anywhere...

I'm not sure that I understand your objections to global variables here, you would only need 1 if you use the Application.SelectionChange event. However, you wouldn't need any if you utilize the Workbook class code behind (to trap the Workbook.SelectionChange event) or the Worksheet class code behind (to trap the Worksheet.SelectionChange) event. (Unless your issue is the "global variable reset" problem in VBA, for which there is only one solution: error handling everywhere. Do not allow any unhandled errors, instead log them and/or "soft-report" an error as a message box to the user.)

You might also need to trap the Worksheet.Activate() and Worksheet.Deactivate() events (or the equivalent in the Workbook class) and/or the Workbook.Activate and Workbook.Deactivate() events so that you know when the user has switched worksheets and/or workbooks. The Window activate and deactivate events should make this approach complete. They could all call the same exact procedure, however, they all denote the same thing: the user changed the "focus", if you will.

If you don't like VBA, btw, you can do the same using VB.NET or C#.

[Edit: Dbb makes a very good point about the SelectionChange event not picking up a click when the user clicks within the currently selected cell. If you need to pick that up, then you would need to use subclassing.]

is it possible to update UIButton title/text programmatically?

One more possible cause is this:

If you attempt to set the button's title in the (id)initWithNibName: ... method, then you're button property will still be nil. It hasn't yet been assigned to the UIButton.

You must be sure that you're setting your buttons in a method like (void)viewWillLoad or (void)viewWillAppear, but you probably don't want to set them as late as (void)viewDidAppear.

ipython notebook clear cell output in code

You can use the IPython.display.clear_output to clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print(i, flush=True)

Python Replace \\ with \

path = "C:\\Users\\Programming\\Downloads"
# Replace \\ with a \ along with any random key multiple times
path.replace('\\', '\pppyyyttthhhooonnn')
# Now replace pppyyyttthhhooonnn with a blank string
path.replace("pppyyyttthhhooonnn", "")

print(path)

#Output... C:\Users\Programming\Downloads

@Html.DropDownListFor how to set default value

Like this:

@Html.DropDownListFor(model => model.Status, new List<SelectListItem> 
       { new SelectListItem{Text="Active", Value="True"},
         new SelectListItem{Text="Deactive", Value="False"}},"Select One")

If you want Active to be selected by default then use Selected property of SelectListItem:

@Html.DropDownListFor(model => model.Status, new List<SelectListItem> 
           { new SelectListItem{Text="Active", Value="True",Selected=true},
             new SelectListItem{Text="Deactive", Value="False"}},"Select One")

If using SelectList, then you have to use this overload and specify SelectListItem Value property which you want to set selected:

@Html.DropDownListFor(model => model.title, 
                     new SelectList(new List<SelectListItem>
  {
      new SelectListItem { Text = "Active" , Value = "True"},
      new SelectListItem { Text = "InActive", Value = "False" }
  },
    "Value", // property to be set as Value of dropdown item
    "Text",  // property to be used as text of dropdown item
    "True"), // value that should be set selected of dropdown
     new { @class = "form-control" })

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

You can eliminate the client from the problem by using wftech, this is an old tool but I have found it useful in diagnosing authentication issues. wfetch allows you to specify NTLM, Negotiate and kerberos, this may well help you better understand your problem. As you are trying to call a service and wfetch knows nothing about WCF, I would suggest applying your endpoint binding (PROVIDERSSoapBinding) to the serviceMetadata then you can do an HTTP GET of the WSDL for the service with the same security settings.

Another option, which may be available to you is to force the server to use NTLM, you can do this by either editing the metabase (IIS 6) and removing the Negotiate setting, more details at http://support.microsoft.com/kb/215383.

If you are using IIS 7.x then the approach is slightly different, details of how to configure the authentication providers are here http://www.iis.net/configreference/system.webserver/security/authentication/windowsauthentication.

I notice that you have blocked out the server address with xxx.xx.xx.xxx, so I'm guessing that this is an IP address rather than a server name, this may cause issues with authentication, so if possible try targeting the machine name.

Sorry that I haven't given you the answer but rather pointers for getting closer to the issue, but I hope it helps.

I'll finish by saying that I have experienced this same issue and my only recourse was to use Kerberos rather than NTLM, don't forget you'll need to register an SPN for the service if you do go down this route.

How to remove empty lines with or without whitespace in Python

My version:

while '' in all_lines:
    all_lines.pop(all_lines.index(''))

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

when do you need .ascx files and how would you use them?

Ascx-files are called User Controls and are meant for reusability and also for making complex aspx-pages less complex (lift out some part of the page). They could also be beneficial for something called donut caching, that is when you would like to cache a certain part of a page.

How to get response status code from jQuery.ajax?

jqxhr is a json object:

complete returns:
The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

see: jQuery ajax

so you would do:

jqxhr.status to get the status

Apply style ONLY on IE

I think for best practice you should write IE conditional statement inside the <head> tag that inside has a link to your special ie style sheet. This HAS TO BE after your custom css link so it overrides the latter, I have a small site so i use the same ie css for all pages.

<link rel="stylesheet" type="text/css" href="index.css" />
<!--[if IE]>
    <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->

this differs from james answer as i think(personal opinion because i work with a designer team and i dont want them to touch my html files and mess up something there) you should never include styles in your html file.

How can I debug git/git-shell related problems?

try this one:

GIT_TRACE=1 git pull origin master

PHP how to get value from array if key is in a variable

$value = ( array_key_exists($key, $array) && !empty($array[$key]) ) 
         ? $array[$key] 
         : 'non-existant or empty value key';

A div with auto resize when changing window width\height

In this scenario, the outer <div> has a width and height of 90%. The inner div> has a width of 100% of its parent. Both scale when re-sizing the window.

HTML

<div>
    <div>Hello there</div>
</div>

CSS

html, body {
    width: 100%;
    height: 100%;
}

body > div {
    width: 90%;
    height: 100%;
    background: green;
}

body > div > div {
    width: 100%;
    background: red;
}

Demo

Try before buy

Java web start - Unable to load resource

enter image description here

In Advance Tab -> scroll down and un-checked all options in advance security setting and try by checking one-by-one and finally app start running with one option TLS 1.1

that was the solution I got it.

SQL: set existing column as Primary Key in MySQL

ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);

The FastCGI process exited unexpectedly

You might be using C:/[your-php-directory]/php.exe in Handler mapping of IIS just change it C:/[your-php-directory]/php-cgi.exe.

top nav bar blocking top content of the page

Add this:

.navbar {
  position: relative;
}

Java HashMap performance optimization / alternative

Another poster already pointed out that your hashcode implementation will result in a lot of collisions due to the way that you're adding values together. I'm willing to be that, if you look at the HashMap object in a debugger, you'll find that you have maybe 200 distinct hash values, with extremely long bucket chains.

If you always have values in the range 0..51, each of those values will take 6 bits to represent. If you always have 5 values, you can create a 30-bit hashcode with left-shifts and additions:

    int code = a[0];
    code = (code << 6) + a[1];
    code = (code << 6) + b[0];
    code = (code << 6) + b[1];
    code = (code << 6) + b[2];
    return code;

The left-shift is fast, but will leave you with hashcodes that aren't evenly distributed (because 6 bits implies a range 0..63). An alternative is to multiply the hash by 51 and add each value. This still won't be perfectly distributed (eg, {2,0} and {1,52} will collide), and will be slower than the shift.

    int code = a[0];
    code *= 51 + a[1];
    code *= 51 + b[0];
    code *= 51 + b[1];
    code *= 51 + b[2];
    return code;

how to update spyder on anaconda

Using pip directly:

WARNING: This will break your Anaconda Installation as described by Spyder maintainer in the comments below; you can try this solution only if the solution mentioned above that use Conda do not work

pip install --upgrade spyder

You might get an error once launching the new Spyder "nbconvert >= 4.0: None (NOK)", which will require you to resinstall configparser:

conda uninstall configparser

conda install configparser

You should now have a fresh and up to date installation of Spyder.

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

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

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

Using a Glyphicon as an LI bullet point (Bootstrap 3)

I'm using a simplyfied version (just using position relative) based on @SimonEast answer:

li:before {
    content: "\e080";
    font-family: 'Glyphicons Halflings';
    font-size: 9px;
    position: relative;
    margin-right: 10px;
    top: 3px;
    color: #ccc;
}

Which is better, return value or out parameter?

You should generally prefer a return value over an out param. Out params are a necessary evil if you find yourself writing code that needs to do 2 things. A good example of this is the Try pattern (such as Int32.TryParse).

Let's consider what the caller of your two methods would have to do. For the first example I can write this...

int foo = GetValue();

Notice that I can declare a variable and assign it via your method in one line. FOr the 2nd example it looks like this...

int foo;
GetValue(out foo);

I'm now forced to declare my variable up front and write my code over two lines.

update

A good place to look when asking these types of question is the .NET Framework Design Guidelines. If you have the book version then you can see the annotations by Anders Hejlsberg and others on this subject (page 184-185) but the online version is here...

http://msdn.microsoft.com/en-us/library/ms182131(VS.80).aspx

If you find yourself needing to return two things from an API then wrapping them up in a struct/class would be better than an out param.

How to set background color of a button in Java GUI?

It seems that the setBackground() method doesn't work well on some platforms (I'm using Windows 7). I found this answer to this question helpful. However, I didn't entirely use it to solve my problem. Instead, I decided it'd be much easier and almost as aesthetic to color a panel next to the button.

Detect touch press vs long press vs movement?

I think you should implement GestureDetector.OnGestureListener as described in Using GestureDetector to detect Long Touch, Double Tap, Scroll or other touch events in Android and androidsnippets and then implement tap logic in onSingleTapUp and move logic in onScroll events

Convert a list to a string in C#

The .ToString() method for reference types usually resolves back to System.Object.ToString() unless you override it in a derived type (possibly using extension methods for the built-in types). The default behavior for this method is to output the name of the type on which it's called. So what you're seeing is expected behavior.

You could try something like string.Join(", ", myList.ToArray()); to achieve this. It's an extra step, but it could be put in an extension method on System.Collections.Generic.List<T> to make it a bit easier. Something like this:

public static class GenericListExtensions
{
    public static string ToString<T>(this IList<T> list)
    {
        return string.Join(", ", list);
    }
}

(Note that this is free-hand and untested code. I don't have a compiler handy at the moment. So you'll want to experiment with it a little.)

How can you detect the version of a browser?

Here are several prominent libraries that handle browser detection as of May 2019.

Bowser by lancedikson - 3,761?s - Last updated May 26, 2019 - 4.8KB

_x000D_
_x000D_
var result = bowser.getParser(window.navigator.userAgent);_x000D_
console.log(result);_x000D_
document.write("You are using " + result.parsedResult.browser.name +_x000D_
               " v" + result.parsedResult.browser.version + _x000D_
               " on " + result.parsedResult.os.name);
_x000D_
<script src="https://unpkg.com/[email protected]/es5.js"></script>
_x000D_
_x000D_
_x000D_

*supports Edge based on Chromium


Platform.js by bestiejs - 2,250?s - Last updated Oct 30, 2018 - 5.9KB

_x000D_
_x000D_
console.log(platform);_x000D_
document.write("You are using " + platform.name +_x000D_
               " v" + platform.version + _x000D_
               " on " + platform.os);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery Browser by gabceb - 504?s - Last updated Nov 23, 2015 - 1.3KB

_x000D_
_x000D_
console.log($.browser)_x000D_
document.write("You are using " + $.browser.name +_x000D_
               " v" + $.browser.versionNumber + _x000D_
               " on " + $.browser.platform);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>
_x000D_
_x000D_
_x000D_

Detect.js (Archived) by darcyclarke - 522?s - Last updated Oct 26, 2015 - 2.9KB

_x000D_
_x000D_
var result = detect.parse(navigator.userAgent);_x000D_
console.log(result);_x000D_
document.write("You are using " + result.browser.family +_x000D_
               " v" + result.browser.version + _x000D_
               " on " + result.os.family);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>
_x000D_
_x000D_
_x000D_

Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B

_x000D_
_x000D_
console.log(BrowserDetect)_x000D_
document.write("You are using " + BrowserDetect.browser +_x000D_
               " v" + BrowserDetect.version + _x000D_
               " on " + BrowserDetect.OS);
_x000D_
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>
_x000D_
_x000D_
_x000D_


Notable Mentions:

  • WhichBrowser - 1,355?s - Last updated Oct 2, 2018
  • Modernizr - 23,397?s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.

Further Reading

What exactly are DLL files, and how do they work?

DLL files contain an Export Table which is a list of symbols which can be looked up by the calling program. The symbols are typically functions with the C calling convention (__stcall). The export table also contains the address of the function.

With this information, the calling program can then call the functions within the DLL even though it did not have access to the DLL at compile time.

Introducing Dynamic Link Libraries has some more information.

getting only name of the class Class.getName()

Social.class.getSimpleName()

getSimpleName() : Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous. The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

Why does flexbox stretch my image rather than retaining aspect ratio?

Adding margin to align images:

Since we wanted the image to be left-aligned, we added:

img {
  margin-right: auto;
}

Similarly for image to be right-aligned, we can add margin-right: auto;. The snippet shows a demo for both types of alignment.

Good Luck...

_x000D_
_x000D_
div {_x000D_
  display:flex; _x000D_
  flex-direction:column;_x000D_
  border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  text-align: center;_x000D_
}_x000D_
hr {_x000D_
  border: 1px black solid;_x000D_
  width: 100%_x000D_
}_x000D_
img.one {_x000D_
  margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
  <h1>Flex Box</h1>_x000D_
  _x000D_
  <hr />_x000D_
  _x000D_
  <img src="https://via.placeholder.com/80x80" class="one" _x000D_
  />_x000D_
  _x000D_
  _x000D_
  <img src="https://via.placeholder.com/80x80" class="two" _x000D_
  />_x000D_
  _x000D_
  <hr />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Setting POST variable without using form

You can do it using jQuery. Example:

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<script>
    $.ajax({
        url : "next.php",
        type: "POST",
        data : "name=Denniss",
        success: function(data)
        {
            //data - response from server
            $('#response_div').html(data);
        }
    });
</script>

How to display the string html contents into webbrowser control?

As commented by Thomas W. - I almost missed this comment but I had the same issues so it's worth rewriting as an answer I think.

The main issue being that after the first assignment of webBrowser1.DocumentText to some html, subsequent assignments had no effect.

The solution as linked by Thomas can be found in detail at http://weblogs.asp.net/gunnarpeipman/archive/2009/08/15/displaying-custom-html-in-webbrowser-control.aspx however I will summarize below in case this page becomes unavailable in the future.

In short, due to the way the webBrowser control works, you must navigate to a new page each time you wish to change the content. Therefore the author proposes a method to update the control as:

private void DisplayHtml(string html)
{
    webBrowser1.Navigate("about:blank");
    if (webBrowser1.Document != null)
    {
        webBrowser1.Document.Write(string.Empty);
    }
    webBrowser1.DocumentText = html;
}

I have however found that in my current application I get a CastException from the line if(webBrowser1.Document != null). I'm not sure why this is, but I've found that if I wrap the whole if block in a try catch the desired effect still works. See:

private void DisplayHtml(string html)
{
    webBrowser1.Navigate("about:blank");
    try
    {
        if (webBrowser1.Document != null)
        {
            webBrowser1.Document.Write(string.Empty);
        }
    }
    catch (CastException e)
    { } // do nothing with this
    webBrowser1.DocumentText = html;
}

So every time the function to DisplayHtml is executed I receive a CastException from the if statement, so the contents of the if statement are never reached. However if I comment out the if statement so as not to receive the CastException, then the browser control doesn't get updated. I suspect there is another side effect of the code behind the Document property which causes this effect despite the fact that it also throws an exception.

Anyway I hope this helps people.

How can getContentResolver() be called in Android?

A solution would be to get the ContentResolver from the context

ContentResolver contentResolver = getContext().getContentResolver();

Link to the documentation : ContentResolver

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

Eclipse hooks Dynamic Web projects into tomcat and maintains it's own configuration but does not deploy the standard tomcat ROOT.war. As http://localhost:8085/ link returns 404 does indeed show that tomcat is up and running, just can't find a web app deployed to root.

By default, any deployed dynamic web projects use their project name as context root, so you should see http://localhost:8085/yourprojectname working properly, but check the Servers tab first to ensure that your web project has actually been deployed.

Hope that helps.

How do you create a daemon in Python?

Current solution

A reference implementation of PEP 3143 (Standard daemon process library) is now available as python-daemon.

Historical answer

Sander Marechal's code sample is superior to the original, which was originally posted in 2004. I once contributed a daemonizer for Pyro, but would probably use Sander's code if I had to do it over.

MySQL Data - Best way to implement paging?

Define OFFSET for the query. For example

page 1 - (records 01-10): offset = 0, limit=10;

page 2 - (records 11-20) offset = 10, limit =10;

and use the following query :

SELECT column FROM table LIMIT {someLimit} OFFSET {someOffset};

example for page 2:

SELECT column FROM table
LIMIT 10 OFFSET 10;

Select distinct values from a table field

In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by() on distinct("field_name") queries. This is, however, a Postgres only feature!

If you are using Postgres and if you define a field name that the query should be distinct for, then order_by() needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).

Note

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.

If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:

# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')  

The character encoding of the plain text document was not declared - mootool script

I fixed this issue by adding a slash at the beginning to my relative path

How to remove space from string?

You can also use echo to remove blank spaces, either at the beginning or at the end of the string, but also repeating spaces inside the string.

$ myVar="    kokor    iiij     ook      "
$ echo "$myVar"
    kokor    iiij     ook      
$ myVar=`echo $myVar`
$
$ # myVar is not set to "kokor iiij ook"
$ echo "$myVar"
kokor iiij ook

c++ array assignment of multiple values

There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.

Here is what you can do:

#include <algorithm>

int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);

However, in C++0x, you can do this:

std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};

Of course, if you choose to use std::vector instead of raw array.

Get Cell Value from a DataTable in C#

You can call the indexer directly on the datatable variable as well:

var cellValue = dt[i].ColumnName

Broken references in Virtualenvs

A update version @Chris Wedgwood's answer for keeping site-packages (keeping packages installed)

cd ~/.virtualenv/name_of_broken_venv


mv lib/python2.7/site-packages ./    
rm -rf .Python bin lib include
virtualenv .
rm -rf lib/python2.7/site-packages
mv ./site-packages lib/python2.7/

Find where java class is loaded from

This approach works for both files and jars:

Class clazz = Class.forName(nameOfClassYouWant);

URL resourceUrl = clazz.getResource("/" + clazz.getCanonicalName().replace(".", "/") + ".class");
InputStream classStream = resourceUrl.openStream(); // load the bytecode, if you wish

Most efficient way to convert an HTMLCollection to an Array

var arr = Array.prototype.slice.call( htmlCollection )

will have the same effect using "native" code.

Edit

Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is effectively equivalent:

var arr = [].slice.call(htmlCollection);

But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.

Edit

Since ECMAScript 2015 (ES 6) there is also Array.from:

var arr = Array.from(htmlCollection);

Edit

ECMAScript 2015 also provides the spread operator, which is functionally equivalent to Array.from (although note that Array.from supports a mapping function as the second argument).

var arr = [...htmlCollection];

I've confirmed that both of the above work on NodeList.

A performance comparison for the mentioned methods: http://jsben.ch/h2IFA

How to trap the backspace key using jQuery?

try this one :

 $('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})  

Connect to SQL Server through PDO using SQL Server Driver

This works for me, and in this case was a remote connection: Note: The port was IMPORTANT for me

$dsn = "sqlsrv:Server=server.dyndns.biz,1433;Database=DBNAME";
$conn = new PDO($dsn, "root", "P4sw0rd");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$sql = "SELECT * FROM Table";

foreach ($conn->query($sql) as $row) {
    print_r($row);
} 

How to find the .NET framework version of a Visual Studio project?

  • VB

Project Properties -> Compiler Tab -> Advanced Compile Options button

  • C#

Project Properties -> Application Tab

Error "The input device is not a TTY"

It's not exactly what you are asking, but:

The -T key would help people who are using docker-compose exec!

docker-compose -f /srv/backend_bigdata/local.yml exec -T postgres backup

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE).

Since your integer array cannot contain a value larger than Integer.MAX_VALUE and smaller than Integer.MIN_VALUE your code works across all edge cases.

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

What does "select count(1) from table_name" on any database tables mean?

This is similar to the difference between

SELECT * FROM table_name and SELECT 1 FROM table_name.  

If you do

SELECT 1 FROM table_name

it will give you the number 1 for each row in the table. So yes count(*) and count(1) will provide the same results as will count(8) or count(column_name)

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

HTML button onclick event

Try this:-

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="ISO-8859-1"> 
    <title>Online Student Portal</title> 
</head> 
<body> 
    <form action="">
         <input type="button" value="Add Students" onclick="window.location.href='Students.html';"/>
         <input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"/>
         <input type="button" value="Student Payments" onclick="window.location.href='Payment.html';"/>
    </form> 
</body> 
</html>

How to add 'libs' folder in Android Studio?

also you should click right button on mouse at your projectname and choose "open module settings" or press F4 button. Then on "dependencies" tab add your lib.jar to declare needed lib

What's an object file in C?

An object file is just what you get when you compile one (or several) source file(s).

It can be either a fully completed executable or library, or intermediate files.

The object files typically contain native code, linker information, debugging symbols and so forth.

Good tool to visualise database schema?

I found SchemaSpy quite good - you have to run the script every time schema changes but it is not so big deal.

As pointed out in the comments there is also a GUI for it.

Another nice tool is SchemaCrawler.