Found an alternative at Child elements with margins within DIVs You can also add:
.parent { overflow: auto; }
or:
.parent { overflow: hidden; }
This prevents the margins to collapse. Border and padding do the same. Hence, you can also use the following to prevent a top-margin collapse:
.parent {
padding-top: 1px;
margin-top: -1px;
}
Update by popular request: The whole point of collapsing margins is handling textual content. For example:
h1, h2, p, ul {_x000D_
margin-top: 1em;_x000D_
margin-bottom: 1em;_x000D_
}
_x000D_
<h1>Title!</h1>_x000D_
<div class="text">_x000D_
<h2>Title!</h2>_x000D_
<p>Paragraph</p>_x000D_
</div>_x000D_
<div class="text">_x000D_
<h2>Title!</h2>_x000D_
<p>Paragraph</p>_x000D_
<ul>_x000D_
<li>list item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Because the browser collapses margins, the text would appear as you'd expect, and the <div>
wrapper tags don't influence the margins. Each element ensures it has spacing around it, but spacing won't be doubled. The margins of the <h2>
and <p>
won't add up, but slide into each other (they collapse). The same happens for the <p>
and <ul>
element.
Sadly, with modern designs this idea can bite you when you explicitly want a container. This is called a new block formatting context in CSS speak. The overflow
or margin trick will give you that.
On 12 March 2020, a draft has been added by WICG for Text Fragments, and now you can link to text on a page as if you were searching for it by adding the following to the hash
#:~:text=<Text To Link to>
Working example on Chrome Version 81.0.4044.138
:
Click on this link Should reload the page and highlight the link's text
To add to what Brad and squadette have said, the self-closing XML syntax <script />
actually is correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like application/xhtml+xml
in the HTTP Content-Type header (and not as text/html
).
However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes text/html
.
From w3:
In summary, 'application/xhtml+xml' SHOULD be used for XHTML Family documents, and the use of 'text/html' SHOULD be limited to HTML-compatible XHTML 1.0 documents. 'application/xml' and 'text/xml' MAY also be used, but whenever appropriate, 'application/xhtml+xml' SHOULD be used rather than those generic XML media types.
I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old <script></script>
syntax with text/html
(HTML syntax + HTML mimetype).
If your server sends the text/html
type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that <script />
will not work (this is a change, Firefox was previously less strict).
This will happen regardless of any fiddling with http-equiv
meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the text/html
header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand <script />
.
If you want to use the iframe's scrollbar and not the parent's use this:
document.body.style.overflow = 'hidden';
If you want to use the parent's scrollbar and not the iframe's then you need to use:
document.getElementById('your_iframes_id').scrolling = 'no';
or set the scrolling="no"
attribute in your iframe's tag: <iframe src="some_url" scrolling="no">
.
<i>
, <b>
, <em>
and <strong>
tags are traditionally representational. But they have been given new semantic meaning in HTML5.
<i>
and <b>
was used for font style in HTML4. <i>
was used for italic and <b>
for bold. In HTML5 <i>
tag has new semantic meaning of 'alternate voice or mood' and <b>
tag has the meaning of stylistically offset.
Example uses of <i>
tag are - taxonomic designation, technical term, idiomatic phrase from another language, transliteration, a thought, ship names in western texts. Such as -
<p><i>I hope this works</i>, he thought.</p>
Example uses of <b>
tag are keywords in a document extract, product names in a review, actionable words in an interactive text driven software, article lead.
The following example paragraph is stylistically offset from the paragraphs that follow it.
<p><b class="lead">The event takes place this upcoming Saturday, and over 3,000 people have already registered.</b></p>
<em>
and <strong>
had the meaning of emphasis and strong emphasis in HTML4. But in HTML5 <em>
means stressed emphasis and <strong>
means strong importance.
In the following example there should be a linguistic change while reading the word before ...
<p>Make sure to sign up <em>before</em> the day of the event, September 16, 2016</p>
In the same example we can use the <strong>
tag as follows ..
<p>Make sure to sign up <em>before</em> the day of the event, <strong>September 16, 2016</strong></p>
to give importance on the event date.
MDN Ref:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
There are many methods :
CSS
<div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div>
2 . Center horizontally and vertically a single line of text
CSS
<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>
3 . Center horizontal and vertical align of an element with no specific measure
CSS
<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>
<h1><span>This is</span> a Headline</h1>
h1 { font-weight: normal; text-transform: uppercase; }
h1 span { font-weight: bold; }
I'm not sure if it was just for the sake of showing us, but as a side note, you should always set uppercase text with CSS :)
Just a heads up - you can now do this with HTML5 without JavaScript for browsers that support it:
<input type="text" autofocus>
You probably want to start with this and build onto it with JavaScript to provide a fallback for older browsers.
Solution:
ul {
font-size: 0;
}
ul li {
font-size: 14px;
display: inline-block;
}
You must set parent font size to 0
It is likely because they used a single function for escaping attributes and text nodes. &
doesn't do any harm so why complicate your code and make it more error-prone by having two escaping functions and having to pick between them?
In addition, if you run a HTML document with multiple <tbody>
tags through W3C's HTML Validator, with a HTML5 DOCTYPE, it will successfully validate.
In Opera 9.62, Mozilla 3.0.4, Safari 3.2 (for Windows) it helps, if you put some text or at least a whitespace within the same line as the input field.
<div style="line-height: 60px; height: 60px; border: 1px solid black;">
<input type="text" value="foo" />
</div>
(imagine an   after the input-statement)
IE 7 ignores every CSS hack I tried. I would recommend using padding for IE only. Should make it easier for you to position it correctly if it only has to work within one specific browser.
Give the DIV a specific with in percentage or pixels and center it using CSS margin property.
HTML
<div id="my-main-div"></div>
CSS
#my-main-div { margin: 0 auto; }
enjoy :)
"
is the correct way, the third of your tests:
<option value=""asd">test</option>
You can see this working below, or on jsFiddle.
alert($("option")[0].value);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value=""asd">Test</option>_x000D_
</select>
_x000D_
Alternatively, you can delimit the attribute value with single quotes:
<option value='"asd'>test</option>
Check out XML2 from http://www.ofb.net/~egnor/xml2/ which converts XML to a line-oriented format.
make these changes in your div's style
z-index:100;
some higher value makes sure that this element is above allposition:fixed;
this makes sure that even if scrolling is done, div lies on top and always visible
HTML Comments:
<!-- <div> This div will not show </div> -->
CSS Comments:
/* This style will not apply */
JavaScript Comments:
// This single line JavaScript code will not execute
OR
/*
The whole block of JavaScript code will not execute
*/
Chiming in a bit late here, but couldn't resist.
You're question is half-flawed. Let me explain:
The first half of your question, on image replacement, is a valid question, and my opinion is that for a logo, a simple image; an alt attribute; and CSS for its positioning are sufficient.
The second half of your question, on the "SEO value" of the H1 for a logo is the wrong approach to deciding on which elements to use for different types of content.
A logo isn't a primary heading, or even a heading at all, and using the H1 element to markup the logo on each page of your site will do (slightly) more harm than good for your rankings. Semantically, headings (H1 - H6) are appropriate for, well, just that: headings and subheadings for content.
In HTML5, more than one heading is allowed per page, but a logo isn't deserving of one of them. Your logo, which might be a fuzzy green widget and some text is in an image off to the side of the header for a reason - it's sort of a "stamp", not a hierarchical element to structure your content. The first (whether you use more depends on your heading hierarchy) H1 of each page of your site should headline its subject matter. The main primary heading of your index page might be 'The Best Source For Fuzzy Green Widgets in NYC'. The primary heading on another page might be 'Shipping Details for Our Fuzzy Widgets'. On another page, it may be 'About Bert's Fuzzy Widgets Inc.'. You get the idea.
Side note: As incredible as it sounds, don't look at the source of Google-owned web properties for examples of correct markup. This is a whole post unto itself.
To get the most "SEO value" out HTML and its elements, take a look at the HTML5 specs, and make make markup decisions based on (HTML) semantics and value to users before search engines, and you'll have better success with your SEO.
Using the Firefox Web Developer Toolbar (https://addons.mozilla.org/en-US/firefox/addon/60)
Just go to View Source -> View Generated Source
I use it all the time for the exact same thing.
From http://readableweb.com/mo-bulletproofer-font-face-css-syntax/
Now that web fonts are supported in Firefox 3.5 and 3.6, Internet Explorer, Safari, Opera 10.5, and Chrome, web authors face new questions: How do these implementations differ? What CSS techniques will accommodate all? Firefox developer John Daggett recently posted a little roundup about these issues and the workarounds that are being explored. In response to that post, and in response to, particularly, Paul Irish’s work, I came up with the following @font-face CSS syntax. It’s been tested in all of the above named browsers including IE 8, 7, and 6. So far, so good. The following is a test page that declares the free Droid font as a complete font-family with Regular, Italic, Bold, and Bold Italic. View source for details. Alert: Be aware that Readable Web has released it’s first @font-face related software utility for creating natively compressed EOT files quickly and easily. It has it’s own web site and, in addition to the utility itself, the download package contains helpful documentation, a test font, and an EOT test page. It’s called EOTFAST If you’re working with @font-face, it’s a must-have.
Here’s The Mo’ Bulletproofer Code:
@font-face{ /* for IE */
font-family:FishyFont;
src:url(fishy.eot);
}
@font-face { /* for non-IE */
font-family:FishyFont;
src:url(http://:/) format("No-IE-404"),url(fishy.ttf) format("truetype");
}
An HTML parser will treat everything between <script>
and </script>
as part of the script. Some implementations don't even need a correct closing tag; they stop script interpretation at ". </
", which is correct according to the specs
Update In HTML5, and with current browsers, that is not the case anymore.
So, in HTML, this is not possible:
<script>
var x = '</script>';
alert(x)
</script>
A CDATA
section has no effect at all. That's why you need to write
var x = '<' + '/script>'; // or
var x = '<\/script>';
or similar.
This also applies to XHTML files served as text/html
. (Since IE does not support XML content types, this is mostly true.)
In XML, different rules apply. Note that (non IE) browsers only use an XML parser if the XHMTL document is served with an XML content type.
To the XML parser, a script
tag is no better than any other tag. Particularly, a script node may contain non-text child nodes, triggered by "<
"; and a "&
" sign denotes a character entity.
So, in XHTML, this is not possible:
<script>
if (a<b && c<d) {
alert('Hooray');
}
</script>
To work around this, you can wrap the whole script in a CDATA
section. This tells the parser: 'In this section, don't treat "<
" and "&
" as control characters.' To prevent the JavaScript engine from interpreting the "<![CDATA[
" and "]]>
" marks, you can wrap them in comments.
If your script does not contain any "<
" or "&
", you don't need a CDATA
section anyway.
Why don't you just do this
<a href="yoururl.html"><div>...</div></a>
That should work fine and will prompt the "clickable item" cursor change, which the aforementioned solution will not do.
You could just give the first cell (therefore column) a width and have the rest default to auto
table {_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
td {_x000D_
border: 1px solid #000;_x000D_
width: 150px;_x000D_
}_x000D_
td+td {_x000D_
width: auto;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>150px</td>_x000D_
<td>equal</td>_x000D_
<td>equal</td>_x000D_
</tr>_x000D_
</table>
_x000D_
or alternatively the "proper way" to get column widths might be to use the col
element itself
table {_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
td {_x000D_
border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
width: 150px;_x000D_
}
_x000D_
<table>_x000D_
<col span="1" class="wide">_x000D_
<tr>_x000D_
<td>150px</td>_x000D_
<td>equal</td>_x000D_
<td>equal</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Just add margin: 0 auto;
to the inside div.
CDATA
has no meaning at all in HTML.
CDATA
is an XML construct which sets a tag's contents that is normally #PCDATA - parsed character data, to be instead taken as #CDATA, that is, non-parsed character data. It is only relevant and valid in XHTML.
It is used in script
tags to avoid parsing <
and &
. In HTML, this is not needed, because in HTML, script
is already #CDATA.
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
HTML structure
<div id="app">
<div class="box">
<div class="title">How to preview link with iframe and javascript?</div>
<div class="note"><small>Note: Click to every link on content below to preview</small></div>
<div id="content">
We'll first attach all the events to all the links for which we want to <a href="https://htmlcssdownload.com/">preview</a> with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.
</div>
<h3>Preview the link</h3>
<div id="result"></div>
</div>
We'll first attach all the events to all the links for which we want to preview with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.
<script type="text/javascript">
(()=>{
let content = document.getElementById('content');
let links = content.getElementsByTagName('a');
for (let index = 0; index < links.length; index++) {
const element = links[index];
element.addEventListener('click',(e)=>{
e.preventDefault();
openDemoLink(e.target.href);
})
}
function openDemoLink(link){
let div = document.createElement('div');
div.classList.add('preview_frame');
let frame = document.createElement('iframe');
frame.src = link;
let close = document.createElement('a');
close.classList.add('close-btn');
close.innerHTML = "Click here to close the example";
close.addEventListener('click', function(e){
div.remove();
})
div.appendChild(frame);
div.appendChild(close);
document.getElementById('result').appendChild(div);
}
})()
To see detail at How to live preview link
Just collapse the table borders and remove the borders from table cells (td
elements).
table {
border: 1px solid #CCC;
border-collapse: collapse;
}
td {
border: none;
}
Without explicitly setting border-collapse
cross-browser removal of table cell borders is not guaranteed.
This worked for me in Firefox and Chrome and IE8...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style type="text/css">
div.section:hover div.image, div.section:hover div.layer {
border: solid 1px red;
}
</style>
</head>
<body>
<div class="section">
<div class="image"><img src="myImage.jpg" /></div>
<div class="layer">Lorem Ipsum</div>
</div>
</body>
</html>
... you may want to test this with IE6 as well (I'm not sure if it'll work there).
The following will solve your problem:
td.last {
width: 1px;
white-space: nowrap;
}
And a more flexible solution is creating a .fitwidth
class and applying that to any columns you want to ensure their contents are fit on one line:
td.fitwidth {
width: 1px;
white-space: nowrap;
}
And then in your HTML:
<tr>
<td class="fitwidth">ID</td>
<td>Description</td>
<td class="fitwidth">Status</td>
<td>Notes</td>
</tr>
You must write
<img src="theSource" style="width:30px;height:30px;" />
Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.
It would be better to set up a 301 redirect. See the Google's Webmaster Tools article 301 redirects.
Typically one would use one (or more) image tags, maybe in combination with setting div background images in css to act as the submit button. The actual submit would be done in javascript on the click event.
A tutorial on the subject.
You want the first >
not preceded by a /
. Look here for details on how to do that. It's referred to as negative lookbehind.
However, a naïve implementation of that will end up matching <bar/></foo>
in this example document
<foo><bar/></foo>
Can you provide a little more information on the problem you're trying to solve? Are you iterating through tags programatically?
Well, I think you get to convert the powerpoint to flash first. PowerPoint is not a sharable format on Internet. Some tool like PowerPoint to Flash could be helpful for you.
This is an old question. CSS has evolved. There now is the vh
(viewport height) unit, also new layout options like flexbox
or CSS grid
to achieve classical designs in cleaner ways.
With CSS tables, you could wrap a div around the two you have there and use this css/html structure:
<style type="text/css">
.container { display:table; width:100%; height:100%; }
#div1 { display:table-row; height:50px; background-color:red; }
#div2 { display:table-row; background-color:blue; }
</style>
<div class="container">
<div id="div1"></div>
<div id="div2"></div>
</div>
Depends on what browsers support these display types, however. I don't think IE8 and below do. EDIT: Scratch that-- IE8 does support CSS tables.
jQuery
$('head').append( ... );
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
First you should create a div
with id='footer'
after your content
div and then simply do this.
Your HTML should look like this:
<html>
<body>
<div id="content">
...
</div>
<div id="footer"></div>
</body>
</html>
And the CSS:
?html, body {
height: 100%;
}
#content {
height: 100%;
}
#footer {
clear: both;
}
...
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:local="urn:local" extension-element-prefixes="msxsl">
<msxsl:script language="CSharp" implements-prefix="local">
public string dateTimeNow()
{
return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
</msxsl:script>
...
<xsl:value-of select="local:dateTimeNow()"/>
Not sure if this is valid but it worked for me.
The code :
<div style='position:relative;background-color:#000000;width:600px;height:30px;border:solid;'>_x000D_
<p style='display:inline;color:#ffffff;float:left;'> Whatever </p> _x000D_
<a style='position:absolute;top:0px;left:0px;width:100%;height:100%;display:inline;' href ='#'></a>_x000D_
</div>
_x000D_
<div style="text-align: center; border-top: 1px solid black">
<div style="display: inline-block; position: relative; top: -10px; background-color: white; padding: 0px 10px">text</div>
</div>
While I agree tables shouldn't be used for design layouts contrary to popular belief they do pass validation. i.e. the table tag is not deprecated. The best way to align radio buttons is using the vertical align middle CSS with margins adjusted on the input elements.
If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.
try this.
$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');
I found a way to do it with plain old HTML and JavaScript/jQuery that degrades gracefully. Tested in IE7-10, Safari, Chrome, and FF:
HTML for download link:
<p>Thanks for downloading! If your download doesn't start shortly,
<a id="downloadLink" href="...yourpdf.pdf" target="_blank"
type="application/octet-stream" download="yourpdf.pdf">click here</a>.</p>
jQuery (pure JavaScript code would be more verbose) that simulates clicking on link after a small delay:
var delay = 3000;
window.setTimeout(function(){$('#downloadLink')[0].click();},delay);
To make this more robust you could add HTML5 feature detection and if it's not there then use window.open()
to open a new window with the file.
Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.
You should be using HTML5 doctype, then you don't need it for text/html. Better start from template like this :
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>domcument title</title>
<link rel="stylesheet" href="/stylesheet.css" type="text/css" />
</head>
<body>
<!-- your html content -->
<script src="/script.js"></script>
</body>
</html>
When you have put your Doctype straight - do and validate you html and your css .
That usually will sove you layout issues.
My understanding has always been:
ID's are single use and are only applied to one element...
Classes can be used more than once...
The parser is expecting some HTML content, so it sees &
as the beginning of an entity, like è
.
Use this workaround:
<script type="text/javascript">
// <![CDATA[
Javascript code here
// ]]>
</script>
so you specify that the code is not HTML text but just data to be used as is.
I created jquery.backgroundSize.js: a 1.5K jquery plugin that can be used as a IE8 fallback for "cover" and "contain" values. Have a look at the demo.
Solving your problem could be as simple as:
$("h2#news").css({backgroundSize: "cover"});
Coming very late to the party, I found that ✓
(✓) worked in Opera. I haven't tested it on any other browsers, but it might be useful for some people.
You can't. Your only option is to divide this into multiple tables and put the form tag outside of it. You could end up nesting your tables, but this is not recommended:
<table>
<tr><td><form>
<table><tr><td>id</td><td>name</td>...</tr></table>
</form></td></tr>
</table>
I would remove the tables entirely and replace it with styled html elements like divs and spans.
why do that to yourself?
jQuery:
$("#element").fadeOut();
$("#element").fadeIn();
I think that's easier.
I had a git conflict left in my workspace.xml i.e.
<<<<———————HEAD
which caused the unknown tag error. It is a bit annoying that it doesn’t name the file.
Or you can use relative units, e.g.
#thing {
position: absolute;
width: 50vw;
right: 25vw;
}
Another way:
li:before {
content: '\2014\00a0\00a0'; /* em-dash followed by two non-breaking spaces*/
}
li {
list-style: none;
text-indent: -1.5em;
padding-left: 1.5em;
}
I like to make use of the css :before
and a data-*
attribute for the list
HTML:
<ul data-header="heading">
<li>list item </li>
<li>list item </li>
<li>list item </li>
</ul>
CSS:
ul:before{
content:attr(data-header);
font-size:120%;
font-weight:bold;
margin-left:-15px;
}
This will make a list with the header on it that is whatever text is specified as the list's data-header
attribute. You can then easily style it to your needs.
From http://pmob.co.uk/pob/centred-float.htm:
The premise is simple and basically just involves a widthless float wrapper that is floated to the left and then shifted off screen to the left width position:relative; left:-50%. Next the nested inner element is reversed and a relative position of +50% is applied. This has the effect of placing the element dead in the center. Relative positioning maintains the flow and allows other content to flow underneath.
#buttons{
float:right;
position:relative;
left:-50%;
text-align:left;
}
#buttons ul{
list-style:none;
position:relative;
left:50%;
}
#buttons li{float:left;position:relative;}/* ie needs position:relative here*/
#buttons a{
text-decoration:none;
margin:10px;
background:red;
float:left;
border:2px outset blue;
color:#fff;
padding:2px 5px;
text-align:center;
white-space:nowrap;
}
#buttons a:hover{ border:2px inset blue;color:red;background:#f2f2f2;}
#content{overflow:hidden}/* hide horizontal scrollbar*/
_x000D_
<div id="buttons">
<ul>
<li><a href="#">Button 1</a></li>
<li><a href="#">Button 2's a bit longer</a></li>
<li><a href="#">Butt 3</a></li>
<li><a href="#">Button 4</a></li>
</ul>
</div>
_x000D_
Should be something similar to:
//a[text()='text_i_want_to_find']/@href
Included page:
<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>
Including page:
<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
ui:composition
as shown above.ui:include
in the including xhtml file as also shown above.Cleaner way to remove those spaces is by using float: left;
:
HTML:
<div>Some Text</div>
<div>Some Text</div>
CSS:
div {
background-color: red;
float: left;
}
I'ts supported in all new browsers. Never got it why back when IE ruled lot's of developers didn't make sue their site works well on firefox/chrome, but today, when IE is down to 14.3 %. anyways, didn't have many issues in IE-9 even thought it's not supported, for example the above demo works fine.
Answer is YES
<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>
<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>
</form>
</body>
</html>
As an addendum: Before HTML 5 while a div inside a li is valid, a div inside a dl, dd, or dt is not!
There is no good way to store an array into a single field.
You need to examine your relational data and make the appropriate changes to your schema. See example below for a reference to this approach.
If you must save the array into a single field then the serialize()
and unserialize()
functions will do the trick. But you cannot perform queries on the actual content.
As an alternative to the serialization function there is also json_encode()
and json_decode()
.
Consider the following array
$a = array(
1 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
2 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
);
To save it in the database you need to create a table like this
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
$r = mysql_query(
'DROP TABLE IF EXISTS test');
$r = mysql_query(
'CREATE TABLE test (
id INTEGER UNSIGNED NOT NULL,
a INTEGER UNSIGNED NOT NULL,
b INTEGER UNSIGNED NOT NULL,
c INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (id)
)');
To work with the records you can perform queries such as these (and yes this is an example, beware!)
function getTest() {
$ret = array();
$c = connect();
$query = 'SELECT * FROM test';
$r = mysql_query($query,$c);
while ($o = mysql_fetch_array($r,MYSQL_ASSOC)) {
$ret[array_shift($o)] = $o;
}
mysql_close($c);
return $ret;
}
function putTest($t) {
$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (id,".
implode(',',array_keys($v)).
") VALUES ($k,".
implode(',',$v).
")";
$r = mysql_query($query,$c);
}
mysql_close($c);
}
putTest($a);
$b = getTest();
The connect()
function returns a mysql connection resource
function connect() {
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
return $c;
}
Yes, it is case-sensitive. You can do a case-insensitive indexOf
by converting your String and the String parameter both to upper-case before searching.
String str = "Hello world";
String search = "hello";
str.toUpperCase().indexOf(search.toUpperCase());
Note that toUpperCase may not work in some circumstances. For instance this:
String str = "Feldbergstraße 23, Mainz";
String find = "mainz";
int idxU = str.toUpperCase().indexOf (find.toUpperCase ());
int idxL = str.toLowerCase().indexOf (find.toLowerCase ());
idxU will be 20, which is wrong! idxL will be 19, which is correct. What's causing the problem is tha toUpperCase() converts the "ß" character into TWO characters, "SS" and this throws the index off.
Consequently, always stick with toLowerCase()
I had the same problem while I was testing a project and it turned that running Fiddler was the cause for this error..!!
If you are using Fiddler to intercept the http request, shut it down ...
This is one of the many causes for such error.
To fix Fiddler you may need to Reset Fiddler Https Certificates.
Sure you could write that:
public static class Utils {
public static bool IsAny<T>(this IEnumerable<T> data) {
return data != null && data.Any();
}
}
however, be cautious that not all sequences are repeatable; generally I prefer to only walk them once, just in case.
<script>
function show() {
if(document.getElementById('benefits').style.display=='none') {
document.getElementById('benefits').style.display='block';
}
return false;
}
function hide() {
if(document.getElementById('benefits').style.display=='block') {
document.getElementById('benefits').style.display='none';
}
return false;
}
</script>
<div id="opener"><a href="#1" name="1" onclick="return show();">click here</a></div>
<div id="benefits" style="display:none;">some input in here plus the close button
<div id="upbutton"><a onclick="return hide();">click here</a></div>
</div>
Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"
Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.
If System.IO.File.Exists(SavePath) Then
'The file exists
Else
'the file doesn't exist
End If
Copy the contents of the PATH settings to a notepad and check if the location for the 1.4.2 comes before that of the 7. If so, remove the path to 1.4.2 in the PATH setting and save it.
After saving and applying "Environment Variables" close and reopen the cmd line. In XP the path does no get reflected in already running programs.
Try
ThisWorkbook.Sheets("name of sheet 2").Range("A1")
to access a range in sheet 2 independently of where your code is or which sheet is currently active. To make sheet 2 the active sheet, try
ThisWorkbook.Sheets("name of sheet 2").Activate
If you just need the sum of a row in a different sheet, there is no need for using VBA at all. Enter a formula like this in sheet 1:
=SUM([Name-Of-Sheet2]!A1:D1)
Try fixing the capitalization. onclick
instead of onClick
Reference: Mozilla Developer Docs
Furthermore: the textarea tag shows spaces for new lines, tabs, etc, in multiline code.
for people new to this you can also use a callback for example:
In your service:
.factory('DataHandler',function ($http){
var GetRandomArtists = function(data, callback){
$http.post(URL, data).success(function (response) {
callback(response);
});
}
})
In your controller:
DataHandler.GetRandomArtists(3, function(response){
$scope.data.random_artists = response;
});
To support IE11 with auto-placement, I converted grid
to table
layout every time I used the grid layout in 1 dimension only. I also used margin
instead of grid-gap
.
The result is the same, see how you can do it here https://jsfiddle.net/hp95z6v1/3/
df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <- letters[1:10]
df[c('a','b'),]
add {3,5}
to your expression which means length between 3 to 5
/^([a-zA-Z0-9_-]){3,5}$/
Question#1 - These are the only way to handle view clicks.
Question#2 -
Option#1/Option#4 - There's not much difference between option#1 and option#4. The only difference I see is in one case activity is implementing the OnClickListener, whereas, in the other case, there'd be an anonymous implementation.
Option#2 - In this method an anonymous class will be generated. This method is a bit cumborsome, as, you'd need to do it multiple times, if you have multiple buttons. For Anonymous classes, you have to be careful for handling memory leaks.
Option#3 - Though, this is a easy way. Usually, Programmers try not to use any method until they write it, and hence this method is not widely used. You'd see mostly people use Option#4. Because it is cleaner in term of code.
You can instead use the mysqlclient
package as a drop-in replacement for MySQL-python. It is a fork of MySQL-python
with added support for Python 3.
I had luck with simply
pip install mysqlclient
in my python3.4 virtualenv after
sudo apt-get install python3-dev libmysqlclient-dev
which is obviously specific to ubuntu/debian, but I just wanted to share my success :)
Using SQL SERVER 2005, you can try
SELECT i.name AS IndexName,
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i INNER JOIN
sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
Found at SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database
$(document).ready(function() {
$("input:text").focus(function() { $(this).select(); } );
});
If the images are generated via an ASP Response.Write()
, make sure you don't call Response.Close();
. Chrome doesn't like it.
Use .closest()
, which gets the first ancestor element that matches the given selector 'div'
:
var classes = $(this).closest('div').attr('class').split(' ');
EDIT:
As @Shef noted, .closest()
will return the current element if it happens to be a DIV also. To take that into account, use .parent()
first:
var classes = $(this).parent().closest('div').attr('class').split(' ');
Delete lines from all files that match the match
grep -rl 'text_to_search' . | xargs sed -i '/text_to_search/d'
To select the sibling, you'd need something like:
$(this).next();
So, Shog9's comment is not correct. First of all, you'd need to name the variable "clicked" outside of the div click function, otherwise, it is lost after the click occurs.
var clicked;
$("div a").click(function(){
clicked = $(this).next();
// Do what you need to do to the newly defined click here
});
// But you can also access the "clicked" element here
This is possible in HTML5. Example (PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
Here's what it looks like in Chrome after selecting 2 items in the file dialog:
And here's what it looks like after clicking the "Upload" button.
This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.
With jQuery (and without FormData API) you can use something like this:
function readFile(file){
var loader = new FileReader();
var def = $.Deferred(), promise = def.promise();
//--- provide classic deferred interface
loader.onload = function (e) { def.resolve(e.target.result); };
loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
loader.onerror = loader.onabort = function (e) { def.reject(e); };
promise.abort = function () { return loader.abort.apply(loader, arguments); };
loader.readAsBinaryString(file);
return promise;
}
function upload(url, data){
var def = $.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = $.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });
promise.abort = function(){ return req.abort.apply(req, arguments); }
return promise;
}
var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}
for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}
return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};
//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, $file[0].files[0].name];
upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});
With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})
Syntax:
$(selector).text()
content
: $(selector).text(content)
$(selector).text(function(index, curContent))
I'm using pandas 0.16.2. This has better performance on my large dataset:
data.groupby(data.date.dt.year)
Using the dt
option and playing around with weekofyear
, dayofweek
etc. becomes far easier.
In regards to testing if a module you are utilizing is secure or not there are several routes you can take. I will touch on the pros/cons of each so you can make a more informed decision.
Currently, there aren't any vulnerabilities for the module you are utilizing, however, this can often lead to a false sense of security as there very well could be a vulnerability currently exploiting the module/software package you are using and you wouldn't be alerted to a problem until the vendor applies a fix/patch.
To keep abreast of vulnerabilities you will need to follow mailing lists, forums, IRC & other hacking related discussions. PRO: You can often times you will become aware of potential problems within a library before a vendor has been alerted or has issued a fix/patch to remedy the potential avenue of attack on their software. CON: This can be very time consuming and resource intensive. If you do go this route a bot using RSS feeds, log parsing (IRC chat logs) and or a web scrapper using key phrases (in this case node-mysql-native) and notifications can help reduce time spent trolling these resources.
Create a fuzzer, use a fuzzer or other vulnerability framework such as metasploit, sqlMap etc. to help test for problems that the vendor may not have looked for. PRO: This can prove to be a sure fire method of ensuring to an acceptable level whether or not the module/software you are implementing is safe for public access. CON: This also becomes time consuming and costly. The other problem will stem from false positives as well as uneducated review of the results where a problem resides but is not noticed.
Really security, and application security in general can be very time consuming and resource intensive. One thing managers will always use is a formula to determine the cost effectiveness (manpower, resources, time, pay etc) of performing the above two options.
Anyways, I realize this is not a 'yes' or 'no' answer that may have been hoping for but I don't think anyone can give that to you until they perform an analysis of the software in question.
I created a little javascript tool to style elements on screen size without using media queries or recompiling bootstrap css:
https://github.com/Heras/Responsive-Breakpoints
Just add class responsive-breakpoints
to any element, and it will automagically add xs sm md lg xl
classes to those elements.
var date = new Date('2012.08.10');
var unixTimeStamp = Math.floor(date.getTime() / 1000);
In this case it's important to return only a whole number (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses Math.floor()
and not Math.round()
).
Since 9.6 this is a lot easier as it introduced the function pg_blocking_pids()
to find the sessions that are blocking another session.
So you can use something like this:
select pid,
usename,
pg_blocking_pids(pid) as blocked_by,
query as blocked_query
from pg_stat_activity
where cardinality(pg_blocking_pids(pid)) > 0;
I had the exact same problem yesterday working through problem 2-3 in Accelerated C++. The key is to change all variables you will be comparing (using Boolean operators) to compatible types. In this case, that means string::size_type
(or unsigned int
, but since this example is using the former, I will just stick with that even though the two are technically compatible).
Notice that in their original code they did exactly this for the c counter (page 30 in Section 2.5 of the book), as you rightly pointed out.
What makes this example more complicated is that the different padding variables (padsides and padtopbottom), as well as all counters, must also be changed to string::size_type
.
Getting to your example, the code that you posted would end up looking like this:
cout << "Please enter the size of the frame between top and bottom";
string::size_type padtopbottom;
cin >> padtopbottom;
cout << "Please enter size of the frame from each side you would like: ";
string::size_type padsides;
cin >> padsides;
string::size_type c = 0; // definition of c in the program
if (r == padtopbottom + 1 && c == padsides + 1) { // where the error no longer occurs
Notice that in the previous conditional, you would get the error if you didn't initialize variable r as a string::size_type
in the for
loop. So you need to initialize the for loop using something like:
for (string::size_type r=0; r!=rows; ++r) //If r and rows are string::size_type, no error!
So, basically, once you introduce a string::size_type
variable into the mix, any time you want to perform a boolean operation on that item, all operands must have a compatible type for it to compile without warnings.
I was able to resolve the problem by following steps: a. upgrade to the latest chrome version, clear the cache and close the chrome browser b. Download latest Selenium 3.0
It must be at least 64 bits. Other than that it's implementation defined.
Strictly speaking, unsigned long long
isn't standard in C++ until the C++0x standard. unsigned long long
is a 'simple-type-specifier' for the type unsigned long long int
(so they're synonyms).
The long long
set of types is also in C99 and was a common extension to C++ compilers even before being standardized.
I write it like this:
var max_int = 0x20000000000000;
var min_int = -0x20000000000000;
(max_int + 1) === 0x20000000000000; //true
(max_int - 1) < 0x20000000000000; //true
Same for int32
var max_int32 = 0x80000000;
var min_int32 = -0x80000000;
I had the same problem. However, nothing worked for me. I solved the issue by adding
exit 0
to my code. The problem was that while I was doing copying of the files, sometimes the last file could not be found, and the bat returned a non-zero value.
Hope this helps someone!
I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.
<ul ng-repeat="vote in votes" ...>
<li data-choice="selected" data-value="vote.id">...</li>
</ul>
You can simply add this class.
.btn {
white-space:normal !important;
word-wrap: break-word;
}
The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,
In Angular 6, you can do this:
In your service file:
function_name(data) {
const url = `the_URL`;
let input = new FormData();
input.append('url', data); // "url" as the key and "data" as value
return this.http.post(url, input).pipe(map((resp: any) => resp));
}
In component.ts file: in any function say xyz,
xyz(){
this.Your_service_alias.function_name(data).subscribe(d => { // "data" can be your file or image in base64 or other encoding
console.log(d);
});
}
#define MULTILINE(...) #__VA_ARGS__
Consumes everything between the parentheses.
Replaces any number of consecutive whitespace characters by a single space.
Random string, every run file = different string
auto randchar = []() -> char
{
const char charset[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
const size_t max_index = (sizeof(charset) - 1);
return charset[randomGenerator(0, max_index)];
};
std::string custom_string;
size_t LENGTH_NAME = 6 // length of name
generate_n(custom_string.begin(), LENGTH_NAME, randchar);
If you are using Windows, follow this:
When you pass a pointer by a non-const
reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.
To fix this error, either declare x
constant
// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
*x = 1000;
}
or make a variable to which you assign a pointer to nKByte
before calling test
:
float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);
For Simple Direct Media Layer 2 (SDL2), after installing it on Ubuntu 16.04 via:
sudo apt-get install libsdl2-dev
I used the header:
#include <SDL2/SDL.h>
and the compiler linker command:
-lSDL2main -lSDL2
Additionally, you may also want to install:
apt-get install libsdl2-image-dev
apt-get install libsdl2-mixer-dev
apt-get install libsdl2-ttf-dev
With these headers:
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>
and the compiler linker commands:
-lSDL2_image
-lSDL2_ttf
-lSDL2_mixer
def expiration_time():
import datetime,calendar
timestamp = calendar.timegm(datetime.datetime.now().timetuple())
returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
return returnValue
I found that putting this section in my web.config for each view folder solved it.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
UPDATE mytbl
SET a = ABS(a)
where a < 0
Underscore js solution
let samplLst = [{id:1,title:Lorem},{id:2,title:Ipsum}]
let sampleKey = _.findLastIndex(samplLst,{_id:2});
//result would be 1
console.log(samplLst[sampleKey])
//output - {id:2,title:Ipsum}
pyspark.sql.Column.contains()
is only available in pyspark version 2.2 and above.
df.where(df.location.contains('google.com'))
The #include
directive literally means "copy all the data in that file to this spot." So when you include the header file, it's textually within the code file, and everything in it will be there, give or take the effect of other directives or macro replacements, when the code file (now called the compilation unit or translation unit) is handed off from the preprocessor module to the compiler module.
Which means the declaration and definition of your static member function were really in the same file all along...
Well, technically speaking we can pass a parameter to a computed function, the same way we can pass a parameter to a getter function in vuex. Such a function is a function that returns a function.
For instance, in the getters of a store:
{
itemById: function(state) {
return (id) => state.itemPool[id];
}
}
This getter can be mapped to the computed functions of a component:
computed: {
...mapGetters([
'ids',
'itemById'
])
}
And we can use this computed function in our template as follows:
<div v-for="id in ids" :key="id">{{itemById(id).description}}</div>
We can apply the same approach to create a computed method that takes a parameter.
computed: {
...mapGetters([
'ids',
'itemById'
]),
descriptionById: function() {
return (id) => this.itemById(id).description;
}
}
And use it in our template:
<div v-for="id in ids" :key="id">{{descriptionById(id)}}</div>
This being said, I'm not saying here that it's the right way of doing things with Vue.
However, I could observe that when the item with the specified ID is mutated in the store, the view does refresh its contents automatically with the new properties of this item (the binding seems to be working just fine).
While waiting for the adoption of CSS3 targeting by the major browsers, one could run the following sed
command once the (X)HTML has been created:
sed -i 's|href="http|target="_blank" href="http|g' index.html
It will add target="_blank"
to all external hyperlinks. Variations are also possible.
EDIT
I use this at the end of the makefile
which generates every web page on my site.
You should probably set the property dt.Columns["columnName"].ReadOnly = false;
before.
Very good answer, I have created a Golang implementation of the bjf:
package bjf
import (
"math"
"strings"
"strconv"
)
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func Encode(num string) string {
n, _ := strconv.ParseUint(num, 10, 64)
t := make([]byte, 0)
/* Special case */
if n == 0 {
return string(alphabet[0])
}
/* Map */
for n > 0 {
r := n % uint64(len(alphabet))
t = append(t, alphabet[r])
n = n / uint64(len(alphabet))
}
/* Reverse */
for i, j := 0, len(t) - 1; i < j; i, j = i + 1, j - 1 {
t[i], t[j] = t[j], t[i]
}
return string(t)
}
func Decode(token string) int {
r := int(0)
p := float64(len(token)) - 1
for i := 0; i < len(token); i++ {
r += strings.Index(alphabet, string(token[i])) * int(math.Pow(float64(len(alphabet)), p))
p--
}
return r
}
Hosted at github: https://github.com/xor-gate/go-bjf
If you are using Table.query
property:
from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()
If you are using session.query()
method (as stated in miniwark's answer):
from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()
you need to increase virtual memory of emulator
How to increase virtual memory of emulator
emulator -avd "Emulator Name" -partition-size 2024
after then try to install your apk
I've developed jmxfuse which exposes JMX Mbeans as a Linux FUSE filesystem with similar functionality as the /proc fs. It relies on Jolokia as the bridge to JMX. Attributes and operations are exposed for reading and writing.
http://code.google.com/p/jmxfuse/
For example, to read an attribute:
me@oddjob:jmx$ cd log4j/root/attributes
me@oddjob:jmx$ cat priority
to write an attribute:
me@oddjob:jmx$ echo "WARN" > priority
to invoke an operation:
me@oddjob:jmx$ cd Catalina/none/none/WebModule/localhost/helloworld/operations/addParameter
me@oddjob:jmx$ echo "myParam myValue" > invoke
I know it's very late for this one... But here is a (not so simple) oneliner to get what you were looking for:
git show-branch --all 2>/dev/null | grep -E "\[$(git branch | grep -E '^\*' | awk '{ printf $2 }')" | tail -n+2 | sed -E "s/^[^\[]*?\[/[/"
git show-branch
(sending the warnings to /dev/null
).grep -E "\[$BRANCH_NAME"
.$BRANCH_NAME
is obtained with git branch | grep -E '^\*' | awk '{ printf $2 }'
(the branch with a star, echoed without that star).tail -n+2
.[$BRANCH_NAME]
with sed -E "s/^[^\[]*?\[/[/"
.This has been fully answered here.
See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:
WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'
Here is a good discussion on the topic. Gavin King recommends @Inject over @EJB for non remote EJBs.
http://www.seamframework.org/107780.lace
or
https://web.archive.org/web/20140812065624/http://www.seamframework.org/107780.lace
Re: Injecting with @EJB or @Inject?
- Nov 2009, 20:48 America/New_York | Link Gavin King
That error is very strange, since EJB local references should always be serializable. Bug in glassfish, perhaps?
Basically, @Inject is always better, since:
it is more typesafe, it supports @Alternatives, and it is aware of the scope of the injected object.
I recommend against the use of @EJB except for declaring references to remote EJBs.
and
Re: Injecting with @EJB or @Inject?
Nov 2009, 17:42 America/New_York | Link Gavin King
Does it mean @EJB better with remote EJBs?
For a remote EJB, we can't declare metadata like qualifiers, @Alternative, etc, on the bean class, since the client simply isn't going to have access to that metadata. Furthermore, some additional metadata must be specified that we don't need for the local case (global JNDI name of whatever). So all that stuff needs to go somewhere else: namely the @Produces declaration.
157/32 is int/int
, which results in an int
.
Try using the double literal - 157/32d
, which is int/double
, which results in a double
.
if you do not have any database in your application simply disable the auto-config of datasource by adding below annotation.
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
Simply run set
from cmd
.
Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings.
Please note the fact that: n&(n-1) always eliminates the least significant 1.
Hence we can write the code for calculating the number of 1's as follows:
count=0;
while(n!=0){
n = n&(n-1);
count++;
}
cout<<"Number of 1's in n is: "<<count;
The complexity of the program would be: number of 1's in n (which is constantly < 32).
It sounds like you answered your own question. get_class
will get you the class name. It is procedural and maybe that is what is causing the confusion. Take a look at the php documentation for get_class
Here is their example:
<?php
class foo
{
function name()
{
echo "My name is " , get_class($this) , "\n";
}
}
// create an object
$bar = new foo();
// external call
echo "Its name is " , get_class($bar) , "\n"; // It's name is foo
// internal call
$bar->name(); // My name is foo
To make it more like your example you could do something like:
<?php
class MyClass
{
public static function getClass()
{
return get_class();
}
}
Now you can do:
$className = MyClass::getClass();
This is somewhat limited, however, because if my class is extended it will still return 'MyClass'. We can use get_called_class
instead, which relies on Late Static Binding, a relatively new feature, and requires PHP >= 5.3.
<?php
class MyClass
{
public static function getClass()
{
return get_called_class();
}
public static function getDefiningClass()
{
return get_class();
}
}
class MyExtendedClass extends MyClass {}
$className = MyClass::getClass(); // 'MyClass'
$className = MyExtendedClass::getClass(); // 'MyExtendedClass'
$className = MyExtendedClass::getDefiningClass(); // 'MyClass'
We use object-scan for a lot of data processing. It has some nice properties, especially traversing in delete safe order. Here is how one could implement find, delete and replace for your question.
// const objectScan = require('object-scan');
const tool = (() => {
const scanner = objectScan(['[*]'], {
abort: true,
rtn: 'bool',
filterFn: ({
value, parent, property, context
}) => {
if (value.id === context.id) {
context.fn({ value, parent, property });
return true;
}
return false;
}
});
return {
add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
mod: (data, id, prop, v = undefined) => scanner(data, {
id,
fn: ({ value }) => {
if (value !== undefined) {
value[prop] = v;
} else {
delete value[prop];
}
}
})
};
})();
// -------------------------------
const data = [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ];
const toAdd = { id: 'two', pId: 'foo2', cId: 'bar2' };
const exec = (fn) => {
console.log('---------------');
console.log(fn.toString());
console.log(fn());
console.log(data);
};
exec(() => tool.add(data, 'one', toAdd));
exec(() => tool.mod(data, 'one', 'pId', 'zzz'));
exec(() => tool.mod(data, 'one', 'other', 'test'));
exec(() => tool.mod(data, 'one', 'gone', 'delete me'));
exec(() => tool.mod(data, 'one', 'gone'));
exec(() => tool.del(data, 'three'));
// => ---------------
// => () => tool.add(data, 'one', toAdd)
// => true
// => [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'pId', 'zzz')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'other', 'test')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone', 'delete me')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: 'delete me' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.del(data, 'three')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
Use rsync:
rsync -av --exclude='path1/to/exclude' --exclude='path2/to/exclude' source destination
Note that using source
and source/
are different. A trailing slash means to copy the contents of the folder source
into destination
. Without the trailing slash, it means copy the folder source
into destination
.
Alternatively, if you have lots of directories (or files) to exclude, you can use --exclude-from=FILE
, where FILE
is the name of a file containing files or directories to exclude.
--exclude
may also contain wildcards, such as --exclude=*/.svn*
To achieve your current need, you need to fire below query
> insert overwrite table student
> select *from student
> where id <> 1;
This will delete current table and create new table with same name with all rows except the rows that you want to exclude/delete
I tried this on Hive 1.2.1
I made all this similar tweaks, but from time to time I was getting 501/502 errors (daily).
This are my settings on /etc/php5/fpm/pool.d/www.conf to avoid 501 and 502 nginx errors… The server has 16Gb RAM. This configuration is for a 8Gb RAM server so…
sudo nano /etc/php5/fpm/pool.d/www.conf
then set the following values for
pm.max_children = 70
pm.start_servers = 20
pm.min_spare_servers = 20
pm.max_spare_servers = 35
pm.max_requests = 500
After this changes restart php-fpm
sudo service php-fpm restart
Using dplyr provides an easy syntax for sorting the data frames
library(dplyr)
mtcars %>% arrange(gear, desc(mpg))
It might be useful to use the NSE version as shown here to allow dynamically building the sort list
sort_list <- c("gear", "desc(mpg)")
mtcars %>% arrange_(.dots = sort_list)
You can kill two birds with one regex stone:
>>> r = """
... \n\tName: John Smith
... \n\t Home: Anytown USA
... \n\t Phone: 555-555-555
... \n\t Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t Misc: Data with spaces
... """
>>> import re
>>> print re.findall(r'(\S[^:]+):\s*(.*\S)', r)
[('Name', 'John Smith'), ('Home', 'Anytown USA'), ('Phone', '555-555-555'), ('Other Home', 'Somewhere Else'), ('Notes', 'Other data'), ('Name', 'Jane Smith'), ('Misc', 'Data with spaces')]
>>>
Pitfall:
<my-directive></my-directive>
wont work on IE8 without workaround (https://docs.angularjs.org/guide/ie)<div data-my-directive="ValueOfTheFirstParameter"></div>
Instead of this:
<my-directive my-param="ValueOfTheFirstParameter"></my-directive>
We dont use custom html elements, because if this 2 facts.
Every directive by third party framework can be written in two ways:
<my-directive></my-directive>
or
<div data-my-directive></div>
does the same.
There is, however, no guarantee that the output of SDTOUT
and STDERR
are interweaved line-by-line in timely order, using the POSIX
redirect merge syntax.
If an application uses buffered output, it may happen that the text of one stream is inserted in the other at a buffer boundary, which may appear in the middle of a text line.
A dedicated console output logger (I.e. the "StdOut/StdErr Logger"
by 'LoRd MuldeR'
) may be more reliable for such a task.
Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
@Override
public void afterTextChanged(Editable arg0) {}
});
The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.
EDIT
To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.
class CustomAdapter extends BaseAdapter implements Filterable {
public View getView(){
...
}
public Integer getCount()
{
...
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListNames = (List<String>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mDatabaseOfNames.size(); i++) {
String dataNames = mDatabaseOfNames.get(i);
if (dataNames.toLowerCase().startsWith(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
Log.e("VALUES", results.values.toString());
return results;
}
};
return filter;
}
}
Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.
AngularJS provides a simple and concise way to associate routes with controllers and templates using a $routeProvider
object. While recently updating an application to the latest release (1.2 RC1 at the current time) I realized that $routeProvider
isn’t available in the standard angular.js script any longer.
After reading through the change log I realized that routing is now a separate module (a great move I think) as well as animation and a few others. As a result, standard module definitions and config code like the following won’t work any longer if you’re moving to the 1.2 (or future) release:
var app = angular.module('customersApp', []);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
controller: 'customersController',
templateUrl: '/app/views/customers.html'
});
});
How do you fix it?
Simply add angular-route.js in addition to angular.js to your page (grab a version of angular-route.js here – keep in mind it’s currently a release candidate version which will be updated) and change the module definition to look like the following:
var app = angular.module('customersApp', ['ngRoute']);
If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate module:
var app = angular.module('customersApp', ['ngRoute', 'ngAnimate']);
Your Code can be as follows:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/controllerone', {
controller: 'friendDetails',
templateUrl: 'controller3.html'
}, {
controller: 'friendsName',
templateUrl: 'controller3.html'
}
)
.when('/controllerTwo', {
controller: 'simpleControoller',
templateUrl: 'views.html'
})
.when('/controllerThree', {
controller: 'simpleControoller',
templateUrl: 'view2.html'
})
.otherwise({
redirectTo: '/'
});
});
No,but you can do like this
In html file add this section
<div class="arrow">
</div>
In css you can do like this
p div.arrow {
content: '';
position: absolute;
left:100%;
width: 10px;
height: 100%;
background-color: red;
}
Hope it will help you
**This is a simple way of getting the DAYS between two dates**
var d1 = moment($("#StartDate").data("DateTimePicker").date());
var d2 = moment($("#EndDate").data("DateTimePicker").date());
var diffInDays = d2.diff(d1, 'days');
if (diffInDays > 0)
{
$("#Total").val(diffInDays);
}
else
{
$("#Total").val(0);
}
I got this error because I replaced URL address with new one ending up with "/". I mean record in wc.db database in .svn folder in REPOSITORY table.
When I removed sign: "/" then the error went away.
The easiest way to fix this was to press (CTRL) and (,) in VS Code to open Settings.
After that, on the search bar search for code runner, then scroll down and search for Run In Terminal and check that box as highlighted in the below image:
When FIND
returns #VALUE!
, it is an error, not a string, so you can't compare FIND(...)
with "#VALUE!"
, you need to check if FIND
returns an error with ISERROR
. Also FIND
can work on multiple characters.
So a simplified and working version of your formula would be:
=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))
Or, to remove the double negations:
=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")
UTC dates don't need any timezone info since they're UTC, which by definition means that they have no offset.
This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.
Why don't you just use a singleton?
import android.content.Context;
public class ClassicSingleton {
private Context c=null;
private static ClassicSingleton instance = null;
protected ClassicSingleton()
{
// Exists only to defeat instantiation.
}
public void setContext(Context ctx)
{
c=ctx;
}
public Context getContext()
{
return c;
}
public static ClassicSingleton getInstance()
{
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Then in the activity class:
private ClassicSingleton cs = ClassicSingleton.getInstance();
And in the non activity class:
ClassicSingleton cs= ClassicSingleton.getInstance();
Context c=cs.getContext();
ImageView imageView = (ImageView) ((Activity)c).findViewById(R.id.imageView1);
Change your meta tag to the one below and use placeholder attribute inside your HTML input tag.
<meta http-equiv="X-UA-Compatible" content="IE=edge" />_x000D_
<input type="text" placeholder="Placeholder text" />?
_x000D_
ThomasH has already added a good answer, but I want to show what happens:
>>> a = [[1, 2], [3, 4]]
>>> [x for x in b for b in a]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> [x for b in a for x in b]
[1, 2, 3, 4]
>>> [x for x in b for b in a]
[3, 3, 4, 4]
I guess Python parses the list comprehension from left to right. This means, the first for
loop that occurs will be executed first.
The second "problem" of this is that b
gets "leaked" out of the list comprehension. After the first successful list comprehension b == [3, 4]
.
If you want a one-liner, you can do:
df.rename(columns=df.iloc[0]).drop(df.index[0])
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_assoc($result);
echo $row['option_value'];
I was getting error: some jars are not in classpath.So I just delete the corrupted jar and perrform below steps
1.Project > Setting>Build,Execution,Deployment>Compiler>check build project automatically
2.CTRL+SHIFT+A find/search **registry** --Check for below param
compiler.automake.allow.when.app.running
compiler.automake.trigger.delay=500---According to ur requirement
3.Add devtool in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
4.Build ,If found any probelm while building ,saying some jar in not in class path.Just delete the corrupted jar
and re-build the project angain after sync with maven lib
The difficulty with scrolling is that you may not only need to scroll the page to show a div, but you may need to scroll inside scrollable divs on any number of levels as well.
The scrollTop property is a available on any DOM element, including the document body. By setting it, you can control how far down something is scrolled. You can also use clientHeight and scrollHeight properties to see how much scrolling is needed (scrolling is possible when clientHeight (viewport) is less than scrollHeight (the height of the content).
You can also use the offsetTop property to figure out where in the container an element is located.
To build a truly general purpose "scroll into view" routine from scratch, you would need to start at the node you want to expose, make sure it's in the visible portion of it's parent, then repeat the same for the parent, etc, all the way until you reach the top.
One step of this would look something like this (untested code, not checking edge cases):
function scrollIntoView(node) {
var parent = node.parent;
var parentCHeight = parent.clientHeight;
var parentSHeight = parent.scrollHeight;
if (parentSHeight > parentCHeight) {
var nodeHeight = node.clientHeight;
var nodeOffset = node.offsetTop;
var scrollOffset = nodeOffset + (nodeHeight / 2) - (parentCHeight / 2);
parent.scrollTop = scrollOffset;
}
if (parent.parent) {
scrollIntoView(parent);
}
}
Try to convert the BigInteger to a long like this
Long longNumber= bigIntegerNumber.longValue();
I hit this issue. This architecture (from Lain's answer) worked for me. Here is the solution in Python.
Here is the main email creation function:
def create_message_with_attachment(
sender, to, subject, msgHtml, msgPlain, attachmentFile):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
file: The path to the file to be attached.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEMultipart('mixed')
message['to'] = to
message['from'] = sender
message['subject'] = subject
message_alternative = MIMEMultipart('alternative')
message_related = MIMEMultipart('related')
message_related.attach(MIMEText(msgHtml, 'html'))
message_alternative.attach(MIMEText(msgPlain, 'plain'))
message_alternative.attach(message_related)
message.attach(message_alternative)
print "create_message_with_attachment: file:", attachmentFile
content_type, encoding = mimetypes.guess_type(attachmentFile)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
if main_type == 'text':
fp = open(attachmentFile, 'rb')
msg = MIMEText(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'image':
fp = open(attachmentFile, 'rb')
msg = MIMEImage(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'audio':
fp = open(attachmentFile, 'rb')
msg = MIMEAudio(fp.read(), _subtype=sub_type)
fp.close()
else:
fp = open(attachmentFile, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close()
filename = os.path.basename(attachmentFile)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(msg)
return {'raw': base64.urlsafe_b64encode(message.as_string())}
Here is the full code for sending an email containing html/text/attachment:
import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from apiclient import errors, discovery
import mimetypes
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE1 = 'client_secret.json'
location = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
CLIENT_SECRET_FILE = os.path.join(location, CLIENT_SECRET_FILE1)
APPLICATION_NAME = 'Gmail API Python Send Email'
def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail-python-email-send.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
print 'Storing credentials to ' + credential_path
return credentials
def SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
message1 = create_message_with_attachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
SendMessageInternal(service, "me", message1)
def SendMessageInternal(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message).execute())
print 'Message Id: %s' % message['id']
return message
except errors.HttpError, error:
print 'An error occurred: %s' % error
return "error"
def create_message_with_attachment(
sender, to, subject, msgHtml, msgPlain, attachmentFile):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
file: The path to the file to be attached.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEMultipart('mixed')
message['to'] = to
message['from'] = sender
message['subject'] = subject
message_alternative = MIMEMultipart('alternative')
message_related = MIMEMultipart('related')
message_related.attach(MIMEText(msgHtml, 'html'))
message_alternative.attach(MIMEText(msgPlain, 'plain'))
message_alternative.attach(message_related)
message.attach(message_alternative)
print "create_message_with_attachment: file:", attachmentFile
content_type, encoding = mimetypes.guess_type(attachmentFile)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
if main_type == 'text':
fp = open(attachmentFile, 'rb')
msg = MIMEText(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'image':
fp = open(attachmentFile, 'rb')
msg = MIMEImage(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'audio':
fp = open(attachmentFile, 'rb')
msg = MIMEAudio(fp.read(), _subtype=sub_type)
fp.close()
else:
fp = open(attachmentFile, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close()
filename = os.path.basename(attachmentFile)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(msg)
return {'raw': base64.urlsafe_b64encode(message.as_string())}
def main():
to = "[email protected]"
sender = "[email protected]"
subject = "subject"
msgHtml = "Hi<br/>Html Email"
msgPlain = "Hi\nPlain Email"
attachment = "/path/to/file.pdf"
SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachment)
if __name__ == '__main__':
main()
Creating a data.table
with key=V1
automatically does this for you. Using Stephan's data foo
> require(data.table)
> foo.dt <- data.table(foo, key="V1")
> foo.dt
V1 V2
1: 1 349
2: 1 393
3: 1 392
4: 2 94
5: 3 49
6: 3 32
7: 4 459
I was looking for a way to get the event type when jQuery listens for several events at once, and Google put me here.
So, for those interested, event.type
is my answer :
$('#element').on('keyup keypress blur change', function(event) {
alert(event.type); // keyup OR keypress OR blur OR change
});
More info in the jQuery doc.
In BASH, you can find a user's $HOME
directory by prefixing the user's login ID with a tilde character. For example:
$ echo ~bob
This will echo out user bob
's $HOME
directory.
However, you say you want to be able to execute a script as a particular user. To do that, you need to setup sudo. This command allows you to execute particular commands as either a particular user. For example, to execute foo
as user bob
:
$ sudo -i -ubob -sfoo
This will start up a new shell, and the -i
will simulate a login with the user's default environment and shell (which means the foo
command will execute from the bob's
$HOME` directory.)
Sudo is a bit complex to setup, and you need to be a superuser just to be able to see the shudders file (usually /etc/sudoers
). However, this file usually has several examples you can use.
In this file, you can specify the commands you specify who can run a command, as which user, and whether or not that user has to enter their password before executing that command. This is normally the default (because it proves that this is the user and not someone who came by while the user was getting a Coke.) However, when you run a shell script, you usually want to disable this feature.
It depends on your file path. For me, the current directory was [project]\bin\Debug
, so I had to move to the parent folder twice.
Image image = Image.FromFile(@"..\..\Pictures\"+text+".png");
this.pictureBox1.Image = image;
To find your current directory, you can make a dummy label called label2 and write this:
this.label2.Text = System.IO.Directory.GetCurrentDirectory();
For those also using typescript on node-js and are getting a ReferenceError: fetch is not defined
error
npm install
these packages:
"amazon-cognito-identity-js": "3.0.11"
"node-fetch": "^2.3.0"
Then include:
import Global = NodeJS.Global;
export interface GlobalWithCognitoFix extends Global {
fetch: any
}
declare const global: GlobalWithCognitoFix;
global.fetch = require('node-fetch');
I found a javascript trick, but you have to use the length of the string. Lets say you want 3 lines of width 250px, you can calculate the length per line i.e.
//get the total character length.
//Haha this might vary if you have a text with lots of "i" vs "w"
var totalLength = (width / yourFontSize) * yourNumberOfLines
//then ellipsify
function shorten(text, totalLength) {
var ret = text;
if (ret.length > totalLength) {
ret = ret.substr(0, totalLength-3) + "...";
}
return ret;
}
On the MAC OS X 10.9.5 and Eclipse Luna Service Release 1 (4.4.1), its not found under the Window menu, but instead under: Eclipse > Preferences > Run/Debug > Console.
This worked for me:
select * from mytable
where array_to_string(pub_types, ',') like '%Journal%'
Depending on your normalization needs, it might be better to implement a separate table with a FK reference as you may get better performance and manageability.
Simply saying, any() does this work : according to the condition even if it encounters one fulfilling value in the list, it returns true, else it returns false.
list = [2,-3,-4,5,6]
a = any(x>0 for x in lst)
print a:
True
list = [2,3,4,5,6,7]
a = any(x<0 for x in lst)
print a:
False
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
$('#element').on('change', function() {
$(this).val($(this).prop("defaultValue"));
});
Count all td in table1:
console.log(_x000D_
table1.querySelectorAll("td").length_x000D_
)
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
Count all td into each tr of table1.
table1.querySelectorAll("tr").forEach(function(e){_x000D_
console.log( e.querySelectorAll("td").length )_x000D_
})
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover
(which will allow the image to extend out from the sides) or contain
(which does not allow the image to extend out at all), just set the CSS like so:
body {
background-image: url(img.jpg);
background-position: center top;
background-size: 100% auto;
}
This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.
EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.
Hopefully soon you'll be able to use the new srcset attribute on the img
element. If you want to use img
elements now, the currently accepted answer is probably best.
However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height
to 0 and set the padding-bottom
to a percentage of the element's own width, like so:
.foo {
height: 0;
padding: 0; /* remove any pre-existing padding, just in case */
padding-bottom: 75%; /* for a 4:3 aspect ratio */
background-image: url(foo.png);
background-position: center center;
background-size: 100%;
background-repeat: no-repeat;
}
In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.
It's also possible to use jQuery's .load()
$('#submitform').click(function() {
$('#showresults').load('getinfo.asp #showresults', {
txtsearch: $('#appendedInputButton').val()
}, function() {
// alert('Load was performed.')
// $('#showresults').slideDown('slow')
});
});
unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
We could modify the example above to use only part of the document that is fetched:
$( "#result" ).load( "ajax/test.html #container" );
When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.
This worked for me:
Dim binding As New WebHttpBinding(WebHttpSecurityMode.Transport)
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None
binding.MaxBufferSize = Integer.MaxValue
binding.MaxReceivedMessageSize = Integer.MaxValue
binding.MaxBufferPoolSize = Integer.MaxValue
In addition to gecco's answer I would change step 3 from:
./configure
to:
./configure --prefix=/opt/python3
Then after installation you could also:
# ln -s /opt/python3/bin/python3 /usr/bin/python3
It is to ensure that installation will not conflict with python installed with yum.
See explanation I have found on Internet:
http://www.hosting.com/support/linux/installing-python-3-on-centosredhat-5x-from-source
XmlDocument doc = new XmlDocument();
doc.Load("MonFichierXML.xml");
XmlNode node = doc.SelectSingleNode("Magasin");
XmlNodeList prop = node.SelectNodes("Items");
foreach (XmlNode item in prop)
{
items Temp = new items();
Temp.AssignInfo(item);
lstitems.Add(Temp);
}
echo y | command
should work.
Also, some installers have an "auto-yes" flag. It's -y
for apt-get
on Ubuntu.
Just use this constructor of List<T>
. It accepts any IEnumerable<T>
as an argument.
string[] arr = ...
List<string> list = new List<string>(arr);
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n
will work.
If you use anything else you will cause issues with cut and paste on Windows platforms.
The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n
linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.
Interestingly, in spite of the Unix line end convention being \n
, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n
. Yes, it may not make a lot of sense, but that's history and evolving standards for you!
Bitbucket: Check for Branch permissions in Settings (it may be on 'Deny all'). If that doesn't work, simply clone your branch to a new local branch, push the changes to the remote (a new remote branch will be created), and create a PR.
Another way
num1 = (20*boolVar)+(num1*(not boolVar))
There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. The process of converting source code into native executable code is called "compilation", and it's not supported by scripting languages like VBScript.
Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a self-extracting archive is that decompression software (like WinZip) is not required on the end user's computer to be able to extract or "decompress" the file. If it isn't compressed in the first place, this is a moot point.
Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.
In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be compiled. Visual Basic 6 (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild.
Alternatively, you could go ahead and make the jump to Visual Basic .NET, which remains somewhat similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some huge differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.
I used @jensgram solution to hide a div that contains a disabled input. So I hide the entire parent of the input.
Here is the code :
div:has(>input[disabled=disabled]) {
display: none;
}
Maybe it could help some of you.
I was running into the same issue. I discovered the following solution, which has only been tested in Chrome v31:
table {
table-layout: fixed;
}
tbody {
display: block;
overflow: scroll;
}
Answer by Adamski is a good one and describes the steps in an encoding operation when using the general encode method (that takes a byte buffer as one of the inputs)
However, the method in question (in this discussion) is a variant of encode - encode(CharBuffer in). This is a convenience method that implements the entire encoding operation. (Please see java docs reference in P.S.)
As per the docs, This method should therefore not be invoked if an encoding operation is already in progress (which is what is happening in ZenBlender's code -- using static encoder/decoder in a multi threaded environment).
Personally, I like to use convenience methods (over the more general encode/decode methods) as they take away the burden by performing all the steps under the covers.
ZenBlender and Adamski have already suggested multiple ways options to safely do this in their comments. Listing them all here:
P.S.
java docs references:
This is a very nice and clean example:(check this great tutorial for a full explanation link)
public static IEnumerable<SelectListItem> ToSelectListItems(
this IEnumerable<Album> albums, int selectedId)
{
return
albums.OrderBy(album => album.Name)
.Select(album =>
new SelectListItem
{
Selected = (album.ID == selectedId),
Text = album.Name,
Value = album.ID.ToString()
});
}
In this MSDN link you can read de DropDownList
method documentation.
Hope it helps.
Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).
I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number)
.
I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:
DECLARE
DNO NUMBER;
MAXSAL NUMBER;
BEGIN
DNO := NULL;
GET_MAXSAL_BY_DEPT(
DNO => DNO,
MAXSAL => MAXSAL
);
DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;
I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:
Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc.
To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor
.
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
-- Modify the code to output the variable
-- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;
However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
v_rec emp%rowtype;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
loop
fetch v_Return into v_rec;
exit when v_Return%notfound;
DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
end loop;
END;
The output from the same location:
Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc.
Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:
var rc refcursor
exec :rc := get_emps_by_dept(30)
print rc
In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).
The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.
"When I type just
var rc refcursor;
and select it and run it, I get this error (GUI):"
There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor
and click Execute Statement
(or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script
(or F5 ), even for a single line of SQL*Plus.
"I am so close ... please help."
You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:
exec :rc := get_account(1)
What you need is something like the following. I have used the named notation for clarity.
var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor
exec :tran_cnt := 0
exec :msg_cnt := 123
exec get_account (Vret_val => :ret1,
Vtran_count => :tran_cnt,
Vmessage_count => :msg_cnt,
Vaccount_id => 1,
rc1 => :rc )
print tran_count
print rc
That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.
$text="abc1234567890";
// truncate to 4 chars
echo substr(str_pad($text,4),0,4);
This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)
Alternatively you can use npm which automatically looks into the .bin folder. Then you can use tsc
After the C# 6.0 (including) you can use nameof expression:
using Stuff = Some.Cool.Functionality
class C {
static int Method1 (string x, int y) {}
static int Method1 (string x, string y) {}
int Method2 (int z) {}
string f<T>() => nameof(T);
}
var c = new C()
nameof(C) -> "C"
nameof(C.Method1) -> "Method1"
nameof(C.Method2) -> "Method2"
nameof(c.Method1) -> "Method1"
nameof(c.Method2) -> "Method2"
nameof(z) -> "z" // inside of Method2 ok, inside Method1 is a compiler error
nameof(Stuff) = "Stuff"
nameof(T) -> "T" // works inside of method but not in attributes on the method
nameof(f) -> “f”
nameof(f<T>) -> syntax error
nameof(f<>) -> syntax error
nameof(Method2()) -> error “This expression does not have a name”
Note! nameof
not get the underlying object's runtime Type, it is just the compile-time argument. If a method accepts an IEnumerable then nameof simply returns "IEnumerable", whereas the actual object could be "List".
For me I had to settimeout in addition to @arjun-sk solution's (link), as I was getting the error
setTimeout(() => {
this.modalService.open(this.loginModal, { centered: true })
}, 100);
OAuth 2.0 spec doesn't define the part. But there could be couple of options:
When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.
Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.
Nice formatting add-in: http://blog.stevenlevithan.com/archives/date-time-format.
With that you could write:
var now = new Date();
now.format("yyyy/mm/dd");
This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).
To avoid it, the browser check the Same-origin policy
Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:
If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet
constructor:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
Fix it by adding the context as the constructor arg:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
From the spec:
All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus [backslash] (U+005C), and the control characters U+0000 to U+001F
Just because e.g. Bell (U+0007) doesn't have a single-character escape code does not mean that you don't need to escape it. Use the Unicode escape sequence \u0007
.
A simple tip: A simple space (or invisible special char) in your script, right before the very first <?php
tag, can cause this !
Especially when you are working in a team and somebody is using a "weak" IDE or has messed around in the files with strange text editors.
I have seen these things ;)
You can't request admin rights from a batch file, but you could write a windows scripting host script in %temp% and run that (and that in turn executes your batch as admin) You want to call the ShellExecute method in the Shell.Application object with "runas" as the verb
Unfortunately the previous answers were no option for me so i researched for a while and found this solution:
http://blog.alessio.marchetti.name/post/2011/02/12/the-Oliver-Becker-s-XPath-method
I use it to output text if a certain Node exists. 4 is the length of the text foo. So i guess a more elegant solution would be the use of a variable.
substring('foo',number(not(normalize-space(/elements/the/element/)))*4)
Yes you can, just pass the integer param to the split method
String stSplit = "apple=fruit table price=5"
stSplit.split("=", 2);
Here is a java doc reference : String#split(java.lang.String, int)
If you really want to achieve that you can use a file watcher like inotifywait.
You watch a directory and you save information about file creations in separate file outside that directory.
while true; do
change=$(inotifywait -e close_write,moved_to,create .)
change=${change#./ * }
if [ "$change" = ".*" ]; then ./scriptToStoreInfoAboutFile; fi
done
As no creation time is stored, you can build your own system based on inotify.
file_exists checks whether a file exist in the specified path or not.
Syntax:
file_exists ( string $filename )
Returns TRUE
if the file or directory specified by filename exists; FALSE
otherwise.
$filename = BASE_DIR."images/a/test.jpg";
if (file_exists($filename)){
echo "File exist.";
}else{
echo "File does not exist.";
}
Another alternative method you can use getimagesize(), it will return 0(zero) if file/directory is not available in the specified path.
if (@getimagesize($filename)) {...}
I would recommend using the Chrome extension Clockwork with the Laravel package https://github.com/itsgoingd/clockwork. It's easy to install and use.
Clockwork is a Chrome extension for PHP development, extending Developer Tools with a new panel providing all kinds of information useful for debugging and profiling your PHP scripts, including information on request, headers, GET and POST data, cookies, session data, database queries, routes, visualisation of application runtime and more. Clockwork includes out of the box support for Laravel 4 and Slim 2 based applications, you can add support for any other or custom framework via an extensible API.
I just came across this problem today, and I found this Microsoft Help and Support page that actually did work around the problem.
I had a couple delegates at the top of my file, in the global namespace, and all of a sudden I was getting a MissingManifestResourceException
when running the program, on this line:
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
Then I moved the delegates into the namespace, got the same error. Finally I put the delegates in the only class in that file, and the error went away, but I didn't want the delegates in that class or namespace.
Then I came across that link above, which said
To resolve this problem, move all of the other class definitions so that they appear after the form's class definition.
I put the delegates (which I would not consider "class definitions") at the bottom of that file, outside of the local namespace, and the program didn't get the MissingManifestResourceException
anymore. What an irritating error. But, that seems like a more robust solution than modifying the auto-generated code :)
Collection is the main interface of Java Collections hierarchy and List(Sequence) is one of the sub interfaces that defines an ordered collection.
You can try something like this-
as.vector(unlist(aframe$a2))
It sounds as though you're not in a modern document mode. Internet Explorer 11 shows the SVG just fine when you're in Standards Mode. Make sure that if you have an x-ua-compatible
meta tag, you have it set to Edge, rather than an earlier mode.
<meta http-equiv="X-UA-Compatible" content="IE=edge">
You can determine your document mode by opening up your F12 Developer Tools and checking either the document mode dropdown (seen at top-right, currently "Edge") or the emulation tab:
If you do not have an x-ua-compatible
meta tag (or header), be sure to use a doctype that will put the document into Standards mode, such as <!DOCTYPE html>
.
PHP has several libraries for XML Manipulation.
The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows
<?php
$doc = new DOMDocument( );
$ele = $doc->createElement( 'Root' );
$ele->nodeValue = 'Hello XML World';
$doc->appendChild( $ele );
$doc->save('MyXmlFile.xml');
?>
Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.
Menu File ? Preferences ? User Settings: add this line "workbench.editor.enablePreviewFromQuickOpen": false
Here's a function that can include an optional offset for those fixed headers. No external libraries needed.
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
You can grab the height of an element using JQuery and scroll to it.
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
Update March 2018
Scroll to this answer without using JQuery
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
From experience of my favicon.ico not appearing, I am sharing my experience. You can't get it to show until you put your website on a host, therefore, try put it on a localhost using XAMPP - http://www.apachefriends.org/en/xampp.html. This is how the favicon appears and like others recommended, change:
rel="shortcut icon"
to
rel="icon"
Also this way .png favicons can be used for slickness.
You want to restrict to input fields that are of type text so use the selector input[type=text]
rather than input
(which will apply to all input fields (e.g. those of type submit as well)).
From python >= 3.5 onward, you can use **
, glob.iglob(path/**, recursive=True)
and it seems the most pythonic solution, i.e.:
import glob, os
for filename in glob.iglob('/pardadox-music/**', recursive=True):
if os.path.isfile(filename): # filter dirs
print(filename)
Output:
/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...
Notes:
1 - glob.iglob
glob.iglob(pathname, recursive=False)
Return an iterator which yields the same values as
glob()
without actually storing them all simultaneously.
2 - If recursive is True
, the pattern '**'
will match any files and
zero or more directories
and subdirectories
.
3 - If the directory contains files starting with .
they won’t be matched by default. For example, consider a directory containing card.gif
and .card.gif
:
>>> import glob
>>> glob.glob('*.gif') ['card.gif']
>>> glob.glob('.c*')['.card.gif']
4 - You can also use rglob(pattern)
,
which is the same as calling glob()
with **/
added in front of the given relative pattern.
There is problem in name spacing as in laravel 5.2.3
use DB;
use App\ApiModel; OR use App\name of model;
DB::table('tbl_users')->insert($users);
OR
DB::table('table name')->insert($users);
model
class ApiModel extends Model
{
protected $table='tbl_users';
}
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
Performance wise, it should not make any difference. The explicit join syntax seems cleaner to me as it clearly defines relationships between tables in the from clause and does not clutter up the where clause.
With the newer Spring versions One can do as follows:
If not using native query this can done as below:
public interface ProjectMini {
String getProjectId();
String getProjectName();
}
public interface ProjectRepository extends JpaRepository<Project, String> {
@Query("SELECT p FROM Project p")
List<ProjectMini> findAllProjectsMini();
}
Using native query the same can be done as below:
public interface ProjectRepository extends JpaRepository<Project, String> {
@Query(value = "SELECT projectId, projectName FROM project", nativeQuery = true)
List<ProjectMini> findAllProjectsMini();
}
For detail check the docs
BeautifulSoup has a easy to use prettify()
method.
It indents one space per indentation level. It works much better than lxml's pretty_print and is short and sweet.
from bs4 import BeautifulSoup
bs = BeautifulSoup(open(xml_file), 'xml')
print bs.prettify()
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
Iterable version using a generator function that doesn't modify Number.prototype
.
function sequence(max, step = 1) {_x000D_
return {_x000D_
[Symbol.iterator]: function* () {_x000D_
for (let i = 1; i <= max; i += step) yield i_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
console.log([...sequence(10)])
_x000D_
Actually this error occurs when server makes connection but can't build due to failure in identifying connection function identifier. This problem can be solved by typing connection function in code. For this I take a simple example. In this case function is con your may be different.
SqlCommand cmd = new SqlCommand("insert into ptb(pword,rpword) values(@a,@b)",con);
It is very simple, just add a property:
public string Value {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
The %b
option of sprintf() will convert a boolean to an integer:
echo sprintf("False will print as %b", false); //False will print as 0
echo sprintf("True will print as %b", true); //True will print as 1
If you're not familiar with it: You can give this function an arbitrary amount of parameters while the first one should be your ouput string spiced with replacement strings like %b
or %s
for general string replacement.
Each pattern will be replaced by the argument in order:
echo sprintf("<h1>%s</h1><p>%s<br/>%s</p>", "Neat Headline", "First Line in the paragraph", "My last words before this demo is over");
Yes! And another solution. My solution differs in the keys that are being checked.
In all other solutions we only look at the keys in dict_b
. But here we look in the union of both dictionaries.
Do with it as you please
def update_nested(dict_a, dict_b):
set_keys = set(dict_a.keys()).union(set(dict_b.keys()))
for k in set_keys:
v = dict_a.get(k)
if isinstance(v, dict):
new_dict = dict_b.get(k, None)
if new_dict:
update_nested(v, new_dict)
else:
new_value = dict_b.get(k, None)
if new_value:
dict_a[k] = new_value
def prime(x):
# check that number is greater that 1
if x > 1:
for i in range(2, x + 1):
# check that only x and 1 can evenly divide x
if x % i == 0 and i != x and i != 1:
return False
else:
return True
else:
return False # if number is negative
This is my solution, for any list object you can use this code for convert to xml layout. KeyFather is your principal tag and KeySon is where start your Forech.
public string BuildXml<T>(ICollection<T> anyObject, string keyFather, string keySon)
{
var settings = new XmlWriterSettings
{
Indent = true
};
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement(keyFather);
foreach (var objeto in anyObject)
{
writer.WriteStartElement(keySon);
foreach (PropertyDescriptor item in props)
{
writer.WriteStartElement(item.DisplayName);
writer.WriteString(props[item.DisplayName].GetValue(objeto).ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteFullEndElement();
writer.WriteEndDocument();
writer.Flush();
return builder.ToString();
}
}
To have the active
tab also styled, merge the answer from this thread, from Mansukh Khandhar, with this other answer, from lmgonzalves:
.nav-tabs > li.active > a {
background-color: yellow !important;
border: medium none;
border-radius: 0;
}
Swift 3: Chage ViewController withOut Segue and send AnyObject Use: Identity MainPageViewController on target ViewController
let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "MainPageViewController") as! MainPageViewController
var mainPageNav = UINavigationController(rootViewController: mainPage)
self.present(mainPageNav, animated: true, completion: nil)
or if you want to Change View Controller and send Data
let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "MainPageViewController") as! MainPageViewController
let dataToSend = "**Any String**" or var ObjectToSend:**AnyObject**
mainPage.getData = dataToSend
var mainPageNav = UINavigationController(rootViewController: mainPage)
self.present(mainPageNav, animated: true, completion: nil)
has_key
is fast and efficient.
Instead of array use an hash:
valueTo1={"a","b","c"}
if valueTo1.has_key("a"):
print "Found key in dictionary"
Following code calculates Palidrom for even length and odd length strings.
Not the best solution but works for both the cases
HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE
private static String getLongestPalindrome(String string) {
String odd = getLongestPalindromeOdd(string);
String even = getLongestPalindromeEven(string);
return (odd.length() > even.length() ? odd : even);
}
public static String getLongestPalindromeOdd(final String input) {
int rightIndex = 0, leftIndex = 0;
String currentPalindrome = "", longestPalindrome = "";
for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
leftIndex = centerIndex;
rightIndex = centerIndex + 1;
while (leftIndex >= 0 && rightIndex < input.length()) {
if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
break;
}
currentPalindrome = input.substring(leftIndex, rightIndex + 1);
longestPalindrome = currentPalindrome.length() > longestPalindrome
.length() ? currentPalindrome : longestPalindrome;
leftIndex--;
rightIndex++;
}
}
return longestPalindrome;
}
public static String getLongestPalindromeEven(final String input) {
int rightIndex = 0, leftIndex = 0;
String currentPalindrome = "", longestPalindrome = "";
for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
leftIndex = centerIndex - 1;
rightIndex = centerIndex + 1;
while (leftIndex >= 0 && rightIndex < input.length()) {
if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
break;
}
currentPalindrome = input.substring(leftIndex, rightIndex + 1);
longestPalindrome = currentPalindrome.length() > longestPalindrome
.length() ? currentPalindrome : longestPalindrome;
leftIndex--;
rightIndex++;
}
}
return longestPalindrome;
}
You can add one
public static boolean isNullOrBlank(String param) {
return param == null || param.trim().length() == 0;
}
I have
public static boolean isSet(String param) {
// doesn't ignore spaces, but does save an object creation.
return param != null && param.length() != 0;
}
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
1.Install-Package Microsoft.AspNet.WebApi.Cors
2 . Add this code in WebApiConfig.cs.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
3. Add this
using System.Web.Http.Cors;
4. Add this code in Api Controller (HomeController.cs)
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class HomeController : ApiController
{
[HttpGet]
[Route("api/Home/test")]
public string test()
{
return "";
}
}
UPDATE
syntax is wrongWHERE
clause to target your specific rowChange
UPDATE `access_users`
(`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)
VALUES (:firstname, :surname, :telephone, :email)
to
UPDATE `access_users`
SET `contact_first_name` = :firstname,
`contact_surname` = :surname,
`contact_email` = :email,
`telephone` = :telephone
WHERE `user_id` = :user_id -- you probably have some sort of id
Yes. The VBA equivalent of AltEnter is to use a linebreak character:
ActiveCell.Value = "I am a " & Chr(10) & "test"
Note that this automatically sets WrapText
to True.
Proof:
Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub
To answer the other half of the question, you can call:
return PartialView("viewname");
when you want to return partial HTML. You'll just have to find some way to decide whether the request wants JSON or HTML, perhaps based on a URL part/parameter.
Using Between condition
SELECT *
FROM TEST
WHERE COLUMN_NAME BETWEEN x AND y ;
Or using Just operators,
SELECT *
FROM TEST
WHERE COLUMN_NAME >= x AND COLUMN_NAME <= y;
You are encountering a problem because you cannot construct the ArrayList
and populate it at the same time. You either need to create it and then manually populate it as such:
ArrayList list = new ArrayList<Double>();
list.add(1.38);
...
Or, alternatively if it is more convenient for you, you can populate the ArrayList
from a primitive array containing your values. For example:
Double[] array = {1.38, 2.56, 4.3};
ArrayList<Double> list = new ArrayList<Double>(Arrays.asList(array));
Grouped boxplots, towards subtle academic publication styling... (source)
(Left) Python 2.7.12 Matplotlib v1.5.3. (Right) Python 3.7.3. Matplotlib v3.1.0.
Code:
import numpy as np
import matplotlib.pyplot as plt
# --- Your data, e.g. results per algorithm:
data1 = [5,5,4,3,3,5]
data2 = [6,6,4,6,8,5]
data3 = [7,8,4,5,8,2]
data4 = [6,9,3,6,8,4]
# --- Combining your data:
data_group1 = [data1, data2]
data_group2 = [data3, data4]
# --- Labels for your data:
labels_list = ['a','b']
xlocations = range(len(data_group1))
width = 0.3
symbol = 'r+'
ymin = 0
ymax = 10
ax = plt.gca()
ax.set_ylim(ymin,ymax)
ax.set_xticklabels( labels_list, rotation=0 )
ax.grid(True, linestyle='dotted')
ax.set_axisbelow(True)
ax.set_xticks(xlocations)
plt.xlabel('X axis label')
plt.ylabel('Y axis label')
plt.title('title')
# --- Offset the positions per group:
positions_group1 = [x-(width+0.01) for x in xlocations]
positions_group2 = xlocations
plt.boxplot(data_group1,
sym=symbol,
labels=['']*len(labels_list),
positions=positions_group1,
widths=width,
# notch=False,
# vert=True,
# whis=1.5,
# bootstrap=None,
# usermedians=None,
# conf_intervals=None,
# patch_artist=False,
)
plt.boxplot(data_group2,
labels=labels_list,
sym=symbol,
positions=positions_group2,
widths=width,
# notch=False,
# vert=True,
# whis=1.5,
# bootstrap=None,
# usermedians=None,
# conf_intervals=None,
# patch_artist=False,
)
plt.savefig('boxplot_grouped.png')
plt.savefig('boxplot_grouped.pdf') # when publishing, use high quality PDFs
#plt.show() # uncomment to show the plot.
It worked only after removing the eclipse folder and all related folders like .p2, .eclipse (in my case they are at different location where I have saved eclipse installer) etc. and after re-downloading the eclipse, it worked.
What I do when I mess up my local branch is I just rename my broken branch, and check out/branch the upstream branch again:
git branch -m branch branch-old
git fetch remote
git checkout -b branch remote/branch
Then if you're sure you don't want anything from your old branch, remove it:
git branch -D branch-old
But usually I leave the old branch around locally, just in case I had something in there.
=IF(X2>=85,0.559,IF(X2>=80,0.327,IF(X2>=75,0.255,-1)))
Explanation:
=IF(X2>=85, 'If the value is in the highest bracket
0.559, 'Use the appropriate number
IF(X2>=80, 'Otherwise, if the number is in the next highest bracket
0.327, 'Use the appropriate number
IF(X2>=75, 'Otherwise, if the number is in the next highest bracket
0.255, 'Use the appropriate number
-1 'Otherwise, we're not in any of the ranges (Error)
)
)
)
I am using git-bash in windows.The simplest way is to change the path address to have the forward slashes:
git clone C:/Dev/proposed
P.S: Start the git-bash on the destination folder.
Path used in clone ---> c:/Dev/proposed
Original path in windows ---> c:\Dev\proposed
Of course the answers above all do the job, but still i would like to use something like
gradle run path1 path2
well this can't be done, but what if we can:
gralde run --- path1 path2
If you think it is more elegant, then you can do it, the trick is to process the command line and modify it before gradle does, this can be done by using init scripts
The init script below:
So in your run task (or JavaExec, Exec) you can:
if (project.gradle.hasProperty("appArgs")) {
List<String> appArgs = project.gradle.appArgs;
args appArgs
}
The init script is:
import org.gradle.api.invocation.Gradle
Gradle aGradle = gradle
StartParameter startParameter = aGradle.startParameter
List tasks = startParameter.getTaskRequests();
List<String> appArgs = new ArrayList<>()
tasks.forEach {
List<String> args = it.getArgs();
Iterator<String> argsI = args.iterator();
while (argsI.hasNext()) {
String arg = argsI.next();
// remove '---' and all that follow
if (arg == "---") {
argsI.remove();
while (argsI.hasNext()) {
arg = argsI.next();
// and add it to appArgs
appArgs.add(arg);
argsI.remove();
}
}
}
}
aGradle.ext.appArgs = appArgs
Limitations:
If you don't like global init script, you can specify it in command line
gradle -I init.gradle run --- f:/temp/x.xml
Or better add an alias to your shell:
gradleapp run --- f:/temp/x.xml
You could check out JBoss Tools plugin.
If the file contains backslashes (paths usually) you can try something like this:
sed -i -- 's,<path1>,<path2>,g' *
ex:
sed -i -- 's,/foo/bar,/new/foo/bar,g' *.sh (in all shell scripts available)
It would seem that the attr functionality is getting further deprecated
$(this).attr('TYPE')
undefined
$(this).prop('type')
"text"
Here is a simplified version of this script to copy a pdf into a XL file.
Sub CopyOnePDFtoExcel()
Dim ws As Worksheet
Dim PDF_path As String
PDF_path = "C:\Users\...\Documents\This-File.pdf"
'open the pdf file
ActiveWorkbook.FollowHyperlink PDF_path
SendKeys "^a", True
SendKeys "^c"
Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
Application.ScreenUpdating = False
Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Activate
ws.Range("A1").ClearContents
ws.Range("A1").Select
ws.Paste
Application.ScreenUpdating = True
End Sub
I'm going to add an answer to try to clear up a few things here as there seems to be some confusion. The main issue is that people are asking the wrong question, or at least not being specific enough.
When we talk about a computer's "domain", there are several things that we might be referring to. What follows is not an exhaustive list, but it covers the most common cases:
This is highly dependent on what you are trying to do. The original poster of this question was looking for the computer's "Active Directory domain", which probably means they are looking for the domain to which either the computer's security principal or a user's security principal belongs. Generally you want these when you are trying to talk to Active Directory in some way. Note that the current user principal and the current computer principal are not necessarily in the same domain.
Pieter van Ginkel's answer is actually giving you the local network stack's primary DNS suffix (the same thing that's shown in the top section of the output of ipconfig /all
). In the 99% case, this is probably the same as the domain to which both the computer's security principal and the currently authenticated user's principal belong - but not necessarily. Generally this is what you want when you are trying to talk to devices on the LAN, regardless of whether or not the devices are anything to do with Active Directory. For many applications, this will still be a "good enough" answer for talking to Active Directory.
The last option, a DNS name, is a lot fuzzier and more ambiguous than the other two. Anywhere between zero and infinity DNS records may resolve to a given IP address - and it's not necessarily even clear which IP address you are interested in. user2031519's answer refers to the value of HTTP_HOST
, which is specifically useful when determining how the user resolved your HTTP server in order to send the request you are currently processing. This is almost certainly not what you want if you are trying to do anything with Active Directory.
This one's nice and simple, it's what Tim's answer is giving you.
System.Environment.UserDomainName
This is probably what the OP wanted, for this one we're going to have to ask Active Directory about it.
System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain()
This one will throw a ActiveDirectoryObjectNotFoundException
if the local machine is not part of domain, or the domain controller cannot be contacted.
This is what Pieter van Ginkel's answer is giving you. It's probably not exactly what you want, but there's a good chance it's good enough for you - if it isn't, you probably already know why.
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName
This one's tricky and there's no single answer to it. If this is what you are after, comment below and I will happily discuss your use-case and help you to work out the best solution (and expand on this answer in the process).
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Installing the Chrome extension IE Tab did the job for me.
It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.
You can install IETab for FireFox too.
I get the same error in Chrome after pasting code copied from jsfiddle.
If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.
var student = [];
var obj = {
'first_name': name,
'last_name': name,
'age': age,
}
student.push(obj);
If you have both versions you can create a merge replication from new to old. Create a merge publication on your newer sql server and a subscription on the older version. After initializing the subscription you can create a backup of the database with the same structure and the same content but in an older version and restore it on your old target server. You can use this method also with sql server 2016 to target 2014, 2012 or 2008.
In hadoop1.0:
hadoop fs -rmr /PATH/ON/HDFS
In hadoop2.0:
hdfs dfs -rm -R /PATH/ON/HDFS
Use \
to escape ,
in path
It has also happened to me, in my case it was due to the GDB launcher, which I needed to turn to "Legacy Create Process Launcher". To do so,
either change the default launchers to the "Legacy Create Process Launcher", in Windows>Preferences>Run/Debug>Launching>Default Launchers.
or choose this launcher in the debug configuration of your application (Run>Debug configurations>choose your debug configuration). Under the "main" tab at the bottom, click on "Select other...", check the box "Use configuration specific settings" and choose "Legacy Create Process Launcher".
Simple you can use
db.collectionName.createIndex({urfield:1},{unique:true});
Just put a '!' in front of the boolean expression
All you need is a check on the post side of things.
if(empty($_REQUEST['type_id']) && $_REQUEST['type_id'] != 0)
$_REQUEST['type_id'] = null;
This thread was invaluable to figure out how to generate a binary file and prompt to download the named file, all in client code without a server.
First step for me was generating the binary blob from data that I was saving. There's plenty of samples for doing this for a single binary type, in my case I have a binary format with multiple types which you can pass as an array to create the blob.
saveAnimation: function() {
var device = this.Device;
var maxRow = ChromaAnimation.getMaxRow(device);
var maxColumn = ChromaAnimation.getMaxColumn(device);
var frames = this.Frames;
var frameCount = frames.length;
var writeArrays = [];
var writeArray = new Uint32Array(1);
var version = 1;
writeArray[0] = version;
writeArrays.push(writeArray.buffer);
//console.log('version:', version);
var writeArray = new Uint8Array(1);
var deviceType = this.DeviceType;
writeArray[0] = deviceType;
writeArrays.push(writeArray.buffer);
//console.log('deviceType:', deviceType);
var writeArray = new Uint8Array(1);
writeArray[0] = device;
writeArrays.push(writeArray.buffer);
//console.log('device:', device);
var writeArray = new Uint32Array(1);
writeArray[0] = frameCount;
writeArrays.push(writeArray.buffer);
//console.log('frameCount:', frameCount);
for (var index = 0; index < frameCount; ++index) {
var frame = frames[index];
var writeArray = new Float32Array(1);
var duration = frame.Duration;
if (duration < 0.033) {
duration = 0.033;
}
writeArray[0] = duration;
writeArrays.push(writeArray.buffer);
//console.log('Frame', index, 'duration', duration);
var writeArray = new Uint32Array(maxRow * maxColumn);
for (var i = 0; i < maxRow; ++i) {
for (var j = 0; j < maxColumn; ++j) {
var color = frame.Colors[i][j];
writeArray[i * maxColumn + j] = color;
}
}
writeArrays.push(writeArray.buffer);
}
var blob = new Blob(writeArrays, {type: 'application/octet-stream'});
return blob;
}
The next step is to get the browser to prompt the user to download this blob with a predefined name.
All I needed was a named link I added in the HTML5 that I could reuse to rename the initial filename. I kept it hidden since the link doesn't need display.
<a id="lnkDownload" style="display: none" download="client.chroma" href="" target="_blank"></a>
The last step is to prompt the user to download the file.
var data = animation.saveAnimation();
var uriContent = URL.createObjectURL(data);
var lnkDownload = document.getElementById('lnkDownload');
lnkDownload.download = 'theDefaultFileName.extension';
lnkDownload.href = uriContent;
lnkDownload.click();
I didnt see this question answered:
How should I setup a default Area when the application starts?
So, here is how you can set up a default Area:
var route = routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
).DataTokens = new RouteValueDictionary(new { area = "MyArea" });
There are no multi-dimensional arrays in Java, there are, however, arrays of arrays.
Just make an array of however large you want, then for each element make another array however large you want that one to be.
int array[][];
array = new int[10][];
array[0] = new int[9];
array[1] = new int[8];
array[2] = new int[7];
array[3] = new int[6];
array[4] = new int[5];
array[5] = new int[4];
array[6] = new int[3];
array[7] = new int[2];
array[8] = new int[1];
array[9] = new int[0];
Alternatively:
List<Integer>[] array;
array = new List<Integer>[10];
// of you can do "new ArrayList<Integer>(the desired size);" for all of the following
array[0] = new ArrayList<Integer>();
array[1] = new ArrayList<Integer>();
array[2] = new ArrayList<Integer>();
array[3] = new ArrayList<Integer>();
array[4] = new ArrayList<Integer>();
array[5] = new ArrayList<Integer>();
array[6] = new ArrayList<Integer>();
array[7] = new ArrayList<Integer>();
array[8] = new ArrayList<Integer>();
array[9] = new ArrayList<Integer>();
I had identical problem. To fix it I just changed host from localhost:3306 to just localhost. So error may acour when You sepcify unproper port for connection. It's better to leave it default.
./src/components/BusinessesList.js
Line 51: React Hook useEffect has a missing dependency: 'fetchBusinesses'.
Either include it or remove the dependency array react-hooks/exhaustive-deps
It's not JS/React error but eslint (eslint-plugin-react-hooks) warning.
It's telling you that hook depends on function fetchBusinesses
, so you should pass it as dependency.
useEffect(() => {
fetchBusinesses();
}, [fetchBusinesses]);
It could result in invoking function every render if function is declared in component like:
const Component = () => {
/*...*/
//new function declaration every render
const fetchBusinesses = () => {
fetch('/api/businesses/')
.then(...)
}
useEffect(() => {
fetchBusinesses();
}, [fetchBusinesses]);
/*...*/
}
because every time function is redeclared with new reference
Correct way of doing this stuff is:
const Component = () => {
/*...*/
// keep function reference
const fetchBusinesses = useCallback(() => {
fetch('/api/businesses/')
.then(...)
}, [/* additional dependencies */])
useEffect(() => {
fetchBusinesses();
}, [fetchBusinesses]);
/*...*/
}
or just defining function in useEffect
Sending email programmatically with Kotlin.
I also found this list of email POP services really helpful:
How to use:
val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
val to = listOf(InternetAddress("[email protected]"))
val from = InternetAddress("[email protected]")
val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
val emailService = EmailService("yourSmtpServer", 587)
GlobalScope.launch { // or however you do background threads
emailService.send(email)
}
The code:
import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
class EmailService(private var server: String, private var port: Int) {
data class Email(
val auth: Authenticator,
val toList: List<InternetAddress>,
val from: Address,
val subject: String,
val body: String
)
class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(username, password)
}
}
fun send(email: Email) {
val props = Properties()
props["mail.smtp.auth"] = "true"
props["mail.user"] = email.from
props["mail.smtp.host"] = server
props["mail.smtp.port"] = port
props["mail.smtp.starttls.enable"] = "true"
props["mail.smtp.ssl.trust"] = server
props["mail.mime.charset"] = "UTF-8"
val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
msg.setFrom(email.from)
msg.sentDate = Calendar.getInstance().time
msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
// msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
// msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
msg.replyTo = arrayOf(email.from)
msg.addHeader("X-Mailer", CLIENT_NAME)
msg.addHeader("Precedence", "bulk")
msg.subject = email.subject
msg.setContent(MimeMultipart().apply {
addBodyPart(MimeBodyPart().apply {
setText(email.body, "iso-8859-1")
//setContent(email.htmlBody, "text/html; charset=UTF-8")
})
})
Transport.send(msg)
}
companion object {
const val CLIENT_NAME = "Android StackOverflow programmatic email"
}
}
Gradle:
dependencies {
implementation 'com.sun.mail:android-mail:1.6.4'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}
AndroidManifest:
<uses-permission name="android.permission.INTERNET" />
val df = spark.read.textFile("abc.txt")
case class Abc (amount:Int, types: String, id:Int) //columns and data types
val df2 = df.map(rec=>Amount(rec(0).toInt, rec(1), rec(2).toInt))
rdd2.printSchema
root
|-- amount: integer (nullable = true)
|-- types: string (nullable = true)
|-- id: integer (nullable = true)