It's very important for accessibility reasons that you always specify value of the submit even if you are hiding this text, or if you use <input type="image" .../>
to always specify alt=""
attribute for this input field.
Blind people don't know what button will do if it doesn't contain meaningful alt=""
or value=""
.
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
Solution for me was to set the "form" attribute of button
<form id="form_id_name"><button name="btnSubmit" form="form_id_name" /></form>
or is js:
YOURFORMOBJ.getElementsByTagName("button")[0].setAttribute("form", "form_id_name");
YOURFORMOBJ.submit();
this.mainInput
doesn't actually point to anything. Since you are using a controlled component (i.e. the value of the input is obtained from state) you can set this.state.city
to null:
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({ city: '' });
}
You're really close to the answer yourself
<button type="submit">
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>
Or, you can just remove the type-attribute
<button>
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>
Here is the code that worked to me sure it will help you
<form name="loginBox" target="#here" method="post">
<input name="username" type="text" /><br />
<input name="password" type="password" />
<input type="submit" />
</form>
<script type="text/javascript">
$(function () {
$("form").each(function () {
$(this)
.find("input")
.keypress(function (e) {
if (e.which == 10 || e.which == 13) {
this.form.submit();
}
});
$(this).find("input[type=submit]").hide();
});
});
</script>
This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:
$(function () {
$('body').on('click', '.odom-submit', function (e) {
$(this.form).submit();
$('#myModal').modal('hide');
});
});
To make this work I did this in the modal footer
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary odom-submit">Save changes</button>
</div>
Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.
You need to prevent the default behaviour. You can either use e.preventDefault()
or return false;
In this case, the best thing is, you can use return false;
here:
<form onsubmit="completeAndRedirect(); return false;">
Have both buttons submit to the current page and then add this code at the top:
<?php
if(isset($_GET['firstButtonName'])
header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
if(isset($_GET['secondButtonName'])
header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>
It could also be done using $_SESSION if you don't want them to see the variables.
For --driver-class-path
option you can use :
as delimeter to pass multiple jars.
Below is the example with spark-shell
command but I guess the same should work with spark-submit
as well
spark-shell --driver-class-path /path/to/example.jar:/path/to/another.jar
Spark version: 2.2.0
I prefer (keydown.enter)="mySubmit()"
because there won't be added a line break if the cursor was somewhere within a <textarea>
but not at its end.
<h3>Form</h3>
<form action='' id='theform' >
<div class='row'>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type='text' name='name' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<input class='btn btn-primary pull-right' type="button" value="Submit" id='btnsubmit' />
</div>
</div>
</form>
<script>
$(function()
{
$('#btnsubmit').on('click',function()
{
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#theform').submit();
});
});
</script>
Eg:
if 'newsletter_sub' in request.POST:
# do subscribe
elif 'newsletter_unsub' in request.POST:
# do unsubscribe
I had a very similar problem where for the form action, I had something like:
<form action="http://www.example.com/?q=content/something" method="GET">
<input type="submit" value="Go away..." />
</form>
The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something
also worked. I also could have used a node number (i.e. /node/123
).
you can use OnClick="document.getElementById('formID_NOT_NAME').SUBMIT()"
Yes, it is possible. One of the solutions is below (jsfiddle as a proof).
HTML:
<a id="fire" href="#" title="submit form">Submit form</a>
(see, above there is no form)
JavaScript:
jQuery('#fire').click(function(event){
event.preventDefault();
var newForm = jQuery('<form>', {
'action': 'http://www.google.com/search',
'target': '_top'
}).append(jQuery('<input>', {
'name': 'q',
'value': 'stack overflow',
'type': 'hidden'
}));
newForm.submit();
});
The above example shows you how to create form, how to add inputs and how to submit. Sometimes display of the result is forbidden by X-Frame-Options
, so I have set target
to _top
, which replaces the main window's content. Alternatively if you set _blank
, it can show within new window / tab.
Can you not use AcceptButton
in for the Forms Properties Window? This sets the default behaviour for the Enter key press, but you are still able to use other shortcuts.
To keep the scripting in one place rather than using onClick in the HTML tag, add the following code to your script block:
$('#id-of-the-button').click(function() {document.forms[0].submit()});
Which assumes you just have the one form on the page.
Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.
First considerations are about mixing HTML, Javascript and CSS:
Why is using onClick() in HTML a bad practice?
I will be removing inline content and splitting these into their appropriate files.
Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.
Your function changeBackground
sets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up in the DOM twice.
CSS
#TheForm {
margin-left: 396px;
}
#submitColor {
margin-left: 48px;
margin-top: 5px;
}
HTML
<form id="TheForm">
<input id="color" type="text" />
<br/>
<input id="submitColor" value="Submit" type="button" />
</form>
<span id="coltext">This text should have the same color as you put in the text box</span>
Javascript
function changeBackground() {
var color = document.getElementById("color").value; // cached
// The working function for changing background color.
document.bgColor = color;
// The code I'd like to use for changing the text simultaneously - however it does not work.
document.getElementById("coltext").style.color = color;
}
document.getElementById("submitColor").addEventListener("click", changeBackground, false);
On jsfiddle
Source: w3schools
CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).
Hex values are written as 3 double digit numbers, starting with a # sign.
Update: as pointed out by @Ian
Hex can be either 3 or 6 characters long
Source: W3C
The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.
Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.
For regex testing, I will use this pattern
/^#(?:[0-9a-f]{3}){1,2}$/i
but if you were regex matching and wanted to break the numbers into groups then you would require a different pattern
function changeBackground() {
var color = document.getElementById("color").value.trim(),
rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i;
if (rxValidHex.test(color)) {
document.getElementById("coltext").style.color = color;
} else {
alert("Invalid CSS Hex Color");
}
}
document.getElementById("submitColor").addEventListener("click", changeBackground, false);
On jsfiddle
Here is a further modification that will allow colours by name along with by hex.
function changeBackground() {
var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"],
color = document.getElementById("color").value.trim(),
rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i,
formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase();
if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) {
document.getElementById("coltext").style.color = color;
} else {
alert("Invalid CSS Color");
}
}
document.getElementById("submitColor").addEventListener("click", changeBackground, false);
On jsfiddle
In JQuery you can call
$("form:first").trigger("submit")
Don't know if that is much better. I think form.submit(); is pretty universal.
You need to delegate event to the document level
$(document).on('submit','form.remember',function(){
// code
});
$('form.remember').on('submit'
work same as $('form.remember').submit(
but when you use $(document).on('submit','form.remember'
then it will also work for the DOM added later.
You could do it in one document if you had a conditional based on params sent over. Eg:
if (isset($_GET['secret_param'])) {
<run script>
} else {
<display button>
}
I think the best way though is to have two files.
submit()
method can be used to click on the button present in the form and Type attribute should be "submit".
click()
method is used to click on the button in the webpage.
Correct me if i am wrong.
Try this:
Suppose HTML like this :
<form id="myform" name="myform" method="POST" action="process_edit_questionnaire.php?project=<?php echo $project_id; ?>">
<div id="question_block">
testing form
</div>
<a href="javascript: submit();">Submit</a>
</form>
<script type='text/javascript'>
function submit()
{
document.forms["myform"].submit();
}
</script>
you can check it out here : http://jsfiddle.net/Zm426/7/
Trigger the submit event on the DOM Node, not a jQuery Object.
$('#subscription_order_form')[0].submit();
or
$('#subscription_order_form').get(0).submit();
or
document.getElementById("subscription_order_form").submit();
This bypasses the jQuery bound event allowing the form to submit normally.
Give each input
a name
attribute. Only the clicked input
's name
attribute will be sent to the server.
<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">
And then
<?php
if (isset($_POST['publish'])) {
# Publish-button was clicked
}
elseif (isset($_POST['save'])) {
# Save-button was clicked
}
?>
Edit: Changed value
attributes to alt
. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]
?
Edit: Since this keeps getting upvotes I went ahead and changed the weird alt
/value
code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image]
.
<form>
<input type="submit" value="Submit to a" formaction="/submit/a">
<input type="submit" value="submit to b" formaction="/submit/b">
</form>
Add the disable part in the submit event.
$(document).ready(function () {
$("#yourFormId").submit(function () {
$(".submitBtn").attr("disabled", true);
return true;
});
});
Since a jQuery object inherits from an array, and this array contains the selected DOM elements. Saying you're using an id and so the element should be unique within the DOM, you could perform a direct call to submit by doing :
$(".nextbutton").click(function() {
$("#formID")[0].submit();
});
I made a function which handles arrays as well as single GET or POST values
function subVal($varName, $default=NULL,$isArray=FALSE ){ // $isArray toggles between (multi)array or single mode
$retVal = "";
$retArray = array();
if($isArray) {
if(isset($_POST[$varName])) {
foreach ( $_POST[$varName] as $var ) { // multidimensional POST array elements
$retArray[]=$var;
}
}
$retVal=$retArray;
}
elseif (isset($_POST[$varName]) ) { // simple POST array element
$retVal = $_POST[$varName];
}
else {
if (isset($_GET[$varName]) ) {
$retVal = $_GET[$varName]; // simple GET array element
}
else {
$retVal = $default;
}
}
return $retVal;
}
Examples:
$curr_topdiameter = subVal("topdiameter","",TRUE)[3];
$user_name = subVal("user_name","");
<script type='text/javascript'>
function foo() {
var user_choice = window.confirm('Would you like to continue?');
if(user_choice==true) {
window.location='your url'; // you can also use element.submit() if your input type='submit'
} else {
return false;
}
}
</script>
<input type="button" onClick="foo()" value="save">
this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
No. You can't have the JavaScript post request like a form submit.
What you can have is a form in HTML, then submit it with the JavaScript. (as explained many times on this page).
You can create the HTML yourself, you don't need JavaScript to write the HTML. That would be silly if people suggested that.
<form id="ninja" action="http://example.com/" method="POST">
<input id="donaldduck" type="hidden" name="q" value="a">
</form>
Your function would just configure the form the way you want it.
function postToURL(a,b,c){
document.getElementById("ninja").action = a;
document.getElementById("donaldduck").name = b;
document.getElementById("donaldduck").value = c;
document.getElementById("ninja").submit();
}
Then, use it like.
postToURL("http://example.com/","q","a");
But I would just leave out the function and just do.
document.getElementById('donaldduck').value = "a";
document.getElementById("ninja").submit();
Finally, the style decision goes in the ccs file.
#ninja{
display:none;
}
Personally I think forms should be addressed by name but that is not important right now.
Simple and easy :
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
<input type="submit" />_x000D_
</form>
_x000D_
I find it surprising that no one mentions data
as an object. For me it's the cleanest and easiest way to pass data:
$('form#foo').submit(function () {
$.ajax({
url: 'http://foo.bar/some-ajax-script',
type: 'POST',
dataType: 'json',
data: {
'foo': 'some-foo-value',
'bar': $('#bar').val()
}
}).always(function (response) {
console.log(response);
});
return false;
});
Then, in the backend:
// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar
You can do :
document.forms["loginForm"].submit()
But this won't call the onclick
action of your button, so you will need to call it by hand.
Be aware that you must use the name
of your form and not the id
to access it.
Like @Shoaib answered, you dont need any jQuery or Javascript. You can to this simply with pure html!
<form method="POST" action="index.php?action=contact_agent">
<select name="agent_id" required>
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
<input type="submit" value="Submit">
</form>
&agent_id=
from form action since you don't need it there.name="agent_id"
to the selectrequired
do indicate that this selection is required.Since you are using PHP, then by posting the form to index.php
you can catch agent_id
with $_POST
/** Since you reference action on `form action` then value of $_GET['action'] will be contact_agent */
$action = $_GET['action'];
/** Value of $_POST['agent_id'] will be selected option value */
$agent_id = $_POST['agent_id'];
As conclusion for such a simple task you should not use any javascript or jQuery. To @FelipeAlvarez that answers your comment
HTML5's formaction does not work on old IE browsers. An easy fix, based on some of the responses above, is:
<button onclick="this.form.action='/PropertiesList';"
Account Details </button>
if you need to do something before submitting data, you could use form's onsubmit.
<form method=post onsubmit="return doSomething()">
<input type=text name=text1>
<input type=submit>
</form>
For a similar effect to form's target
attribute, you can also use the formtarget
attribute of input[type="submit]"
or button[type="submit"]
.
From MDN:
...this attribute is a name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the target attribute of the elements's form owner. The following keywords have special meanings:
- _self: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
- _blank: Load the response into a new unnamed browsing context.
- _parent: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
- _top: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
document.getElementById("myform").submit();
This won't work as your form tag doesn't have an id.
Change it like this and it should work:
<form name="myform" id="myform" action="action.php">
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
Insert a coloured box the full size of the slide, set colour to white with 100% transparency. select all, right-click save as picture, select PNG and save.
copy/paste inserted colour box to each slide and repeat
In my case the bitmap image file already existed in the system drive, so my app threw the error "A Generic error occured in GDI+".
The command uptime
gives you load averages for the past 1, 5, and 15 minutes.
I think the most robust solution that will insure that it is posted in uppercase is to use the oninput method inline like:
<input oninput="this.value = this.value.toUpperCase()" />
_x000D_
EDIT
Some people have been complaining that the cursor jumps to the end when editing the value, so this slightly expanded version should resolve that
<input oninput="let p=this.selectionStart;this.value=this.value.toUpperCase();this.setSelectionRange(p, p);" />
_x000D_
Lookarounds can be nested.
So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".
Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"
You might try using:
li {list-style-position: inside; }
But I can't remember if that adjusts the space, or changes where the space occurs.
The above doesn't seem to make any substantial difference. There doesn't seem to be any way to decrease the space between the list-style-type
marker and the text, though it can be increased using margin-left
or text-indent
.
Sorry I can't be of more use.
Just out of curiosity, how about 'faking' the bullet with a background image?
ul {list-style-type: none;
margin: 0;
padding: 0;
}
ul li {background: #fff url(path/to/bullet-image.png) 0 50% no-repeat;
margin: 0;
padding: 0 0 0 10px; /* change 10px to whatever you feel best suits you */
}
It might allow for more fine-tuning.
Should just be this:
var jobject = JsonConvert.DeserializeObject<RootObject>(jsonstring);
You can paste the json string to here: http://json2csharp.com/ to check your classes are correct.
This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data>
element. You setup an intent filter with the <data>
element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)
Here's a short example:
<activity android:name=".MyUriActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="path" />
</intent-filter>
</activity>
As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).
If you want to quickly check if a module is installed (at least on Unix systems, with Bash as shell), add this to your .bashrc file:
alias modver="perl -e\"eval qq{use \\\$ARGV[0];\\\\\\\$v=\\\\\\\$\\\${ARGV[0]}::VERSION;};\ print\\\$@?qq{No module found\\n}:\\\$v?qq{Version \\\$v\\n}:qq{Found.\\n};\"\$1"
Then you can:
=> modver XML::Simple
No module found
=> modver DBI
Version 1.607
Another nice and reusable solution is to create a directive like this:
app.directive( 'backButton', function() {
return {
restrict: 'A',
link: function( scope, element, attrs ) {
element.on( 'click', function () {
history.back();
scope.$apply();
} );
}
};
} );
then just use it like this:
<a href back-button>back</a>
calculate the height of each link no do this
document.getElementById("products").style.height= height_of_each_link* no_of_link
foo.instance_of? String
or
foo.kind_of? String
if you you only care if it is derrived from String
somewhere up its inheritance chain
Open the history tab in Team Explorer from the Branches tile (right-click your branch). Then in the history right-click the commit before the one you don't want to push, choose Reset. That will move the branch back to that commit and should get rid of the extra commit you made. In order to reset before a given commit you thus have to select its parent.
Depending on what you want to do with the changes choose hard, which will get rid of them locally. Or choose soft which will undo the commit but will leave your working directory with the changes in your discarded commit.
More compact:
const chunk = (xs, size) =>_x000D_
xs.map((_, i) =>_x000D_
(i % size === 0 ? xs.slice(i, i + size) : null)).filter(Boolean);_x000D_
_x000D_
// Usage:_x000D_
const sampleArray = new Array(33).fill(undefined).map((_, i) => i);_x000D_
_x000D_
console.log(chunk(sampleArray, 5));
_x000D_
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
Powershell also accept the C/C++/C* not operator
if ( !(Test-Path C:\Code) ){ write "it doesn't exist!" }
I use it often because I'm used to C*...
allows code compression/simplification...
I also find it more elegant...
For "100% of the browser window", if you mean this literally, you should use fixed positioning. The top, bottom, right, and left properties are then used to offset the divs edges from the respective edges of the viewport:
#nav, #content{position:fixed;top:0px;bottom:0px;}
#nav{left:0px;right:235px;}
#content{left:235px;right:0px}
This will set up a screen with the left 235 pixels devoted to the nav, and the right rest of the screen to content.
Note, however, you won't be able to scroll the whole screen at once. Though you can set it to scroll either pane individually, by applying overflow:auto
to either div.
Note also: fixed positioning is not supported in IE6 or earlier.
A lot of the times the implementation will exist in the same namespace as the interface. So, I came up with this:
public class InterfaceConverter : JsonConverter
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.ReadFrom(reader);
var typeVariable = this.GetTypeVariable(token);
if (TypeExtensions.TryParse(typeVariable, out var implimentation))
{ }
else if (!typeof(IEnumerable).IsAssignableFrom(objectType))
{
implimentation = this.GetImplimentedType(objectType);
}
else
{
var genericArgumentTypes = objectType.GetGenericArguments();
var innerType = genericArgumentTypes.FirstOrDefault();
if (innerType == null)
{
implimentation = typeof(IEnumerable);
}
else
{
Type genericType = null;
if (token.HasAny())
{
var firstItem = token[0];
var genericTypeVariable = this.GetTypeVariable(firstItem);
TypeExtensions.TryParse(genericTypeVariable, out genericType);
}
genericType = genericType ?? this.GetImplimentedType(innerType);
implimentation = typeof(IEnumerable<>);
implimentation = implimentation.MakeGenericType(genericType);
}
}
return JsonConvert.DeserializeObject(token.ToString(), implimentation);
}
public override bool CanConvert(Type objectType)
{
return !typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.IsInterface || typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.GetGenericArguments().Any(t => t.IsInterface);
}
protected Type GetImplimentedType(Type interfaceType)
{
if (!interfaceType.IsInterface)
{
return interfaceType;
}
var implimentationQualifiedName = interfaceType.AssemblyQualifiedName?.Replace(interfaceType.Name, interfaceType.Name.Substring(1));
return implimentationQualifiedName == null ? interfaceType : Type.GetType(implimentationQualifiedName) ?? interfaceType;
}
protected string GetTypeVariable(JToken token)
{
if (!token.HasAny())
{
return null;
}
return token.Type != JTokenType.Object ? null : token.Value<string>("$type");
}
}
Therefore, you can include this globally like so:
public static JsonSerializerSettings StandardSerializerSettings => new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new InterfaceConverter()
}
};
With the Material Components Library the best way to make a View
with rounded corners is to use the MaterialShapeDrawable
.
Create a ShapeAppearanceModel with custom rounded corners:
ShapeAppearanceModel shapeAppearanceModelLL1 = new ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,radius16)
.build();
Create a MaterialShapeDrawable
:
MaterialShapeDrawable shapeDrawableLL1 = new MaterialShapeDrawable(shapeAppearanceModeLL1);
If you want to apply also an elevationOverlay for the dark theme use this:
MaterialShapeDrawable shapeDrawableLL1 = MaterialShapeDrawable.createWithElevationOverlay(this, 4.0f);
shapeDrawableLL1.setShapeAppearanceModel(shapeAppearanceModelLL1);
Optional: apply to the shapeDrawable a background color and a stroke
shapeDrawableLL1.setFillColor(
ContextCompat.getColorStateList(this,R.color...));
shapeDrawableLL1.setStrokeWidth(2.0f);
shapeDrawableLL1.setStrokeColor(
ContextCompat.getColorStateList(this,R.color...));
Finally apply the shapeDrawable as background in your LinearLayout
(or other view):
LinearLayout linearLayout1= findViewById(R.id.ll_1);
ViewCompat.setBackground(linearLayout1,shapeDrawableLL1);
I had the same issue.I just uninstalled Java and reinstalled again it worked fine after that . The problem is related to JRE so you can just reinstall JRE.
I had a different approach , used bootstrap panel to show it little more rich. Just to help someone and improve the answer.
.text-on-pannel {_x000D_
background: #fff none repeat scroll 0 0;_x000D_
height: auto;_x000D_
margin-left: 20px;_x000D_
padding: 3px 5px;_x000D_
position: absolute;_x000D_
margin-top: -47px;_x000D_
border: 1px solid #337ab7;_x000D_
border-radius: 8px;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
/* for text on pannel */_x000D_
margin-top: 27px !important;_x000D_
}_x000D_
_x000D_
.panel-body {_x000D_
padding-top: 30px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="container">_x000D_
<div class="panel panel-primary">_x000D_
<div class="panel-body">_x000D_
<h3 class="text-on-pannel text-primary"><strong class="text-uppercase"> Title </strong></h3>_x000D_
<p> Your Code </p>_x000D_
</div>_x000D_
</div>_x000D_
<div>
_x000D_
Note: We need to change the styles in order to use different header size.
You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
expression.
(1) If all you need is the difference between two instants in seconds, the very simple time.time()
does the job.
(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:
gmtime()
returns a time tuple in UTC but mktime()
expects a time tuple in local time.
I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31
>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time
You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow()
which won't jump by an hour when DST goes on/off and may give you more precision than time.time()
I had a similar error "Specified cast is not valid" restoring from SQL Server 2012 to SQL Server 2008 R2
First I got the MDF and LDF Names:
RESTORE FILELISTONLY
FROM DISK = N'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak'
GO
Second I restored with a MOVE using those names returned:
RESTORE DATABASE Davincis3
FROM DISK = 'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak'
WITH
MOVE 'JQueryExampleDb' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.mdf',
MOVE 'JQueryExampleDB_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.ldf',
REPLACE
GO
I have no clue as to the name "JQueryExampleDb", but this worked for me.
Nevertheless, backups (and databases) are not backwards compatible with older versions.
In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.
However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.
In that case, you can use
jekyll serve --host 0.0.0.0
This binds your application to the host & next use following to connect to it from some other host
http://host's IP adress/4000
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
Solution :
login as sysdaba:
sqlplus / as sysdba
then:
sql>Shutdown immediate;
sql>startup restrict;
sql>drop user TEST cascade;
If you want to re-activate DB normally either reset the server or :
sql>Shutdown immediate;
sql>startup;
:)
Print the backspace character \b
several times, and then overwrite the old number with the new number.
keyCode and which represent the actual keyboard key pressed in the form of a numeric value. The reason both exist is that keyCode is available within Internet Explorer while which is available in W3C browsers like FireFox.
charCode is similar, but in this case you retrieve the Unicode value of the character pressed. For example, the letter "A."
The JavaScript expression:
var keyCode = e.keyCode ? e.keyCode : e.charCode;
Essentially says the following:
If the e.keyCode property exists, set variable keyCode to its value. Otherwise, set variable keyCode to the value of the e.charCode property.
Note that retrieving the keyCode or charCode properties typically involve figuring out differences between the event models in IE and in W3C. Some entails writing code like the following:
/*
get the event object: either window.event for IE
or the parameter e for other browsers
*/
var evt = window.event ? window.event : e;
/*
get the numeric value of the key pressed: either
event.keyCode for IE for e.which for other browsers
*/
var keyCode = evt.keyCode ? evt.keyCode : e.which;
EDIT: Corrections to my explanation of charCode as per Tor Haugen's comments.
Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).
First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.
After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:
Dim xlApp as Excel.Application
Let's say you added an Excel Workbook Object in your Form and named it xLObject.
Here is how you Access a Sheet of this Object and change a Range
Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"
(I copied the above from my answer to this question)
Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)
I found this CSS3 feature helpful:
/* to position the element 10px from the right */
background-position: right 10px top;
As far as I know this is not supported in IE8. In latest Chrome/Firefox it works fine.
See Can I use for details on the supported browsers.
Used source: http://tanalin.com/en/blog/2011/09/css3-background-position/
Update:
This feature is now supported in all major browsers, including mobile browsers.
The issue in the original question is that you are not capturing "page" event, to resolve this you need to add (page)='yourEventHandler($event)
' as an attribute in the md-paginator tag.
check a working example here
You can also check the API docs here
The file you give is a shell script, not an awk program. So, try sh my.awk
.
If you want to use awk -f my.awk life.csv > life_out.cs
, then remove awk -F , '
and the last line from the file and add FS=","
in BEGIN
.
First Method
- (void)didMoveToParentViewController:(UIViewController *)parent
{
if (![parent isEqual:self.parentViewController]) {
NSLog(@"Back pressed");
}
}
Second Method
-(void) viewWillDisappear:(BOOL)animated {
if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
// back button was pressed. We know this is true because self is no longer
// in the navigation stack.
}
[super viewWillDisappear:animated];
}
GnuWin32 is worth mentioning, it provides native Win32 version of all standard linux tools, including grep, file, sed, groff, indent, etc.
And it's constantly updated when new versions of these tools are released.
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
a = 5
makes the variable name a
to refer to the integer 5. Later, a = "hello"
makes the variable name a
to refer to a string containing "hello". Static typed languages would have you declare int a
and then a = 5
, but assigning a = "hello"
would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a
refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.a = "5"
(the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5
to get "hello5"
.Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
To update component
@Injectable()
export class LoginService{
private isUserLoggedIn: boolean = false;
public setLoggedInUser(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
this.isUserLoggedIn= flag;
}
public getUserLoggedIn(): boolean {
return this.isUserLoggedIn;
}
Login Component ts
Login Component{
constructor(public service: LoginService){}
public login(){
service.setLoggedInUser(true);
}
}
Inside Header component
Header Component ts
HeaderComponent {
constructor(public service: LoginService){}
public getUserLoggedIn(): boolean { return this.service.getUserLoggedIn()}
}
template of header component: Check for user sign in here
<button *ngIf="getUserLoggedIn()">Sign Out</button>
<button *ngIf="!getUserLoggedIn()">Sign In</button>
You can use many approach like show hide using ngIf
App Component ts
AppComponent {
public showHeader: boolean = true;
}
App Component html
<div *ngIf='showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
<app-header></app-header>
</div>
<router-outlet></router-outlet>
<app-footer></app-footer>
You can also use service
@Injectable()
export class AppService {
private showHeader: boolean = false;
public setHeader(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
this.showHeader = flag;
}
public getHeader(): boolean {
return this.showHeader;
}
}
App Component.ts
AppComponent {
constructor(public service: AppService){}
}
App Component.html
<div *ngIf='service.showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
<app-header></app-header>
</div>
<router-outlet></router-outlet>
<app-footer></app-footer>
Use react-router-dom
library.
From there, import useLocation
hook if you're using functional components:
import { useLocation } from 'react-router-dom';
Then append it to a variable:
Const location = useLocation();
You can then use it normally:
location.pathname
P.S: the returned location
object has five properties only:
{ hash: "", key: "", pathname: "/" search: "", state: undefined__, }
Match the whole line, so add a .*
at the beginning of your regex. This causes the entire line to be replaced with the contents of the group
echo "foo bar <foo> bla 1 2 3.4" |
sed -n 's/.*\([0-9][0-9]*[\ \t][0-9.]*[ \t]*$\)/\1/p'
2 3.4
In the server, do something like this:
Suppose
String data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='
Then:
String base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
Then you can do whatever you like with the bytes like:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
For Visual Studio Users, On Package Manager console:
git branch | %{ git fetch upstream; git merge upstream/master}
A simple and direct Python extension would save both time and efforts.
Linting, debugging, code completion are the available features once installation is done. After this, to run the code proper Python installation path needs to be configured in order to run the code. General settings are available in User scope and Workspace can be configured for Python language– "python.pythonPath": "c:/python27/python.exe"
With above steps at least the basic Python programs can be executed.
You can do like this:
private void datagridview1_SelectionChanged(object sender, EventArgs e)
{
if (datagridview1.SelectedCells.Count > 0)
{
int selectedrowindex = datagridview1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = datagridview1.Rows[selectedrowindex];
string cellValue = Convert.ToString(selectedRow.Cells["enter column name"].Value);
}
}
Almost never. Errors are designed to be issues that applications generally can't do anything about. The only exception might be to handle the presentation of the error but even that might not go as planned depending on the error.
Here is the example works fine in oracle
select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');
The other Answers are correct, especially this one by Stephen C.
Generating a UUID value within Java is limited to Version 4 (random) because of security concerns.
If you want other versions of UUIDs, one avenue is to have your Java app reach outside the JVM to generate UUIDs by calling on:
uuidgen
found in Mac OS X, BSD, and Linux.uuid-ossp
extension often bundled with Postgres. That extension can generates Versions 1, 3, and 4 values and additionally a couple variations:
uuid_generate_v1mc()
– generates a version 1 UUID but uses a random multicast MAC address instead of the real MAC address of the computer.uuid_generate_v5(namespace uuid, name text)
– generates a version 5 UUID, which works like a version 3 UUID except that SHA-1 is used as a hashing method.I had the same error, the problem was because I no longer had disk space. to check the space run this:
$ df -h
Then delete some files that you didn't need.
After this commands:
service mysql start
systemctl status mysql.service
mysql -u root -p
After entering with the root password verify that the mysql service was active
string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";
You can use MPAndroidChart.
It's native, free, easy to use, fast and reliable.
Core features, benefits:
Drawbacks:
Disclaimer: I am the developer of this library.
You can use
np.tile(x,3).reshape((4,3))
tile will generate the reps of the vector
and reshape will give it the shape you want
Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from
result.replace(/"/g,'"')
to
result.replace(/"/g,'"')
Instead of this I use that:
result.replace(/("\;)/g,"\"")
By this notation it works.
I would recommend you well tested PHP library: curl-easy
<?php
$request = new cURL\Request('http://www.externalsite.com/script2.php?variable=45');
$request->getOptions()
->set(CURLOPT_TIMEOUT, 5)
->set(CURLOPT_RETURNTRANSFER, true);
// add callback when the request will be completed
$request->addListener('complete', function (cURL\Event $event) {
$response = $event->response;
$content = $response->getContent();
echo $content;
});
while ($request->socketPerform()) {
// do anything else when the request is processed
}
You need to use a date formatting function for example to_char http://www.postgresql.org/docs/current/static/functions-formatting.html
You need to define a root route.
app.get('/', function(req, res) {
// do something here.
});
Oh and you cannot specify a file within the express.static
. It needs to be a directory. The app.get('/'....
will be responsible to render that file accordingly. You can use express' render method, but your going to have to add some configuration options that will tell express where your views are, traditionally within the app/views/
folder.
add like
<head runat="server">
<script src="Registration.js" type="text/javascript"></script>
</head>
OR can add in code behind.
Page.ClientScript.RegisterClientScriptInclude("Registration", ResolveUrl("~/js/Registration.js"));
built on dmark's answer to get the following, which is useful if you want the equiv of sprintf and hopefully will help someone...
def sprint(object):
result = ''
for i in [v for v in dir(object) if not callable(getattr(object, v)) and v[0] != '_']:
result += '\n%s:' % i + str(getattr(object, i, ''))
return result
Is there a more elegant way to write this code?
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
In addition to selecting all elements with an attribute $('[someAttribute]')
or $('input[someAttribute]')
you can also use a function for doing boolean checks on an object such as in a click handler:
if(! this.hasAttribute('myattr') ) { ...
If you want see your buffer size in terminal, you can take a look at:
/proc/sys/net/ipv4/tcp_rmem
(for read) /proc/sys/net/ipv4/tcp_wmem
(for write)They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.
This example uses jquery-cookie
Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):
if($.cookie('popup') != 'seen'){
$.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
};
Another alternative is setLayoutFrozen
, but it comes with a bunch of other side effects.
Looks like you've got some answers to this, however I think there is something worth mentioning here that will greatly simplify your code. jQuery introduced the $.when
in v1.5. It looks like:
$.when($.ajax(...), $.ajax(...)).then(function (resp1, resp2) {
//this callback will be fired once all ajax calls have finished.
});
Didn't see it mentioned here, hope it helps.
A more reusable approach.
This is a functionality we generally use in most of our apps. Hence here is a reusable piece of code to achieve this.
(Similar to other answers in terms for facts. Posting it here just to simplify and make the implementation reusable)
"fb://page/
does not work with newer versions of the FB app. You should use fb://facewebmodal/f?href=
for newer versions. (Like mentioned in another answer here)
This is a full fledged working code currently live in one of my apps:
public static String FACEBOOK_URL = "https://www.facebook.com/YourPageName";
public static String FACEBOOK_PAGE_ID = "YourPageName";
//method to get the right URL to use in the intent
public String getFacebookPageURL(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
if (versionCode >= 3002850) { //newer versions of fb app
return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
} else { //older versions of fb app
return "fb://page/" + FACEBOOK_PAGE_ID;
}
} catch (PackageManager.NameNotFoundException e) {
return FACEBOOK_URL; //normal web url
}
}
This method will return the correct url for app if installed or web url if app is not installed.
Then start an intent as follows:
Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = getFacebookPageURL(this);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);
That's all you need.
There are many ways of solving this problem, and the ones listed above are the most commonly used ways of achieving the solution. I want to add two more ways, just in case someone is looking for an alternative.
index_list = [1,3]
df.take(pos)
#or
df.query('index in @index_list')
From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.
Add the following to your build.gradle file:
repositories {
jcenter()
}
dependencies {
implementation 'com.journeyapps:zxing-android-embedded:4.1.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
}
android {
buildToolsVersion '28.0.3' // Older versions may give compile errors
}
Older SDK versions
For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:
repositories {
jcenter()
}
dependencies {
implementation('com.journeyapps:zxing-android-embedded:4.1.0') { transitive = false }
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'com.google.zxing:core:3.3.0'
}
android {
buildToolsVersion '28.0.3'
}
You'll also need this in your Android manifest:
<uses-sdk tools:overrideLibrary="com.google.zxing.client.android" />
Source : https://github.com/journeyapps/zxing-android-embedded
It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.
The above were really close. Here's my solution:
Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
Dim i As Integer
outClone = inClone.Clone
Dim dv As DataView = inClone.Tables(0).DefaultView
dv.RowFilter = matchStr
Dim dt As New DataTable
dt = dv.ToTable
For i = 0 To dv.Count - 1
outClone.Tables(0).ImportRow(dv.Item(i).Row)
Next
End Sub
An IEnumerator
is a thing that can enumerate: it has the Current
property and the MoveNext
and Reset
methods (which in .NET code you probably won't call explicitly, though you could).
An IEnumerable
is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator
.
Which do you use? The only reason to use IEnumerator
is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You'd create a new class implementing IEnumerator
. But you'd still need to return that IEnumerator
in an IEnumerable
class.
For a look at what an enumerator (implementing IEnumerator<T>
) looks like, see any Enumerator<T>
class, such as the ones contained in List<T>
, Queue<T>,
or Stack<T>
. For a look at a class implementing IEnumerable
, see any standard collection class.
Please check your /etc/yum.conf
file, maybe it is exclude php
packages.
You should remove php*
from this line so you can download php-*
packages:
exclude= courier* dovecot* exim* filesystem httpd* mod_ssl* mydns* php*
It's seems your server having some scripts like cPanel
In memory usage and speed.
When you call jsonstr = json.dumps(mydata)
it first creates a full copy of your data in memory and only then you file.write(jsonstr)
it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.
When you call json.dump(mydata, file)
-- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.
Source: I checked the source code of json.dump()
and json.dumps()
and also tested both the variants measuring the time with time.time()
and watching the memory usage in htop.
$('#usersSearch').keyup(function() { // handle keyup event on search input field
var key = e.which || e.keyCode; // store browser agnostic keycode
if(key == 13)
$(this).closest('form').submit(); // submit parent form
}
I wrote a general purpose function that scrolls to either a jQuery object, a CSS selector, or a numeric value.
Example usage:
// scroll to "#target-element":
$.scrollTo("#target-element");
// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);
// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");
The function's code:
/**
* Scrolls the container to the target position minus the offset
*
* @param target - the destination to scroll to, can be a jQuery object
* jQuery selector, or numeric position
* @param offset - the offset in pixels from the target position, e.g.
* pass -80 to scroll to 80 pixels above the target
* @param speed - the scroll speed in milliseconds, or one of the
* strings "fast" or "slow". default: 500
* @param container - a jQuery object or selector for the container to
* be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {
if (isNaN(target)) {
if (!(target instanceof jQuery))
target = $(target);
target = parseInt(target.offset().top);
}
container = container || "html, body";
if (!(container instanceof jQuery))
container = $(container);
speed = speed || 500;
offset = offset || 0;
container.animate({
scrollTop: target + offset
}, speed);
};
This is confusing for everyone when it comes IISExpress. There is nothing to read console messages. So for example, in the ASPCORE MVC apps it configures using appsettings.json which does nothing if you are using IISExpress.
For right now you can just add loggerFactory.AddDebug(LogLevel.Debug); in your Configure section and it will at least show you your logs in the Debug Output window.
Good news CORE 2.0 this will all be changing: https://github.com/aspnet/Announcements/issues/255
You miss parenthesis:
var value: string = dataObjects[i].getValue();
var id: number = dataObjects[i].getId();
None of the above worked for me. I SOLVED my problem by saving my source data (save as) Excel file as a single xls Worksheet Excel 5.0/95 and imported without column headings. Also, I created the table in advance and mapped manually instead of letting SQL create the table.
Well one way to do it is set the height of your body to the height
that you want your page
to be. In this example I did 600px
.
Then set your wrapper
height to a percentage of the body here I did 70%
This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.
body {
padding-top: 70px;
border:1px solid black;
height:600px;
}
.mygrid-wrapper-div {
border: solid red 5px;
overflow: scroll;
height: 70%;
}
Update How about a jQuery approach.
$(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
$( window ).resize(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
use
window.location.replace("login.php");
or simply window.location("login.php");
It is better than using window.location.href =,
because replace()
does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href
. If you want to simulate an HTTP redirect, use location.replace
.
INSERT INTO table_name1 (id, name, address, contact_number) SELECT id, name, address, contact_number FROM table_name2;
Set the text of the button by setting the innerHTML
var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.innerHTML = 'test value';
var wrapper = document.getElementById('divWrapper');
wrapper.appendChild(b);
Check your capitalization!
Your host system (Windows or Mac) is case insensitive by default, and Homestead inherits this behavior. Your production server on the other hand is case sensitive.
Whenever you get a ClassNotFound Exception check the following:
you should use rownum in oracle to do what you seek
where rownum <= 100
see also those answers to help you
Here is one simple example.. you can download and test it http://www.pretechsol.com/2014/12/java-ee-websocket-simple-example.html
Just finish it up.
string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";
DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
DataSet ds = new DataSet();
using (SqlCommand cmd = new SqlCommand(
sqlCommand, new SqlConnection(connectionString)))
{
cmd.Connection.Open();
DataTable table = new DataTable();
table.Load(cmd.ExecuteReader());
ds.Tables.Add(table);
}
return ds;
}
AFAIK, {...}
can only be used as a path, not inside a query-param. Try this instead:
public interface FooService {
@GET("/maps/api/geocode/json?sensor=false")
void getPositionByZip(@Query("address") String address, Callback<String> cb);
}
If you have an unknown amount of parameters to pass, you can use do something like this:
public interface FooService {
@GET("/maps/api/geocode/json")
@FormUrlEncoded
void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}
You need a semicolon after font-family: Arial, Helvetica, sans-serif
. This will make your updated code the following:
<!DOCTYPE>
<html>
<head>
<title>DIV Font</title>
<style>
.my_text
{
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="my_text">some text</div>
</body>
</html>
AsyncTask uses a thread pool pattern for running the stuff from doInBackground(). The issue is initially (in early Android OS versions) the pool size was just 1, meaning no parallel computations for a bunch of AsyncTasks. But later they fixed that and now the size is 5, so at most 5 AsyncTasks can run simultaneously. Unfortunately I don't remember in what version exactly they changed that.
UPDATE:
Here is what current (2012-01-27) API says on this:
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. After HONEYCOMB, it is planned to change this back to a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can use the executeOnExecutor(Executor, Params...) version of this method with THREAD_POOL_EXECUTOR; however, see commentary there for warnings on its use.
DONUT is Android 1.6, HONEYCOMB is Android 3.0.
UPDATE: 2
See the comment by kabuko
from Mar 7 2012 at 1:27
.
It turns out that for APIs where "a pool of threads allowing multiple tasks to operate in parallel" is used (starting from 1.6 and ending on 3.0) the number of simultaneously running AsyncTasks depends on how many tasks have been passed for execution already, but have not finished their doInBackground()
yet.
This is tested/confirmed by me on 2.2. Suppose you have a custom AsyncTask that just sleeps a second in doInBackground()
. AsyncTasks use a fixed size queue internally for storing delayed tasks. Queue size is 10 by default. If you start 15 your custom tasks in a row, then first 5 will enter their doInBackground()
, but the rest will wait in a queue for a free worker thread. As soon as any of the first 5 finishes, and thus releases a worker thread, a task from the queue will start execution. So in this case at most 5 tasks will run simultaneously. However if you start 16 your custom tasks in a row, then first 5 will enter their doInBackground()
, the rest 10 will get into the queue, but for the 16th a new worker thread will be created so it'll start execution immediately. So in this case at most 6 tasks will run simultaneously.
There is a limit of how many tasks can be run simultaneously. Since AsyncTask
uses a thread pool executor with limited max number of worker threads (128) and the delayed tasks queue has fixed size 10, if you try to execute more than 138 your custom tasks the app will crash with java.util.concurrent.RejectedExecutionException
.
Starting from 3.0 the API allows to use your custom thread pool executor via AsyncTask.executeOnExecutor(Executor exec, Params... params)
method. This allows, for instance, to configure the size of the delayed tasks queue if default 10 is not what you need.
As @Knossos mentions, there is an option to use AsyncTaskCompat.executeParallel(task, params);
from support v.4 library to run tasks in parallel without bothering with API level. This method became deprecated in API level 26.0.0.
UPDATE: 3
Here is a simple test app to play with number of tasks, serial vs. parallel execution: https://github.com/vitkhudenko/test_asynctask
UPDATE: 4 (thanks @penkzhou for pointing this out)
Starting from Android 4.4 AsyncTask
behaves differently from what was described in UPDATE: 2 section. There is a fix to prevent AsyncTask
from creating too many threads.
Before Android 4.4 (API 19) AsyncTask
had the following fields:
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(10);
In Android 4.4 (API 19) the above fields are changed to this:
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
This change increases the size of the queue to 128 items and reduces the maximum number of threads to the number of CPU cores * 2 + 1. Apps can still submit the same number of tasks.
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).Using CTEs - Common Table Expressions:
WITH MyCTE(MaxPKID, SomeColumn1)
AS(
SELECT MAX(a.MyTablePKID) AS MaxPKID, a.SomeColumn1
FROM MyTable1 a
GROUP BY a.SomeColumn1
)
SELECT b.MyTablePKID, b.SomeColumn1, b.SomeColumn2 MAX(b.NumEstado)
FROM MyTable1 b
INNER JOIN MyCTE c ON c.MaxPKID = b.MyTablePKID
GROUP BY b.MyTablePKID, b.SomeColumn1, b.SomeColumn2
--Note: MyTablePKID is the PrimaryKey of MyTable
I'm using gson 2.2.3
public class Main {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
JsonReader jsonReader = new JsonReader(new FileReader("jsonFile.json"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("descriptor")) {
readApp(jsonReader);
}
}
jsonReader.endObject();
jsonReader.close();
}
public static void readApp(JsonReader jsonReader) throws IOException{
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
System.out.println(name);
if (name.contains("app")){
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String n = jsonReader.nextName();
if (n.equals("name")){
System.out.println(jsonReader.nextString());
}
if (n.equals("age")){
System.out.println(jsonReader.nextInt());
}
if (n.equals("messages")){
jsonReader.beginArray();
while (jsonReader.hasNext()) {
System.out.println(jsonReader.nextString());
}
jsonReader.endArray();
}
}
jsonReader.endObject();
}
}
jsonReader.endObject();
}
}
In general, sizeof(pretty much anything) will change when you compile on different platforms. On a 32 bit platform, pointers are always the same size. On other platforms (64 bit being the obvious example) this can change.
If you’re not averse to using double-dollar scope props and you’re writing a directive whose only content is a repeat, there is a pretty simple solution (assuming you only care about the initial render). In the link function:
const dereg = scope.$watch('$$childTail.$last', last => {
if (last) {
dereg();
// do yr stuff -- you may still need a $timeout here
}
});
This is useful for cases where you have a directive that needs to do DOM manip based on the widths or heights of the members of a rendered list (which I think is the most likely reason one would ask this question), but it’s not as generic as the other solutions that have been proposed.
See Python Web Frameworks wiki.
You probably do not need the full stack frameworks, but the remaining list is still quite long.
ceil from lodash is probably the best
_.ceil("315.9250488",2)
_.ceil(315.9250488,2)
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)
will work also with a number and it's safe
ALTER TABLE tableName MODIFY columnName columnType NULL;
Building on Preet Sangha's solution, the following should safely cover the scenario where you're working with a large solution with the potential for several Inner Exceptions.
try
{
object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{
// Here I was hoping to get an error code.
if (ExceptionContainsErrorCode(e, 10004))
{
// Execute desired actions
}
}
...
private bool ExceptionContainsErrorCode(Exception e, int ErrorCode)
{
Win32Exception winEx = e as Win32Exception;
if (winEx != null && ErrorCode == winEx.ErrorCode)
return true;
if (e.InnerException != null)
return ExceptionContainsErrorCode(e.InnerException, ErrorCode);
return false;
}
This code has been unit tested.
I won't harp too much on the need for coming to appreciate and implement good practice when it comes to Exception Handling by managing each expected Exception Type within their own blocks.
The override
keyword serves two purposes:
To explain the latter:
class base
{
public:
virtual int foo(float x) = 0;
};
class derived: public base
{
public:
int foo(float x) override { ... } // OK
}
class derived2: public base
{
public:
int foo(int x) override { ... } // ERROR
};
In derived2
the compiler will issue an error for "changing the type". Without override
, at most the compiler would give a warning for "you are hiding virtual method by same name".
What you want to do is prevent the default action of the click event. To do this, you will need to modify your script like this:
$(document).ready(function() {
$('.galleryicon').live("click", function(e) {
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
return false;
e.preventDefault();
});
});
So, you're adding an "e" that represents the event in the line $('.galleryicon').live("click", function(e) {
and you're adding the line e.preventDefault();
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}
Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.
Here is the one I most liked.
It is always good to implement exception handling. It does not only help to avoid unexpected exit of script but can also help to log errors and info notification. When using Python requests I prefer to catch exceptions like this:
try:
res = requests.get(adress,timeout=30)
except requests.ConnectionError as e:
print("OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\n")
print(str(e))
renewIPadress()
continue
except requests.Timeout as e:
print("OOPS!! Timeout Error")
print(str(e))
renewIPadress()
continue
except requests.RequestException as e:
print("OOPS!! General Error")
print(str(e))
renewIPadress()
continue
except KeyboardInterrupt:
print("Someone closed the program")
Here renewIPadress() is a user define function which can change the IP address if it get blocked. You can go without this function.
Go into Simulator-> Hardware->Keyboard and unchecking Connect Hardware Keyboard.
The same as many answers above BUT did not change for me until I quit and restart the simulator. xcode 8.2.1 and Simulator 10.0.
try this
in layout.xml :
<TextView
android:id="@+id/xxx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/empty_spaces" />
in strings.xml :
<string name="empty_spaces">\t\t</string>
it worked for me
Your return is useless if you don't assign it
list=defineAList()
There is a much easier and more compact solution for multilevel prototype lookup, but it requires Proxy
support. Usage: SUPER(<instance>).<method>(<args>)
, for example, assuming two classes A
and B extends A
with method m
: SUPER(new B).m()
.
function SUPER(instance) {
return new Proxy(instance, {
get(target, prop) {
return Object.getPrototypeOf(Object.getPrototypeOf(target))[prop].bind(target);
}
});
}
If you have access to change the JVM parameters, adding verbose output should allow you to see what classes are being loaded from which JAR files.
java -verbose:class <other args>
When your program is run, the JVM should dump to standard out information such as:
...
[Loaded junit.framework.Assert from file:/C:/Program%20Files/junit3.8.2/junit.jar]
...
You don't need a regex for this. Use tr:
"some text\nandsomemore".tr("\n","")
I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.
The full shortcut target is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
So I put the following at the start of my script and it seemed to function as expected:
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
Notes:
Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.
Copy/Paste Code below:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date
End Sub
Good luck...
dict1 = {'m': 2, 'n': 4}
dict2 = {'n': 3, 'm': 1}
Making sure that the keys are in the same order:
dict2_sorted = {i:dict2[i] for i in dict1.keys()}
keys = dict1.keys()
values = zip(dict1.values(), dict2_sorted.values())
dictionary = dict(zip(keys, values))
gives:
{'m': (2, 1), 'n': (4, 3)}
remove the ios::binary
from your modes in your ofstream and use studentPassword.c_str()
instead of (char *)&studentPassword
in your write.write()
Voila! No need to fight with Gradle :)
faster to read than non cluster as data is physically storted in index order we can create only one per table.(cluster index)
quicker for insert and update operation than a cluster index. we can create n number of non cluster index.
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
This should do it:
<div class="home-component"
[style.width]="width + 'px'"
[style.height]="height + 'px'">Some stuff in this div</div>
Others have already established that this error is due to another application having a lock on the file. Just wanted to point out that git diff
locks files as well until you quit out of it. That's what caused this in my case.
You may be looking for the special HTML character,
.
You can use this to get a line break, and it can be inserted immediately following the last character in the current line. One place this is especially useful is if you want to include multiple lines in a list within a title or alt
label.
Surprised nobody brought this up earlier, but for the pragmatists requiring a database: MongoDB has excellent support for Geo queries including this one.
What you are looking for is:
db.neighborhoods.findOne({ geometry: { $geoIntersects: { $geometry: { type: "Point", coordinates: [ "longitude", "latitude" ] } } } })
Neighborhoods
is the collection that stores one or more polygons in standard GeoJson format. If the query returns null it is not intersected otherwise it is.
Very well documented here: https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/
The performance for more than 6,000 points classified in a 330 irregular polygon grid was less than one minute with no optimization at all and including the time to update documents with their respective polygon.
I suggest to use npm ci
. If you want to install only production-needed packages (as you wrote - without devDependencies
) then:
npm ci --only=production
or
NODE_ENV=production npm ci
If you prefer oldschool npm install
then:
npm install --production
or
NODE_ENV=production npm install
Here is good answer why you should use npm ci
.
memset(msg, 0, 65546)
As mentioned in many sites, there are various reasons for this. For me it was due to the length of Source and Destination (Path length). I tried xcopy in the command prompt and I was unable to type the complete source and path (after some characters it wont allow you to type). I then reduced the path length and was able to run. Hope this helps.
You might want to start with scapy.
In RStudio you can write directly in a cell.
Suppose your data.frame is called myDataFrame
and the row and column are called columnName
and rowName
.
Then the code would look like:
myDataFrame["rowName", "columnName"] <- value
Hope that helps!
I had the same warning in VS 2017. As it turned out in my case I had added a unit test project and needed to set a dependency for the unit test on the DLL it was testing.
git ls-files
lists the files in the current directory. If you want to list untracked files from anywhere in the tree, this might work better:
git ls-files -o --exclude-standard $(git rev-parse --show-toplevel)
To add all untracked files in the tree:
git ls-files -o --exclude-standard $(git rev-parse --show-toplevel) | xargs git add
I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join
helper=1
for i in df1.index:
df1.loc[i,'helper']=helper
helper=helper+1
for i in df2.index:
df2.loc[i,'helper']=helper
helper=helper+1
df1.merge(df2,on='helper',how='outer')
I had to add width: 100%; to display table to fix some strange bahavior in IE and FF, when i used this example. IE and FF had some problems displaying the col-md-* tags at the right width
.display-table {
display: table;
table-layout: fixed;
width: 100%;
}
.display-cell {
display: table-cell;
vertical-align: middle;
float: none;
}
A module is a single file (or files) that are imported under one import and used. e.g.
import my_module
A package is a collection of modules in directories that give a package hierarchy.
from my_package.timing.danger.internets import function_of_love
Here is a non-numpy solution:
>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
Republishing the site fixed the issue for me.
You can use a TextView and change its background to the image you want to use
Simplest way I found in Java is:
List<WebElement> linkSearch= driver.findElements(By.id("linkTag"));
int checkLink=linkSearch.size();
if(checkLink!=0){ //do something you want}
You may want to take a different approach: Instead of changing the css dynamically, predefine your styles in CSS the way you want them. Then use JQuery to add and remove styles from within Javascript. (see code from Ajmal)
This discussion has been for a while and @Alexander T.'s answer provided a good guide to follow for newer of React like me. And I'm gonna share some additional know-hows about calling the same API multiple times to refresh the component, I think it's probably a common problem that newbie may face at the beginning.
componentWillReceiveProps(nextProps)
, from official documentation :
If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.
We could conclude that here is the place we handle props from the parent component, have API calls, and update state.
Base on @Alexander T.'s example:
export default class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {person: []};
}
componentDidMount() {
//For our first load.
this.UserList(this.props.group); //maybe something like "groupOne"
}
componentWillReceiveProps(nextProps) {
// Assuming parameter comes from url.
// let group = window.location.toString().split("/")[*indexParameterLocated*];
// this.UserList(group);
// Assuming parameter comes from props that from parent component.
let group = nextProps.group; // Maybe something like "groupTwo"
this.UserList(group);
}
UserList(group) {
$.getJSON('https://randomuser.me/api/' + group)
.then(({ results }) => this.setState({ person: results }));
}
render() {
return (...)
}
}
componentWillReceiveProps()
would be deprecated.
Here are only some methods (all of them in Doc) in the life cycle which I think would be related to deploying API in general case:
By referring the diagram above:
Deploy API in componentDidMount()
The proper scenario to have API call here is that the content (from the response of API) of this component will be static, componentDidMount()
only fire once while the component is mounting, even new props are passed from parent component or have actions to lead re-rendering
.
The component do check difference to re-render but not re-mount.
Quote from doc:
If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
static getDerivedStateFromProps(nextProps, prevState)
We should notice that there are two kinds of component updating, setState()
in current component would not lead this method to trigger, but re-rendering or new props from parent component do.
We could found out that this method also fires while mounting.
This is a proper place to deploy API if we want to use the current component like a template, and the new parameters for API are props coming from parent component.
We receive a different response from API and return a new state
here to change the content of this component.
For example:
We have a dropdown list for different Cars in the parent component, this component needs to show the details of the selected one.
componentDidUpdate(prevProps, prevState)
Differ from static getDerivedStateFromProps()
, this method is invoked immediately after every rendering except the initial rendering. We could have API calling and render difference in one component.
Extend the previous example:
The component to show Car's details may contain a list of series of this car, if we want to check the 2013 production one, we may click or select or ... the list item to lead a first setState()
to reflect this behavior (such as highlighting the list item) in this component, and in the following componentDidUpdate()
we send our request with new parameters (state). After getting the response, we setState()
again for rendering the different content of the Car details. To prevent the following componentDidUpdate()
from causing the infinity loop, we need to compare the state by utilizing prevState
at the beginning of this method to decide if we send the API and render the new content.
This method really could be utilized just like static getDerivedStateFromProps()
with props, but need to handle the changes of props
by utilizing prevProps
. And we need to cooperate with componentDidMount()
to handle the initial API call.
Quote from doc:
... This is also a good place to do network requests as long as you compare the current props to previous props ...
If you just want to change the legend title, you can do the following:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.lmplot(
x="total_bill",
y="tip",
hue="smoker",
data=tips,
legend=True
)
g._legend.set_title("New Title")
In my experience, Oracle is very good at pushing simple predicates around. The following test was made on Oracle 11.2. I'm fairly certain it produces the same execution plan on all releases of 10g as well.
(Please people, feel free to leave a comment if you run an earlier version and tried the following)
create table table1(a number, b number);
create table table2(a number, b number);
explain plan for
select *
from (select a,b from table1
union
select a,b from table2
)
where a > 1;
select *
from table(dbms_xplan.display(format=>'basic +predicate'));
PLAN_TABLE_OUTPUT
---------------------------------------
| Id | Operation | Name |
---------------------------------------
| 0 | SELECT STATEMENT | |
| 1 | VIEW | |
| 2 | SORT UNIQUE | |
| 3 | UNION-ALL | |
|* 4 | TABLE ACCESS FULL| TABLE1 |
|* 5 | TABLE ACCESS FULL| TABLE2 |
---------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
4 - filter("A">1)
5 - filter("A">1)
As you can see at steps (4,5), the predicate is pushed down and applied before the sort (union).
I couldn't get the optimizer to push down an entire sub query such as
where a = (select max(a) from empty_table)
or a join. With proper PK/FK constraints in place it might be possible, but clearly there are limitations :)
Only way to know how many lines there are in file is to count them. You can of course create a metric from your data giving you an average length of one line and then get the file size and divide that with avg. length but that won't be accurate.
I must add one more point in this thread. To install/uninstall 64-bit
version of assemblies one should use 64-bit
version of tool. To install a service, the command should be:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
"C:\YourFolder\YourService.exe"
and to uninstall the command should be:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe" -u
"C:\YourFolder\YourService.exe"
Assuming your server side script doesn't set the proper Content-Type: application/json
response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json'
parameter.
Then you could use the $.each()
function to loop through the data:
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});
or use the $.getJSON
method:
$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
Set a session variable for every page on your site (actual pages not includes or rpcs) that contains the current page name, then in your Ajax call pass a nonce salted with the $_SERVER['SCRIPT_NAME'];
<?php
function create_nonce($optional_salt='')
{
return hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']);
}
$_SESSION['current_page'] = $_SERVER['SCRIPT_NAME'];
?>
<form>
<input name="formNonce" id="formNonce" type="hidden" value="<?=create_nonce($_SERVER['SCRIPT_NAME']);?>">
<label class="form-group">
Login<br />
<input name="userName" id="userName" type="text" />
</label>
<label class="form-group">
Password<br />
<input name="userPassword" id="userPassword" type="password" />
</label>
<button type="button" class="btnLogin">Sign in</button>
</form>
<script type="text/javascript">
$("form.login button").on("click", function() {
authorize($("#userName").val(),$("#userPassword").val(),$("#formNonce").val());
});
function authorize (authUser, authPassword, authNonce) {
$.ajax({
type: "POST",
url: "/inc/rpc.php",
dataType: "json",
data: "userID="+authUser+"&password="+authPassword+"&nonce="+authNonce
})
.success(function( msg ) {
//some successful stuff
});
}
</script>
Then in the rpc you are calling test the nonce you passed, if it is good then odds are pretty great that your rpc was legitimately called:
<?php
function check_nonce($nonce, $optional_salt='')
{
$lasthour = date("G")-1<0 ? date('Ymd').'23' : date("YmdG")-1;
if (hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce ||
hash_hmac('sha256', session_id().$optional_salt, $lasthour.'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce)
{
return true;
} else {
return false;
}
}
$ret = array();
header('Content-Type: application/json');
if (check_nonce($_POST['nonce'], $_SESSION['current_page']))
{
$ret['nonce_check'] = 'passed';
} else {
$ret['nonce_check'] = 'failed';
}
echo json_encode($ret);
exit;
?>
edit: FYI the way I have it set the nonce is only good for an hour and change, so if they have not refreshed the page doing the ajax call in the last hour or 2 the ajax request will fail.
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
Write this below line after script tag start.
previous_Window=null;
It will work 100%. by using this code
radius= circle.getRadius()/1000;
radius_mile= circle.getRadius()/1609.344;
newRadious = 'This Circle Radius Covers Approx ' + radius.toFixed(1) + ' Km'+' <br> This circle Radius Covers Approx '+ radius_mile.toFixed(1)+ 'Miles';
var infoWindow= new google.maps.InfoWindow({
content: newRadious
});
infoWindow.setContent(newRadious)
infoWindow.setPosition(circle.getCenter());
if (previous_Window)
previous_Window.close();
infoWindow.open(map);
previous_Window=infoWindow;
>>> x = 2.51
>>> x*100
250.99999999999997
the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.
you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library http://code.google.com/p/mpmath/ :),
It's always good to use JavaScript equivalents as compared to jQuery. One reason is one fewer library to depend on and they are much faster than the jQuery equivalents.
One fantastic reference for jQuery equivalents is http://youmightnotneedjquery.com/.
As far as your question is concerned, I took the below code from the above link :) Only caveat is it only works with Internet Explorer 9 and later.
function ready(fn) {
if (document.readyState != 'loading') {
fn();
}
else {
document.addEventListener('DOMContentLoaded', fn);
}
}
var sum1 = 0
for i in 0...100{
sum1 += i
}
print (sum1)
for i in (10...100).reverse(){
sum1 /= i
}
print(sum1)
You can do it simply in one line when taking input.
[int(i) for i in input().split("")]
Split it where you want.
If you want to convert a list not list simply put your list name in the place of input().split("")
.
I had the same problem, I wanted no access of Save Dialogue.
Below code can help:
FirefoxProfile fp = new FirefoxProfile();
fp.setPreference("browser.download.folderList",2);
fp.setPreference("browser.download.manager.showWhenStarting",false);
fp.setPreference("browser.helperApps.alwaysAsk.force", false);
// Below you have to set the content-type of downloading file(I have set simple CSV file)
fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
According to the file type which is being downloaded, You need to specify content types.
You can specify multiple content-types separated with ' ; '
e.g:
fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv;application/vnd.ms-excel;application/msword");
Given you use typescript: Many of the solutions above might not work or are overly complex.
Situation: The strings are not the same as the enum values (casing differs)
enum Color {
Green = "green",
Red = "red"
}
Just use:
const color = "green" as Color
Please note that this does not guarantee a valid enum.
Use modulo:
$hours = $time_in_seconds / 3600;
$minutes = ($time_in_seconds / 60) % 60;
I had almost just as same error with my Ruby on Rails application running postgresql(mac). This worked for me:
brew services restart postgresql
With a running instance of myExecutableName
having a PID 15073
:
hitting Tab twice after $ gdb myExecu
in the command line, will automagically autocompletes to:
$ gdb myExecutableName 15073
and will attach gdb to this process. That's nice!
It works for me with $(window).focus().
var w;
var src = 'http://pagetoprint';
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
w = $('<iframe></iframe>');
w.attr('src', src);
w.css('display', 'none');
$('body').append(w);
w.load(function() {
w[0].focus();
w[0].contentWindow.print();
});
$(window).focus(function() {
console.log('After print');
});
}
else {
w = window.open(src);
$(w).unload(function() {
console.log('After print');
});
}
If you just want to have an event when a tab is selected, this is the correct way:
<TabControl>
<TabItem Selector.Selected="OnTabSelected" />
<TabItem Selector.Selected="OnTabSelected" />
<TabItem Selector.Selected="OnTabSelected" />
<!-- You can also catch the unselected event -->
<TabItem Selector.Unselected="OnTabUnSelected" />
</TabControl>
And in your code
private void OnTabSelected(object sender, RoutedEventArgs e)
{
var tab = sender as TabItem;
if (tab != null)
{
// this tab is selected!
}
}
Try this
$('#add_here').text('new-dynamic-text');
i have ran into the same problem and found a solution (not totally by myself, but there is the internet for)
Color blue = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;
foreach (DataGridViewRow r in datagridIncome.Rows)
{
if (r.Cells[5].Value.ToString().Contains("1")) {
r.DefaultCellStyle.BackColor = blue;
r.DefaultCellStyle.SelectionBackColor = blue;
r.DefaultCellStyle.SelectionForeColor = letters;
}
else {
r.DefaultCellStyle.BackColor = red;
r.DefaultCellStyle.SelectionBackColor = red;
r.DefaultCellStyle.SelectionForeColor = letters;
}
}
This is a small trick, the only way you can see a row is selected, is by the very first column (not column[0], but the one therefore). When you click another row, you will not see the blue selection anymore, only the arrow indicates which row have selected. As you understand, I use rowSelection in my gridview.
You can use:
PyXML:
from xml.dom.ext.reader import Sax2
from xml import xpath
doc = Sax2.FromXmlFile('foo.xml').documentElement
for url in xpath.Evaluate('//@Url', doc):
print url.value
libxml2:
import libxml2
doc = libxml2.parseFile('foo.xml')
for url in doc.xpathEval('//@Url'):
print url.content
I found this link helpful
$scope.loadSkillTags = function (query) {
var data = {qData: query};
return SkillService.querySkills(data).then(function(response) {
return response.data;
});
};
Thanks for the suggestions in the comments. I made a bit of a dirty hack to get what I want without having to create my own image. With javascript I first hide the default tag that's being used for the down arrow, like so:
$('b[role="presentation"]').hide();
I then included font-awesome in my page and add my own down arrow, again with a line of javascript, to replace the default one:
$('.select2-arrow').append('<i class="fa fa-angle-down"></i>');
Then with CSS I style the select boxes. I set the height, change the background color of the arrow area to a gradient black, change the width, font-size and also the color of the down arrow to white:
.select2-container .select2-choice {
padding: 5px 10px;
height: 40px;
width: 132px;
font-size: 1.2em;
}
.select2-container .select2-choice .select2-arrow {
background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
background-image: -moz-linear-gradient(top, #424242, #030303);
background-image: -ms-linear-gradient(top, #424242, #030303);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
background-image: -webkit-linear-gradient(top, #424242, #030303);
background-image: -o-linear-gradient(top, #424242, #030303);
background-image: linear-gradient(#424242, #030303);
width: 40px;
color: #fff;
font-size: 1.3em;
padding: 4px 12px;
}
The result is the styling the way I want it:
Update 5/6/2015 As @Katie Lacy mentioned in the other answer the classnames have been changed in version 4 of Select2. The updated CSS with the new classnames should look like this:
.select2-container--default .select2-selection--single{
padding:6px;
height: 37px;
width: 148px;
font-size: 1.2em;
position: relative;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
background-image: -moz-linear-gradient(top, #424242, #030303);
background-image: -ms-linear-gradient(top, #424242, #030303);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
background-image: -webkit-linear-gradient(top, #424242, #030303);
background-image: -o-linear-gradient(top, #424242, #030303);
background-image: linear-gradient(#424242, #030303);
width: 40px;
color: #fff;
font-size: 1.3em;
padding: 4px 12px;
height: 27px;
position: absolute;
top: 0px;
right: 0px;
width: 20px;
}
JS:
$('b[role="presentation"]').hide();
$('.select2-selection__arrow').append('<i class="fa fa-angle-down"></i>');
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
task deleteJar(type: Delete) {
delete 'libs/mylibrary.jar'
}
task exportjar(type: Copy) {
from('build/intermediates/compile_library_classes/release/')
into('libs/')
include('classes.jar')
rename('classes.jar', 'mylibrary.jar')
}
exportjar.dependsOn(deleteJar, build)
Allocate maximum memory to your docker machine from (docker preference -> advance )
Screenshot of advance settings:
This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.
docker run -m=4g {imageID}
Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.
After trying almost everything on this thread and others, continuing to Google, the only thing that worked for me, in the end, was to start Visual Studio as my AD user via command line:
cd C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE
runas /netonly /user:<comp\name.surname> devenv.exe
Original issue: [1]: https://developercommunity.visualstudio.com/content/problem/304224/git-failed-with-a-fatal-errorauthentication-failed.html
My situation is I'm on a personal machine connecting to a company's internal/local devops server (not cloud-based) that uses AD authorization. I had no issue with TFS, but with git could not get the clone to work (Git failed with a fatal error. Authentication failed for [url]) until I did that.
In ASP.NET MVC 3 you can simply add your list to ViewData...
var options = new List<SelectListItem>();
options.Add(new SelectListItem { Value = "1", Text = "1" });
options.Add(new SelectListItem { Value = "2", Text = "2" });
options.Add(new SelectListItem { Value = "3", Text = "3", Selected = true });
ViewData["options"] = options;
...and then reference it by name in your razor view...
@Html.DropDownList("options")
You don't have to manually "use" the list in the DropDownList call. Doing it this way correctly set the selected value for me too.
Disclaimer:
This was my solution:
I added required to the select tag:
<div class="col-lg-10">
<select class="form-control" name="HoursEntry" id="HoursEntry" required>
<option value="">Select.....</option>
<option value="0.25">0.25</option>
<option value="0.5">0.50</option>
<option value="1">1.00</option>
<option value="1.25">1.25</option>
<option value="1.5">1.50</option>
<option value="2">2.00</option>
<option value="2.25">2.25</option>
<option value="2.5">2.50</option>
<option value="3">3.00</option>
<option value="3.25">3.25</option>
<option value="3.5">3.50</option>
<option value="4">4.00</option>
<option value="4.25">4.25</option>
<option value="4.5">4.50</option>
<option value="5">5.00</option>
<option value="5.25">5.25</option>
<option value="5.5">5.50</option>
<option value="6">6.00</option>
<option value="6.25">6.25</option>
<option value="6.5">6.50</option>
<option value="7">7.00</option>
<option value="7.25">7.25</option>
<option value="7.5">7.50</option>
<option value="8">8.00</option>
</select>
Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.
Check the answer -> Here
And here is an example:
Converter.bat
::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b
:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b
'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester
The views are probably created using the WITH SCHEMABINDING option and this means they are explicitly wired up to prevent such changes. Looks like the schemabinding worked and prevented you from breaking those views, lucky day, heh? Contact your database administrator and ask him to do the change, after it asserts the impact on the database.
From MSDN:
SCHEMABINDING
Binds the view to the schema of the underlying table or tables. When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified.
For anyone interested in a shorter way:
gotdata = len(dlist)>1 and dlist[1] or 'null'
But for best performance, I suggest using False
instead of 'null'
, then a one line test will suffice:
gotdata = len(dlist)>1 and dlist[1]
this is what it worked for me:
select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
AND STR_TO_DATE('07/10/15', '%d/%m/%Y')
Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load
I think the most important thing to keep in mind is: is the name descriptive enough? Can you tell by looking at the name what the Class is supposed to do? Using words like "Manager", "Service" or "Handler" in your class names can be considered too generic, but since a lot of programmers use them it also helps understanding what the class is for.
I myself have been using the facade-pattern a lot (at least, I think that's what it is called). I could have a User
class that describes just one user, and a Users
class that keeps track of my "collection of users". I don't call the class a UserManager
because I don't like managers in real-life and I don't want to be reminded of them :) Simply using the plural form helps me understand what the class does.
Here is a complete solution to your question using Python's built-in functions:
# Create the List
numbers = input("Enter the elements of the list. Separate each value with a comma. Do not put a comma at the end.\n").split(",")
# Convert the elements in the list (treated as strings) to integers
numberL = [int(element) for element in numbers]
# Loop through the list with a for-loop
for elements in numberL:
maxEle = max(numberL)
indexMax = numberL.index(maxEle)
print(maxEle)
print(indexMax)
place the required dlls in folder and set the folder path in PATH environment variable. make sure updated environment PATH variable is reflected.
Also, this will go up a directory and then back down to another subfolder.
<a href = "../subfolder/page.html">link</a>
To go up multiple directories you can do this.
<a href = "../../page.html">link</a>
To go the root, I use this
<a href = "~/page.html">link</a>
As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE
which "shows the CREATE TABLE
statement that creates a given table, or the CREATE VIEW
statement that creates a given view."
Usage:
SHOW CREATE TABLE myTable;
Do you have the right import ?
import React, { useState } from 'react';
Most suggestions are assuming that you need to somehow destroy the last 20 commits, which is why it means "rewriting history", but you don't have to.
Just create a new branch from the commit #80 and work on that branch going forward. The other 20 commits will stay on the old orphaned branch.
If you absolutely want your new branch to have the same name, remember that branch are basically just labels. Just rename your old branch to something else, then create the new branch at commit #80 with the name you want.
First you need an object
public class MyObject {
public string Id {get;set;}
public string Text {get;set;}
...
}
Then in here
using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {
using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
}
}
I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.
JavaScriptSerializer System.Web.Script.Serialization
Another alternative to @TouchBoarder's answer above is that you may also have two layout files with the same name but for different api versions. You should delete the older my_file.xml file
my_file.xml
my_file.xml(v21)
Here's what I did to solve this issue:
Basically:
1) Enable "Embedded Browser OAuth Login"
2) Disable "Use Strict Mode for Redirect URIs" and enter a redirect URI like the way I did.
3) Leave all the rest of the options as they are.
4) Save your changes.
5) Enjoy :)
Just above JSON.parse
, use:
var newData = JSON.stringify(userData)
Here's a one-liner to remove all remote-tracking branches matching a pattern:
git branch -rd $(git branch -a | grep '{pattern}' | cut -d'/' -f2-10 | xargs)
this works for me because it works fine in ie8.
$('#iframe').contents().find("html").html();
but if you like to use javascript aside for jquery you may use like this
var iframe = document.getElementById('iframecontent');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var val_1 = innerDoc.getElementById('value_1').value;
You can add escaped double quotes like this: String name = "\"john\"";
To create a linear layout in which each child uses the same amount of space on the screen, set the android:layout_height of each view to "0dp" (for a vertical layout) or the android:layout_width of each view to "0dp" (for a horizontal layout). Then set the android:layout_weight of each view to "1".
In order for this to work in the LinearLayout
view group the attribute values for android:layout_width
and android:layout_height
need to be equal to "match_parent"
...
This is from the Docker documentation itself, might be of help, simple and plain:
"The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.".
Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html
Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.
There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices
.
You can use like this:
public static String executeHttpPost1(String url,
HashMap<String, String> postParameters) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
HttpClient client = getNewHttpClient();
try{
request = new HttpPost(url);
}
catch(Exception e){
e.printStackTrace();
}
if(postParameters!=null && postParameters.isEmpty()==false){
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
String k, v;
Iterator<String> itKeys = postParameters.keySet().iterator();
while (itKeys.hasNext())
{
k = itKeys.next();
v = postParameters.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(nameValuePairs);
request.setEntity(urlEntity);
}
try {
Response = client.execute(request,localContext);
HttpEntity entity = Response.getEntity();
int statusCode = Response.getStatusLine().getStatusCode();
Log.i(TAG, ""+statusCode);
Log.i(TAG, "------------------------------------------------");
try{
InputStream in = (InputStream) entity.getContent();
//Header contentEncoding = Response.getFirstHeader("Content-Encoding");
/*if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
response = str.toString();
Log.i(TAG, "response"+response);
}
catch(IllegalStateException exc){
exc.printStackTrace();
}
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+response);
}
finally {
}
return response;
}
It is sample extension
public class GetModelErrors
{
//Usage return Json to View :
//return Json(new { state = false, message = new GetModelErrors(ModelState).MessagesWithKeys() });
public class KeyMessages
{
public string Key { get; set; }
public string Message { get; set; }
}
private readonly ModelStateDictionary _entry;
public GetModelErrors(ModelStateDictionary entry)
{
_entry = entry;
}
public int Count()
{
return _entry.ErrorCount;
}
public string Exceptions(string sp = "\n")
{
return string.Join(sp, _entry.Values
.SelectMany(v => v.Errors)
.Select(e => e.Exception));
}
public string Messages(string sp = "\n")
{
string msg = string.Empty;
foreach (var item in _entry)
{
if (item.Value.ValidationState == ModelValidationState.Invalid)
{
msg += string.Join(sp, string.Join(",", item.Value.Errors.Select(i => i.ErrorMessage)));
}
}
return msg;
}
public List<KeyMessages> MessagesWithKeys(string sp = "<p> ? ")
{
List<KeyMessages> list = new List<KeyMessages>();
foreach (var item in _entry)
{
if (item.Value.ValidationState == ModelValidationState.Invalid)
{
list.Add(new KeyMessages
{
Key = item.Key,
Message = string.Join(null, item.Value.Errors.Select(i => sp + i.ErrorMessage))
});
}
}
return list;
}
}
Below is an other approach that was useful for me
convertLittleEndianByteArrayToBigEndianByteArray (byte littlendianByte[], byte bigEndianByte[], int ArraySize){
int i =0;
for(i =0;i<ArraySize;i++){
bigEndianByte[i] = (littlendianByte[ArraySize-i-1] << 7 & 0x80) | (littlendianByte[ArraySize-i-1] << 5 & 0x40) |
(littlendianByte[ArraySize-i-1] << 3 & 0x20) | (littlendianByte[ArraySize-i-1] << 1 & 0x10) |
(littlendianByte[ArraySize-i-1] >>1 & 0x08) | (littlendianByte[ArraySize-i-1] >> 3 & 0x04) |
(littlendianByte[ArraySize-i-1] >>5 & 0x02) | (littlendianByte[ArraySize-i-1] >> 7 & 0x01) ;
}
}
I was looking into this but wanted to have a different transition rate for in and out.
This is what I ended up doing:
//css
.addedClass {
background: #5eb4fc;
}
// js
function setParentTransition(id, prop, delay, style, callback) {
$(id).css({'-webkit-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'-moz-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'-o-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'transition' : prop + ' ' + delay + ' ' + style});
callback();
}
setParentTransition(id, 'background', '0s', 'ease', function() {
$('#elementID').addClass('addedClass');
});
setTimeout(function() {
setParentTransition(id, 'background', '2s', 'ease', function() {
$('#elementID').removeClass('addedClass');
});
});
This instantly turns the background color to #5eb4fc and then slowly fades back to normal over 2 seconds.
Here's a fiddle
it's so easy...converting a date to calendar like this:
Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();
Added a method replace_in_javascript
which will satisfy your requirement. Also found that you are writing a string "new_text"
in document.write()
which is supposed to refer to a variable new_text
.
let replace_in_javascript= (replaceble, replaceTo, text) => {_x000D_
return text.replace(replaceble, replaceTo)_x000D_
}_x000D_
_x000D_
var text = "this is some sample text that i want to replace";_x000D_
var new_text = replace_in_javascript("want", "dont want", text);_x000D_
document.write(new_text);
_x000D_
try this
final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = tm.getDeviceId();
Building on everyone's great answers and comments, this is the shortest and sweetest version:
grep -o "$needle" <<< "$haystack" | wc -l
Based on comments below, it no longer works in modern browsers
This question demonstrates an approach that might be helpful to you: Silent print an embedded PDF
It uses the <embed>
tag to embed the PDF in the document:
<embed
type="application/pdf"
src="path_to_pdf_document.pdf"
id="pdfDocument"
width="100%"
height="100%" />
Then you call the .print()
method on the element in Javascript when the PDF is loaded:
function printDocument(documentId) {
var doc = document.getElementById(documentId);
//Wait until PDF is ready to print
if (typeof doc.print === 'undefined') {
setTimeout(function(){printDocument(documentId);}, 1000);
} else {
doc.print();
}
}
You could place the embed in a hidden iframe and print it from there, giving you a seamless experience.
You could do this with MapReduce:
mr = db.runCommand({
"mapreduce" : "my_collection",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "my_collection" + "_keys"
})
Then run distinct on the resulting collection so as to find all the keys:
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
The Python csv library can do your parsing and your code can translate them into Products()
.
I think you should consider using IO.binread("/path/to/file")
if you have a recent ruby interpreter (i.e. >= 1.9.2)
You could find IO
class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html
div
's will naturally resize in accordance with their content.
If you set no height on your div, it will expand to contain its conent.
An exception to this rule is when the div contains floating elements. If this is the case you'll need to do a bit extra to ensure that the containing div (wrapper) clears the floats.
Here's some ways to do this:
#wrapper{
overflow:hidden;
}
Or
#wrapper:after
{
content:".";
display:block;
clear:both;
visibility:hidden;
}
I recommend the answer posted by Martin.
But you seem to be concerned about your queries getting too complex:
To create localized table for every table is making design and querying complex...
So you might be thinking, that instead of writing simple queries like this:
SELECT price, name, description FROM Products WHERE price < 100
...you would need to start writing queries like that:
SELECT
p.price, pt.name, pt.description
FROM
Products p JOIN ProductTranslations pt
ON (p.id = pt.id AND pt.lang = "en")
WHERE
price < 100
Not a very pretty perspective.
But instead of doing it manually you should develop your own database access class, that pre-parses the SQL that contains your special localization markup and converts it to the actual SQL you will need to send to the database.
Using that system might look something like this:
db.setLocale("en");
db.query("SELECT p.price, _(p.name), _(p.description)
FROM _(Products p) WHERE price < 100");
And I'm sure you can do even better that that.
The key is to have your tables and fields named in uniform way.