I added borderBottomWidth: 0 and it worked fine for me in android.
data = [4, 5, 6] # Your global variable
def print_data(data): # <-- Pass in a parameter called "data"
print data # <-- Note: You can access global variable inside your function, BUT for now, which is which? the parameter or the global variable? Confused, huh?
print_data(data)
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
You can create an extension for UIView to access these values in the design editor
extension UIView{
@IBInspectable var shadowOffset: CGSize{
get{
return self.layer.shadowOffset
}
set{
self.layer.shadowOffset = newValue
}
}
@IBInspectable var shadowColor: UIColor{
get{
return UIColor(cgColor: self.layer.shadowColor!)
}
set{
self.layer.shadowColor = newValue.cgColor
}
}
@IBInspectable var shadowRadius: CGFloat{
get{
return self.layer.shadowRadius
}
set{
self.layer.shadowRadius = newValue
}
}
@IBInspectable var shadowOpacity: Float{
get{
return self.layer.shadowOpacity
}
set{
self.layer.shadowOpacity = newValue
}
}
}
I would agree with @evillinux, It would be best to make your background image semi transparent so it supports < ie8
The other suggestions of using another div are also a great option, and it's the way to go if you want to do this in css. For example if the site had such features as selecting your own background color. I would suggest using a filter for older IE. eg:
filter:Alpha(opacity=50)
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.
It supports box-shadow
(except for the inset
keyword).
There's a proposed feature which you could use for arbitrarily shaped drop shadows. You could see it here, courtesy of Lea Verou:
http://www.netmagazine.com/features/hot-web-standards-css-blending-modes-and-filters-shadow-dom
Browser support is minimal, though.
This looks like it's working: http://tips4php.net/2010/08/nice-css-text-shadow-effects/
He's using multiple shadows to achieve that effect as explained here: http://www.w3.org/Style/Examples/007/text-shadow#multiple
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="20dp" > <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:shadowColor="#000" android:shadowDx="0" android:shadowDy="0" android:shadowRadius="50" android:text="Text Shadow Example1" android:textColor="#FBFBFB" android:textSize="28dp" android:textStyle="bold" /> <TextView android:id="@+id/textview2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Text Shadow Example2" android:textColor="#FBFBFB" android:textSize="28dp" android:textStyle="bold" /> </LinearLayout>
In the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the configuration items are
android:shadowDx – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right
android:shadowDy – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.
android:shadowRadius – specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent. android:shadowColor – specifies the shadow color
Shadow Effect on Android TextView pragmatically
Use below code snippet to get the shadow effect on the second TextView pragmatically.
TextView textv = (TextView) findViewById(R.id.textview2); textv.setShadowLayer(30, 0, 0, Color.RED);
Output :
While it's impossible to set a blur radius directly on UILabel
, you definitely could change it by manipulating CALayer.
Just set:
//Required properties
customLabel.layer.shadowRadius = 5.0 //set shadow radius to your desired value.
customLabel.layer.shadowOpacity = 1.0 //Choose an opacity. Make sure it's visible (default is 0.0)
//Other options
customLabel.layer.shadowOffset = CGSize(width: 10, height: 10)
customLabel.layer.shadowColor = UIColor.black.cgColor
customLabel.layer.masksToBounds = false
What I hope will help someone and other answers failed to clarify is that it will not work if you also set UILabel Shadow Color
property directly on Interface Builder while trying to setup .layer.shadowRadius
.
So if setting label.layer.shadowRadius
didn't work, please verify Shadow Color
for this UILabel
on Interface Builder. It should be set to default
. And then, please, if you want a shadow color other than black, set this color also through .layer
property.
A by far easier approach is to set some layer attributes of the view on initialization:
self.layer.masksToBounds = NO;
self.layer.shadowOffset = CGSizeMake(-15, 20);
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;
You need to import QuartzCore.
#import <QuartzCore/QuartzCore.h>
Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.
See commit ed178ef by Jeff King (peff
), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster
-- in commit 05c3967, 19 May 2015)
Note: This has been reverted. See below.
stash
: require a clean index to apply/pop
If you have staged contents in your index and run "
stash apply/pop
", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.
In other words:
"
git stash pop/apply
" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.
We can make this safer by refusing to apply when there are staged changes.
That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:
Cannot apply stash: Your index contains uncommitted changes.
Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before
git stash apply/pop
) with agit reset --hard
.
See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit bfb539b, 24 Jun 2015)
That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.
Unfortunately, this hurts some common workflows around "
git stash -k
", like:
git add -p ;# (1) stage set of proposed changes
git stash -k ;# (2) get rid of everything else
make test ;# (3) make sure proposal is reasonable
git stash apply ;# (4) restore original working tree
If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).
UPDATE YourTable SET MyField = 0 WHERE MyField IS NULL
works in most SQL dialects. I don't use Access, but that should get you started.
You can plot multiple subplots of multiple pandas data frames using matplotlib with a simple trick of making a list of all data frame. Then using the for loop for plotting subplots.
Working code:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# dataframe sample data
df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
#define number of rows and columns for subplots
nrow=3
ncol=2
# make a list of all dataframes
df_list = [df1 ,df2, df3, df4, df5, df6]
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
for c in range(ncol):
df_list[count].plot(ax=axes[r,c])
count=+1
Using this code you can plot subplots in any configuration. You need to just define number of rows nrow
and number of columns ncol
. Also, you need to make list of data frames df_list
which you wanted to plot.
You need to align the text to the left of radio button using float:left
input[type="radio"]{
float:left;
}
You may use label too for more responsive output.
For "Arrays":
If you know the index:
array.splice(index, 1);
If you know the value:
function removeItem(array, value) {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
return array;
}
The most upvoted answer for delete
works well in case of objects but not for the real arrays. If I use delete
it removes elements from loops but keeps the element as empty
and length of array wont change. This may be a problem in some scenarios.
For example, if I do myArray.toString() on myArray after removal via delete
, it creates an empty entry, i.e. ,,
.
The SimpleNamespace
class could be used to create new attributes with setattr
, or subclass SimpleNamespace
and create your own function to add new attribute names (variables).
from types import SimpleNamespace
variables = {"b":"B","c":"C"}
a = SimpleNamespace(**variables)
setattr(a,"g","G")
a.g = "G+"
something = a.a
At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON
AJAX method because it easily returns JSONP using the ?callback=?
without having any issues with CORS.
data ='USER=<?echo trim($USER)?>' +
'&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();
//Call the REST program/method returns: JSONP
$.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
.done(function( json ) {
// loading...
if ($.trim(json.ERROR) != '') {
$("#error-msg").text(message).show();
}
else{
$(".error").hide();
$("#jsonp").text(json.whatever);
}
})
.fail(function( jqXHR, textStatus, error ) {
var err = textStatus + ", " + error;
alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
});
This answers in an extension to what avs099 has given above, for those who are still having problems:
1.Makesure that you have php_openssl.dll installed(else find it online and install it);
2.Go to your php.ini; find extension=php_openssl.dll enable it/uncomment
3.Go to github and downland the latetest version :6.0 at this time.
4.Extract the master copy into the path that works better for you(I recommend the same directory as the calling file)
Now copy this code into your foo-mailer.php and render it with your gmail stmp authentications.
require("/PHPMailer-master/src/PHPMailer.php");
require("/PHPMailer-master/src/SMTP.php");
require("/PHPMailer-master/src/Exception.php");
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 1;
$mail->Port = 465 ; //465 or 587
$mail->SMTPSecure = 'ssl';
$mail->SMTPAuth = true;
$mail->IsHTML(true);
//Authentication
$mail->Username = "[email protected]";
$mail->Password = "*******";
//Set Params
$mail->SetFrom("[email protected]");
$mail->AddAddress("[email protected]");
$mail->Subject = "Test";
$mail->Body = "hello";
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
Disclaimer:The original owner of the code above is avs099 with just my little input.
Take note of the additional:
a) (PHPMailer\PHPMailer) namespace:needed for name conflict resolution.
b) The (require("/PHPMailer-master/src/Exception.php");):It was missing in avs099's code thus the problem encountered by aProgger,you need that line to tell the mailer class where the Exception class is located.
Just another information... Had that problem today on a Windows 2012 R2 x64 TS system where the application was started from a unc/network path. The issue occured for one application for all terminal server users. Executing the application locally worked without problems. After a reboot it started working again - the SEHException's thrown had been Constructor init and TargetInvocationException
Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
Solution : Check if value is not undefined
React / Formik / Bootstrap / TypeScript
example :
{ values?.purchaseObligation.remainingYear ?
<Input
tag={Field}
name="purchaseObligation.remainingYear"
type="text"
component="input"
/> : null
}
You can set the line-height
in pixels instead of percentage. Is that what you mean?
both would work the same, its just two different methods to call the same function. Try the following:
<a href="javascript:history.back();">[Go Back]</a>
Anyone else stumbling upon this answer should note that jQuery now (>=1.3) has outerHeight
/outerWidth
functions to retrieve the width including padding/borders, e.g.
$(elem).outerWidth(); // Returns the width + padding + borders
To include the margin as well, simply pass true
:
$(elem).outerWidth( true ); // Returns the width + padding + borders + margins
Try this
new DropdownButton<String>(
items: <String>['A', 'B', 'C', 'D'].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (_) {},
)
You can create custom background for your text view. Steps 1. Go to your project. 2. Go to resources and right click to drawable. 3. Click on New -> Drawable Resource File 4. Give name to you file 5. Paste following code in the file
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="@color/colorBlack" />
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp" />
<corners android:radius="6dp" />
<solid android:color="#ffffffff" />
For your text view where you want to use it as backgroud,
android:background="@drawable/your_fileName"
For joins, I strongly prefer query-syntax for all the details that are happily hidden (not the least of which are the transparent identifiers involved with the intermediate projections along the way that are apparent in the dot-syntax equivalent). However, you asked regarding Lambdas which I think you have everything you need - you just need to put it all together.
var categorizedProducts = product
.Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
.Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new { ppc, c })
.Select(m => new {
ProdId = m.ppc.p.Id, // or m.ppc.pc.ProdId
CatId = m.c.CatId
// other assignments
});
If you need to, you can save the join into a local variable and reuse it later, however lacking other details to the contrary, I see no reason to introduce the local variable.
Also, you could throw the Select
into the last lambda of the second Join
(again, provided there are no other operations that depend on the join results) which would give:
var categorizedProducts = product
.Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
.Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new {
ProdId = ppc.p.Id, // or ppc.pc.ProdId
CatId = c.CatId
// other assignments
});
...and making a last attempt to sell you on query syntax, this would look like this:
var categorizedProducts =
from p in product
join pc in productcategory on p.Id equals pc.ProdId
join c in category on pc.CatId equals c.Id
select new {
ProdId = p.Id, // or pc.ProdId
CatId = c.CatId
// other assignments
};
Your hands may be tied on whether query-syntax is available. I know some shops have such mandates - often based on the notion that query-syntax is somewhat more limited than dot-syntax. There are other reasons, like "why should I learn a second syntax if I can do everything and more in dot-syntax?" As this last part shows - there are details that query-syntax hides that can make it well worth embracing with the improvement to readability it brings: all those intermediate projections and identifiers you have to cook-up are happily not front-and-center-stage in the query-syntax version - they are background fluff. Off my soap-box now - anyhow, thanks for the question. :)
Now it's more easy with management studio 2016.
Using SQL Server Management Studio
To copy data from one table to another
1.Open the table with columns you want to copy and the one you want to copy into by right-clicking the tables, and then clicking Design.
2.Click the tab for the table with the columns you want to copy and select those columns.
3.From the Edit menu, click Copy.
4.Open a new Query Editor window.
5.Right-click the Query Editor, and then click Design Query in Editor.
6.In the Add Table dialog box, select the source and destination table, click Add, and then close the Add Table dialog box.
7.Right-click an open area of the the Query Editor, point to Change Type, and then click Insert Results.
8.In the Choose Target Table for Insert Results dialog box, select the destination table.
9.In the upper portion of the Query Designer, click the source column in the source table.
10.The Query Designer has now created an INSERT query. Click OK to place the query into the original Query Editor window.
11.Execute the query to insert the data from the source table to the destination table.
For More Information https://docs.microsoft.com/en-us/sql/relational-databases/tables/copy-columns-from-one-table-to-another-database-engine
The URL approach will only work for small HTML fragements. The more solid approach is to generate an object URL from a blob and use it as a source of the dynamic iframe.
const html = '<html>...</html>';
const iframe = document.createElement('iframe');
const blob = new Blob([html], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
document.body.appendChild(iframe);
From the docs
IF boolean-expression THEN
statements
ELSE
statements
END IF;
So in your above example the code should look as follows:
IF select count(*) from orders > 0
THEN
DELETE from orders
ELSE
INSERT INTO orders values (1,2,3);
END IF;
You were missing: END IF;
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
I had issues with trying to delete a returned JSON object and found that it was actually a string. If you JSON.parse() before deleting you can be sure your key will get deleted.
let obj;
console.log(this.getBody()); // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = this.getBody();
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = JSON.parse(this.getBody());
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805}
You comment:
valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....
If you are interested in each term, then write the code so it deals with each. For example.
for b in valeur<=0.6:
if b:
print ("this works")
else:
print ("valeur is too high")
This will write 2 lines.
The error is produced by numpy
code when you try to use it a context that expects a single, scalar, value. if b:...
can only do one thing. It does not, by itself, iterate through the elements of b
doing a different thing for each.
You could also cast that iteration as list comprehension, e.g.
['yes' if b else 'no' for b in np.array([True, False, True])]
Best out there:
Works with bootstrap
Update:
/*!_x000D_
*_x000D_
* Reflex v1.0_x000D_
*_x000D_
* Reflex is a flexbox grid which provides a way to take advantage of emerging_x000D_
* flexbox support while providing a fall back to inline-block on older browsers_x000D_
*_x000D_
* Built by Lee Jordan G.C.S.E._x000D_
* email: [email protected]_x000D_
* github: https://github.com/leejordan_x000D_
*_x000D_
* Structure and calculations are inspired by twitter bootstrap_x000D_
*_x000D_
*/_x000D_
.reflex-order-12 {_x000D_
-webkit-order: 12;_x000D_
-ms-flex-order: 12;_x000D_
order: 12;_x000D_
}_x000D_
.reflex-order-11 {_x000D_
-webkit-order: 11;_x000D_
-ms-flex-order: 11;_x000D_
order: 11;_x000D_
}_x000D_
.reflex-order-10 {_x000D_
-webkit-order: 10;_x000D_
-ms-flex-order: 10;_x000D_
order: 10;_x000D_
}_x000D_
.reflex-order-9 {_x000D_
-webkit-order: 9;_x000D_
-ms-flex-order: 9;_x000D_
order: 9;_x000D_
}_x000D_
.reflex-order-8 {_x000D_
-webkit-order: 8;_x000D_
-ms-flex-order: 8;_x000D_
order: 8;_x000D_
}_x000D_
.reflex-order-7 {_x000D_
-webkit-order: 7;_x000D_
-ms-flex-order: 7;_x000D_
order: 7;_x000D_
}_x000D_
.reflex-order-6 {_x000D_
-webkit-order: 6;_x000D_
-ms-flex-order: 6;_x000D_
order: 6;_x000D_
}_x000D_
.reflex-order-5 {_x000D_
-webkit-order: 5;_x000D_
-ms-flex-order: 5;_x000D_
order: 5;_x000D_
}_x000D_
.reflex-order-4 {_x000D_
-webkit-order: 4;_x000D_
-ms-flex-order: 4;_x000D_
order: 4;_x000D_
}_x000D_
.reflex-order-3 {_x000D_
-webkit-order: 3;_x000D_
-ms-flex-order: 3;_x000D_
order: 3;_x000D_
}_x000D_
.reflex-order-2 {_x000D_
-webkit-order: 2;_x000D_
-ms-flex-order: 2;_x000D_
order: 2;_x000D_
}_x000D_
.reflex-order-1 {_x000D_
-webkit-order: 1;_x000D_
-ms-flex-order: 1;_x000D_
order: 1;_x000D_
}_x000D_
.reflex-order-0 {_x000D_
-webkit-order: 0;_x000D_
-ms-flex-order: 0;_x000D_
order: 0;_x000D_
}_x000D_
.reflex-container {_x000D_
display: inline-block;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
zoom: 1;_x000D_
*display: inline;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
position: relative;_x000D_
width: 100%;_x000D_
letter-spacing: -0.31em;_x000D_
*letter-spacing: normal;_x000D_
word-spacing: -0.43em;_x000D_
list-style-type: none;_x000D_
}_x000D_
.reflex-container *,_x000D_
.reflex-container:before,_x000D_
.reflex-container:after {_x000D_
-webkit-box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
box-sizing: border-box;_x000D_
max-width: 100%;_x000D_
letter-spacing: normal;_x000D_
word-spacing: normal;_x000D_
white-space: normal;_x000D_
}_x000D_
.reflex-container *:before,_x000D_
.reflex-container *:after {_x000D_
-webkit-box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
[class*="reflex-col-"] {_x000D_
width: 100%;_x000D_
vertical-align: top;_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
zoom: 1;_x000D_
*display: inline;_x000D_
text-align: left;_x000D_
text-align: start;_x000D_
}_x000D_
.reflex-item {_x000D_
display: block;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-direction: column;_x000D_
flex-direction: column;_x000D_
-webkit-flex: 1 1 auto;_x000D_
flex: 1 1 auto;_x000D_
}_x000D_
_:-ms-fullscreen,_x000D_
:root .reflex-item {_x000D_
width: 100%;_x000D_
}_x000D_
.reflex-col-12 {_x000D_
width: 100%;_x000D_
*width: 99.9%;_x000D_
}_x000D_
.reflex-col-11 {_x000D_
width: 91.66666666666666%;_x000D_
*width: 91.56666666666666%;_x000D_
}_x000D_
.reflex-col-10 {_x000D_
width: 83.33333333333334%;_x000D_
*width: 83.23333333333335%;_x000D_
}_x000D_
.reflex-col-9 {_x000D_
width: 75%;_x000D_
*width: 74.9%;_x000D_
}_x000D_
.reflex-col-8 {_x000D_
width: 66.66666666666666%;_x000D_
*width: 66.56666666666666%;_x000D_
}_x000D_
.reflex-col-7 {_x000D_
width: 58.333333333333336%;_x000D_
*width: 58.233333333333334%;_x000D_
}_x000D_
.reflex-col-6 {_x000D_
width: 50%;_x000D_
*width: 49.9%;_x000D_
}_x000D_
.reflex-col-5 {_x000D_
width: 41.66666666666667%;_x000D_
*width: 41.56666666666667%;_x000D_
}_x000D_
.reflex-col-4 {_x000D_
width: 33.33333333333333%;_x000D_
*width: 33.23333333333333%;_x000D_
}_x000D_
.reflex-col-3 {_x000D_
width: 25%;_x000D_
*width: 24.9%;_x000D_
}_x000D_
.reflex-col-2 {_x000D_
width: 16.666666666666664%;_x000D_
*width: 16.566666666666663%;_x000D_
}_x000D_
.reflex-col-1 {_x000D_
width: 8.333333333333332%;_x000D_
*width: 8.233333333333333%;_x000D_
}_x000D_
@media (min-width: 480px) {_x000D_
.reflex-col-xs-12 {_x000D_
width: 100%;_x000D_
*width: 99.9%;_x000D_
}_x000D_
.reflex-col-xs-11 {_x000D_
width: 91.66666666666666%;_x000D_
*width: 91.56666666666666%;_x000D_
}_x000D_
.reflex-col-xs-10 {_x000D_
width: 83.33333333333334%;_x000D_
*width: 83.23333333333335%;_x000D_
}_x000D_
.reflex-col-xs-9 {_x000D_
width: 75%;_x000D_
*width: 74.9%;_x000D_
}_x000D_
.reflex-col-xs-8 {_x000D_
width: 66.66666666666666%;_x000D_
*width: 66.56666666666666%;_x000D_
}_x000D_
.reflex-col-xs-7 {_x000D_
width: 58.333333333333336%;_x000D_
*width: 58.233333333333334%;_x000D_
}_x000D_
.reflex-col-xs-6 {_x000D_
width: 50%;_x000D_
*width: 49.9%;_x000D_
}_x000D_
.reflex-col-xs-5 {_x000D_
width: 41.66666666666667%;_x000D_
*width: 41.56666666666667%;_x000D_
}_x000D_
.reflex-col-xs-4 {_x000D_
width: 33.33333333333333%;_x000D_
*width: 33.23333333333333%;_x000D_
}_x000D_
.reflex-col-xs-3 {_x000D_
width: 25%;_x000D_
*width: 24.9%;_x000D_
}_x000D_
.reflex-col-xs-2 {_x000D_
width: 16.666666666666664%;_x000D_
*width: 16.566666666666663%;_x000D_
}_x000D_
.reflex-col-xs-1 {_x000D_
width: 8.333333333333332%;_x000D_
*width: 8.233333333333333%;_x000D_
}_x000D_
}_x000D_
@media (min-width: 768px) {_x000D_
.reflex-col-sm-12 {_x000D_
width: 100%;_x000D_
*width: 99.9%;_x000D_
}_x000D_
.reflex-col-sm-11 {_x000D_
width: 91.66666666666666%;_x000D_
*width: 91.56666666666666%;_x000D_
}_x000D_
.reflex-col-sm-10 {_x000D_
width: 83.33333333333334%;_x000D_
*width: 83.23333333333335%;_x000D_
}_x000D_
.reflex-col-sm-9 {_x000D_
width: 75%;_x000D_
*width: 74.9%;_x000D_
}_x000D_
.reflex-col-sm-8 {_x000D_
width: 66.66666666666666%;_x000D_
*width: 66.56666666666666%;_x000D_
}_x000D_
.reflex-col-sm-7 {_x000D_
width: 58.333333333333336%;_x000D_
*width: 58.233333333333334%;_x000D_
}_x000D_
.reflex-col-sm-6 {_x000D_
width: 50%;_x000D_
*width: 49.9%;_x000D_
}_x000D_
.reflex-col-sm-5 {_x000D_
width: 41.66666666666667%;_x000D_
*width: 41.56666666666667%;_x000D_
}_x000D_
.reflex-col-sm-4 {_x000D_
width: 33.33333333333333%;_x000D_
*width: 33.23333333333333%;_x000D_
}_x000D_
.reflex-col-sm-3 {_x000D_
width: 25%;_x000D_
*width: 24.9%;_x000D_
}_x000D_
.reflex-col-sm-2 {_x000D_
width: 16.666666666666664%;_x000D_
*width: 16.566666666666663%;_x000D_
}_x000D_
.reflex-col-sm-1 {_x000D_
width: 8.333333333333332%;_x000D_
*width: 8.233333333333333%;_x000D_
}_x000D_
}_x000D_
@media (min-width: 992px) {_x000D_
.reflex-col-md-12 {_x000D_
width: 100%;_x000D_
*width: 99.9%;_x000D_
}_x000D_
.reflex-col-md-11 {_x000D_
width: 91.66666666666666%;_x000D_
*width: 91.56666666666666%;_x000D_
}_x000D_
.reflex-col-md-10 {_x000D_
width: 83.33333333333334%;_x000D_
*width: 83.23333333333335%;_x000D_
}_x000D_
.reflex-col-md-9 {_x000D_
width: 75%;_x000D_
*width: 74.9%;_x000D_
}_x000D_
.reflex-col-md-8 {_x000D_
width: 66.66666666666666%;_x000D_
*width: 66.56666666666666%;_x000D_
}_x000D_
.reflex-col-md-7 {_x000D_
width: 58.333333333333336%;_x000D_
*width: 58.233333333333334%;_x000D_
}_x000D_
.reflex-col-md-6 {_x000D_
width: 50%;_x000D_
*width: 49.9%;_x000D_
}_x000D_
.reflex-col-md-5 {_x000D_
width: 41.66666666666667%;_x000D_
*width: 41.56666666666667%;_x000D_
}_x000D_
.reflex-col-md-4 {_x000D_
width: 33.33333333333333%;_x000D_
*width: 33.23333333333333%;_x000D_
}_x000D_
.reflex-col-md-3 {_x000D_
width: 25%;_x000D_
*width: 24.9%;_x000D_
}_x000D_
.reflex-col-md-2 {_x000D_
width: 16.666666666666664%;_x000D_
*width: 16.566666666666663%;_x000D_
}_x000D_
.reflex-col-md-1 {_x000D_
width: 8.333333333333332%;_x000D_
*width: 8.233333333333333%;_x000D_
}_x000D_
}_x000D_
@media (min-width: 1200px) {_x000D_
.reflex-col-lg-12 {_x000D_
width: 100%;_x000D_
*width: 99.9%;_x000D_
}_x000D_
.reflex-col-lg-11 {_x000D_
width: 91.66666666666666%;_x000D_
*width: 91.56666666666666%;_x000D_
}_x000D_
.reflex-col-lg-10 {_x000D_
width: 83.33333333333334%;_x000D_
*width: 83.23333333333335%;_x000D_
}_x000D_
.reflex-col-lg-9 {_x000D_
width: 75%;_x000D_
*width: 74.9%;_x000D_
}_x000D_
.reflex-col-lg-8 {_x000D_
width: 66.66666666666666%;_x000D_
*width: 66.56666666666666%;_x000D_
}_x000D_
.reflex-col-lg-7 {_x000D_
width: 58.333333333333336%;_x000D_
*width: 58.233333333333334%;_x000D_
}_x000D_
.reflex-col-lg-6 {_x000D_
width: 50%;_x000D_
*width: 49.9%;_x000D_
}_x000D_
.reflex-col-lg-5 {_x000D_
width: 41.66666666666667%;_x000D_
*width: 41.56666666666667%;_x000D_
}_x000D_
.reflex-col-lg-4 {_x000D_
width: 33.33333333333333%;_x000D_
*width: 33.23333333333333%;_x000D_
}_x000D_
.reflex-col-lg-3 {_x000D_
width: 25%;_x000D_
*width: 24.9%;_x000D_
}_x000D_
.reflex-col-lg-2 {_x000D_
width: 16.666666666666664%;_x000D_
*width: 16.566666666666663%;_x000D_
}_x000D_
.reflex-col-lg-1 {_x000D_
width: 8.333333333333332%;_x000D_
*width: 8.233333333333333%;_x000D_
}_x000D_
}_x000D_
.reflex-wrap {_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
.reflex-wrap-reverse {_x000D_
-webkit-flex-wrap: wrap-reverse;_x000D_
flex-wrap: wrap-reverse;_x000D_
}_x000D_
.reflex-direction-row-reverse {_x000D_
-webkit-flex-direction: row-reverse;_x000D_
flex-direction: row-reverse;_x000D_
}_x000D_
.reflex-direction-column {_x000D_
-webkit-flex-direction: column;_x000D_
flex-direction: column;_x000D_
}_x000D_
.reflex-direction-column-reverse {_x000D_
-webkit-flex-direction: column-reverse;_x000D_
flex-direction: column-reverse;_x000D_
}_x000D_
.reflex-align-start {_x000D_
-webkit-align-items: flex-start;_x000D_
align-items: flex-start;_x000D_
}_x000D_
.reflex-align-end {_x000D_
-webkit-align-items: flex-end;_x000D_
align-items: flex-end;_x000D_
}_x000D_
.reflex-align-end [class*="reflex-col-"] {_x000D_
vertical-align: bottom;_x000D_
}_x000D_
.reflex-align-center {_x000D_
-webkit-align-items: center;_x000D_
align-items: center;_x000D_
}_x000D_
.reflex-align-center [class*="reflex-col-"] {_x000D_
vertical-align: middle;_x000D_
}_x000D_
.reflex-align-baseline {_x000D_
-webkit-align-items: baseline;_x000D_
align-items: baseline;_x000D_
}_x000D_
.reflex-align-baseline [class*="reflex-col-"] {_x000D_
vertical-align: baseline;_x000D_
}_x000D_
.reflex-align-content-start {_x000D_
-webkit-align-content: flex-start;_x000D_
align-content: flex-start;_x000D_
}_x000D_
.reflex-align-content-end {_x000D_
-webkit-align-content: flex-end;_x000D_
align-content: flex-end;_x000D_
}_x000D_
.reflex-align-content-end [class*="reflex-col-"] {_x000D_
vertical-align: bottom;_x000D_
}_x000D_
.reflex-align-content-center {_x000D_
-webkit-align-content: center;_x000D_
align-content: center;_x000D_
}_x000D_
.reflex-align-content-space-between {_x000D_
-webkit-align-content: space-between;_x000D_
align-content: space-between;_x000D_
}_x000D_
.reflex-align-content-space-around {_x000D_
-webkit-align-content: space-around;_x000D_
align-content: space-around;_x000D_
}_x000D_
.reflex-align-self-stretch {_x000D_
-webkit-align-self: stretch;_x000D_
align-self: stretch;_x000D_
}_x000D_
.reflex-align-self-start {_x000D_
-webkit-align-self: flex-start;_x000D_
align-self: flex-start;_x000D_
}_x000D_
.reflex-align-self-end {_x000D_
-webkit-align-self: flex-end;_x000D_
align-self: flex-end;_x000D_
vertical-align: bottom;_x000D_
}_x000D_
.reflex-align-self-center {_x000D_
-webkit-align-self: center;_x000D_
align-self: center;_x000D_
vertical-align: middle;_x000D_
}_x000D_
.reflex-align-self-baseline {_x000D_
-webkit-align-self: baseline;_x000D_
align-self: baseline;_x000D_
vertical-align: baseline;_x000D_
}_x000D_
.reflex-justify-start {_x000D_
text-align: left;_x000D_
-webkit-justify-content: flex-start;_x000D_
justify-content: flex-start;_x000D_
}_x000D_
.reflex-justify-end {_x000D_
text-align: right;_x000D_
-webkit-justify-content: flex-end;_x000D_
justify-content: flex-end;_x000D_
}_x000D_
.reflex-justify-center {_x000D_
text-align: center;_x000D_
-webkit-justify-content: center;_x000D_
justify-content: center;_x000D_
}_x000D_
.reflex-justify-space-between {_x000D_
text-align: justify;_x000D_
-moz-text-align-last: justify;_x000D_
text-align-last: justify;_x000D_
-webkit-justify-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.reflex-justify-space-around {_x000D_
text-align: justify;_x000D_
-moz-text-align-last: justify;_x000D_
text-align-last: justify;_x000D_
-webkit-justify-content: space-around;_x000D_
justify-content: space-around;_x000D_
}_x000D_
.reflex-item-margin-sm {_x000D_
margin: 0 0.25em 0.5em;_x000D_
}_x000D_
.reflex-item-margin-md {_x000D_
margin: 0 0.5em 1em;_x000D_
}_x000D_
.reflex-item-margin-lg {_x000D_
margin: 0 1em 2em;_x000D_
}_x000D_
.reflex-item-content-margin-sm * {_x000D_
margin-right: 0.25em;_x000D_
margin-left: 0.25em;_x000D_
}_x000D_
.reflex-item-content-margin-md * {_x000D_
margin-right: 0.5em;_x000D_
margin-left: 0.25em;_x000D_
}_x000D_
.reflex-item-content-margin-lg * {_x000D_
margin-right: 1em;_x000D_
margin-left: 1em;_x000D_
}_x000D_
.reflex-img {_x000D_
display: inline-block;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
zoom: 1;_x000D_
*display: inline;_x000D_
-webkit-flex: 0 0 auto;_x000D_
flex: 0 0 auto;_x000D_
margin-left: 0;_x000D_
margin-right: 0;_x000D_
max-width: 100%;_x000D_
width: 100%;_x000D_
height: auto;_x000D_
}_x000D_
.reflex-item-footer {_x000D_
margin-top: auto;_x000D_
margin-left: 0;_x000D_
margin-right: 0;_x000D_
}
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="reflex-container reflex-wrap">_x000D_
<div class="reflex-col-xs-12 reflex-col-sm-4 panel" style="background-color: red">_x000D_
some content_x000D_
</div>_x000D_
<div class="reflex-col-xs-6 reflex-col-sm-4 panel" style="background-color: yellow">_x000D_
kittenz_x000D_
<img src="http://upload.wikimedia.org/wikipedia/en/1/13/Matrona.jpg">_x000D_
</div>_x000D_
<div class="reflex-col-xs-6 reflex-col-sm-4 panel" style="background-color: blue">_x000D_
some more content_x000D_
</div>_x000D_
</div>
_x000D_
First give the link of logout.php
page in that logout button.In that page make the code which is given below:
Here is the code:
<?php
session_start();
session_destroy();
?>
When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.
This works for me: \newcommand{\variablename}{the text}
For eg: \newcommand\m{100}
So when you type " \m\ is my mark " in the source code,
the pdf output displays as :
100 is my mark
The way of getting size of ResultSet, No need of using ArrayList etc
int size =0;
if (rs != null)
{
rs.beforeFirst();
rs.last();
size = rs.getRow();
}
Now You will get size, And if you want print the ResultSet, before printing use following line of code too,
rs.beforeFirst();
find()
will consider the sub-string against the regular expression where as matches()
will consider complete expression.
find()
will returns true only if the sub-string of the expression matches the pattern.
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d");
String candidate = "Java123";
Matcher m = p.matcher(candidate);
if (m != null){
System.out.println(m.find());//true
System.out.println(m.matches());//false
}
}
Through a combination of the suggestions I got, I came up with this:
private void DrawLetter()
{
Graphics g = this.CreateGraphics();
float width = ((float)this.ClientRectangle.Width);
float height = ((float)this.ClientRectangle.Width);
float emSize = height;
Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);
font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);
SizeF size = g.MeasureString(letter.ToString(), font);
g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);
}
private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
{
// Compute actual size, shrink if needed
while (true)
{
SizeF size = g.MeasureString(text, font);
// It fits, back out
if (size.Height <= proposedSize.Height &&
size.Width <= proposedSize.Width) { return font; }
// Try a smaller font (90% of old size)
Font oldFont = font;
font = new Font(font.Name, (float)(font.Size * .9), font.Style);
oldFont.Dispose();
}
}
So far, this works flawlessly.
The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness.
This issue can be resolved by setting the higher values for the MySQL variable innodb_buffer_pool_size
. The default value for innodb_buffer_pool_size
will be 8,388,608
.
To change the settings value for innodb_buffer_pool_size
please see the below set.
my.cnf
from the server. For Linux servers this will be mostly at /etc/my.cnf
innodb_buffer_pool_size=64MB
to this fileTo restart the MySQL server, you can use anyone of the below 2 options:
Reference The total number of locks exceeds the lock table size
You should not add to your list using c
inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element)
, the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N)
. If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg
i <- 1
while(...) {
l[[i]] <- new_element
i <- i + 1
}
For more info have a look at Patrick Burns' The R Inferno (Chapter 2).
Although ES6 Solution is the best, I'm baffled as to how nobody has shown the following solution:
function removeDuplicates(arr){
o={}
arr.forEach(function(e){
o[e]=true
})
return Object.keys(o)
}
The thing to remember here is that objects MUST have unique keys. We are exploiting this to remove all the duplicates. I would have thought this would be the fastest solution (before ES6).
Bear in mind though that this also sorts the array.
Today, I mistakenly checked out on a commit and started working on it, making some commits on a detach HEAD state. Then I pushed to the remote branch using the following command:
git push origin HEAD: <My-remote-branch>
Then
git checkout <My-remote-branch>
Then
git pull
I finally got my all changes in my branch that I made in detach HEAD.
overflow: auto;
or overflow: hidden;
should do it I think.
I may also add, that nowadays it is possible to decompile Android application online, no software needed!
Here are 2 options for you:
Timings on Excel 2013 fairly slow machine with a big bad used range million rows:
26ms Cells.Find xlPrevious method (as above)
0.4ms Sheet.UsedRange (just call it)
0.14ms Counta binary search + 0.4ms Used Range to start search (12 CountA calls)
So the Find xlPrevious is quite slow if that is of concern.
The CountA binary search approach is to first do a Used Range. Then chop the range in half and see if there are any non-empty cells in the bottom half, and then halve again as needed. It is tricky to get right.
You should post it with ajax, this will stop it from changing the page, and you will still get the information back.
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: 'submit.php',
data: { username: $(this).name.value,
password: $(this).password.value }
});
return false;
});
})
You can use custom ActionFilter in Web Api to validate model:
public class DRFValidationFilters : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
//BadRequest(actionContext.ModelState);
}
}
public override Task OnActionExecutingAsync(HttpActionContext actionContext,
CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
});
}
public class AspirantModel
{
public int AspirantId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string AspirantType { get; set; }
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
ErrorMessage = "Not a valid Phone number")]
public string MobileNumber { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
public int CenterId { get; set; }
[HttpPost]
[Route("AspirantCreate")]
[DRFValidationFilters]
public IHttpActionResult Create(AspirantModel aspirant)
{
if (aspirant != null)
{
}
else
{
return Conflict();
}
return Ok();
}
}
}
Register CustomAttribute class in webApiConfig.cs config.Filters.Add(new DRFValidationFilters());
N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):
N[i]/2
will be a float64
but range()
expects an integer. Just cast the call to
for j in range(int(N[i]/2)):
On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.
If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.
You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.
Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
_x000D_
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">
_x000D_
The following will do a dry run, as it says. HEAD being current version, PREV is previous, then the path to your file, or committed item:
svn merge --dry-run -rHEAD:PREV https://example.com/svn/myproject/trunk
If the dry run looks good, run the command without the --dry-run
Verify the change in revision and re-commit. To browse for version numbers try:
svn log
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
I think nt86's solution is the most appropriate because it leverages the underlying Windows infrastructure (certificate store). But it doesn't explain how to install python-certifi-win32 to start with since pip is non functional.
The trick is to use --trustedhost
to install python-certifi-win32 and then after that, pip will automatically use the windows certificate store to load the certificate used by the proxy.
So in a nutshell, you should do:
pip install python-certifi-win32 -trustedhost pypi.org
and after that you should be good to go
If you are looking for an authentication framework for Connect or Express, Passport is worth investigating: https://github.com/jaredhanson/passport
(Disclosure: I'm the developer of Passport)
I developed Passport after investigating both connect-auth and everyauth. While they are both great modules, they didn't suit my needs. I wanted something that was more light-weight and unobtrusive.
Passport is broken down into separate modules, so you can choose to use only what you need (OAuth, only if necessary). Passport also does not mount any routes in your application, giving you the flexibility to decide when and where you want authentication, and hooks to control what happens when authentication succeeds or fails.
For example, here is the two-step process to setup form-based (username and password) authentication:
passport.use(new LocalStrategy(
function(username, password, done) {
// Find the user from your DB (MongoDB, CouchDB, other...)
User.findOne({ username: username, password: password }, function (err, user) {
done(err, user);
});
}
));
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
// Authentication successful. Redirect home.
res.redirect('/');
});
Additional strategies are available for authentication via Facebook, Twitter, etc. Custom strategies can be plugged-in, if necessary.
You need to update your Apache configuration to make sure it's outputting php
as the type text/HTML.
The below code should work, but some configurations are different.
AddHandler php5-script .php
AddType text/html .php
You can use the following CSS to center the form (note that it is important to set the width to something that isn´t 'auto' for this to work):
form {
margin-left:auto;
margin-right:auto;
width:100px;
}
OK, thanks all for the help.
However the problem was much easier than that.
All I need to do is to fix my JSON to assign the array, to an attribute called data, as following.
{
"data": [{
"name_en": "hello",
"phone": "55555555",
"email": "a.shouman",
"facebook": "https:\/\/www.facebook.com"
}, ...]
}
If you want to submit files using ajax use "jquery.form.js" This submits all form elements easily.
Samples http://jquery.malsup.com/form/#ajaxSubmit
rough view :
<form id='AddPhotoForm' method='post' action='../photo/admin_save_photo.php' enctype='multipart/form-data'>
<script type="text/javascript">
function showResponseAfterAddPhoto(responseText, statusText)
{
information= responseText;
callAjaxtolist();
$("#AddPhotoForm").resetForm();
$("#photo_msg").html('<div class="album_msg">Photo uploaded Successfully...</div>');
};
$(document).ready(function(){
$('.add_new_photo_div').live('click',function(){
var options = {success:showResponseAfterAddPhoto};
$("#AddPhotoForm").ajaxSubmit(options);
});
});
</script>
I don't believe search and replace will do it for you (doesn't work for me in Excel 2010 Home). Are you sure you want to put "null" in EVERY cell in the sheet? That is millions of cells, in which case there is no way a search and replace would be able to handle it memory-wise (correct me if I am wrong).
In the case I am right and you don't want millions of "null" cells, then here is a macro. It asks you to select the range then put "null" inside every cell that was blank.
Sub FillWithNull()
Dim cell As range
Dim myRange As range
Set myRange = Application.InputBox("Select the range", Type:=8)
Application.ScreenUpdating = False
For Each cell In myRange
If Len(cell) = 0 Then
cell.Value = "Null"
End If
Next
Application.ScreenUpdating = True
End Sub
Fun! There are a few things to tease out here:
$leadID
seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework."
or '
characters. Since you’re already inside both "
and '
, you’ll want to escape whichever you choose. \'
to escape the PHP quotes, or '
to escape the HTML quotes.<a />
elements are commonly used for “hyper”links, and almost always with a href
attribute to indicate their destination, like this: <a href="http://www.google.com">Google homepage</a>
.return false;
to a Javascript event to suppress default behavior.onclick
doesn’t mean anything on its own. That’s because onclick
is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick
we’re talking about! One such object is window
. You could write <a href="javascript:window.onclick = location.reload;">Activate me to reload when anything is clicked</a>
.onclick
can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">
. I bet you had this in mind.=
assignments. The Javascript =
expects something that hasn’t been run yet. You can wrap things in a function
block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload
): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ...
.<a href="http://www.google.com" target="_blank">Google homepage</a>
.Hope those are useful.
Today 2021.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions.
For all browsers
I perform 2 tests cases:
Below snippet presents solutions Aa Ab Ba Bb Ca Cb Da Db E F
// https://stackoverflow.com/questions/10398931/how-to-strToRemove-text-from-a-string
// https://stackoverflow.com/a/10398941/860099
function Aa(str,strToRemove) {
return str.replace(strToRemove,'');
}
// https://stackoverflow.com/a/63362111/860099
function Ab(str,strToRemove) {
return str.replaceAll(strToRemove,'');
}
// https://stackoverflow.com/a/23539019/860099
function Ba(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replace(new RegExp(re),'');
}
// https://stackoverflow.com/a/63362111/860099
function Bb(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replaceAll(new RegExp(re,'g'),'');
}
// https://stackoverflow.com/a/27098801/860099
function Ca(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/27098801/860099
function Cb(str,strToRemove) {
let start = str.search(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/23181792/860099
function Da(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/23181792/860099
function Db(str,strToRemove) {
let start = str.search(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/49857431/860099
function E(str,strToRemove) {
return str.split(strToRemove).join('');
}
// https://stackoverflow.com/a/45406624/860099
function F(str,strToRemove) {
var n = str.search(strToRemove);
while (str.search(strToRemove) > -1) {
n = str.search(strToRemove);
str = str.substring(0, n) + str.substring(n + strToRemove.length, str.length);
}
return str;
}
let str = "data-123";
let strToRemove = "data-";
[Aa,Ab,Ba,Bb,Ca,Cb,Da,Db,E,F].map( f=> console.log(`${f.name.padEnd(2,' ')} ${f(str,strToRemove)}`));
_x000D_
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
And here are example results for chrome
@xpmatteo has the answer to disabling portions of code, but in addition to this, the default eclipse settings should be set to only format edited lines of code instead of the whole file.
Preferences->Java->Editor->Save Actions->Format Source Code->Format Edited Lines
This would have prevented it from happening in the first place since your coworkers are reformatting code they didn't actually change. This is a good practice to prevent mishaps that render diff on your source control useless (when an entire file is reformatted because of minor format setting differences).
It would also prevent the reformatting if the on/off tags option was turned off.
I didn't find the package of the most voted answer in my Python 3 dist.
I had the same problem and solved it installing the module pywin32:
In a normal python:
pip install pywin32
In anaconda:
conda install pywin32
My python installation (Intel® Distribution for Python) had some kind of dependency problem and was giving this error. After installing this module it stopped appearing.
This can be used in to solve this problem
<div id='scrol'></div>
in javascript use this
jQuery("div#scrol").scrollTop(jQuery("div#scrol")[0].scrollHeight);
You can also pass an array as the second argument after the view template name, instead of stringing together a bunch of ->with()
methods.
return View::make('blog', array('posts' => $posts));
Or, if you're using PHP 5.4 or better you can use the much nicer "short" array syntax:
return View::make('blog', ['posts' => $posts]);
This is useful if you want to compute the array elsewhere. For instance if you have a bunch of variables that every controller needs to pass to the view, and you want to combine this with an array of variables that is unique to each particular controller (using array_merge
, for instance), you might compute $variables
(which contains an array!):
return View::make('blog', $variables);
(I did this off the top of my head: let me know if a syntax error slipped in...)
Expansion of the same answer
THIS IS A ROUGH ESTIMATION TABLE FOR QUICK DECISIONS!
x-x
Type | A= worst case (x/3) | B = best case (x) | words estimate (A/4.5) - (B/4.5)
-----------+---------------------------------------------------------------------------
TINYTEXT | 85 | 255 | 18 - 56
TEXT | 21,845 | 65,535 | 4,854.44 - 14,563.33
MEDIUMTEXT | 5,592,415 | 16,777,215 | 1,242,758.8 - 3,728,270
LONGTEXT | 1,431,655,765 | 4,294,967,295 | 318,145,725.5 - 954,437,176.6
Please refer to Chris V's answer as well : https://stackoverflow.com/a/35785869/1881812
Using CentOS Linux I found that the easiest syntax would be:
wget "link" -O file.ext
where "link"
is the web address you want to save and "file.ext"
is the filename and extension of your choice.
int index = sourceString.IndexOf(removeString);
string cleanPath = (index < 0)
? sourceString
: sourceString.Remove(index, removeString.Length);
One liner for Classification:
Classifying data into pre-defined categories
One liner for Clustering:
Grouping data into a set of categories
Key difference:
Classification is taking data and putting it into pre-defined categories and in Clustering the set of categories, that you want to group the data into, is not known beforehand.
Conclusion:
I have written a long post on the same topic which you can find here:
The common convention would be to put it in a .sh file that looks like this -
#!/bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar;... etc
Note that '\' become '/'.
You could execute as
sh myfile.sh
or set the x bit on the file
chmod +x myfile.sh
and then just call
myfile.sh
On input type=file add an event onchange="preview()"
For the function preview()
type:
thumb.src=URL.createObjectURL(event.target.files[0]);
Live example:
function preview() {
thumb.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
<input type="file" onchange="preview()">
<img id="thumb" src="" width="150px"/>
</form>
_x000D_
I had a similar issue, I was getting 400, Bad Request only with the PUT, where as POST request was perfectly fine.
Below code worked fine for POST but was giving BAD Request for PUT:
conn.setRequestProperty("Content-Type", "application/json");
os.writeBytes(json);
After making below changes worked fine for both POST and PUT
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
os.write(json.getBytes("UTF-8"));
You can create a function with the pattern ShouldSerialize{PropertyName}
which tells the XmlSerializer if it should serialize the member or not.
For example, if your class property is called MyNullableInt
you could have
public bool ShouldSerializeMyNullableInt()
{
return MyNullableInt.HasValue;
}
Here is a full sample
public class Person
{
public string Name {get;set;}
public int? Age {get;set;}
public bool ShouldSerializeAge()
{
return Age.HasValue;
}
}
Serialized with the following code
Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);
Results in the followng XML - Notice there is no Age
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Chris</Name>
</Person>
I tried @Joanna's method and tested on the following websites and it didn't work.
I then modified it to and it worked.
/([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+
This error occurred for me when a value was returned as -1.#IND due to a division by zero. More info on IEEE floating-point exceptions in C++ here on SO and by John Cook
For the one who has downvoted this answer (and did not specify why), the reason why this answer can be significant to some is that a division by zero will lead to an infinitely large number and thus a value that doesn't fit in an Int32 (or even Int64). So the error you receive will be the same (Arithmetic operation resulted in an overflow) but the reason is slightly different.
$('#form').append('<input type="text" value="'+yourValue+'" />');
Add ConnectionString to MVC Project Web.config file
It could be done by getting the page title by Selenium and do assertion by using TestNG.
Import Assert class in the import section:
`import org.testng.Assert;`
Create a WebDriver object:
WebDriver driver=new FirefoxDriver();
Apply this to assert the title of the page:
Assert.assertEquals("Expected page title", driver.getTitle());
Normally a jdk installation has javac in the environment path variables ... so if you check for javac in the path, that's pretty much a good indicator that you have a jdk installed.
Ted Hopp is correct, from the API Documentation :
public void copyPixelsToBuffer (Buffer dst)
"... After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements written in the buffer. "
and
public ByteBuffer get (byte[] dst, int dstOffset, int byteCount)
"Reads bytes from the current position into the specified byte array, starting at the specified offset, and increases the position by the number of bytes read."
This is what worked for me:
Enter the command:
osql -S localhost\SQLEXPRESS -E
(or change localhost to whatever your PC is called).
At the prompt type the following commands:
CREATE LOGIN my_Login_here WITH PASSWORD = 'my_Password_here'
go
sp_addsrvrolemember 'my_Login_here', 'sysadmin'
go
quit
Stop the "SQL Server (SQLEXPRESS)" service.
Remove the "-m" from the Start parameters field (if still there).
Start the service.
In Management Studio, use the login and password you just created. This should give it admin permission.
Edit this element is not recommended, but if you want to try it's like any other HTML element.
Edit example:
/* Edit select */
select {
/* CSS style here */
}
/* Edit option */
option {
/* CSS style here */
}
/* Edit selected option */
/* element attr attr value */
option[selected="selected"] {
/* CSS style here */
}
<select>
<option >Something #1</option>
<option selected="selected">Something #2</option>
<option >Something #3</option>
</select>
In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__
.
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
Update: Please see marked answer as a better solution to implement this. The following solution is no longer required.
Converting the json date to this format "mm/dd/yyyy HH:MM:ss"
dateFormat is a jasondate format.js file found at blog.stevenlevithan.com
var _meetStartTime = dateFormat(now, "mm/dd/yyyy HH:MM:ss");
Assign empty value:
document.getElementById('numquest').value=null;
or, if want to clear all form fields. Just call form reset method as:
document.forms['form_name'].reset()
Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example:
foreach (var s in strings)
query = query.Where(i => i.Prop == s); // access to modified closure
I do:
foreach (var s in strings)
{
string search = s;
query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.
}
Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have ever done so.
Try this, to set the focus to the first input field:
$(this).parent().siblings('div.bottom').find("input.post").focus();
The Group Policy editor is not mentioned in the post above. I have used GPedit quite a few times to perform a task on bootup or shutdown. Here are Microsoft's instructions on how to access and maneuver GPedit.
How To Use the Group Policy Editor to Manage Local Computer Policy in Windows XP
Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like
Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.
Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.
Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.
HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.
If we go into more detail, then answer to this question go longer. We can understand more from following posts:
def find_dog(new_ls):
splt = new_ls.split()
if 'dog' in splt:
print("True")
else:
print('False')
find_dog("Is there a dog here?")
Window > Show view > Server
or right click on the server in "Servers" view, select "Properties".You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.
If Khanh TO's solution caused UI issues for you (like it did for me) try using $timeout
to not update the attribute until it has been unchanged for 500ms.
var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
var newWidth = window.innerWidth,
updateStuffTimer;
if (newWidth !== oldWidth) {
$timeout.cancel(updateStuffTimer);
}
updateStuffTimer = $timeout(function() {
updateStuff(newWidth); // Update the attribute based on window.innerWidth
}, 500);
});
$scope.$on('$destroy',function (){
$(window).off('resize.doResize'); // remove the handler added earlier
});
Reference: https://gist.github.com/tommaitland/7579618
I generated the "ssh" key again and added to my git account. This worked for me.
Please find following commands to generate the "ssh-key":
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
-> This creates a new ssh key, using the provided email as a label.
Generating public/private rsa key pair.
-> When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.
Enter a file in which to save the key (/home/you/.ssh/id_rsa): [Press enter]
-> At the prompt, type a secure passphrase. For more information, see "Working with SSH key passphrases"
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
-> Your key is generated, to copy the key:
$ sudo cat /root/.ssh/id_rsa-pub
Hope this works!
You don't specify which shell (there are many), so I am assuming Bourne Shell, that is I think your script starts with:
#!/bin/sh
Please remember to tag future questions with the shell type, as this will help the community answer your question.
You need to define your functions before you call them. Using ()
:
process_install()
{
echo "Performing process_install() commands, using arguments [${*}]..."
}
process_exit()
{
echo "Performing process_exit() commands, using arguments [${*}]..."
}
Then you can call your functions, just as if you were calling any command:
if [ "$choice" = "true" ]
then
process_install foo bar
elif [ "$choice" = "false" ]
then
process_exit baz qux
You may also wish to check for invalid choices at this juncture...
else
echo "Invalid choice [${choice}]..."
fi
See it run with three different values of ${choice}.
Good luck!
I did it this way
lines_list = open('file.txt').read().splitlines()
Every line comes with its end of line characters (\n\r); this way the characters are removed.
I would use EXISTS
expression since it is more powerful, you can e.g. more precisely choose rows you would like to join. In the case of LEFT JOIN
, you have to take everything that's in the joined table. Its efficiency is probably the same as in the case of LEFT JOIN
with null constraint.
SELECT t1.ID
FROM Table1 t1
WHERE NOT EXISTS (SELECT t2.ID FROM Table2 t2 WHERE t1.ID = t2.ID)
After making changes to .profile, you need to execute the file, in order for the changes to take effect.
root@masternode# . ~/.profile
Once this is done, the echo command will work.
#include
it used to get "things" from another file to the one the #include
is used in.
Ex:
in file: main.cpp
#include "otherfile.h"
// some stuff here using otherfile.h objects,
// functions or classes declared inside
Header guard is used on the top of each header file (*.h) to prevent including the same file more then once (if it happens you will get compile errors).
in file: otherfile.h
#ifndef OTHERFILE
#define OTHERFILE
// declare functions, classes or objects here
#endif
even if you put #include
"otherfile.h" n time in your code, this inside it will not be redeclared.
another simplify version
lastBusDay = datetime.datetime.today()
wk_day = datetime.date.weekday(lastBusDay)
if wk_day > 4: #if it's Saturday or Sunday
lastBusDay = lastBusDay - datetime.timedelta(days = wk_day-4) #then make it Friday
RETURNING
Since PostgreSQL 8.2, that's possible with a single round-trip to the database:
INSERT INTO tbl(filename)
VALUES ('my_filename')
RETURNING tbl_id;
tbl_id
would typically be a serial
or IDENTITY
(Postgres 10 or later) column. More in the manual.
If filename
needs to include tbl_id
(redundantly), you can still use a single query.
Use lastval()
or the more specific currval()
:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval('tbl_tbl_id_seq') -- or lastval()
RETURNING tbl_id;
See:
If multiple sequences may be advanced in the process (even by way of triggers or other side effects) the sure way is to use currval('tbl_tbl_id_seq')
.
The string literal 'tbl_tbl_id_seq'
in my example is supposed to be the actual name of the sequence and is cast to regclass
, which raises an exception if no sequence of that name can be found in the current search_path
.
tbl_tbl_id_seq
is the automatically generated default for a table tbl
with a serial column tbl_id
. But there are no guarantees. A column default can fetch values from any sequence if so defined. And if the default name is taken when creating the table, Postgres picks the next free name according to a simple algorithm.
If you don't know the name of the sequence for a serial
column, use the dedicated function pg_get_serial_sequence()
. Can be done on the fly:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval(pg_get_serial_sequence('tbl', 'tbl_id'))
RETURNING tbl_id;
Try using a div tag and block for span!
<div>
<span style="padding-right:3px; padding-top: 3px; display:block;">
<img class="manImg" src="images/ico_mandatory.gif"></img>
</span>
</div>
@JavaZava your solution is good, but if you want to have a 13 digit long value to be consistent with the time stamp formatting in Java or JavaScript (and other languages) use this method:
NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); // returned as a double
long digits = (long)time; // this is the first 10 digits
int decimalDigits = (int)(fmod(time, 1) * 1000); // this will get the 3 missing digits
long timestamp = (digits * 1000) + decimalDigits;
or (if you need a string):
NSString *timestampString = [NSString stringWithFormat:@"%ld%d",digits ,decimalDigits];
Try the following:
CONVERT(VARCHAR(10),GetDate(),102)
Then you would need to replace the "." with "-".
Here is a site that helps http://www.mssqltips.com/tip.asp?tip=1145
Like this ? (Visual Studio Code version 0.10.11)
Fold All (Ctrl+K Ctrl+0)
Unfold All (Ctrl+K Ctrl+J)
Fold Level n (Ctrl+K Ctrl+N)
Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..)
method. As it is not intuitive, it may perhaps change in a future release.
You can use any one way
NSString *string=[NSString stringWithFormat:@"%@",url1];
or
NSString *str=[url1 absoluteString];
NSLog(@"string :: %@",string);
string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
NSLog(@"str :: %@", str);
str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
To understand event handlers, you need to understand delegates. In C#, you can think of a delegate as a pointer (or a reference) to a method. This is useful because the pointer can be passed around as a value.
The central concept of a delegate is its signature, or shape. That is (1) the return type and (2) the input arguments. For example, if we create a delegate void MyDelegate(object sender, EventArgs e)
, it can only point to methods which return void
, and take an object
and EventArgs
. Kind of like a square hole and a square peg. So we say these methods have the same signature, or shape, as the delegate.
So knowing how to create a reference to a method, let's think about the purpose of events: we want to cause some code to be executed when something happens elsewhere in the system - or "handle the event". To do this, we create specific methods for the code we want to be executed. The glue between the event and the methods to be executed are the delegates. The event must internally store a "list" of pointers to the methods to call when the event is raised.* Of course, to be able to call a method, we need to know what arguments to pass to it! We use the delegate as the "contract" between the event and all the specific methods that will be called.
So the default EventHandler
(and many like it) represents a specific shape of method (again, void/object-EventArgs). When you declare an event, you are saying which shape of method (EventHandler) that event will invoke, by specifying a delegate:
//This delegate can be used to point to methods
//which return void and take a string.
public delegate void MyEventHandler(string foo);
//This event can cause any method which conforms
//to MyEventHandler to be called.
public event MyEventHandler SomethingHappened;
//Here is some code I want to be executed
//when SomethingHappened fires.
void HandleSomethingHappened(string foo)
{
//Do some stuff
}
//I am creating a delegate (pointer) to HandleSomethingHappened
//and adding it to SomethingHappened's list of "Event Handlers".
myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);
//To raise the event within a method.
SomethingHappened("bar");
(*This is the key to events in .NET and peels away the "magic" - an event is really, under the covers, just a list of methods of the same "shape". The list is stored where the event lives. When the event is "raised", it's really just "go through this list of methods and call each one, using these values as the parameters". Assigning an event handler is just a prettier, easier way of adding your method to this list of methods to be called).
There are a couple ways to do this.
First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:
E:\> openssl x509 -pubkey -noout -in cert.pem > pubkey.pem
If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.
openssl> x509 -pubkey -noout -in cert.pem
Output will look something like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----
spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]
index=spell_list.index("Annual")
print(index)
Sets behave different than dicts, you need to use set operations like issubset():
>>> k
{'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True}
>>> set('ip,port,pw'.split(',')).issubset(set(k.keys()))
True
>>> set('ip,port,pw'.split(',')) in set(k.keys())
False
while(inFile1.hasNext()){
token1 = inFile1.nextLine();
// put each value into an array with String#split();
String[] numStrings = line.split(", ");
// parse number string into doubles
double[] nums = new double[numString.length];
for (int i = 0; i < nums.length; i++){
nums[i] = Double.parseDouble(numStrings[i]);
}
}
Let me give an example for Including express module with require & import
-require
var express = require('express');
-import
import * as express from 'express';
So after using any of the above statement we will have a variable called as 'express' with us. Now we can define 'app' variable as,
var app = express();
So we use 'require' with 'CommonJS' and 'import' with 'ES6'.
For more info on 'require' & 'import', read through below links.
require - Requiring modules in Node.js: Everything you need to know
import - An Update on ES6 Modules in Node.js
We can use git merge --continue
with git version 2.12 and above to continue your merging after resolved the conflict. Can see this answer
You may also find the following approach cleaner than including every method:
class Thing
delegate :url_helpers, to: 'Rails.application.routes'
def url
url_helpers.thing_path(self)
end
end
What worked for me: I finally noticed the Build Executor Status window on the left on the main Jenkins dashboard. I run a dev/test instance on my local system with 2 executors. Both were currently occupied with builds that were not running. Upon cancelling these to jobs, my third (pending) job was able to run.
This worked for me:
<html>
<head>
<title>scroll</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<style>
div.container {
overflow:hidden;
width:200px;
height:200px;
}
div.content {
position:relative;
width:200px;
height:200px;
overflow:hidden;
top:0;
}
</style>
<div class="container">
<p>
<a href="javascript:up();"><img src="/images/img_flecha_left.png" class="up" /></a>
<a href="javascript:down();"><img src="/images/img_flecha_left.png" class="down" /></a>
</p>
<div class="content">
<p>Hello World</p><p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
</div>
</div>
<script>
function up() {
var topVal = $(".content").css("top"); //alert(topVal);
var val=parseInt(topVal.replace("px",""));
val=val-20;
$(".content").css("top", val+"px");
}
function down() {
var topVal = $(".content").css("top"); //alert(topVal);
var val=parseInt(topVal.replace("px",""));
val=val+20;
$(".content").css("top", val+"px");
}
</script>
</body>
</html>
You can update to an older revision:
svn update -r 666 file
Or you can just view the file directly:
svn cat -r 666 file | less
Just use the function plot
as follows
figure()
...
plot(t, a)
plot(t, b)
plot(t, c)
In the call back function, use the $request parameter
$parameters = $request->get_params();
echo $parameters['ppc'];
Normally you could access it by its property name:
var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);
or perhaps you've got a JSON string that needs to be turned into an object:
var foo = jQuery.parseJSON(data);
alert(foo.id);
@inoabrian solution above worked for me. I ran into a situation where I would refresh my page and my hidden element would reappear on my page. Here's what I did to resolve it.
export class FooterComponent implements OnInit {
public showJoinTodayBtn: boolean = null;
ngOnInit() {
if (condition is true) {
this.showJoinTodayBtn = true;
} else {
this.showJoinTodayBtn = false;
}
}
You can use gettimeofday()
together with the timedifference_msec()
function below to calculate the number of milliseconds elapsed between two samples:
#include <sys/time.h>
#include <stdio.h>
float timedifference_msec(struct timeval t0, struct timeval t1)
{
return (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) / 1000.0f;
}
int main(void)
{
struct timeval t0;
struct timeval t1;
float elapsed;
gettimeofday(&t0, 0);
/* ... YOUR CODE HERE ... */
gettimeofday(&t1, 0);
elapsed = timedifference_msec(t0, t1);
printf("Code executed in %f milliseconds.\n", elapsed);
return 0;
}
Note that, when using gettimeofday()
, you need to take seconds into account even if you only care about microsecond differences because tv_usec
will wrap back to zero every second and you have no way of knowing beforehand at which point within a second each sample is obtained.
move all files(not include except file) to except_file
find -maxdepth 1 -mindepth 1 -not -name except_file -print0 |xargs -0 mv -t ./except_file
for example(cache is current except file)
find -maxdepth 1 -mindepth 1 -not -name cache -print0 |xargs -0 mv -t ./cache
Must be too late now, but the right version would be:
for(var i = 0; i < restaurants.restaurant.length; i++)
{
if(restaurants.restaurant[i].food == 'chicken')
{
return restaurants.restaurant[i].name;
}
}
The JSON.parse
function accepts an optional DateTime reviver function. You can use a function like this:
dateTimeReviver = function (key, value) {
var a;
if (typeof value === 'string') {
a = /\/Date\((\d*)\)\//.exec(value);
if (a) {
return new Date(+a[1]);
}
}
return value;
}
Then call
JSON.parse(somejsonstring, dateTimeReviver);
And your dates will come out right.
The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.
The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes()
call directly or create a vector for that instead.
This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.
level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses
ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()
or
level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))
ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()
or
directly in the aes()
call without a pre-created vector:
ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()
When just a single result is needed, then no loop should be used. Just fetch the row right away.
In case you need to fetch the entire row into associative array:
$row = $result->fetch_assoc();
in case you need just a single value
$row = $result->fetch_row();
$value = $row[0] ?? false;
The last example will return the first column from the first returned row, or false
if no row was returned. It can be also shortened to a single line,
$value = $result->fetch_row()[0] ?? false;
Below are complete examples for different use cases
When variables are to be used in the query, then a prepared statement must be used. For example, given we have a variable $id
:
$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// in case you need just a single value
$query = "SELECT count(*) FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$value = $result->fetch_row()[0] ?? false;
The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question
In your case, where no variables to be used in the query, you can use the query()
method:
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->query($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$value = $result->fetch_row()[0] ?? false;
By the way, although using raw API while learning is okay, consider using some database abstraction library or at least a helper function in the future:
// using a helper function
$sql = "SELECT email FROM users WHERE id=?";
$value = prepared_select($conn, $sql, [$id])->fetch_row[0] ?? false;
// using a database helper class
$email = $db->getCol("SELECT email FROM users WHERE id=?", [$id]);
As you can see, although a helper function can reduce the amount of code, a class' method could encapsulate all the repetitive code inside, making you to write only meaningful parts - the query, the input parameters and the desired result format (in the form of the method's name).
In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:
>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}
It's fairly easy using the New-SelfSignedCertificate command in Powershell. Open powershell and run these 3 commands.
1) Create certificate:
$cert = New-SelfSignedCertificate -DnsName www.yourwebsite.com -Type CodeSigning -CertStoreLocation Cert:\CurrentUser\My2) set the password for it:
$CertPassword = ConvertTo-SecureString -String "my_passowrd" -Force –AsPlainText3) Export it:
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath "d:\selfsigncert.pfx" -Password $CertPassword
Your certificate selfsigncert.pfx will be located @ D:/
Optional step: You would also require to add certificate password to system environment variables. do so by entering below in cmd: setx CSC_KEY_PASSWORD "my_password"
This article explains all the details http://kunststube.net/encoding/
WRITING TO BUFFER
if you write to a 4 byte buffer, symbol ?
with UTF8 encoding, your binary will look like this:
00000000 11100011 10000001 10000010
if you write to a 4 byte buffer, symbol ?
with UTF16 encoding, your binary will look like this:
00000000 00000000 00110000 01000010
As you can see, depending on what language you would use in your content this will effect your memory accordingly.
e.g. For this particular symbol: ?
UTF16 encoding is more efficient since we have 2 spare bytes to use for the next symbol. But it doesn't mean that you must use UTF16 for Japan alphabet.
READING FROM BUFFER
Now if you want to read the above bytes, you have to know in what encoding it was written to and decode it back correctly.
e.g. If you decode this :
00000000 11100011 10000001 10000010
into UTF16 encoding, you will end up with ?
not ?
Note: Encoding and Unicode are two different things. Unicode is the big (table) with each symbol mapped to a unique code point. e.g. ?
symbol (letter) has a (code point): 30 42 (hex). Encoding on the other hand, is an algorithm that converts symbols to more appropriate way, when storing to hardware.
30 42 (hex) - > UTF8 encoding - > E3 81 82 (hex), which is above result in binary.
30 42 (hex) - > UTF16 encoding - > 30 42 (hex), which is above result in binary.
As all other answers currying helps to create partially applied functions. Javascript does not provide native support for automatic currying. So the examples provided above may not help in practical coding. There is some excellent example in livescript (Which essentially compiles to js) http://livescript.net/
times = (x, y) --> x * y
times 2, 3 #=> 6 (normal use works as expected)
double = times 2
double 5 #=> 10
In above example when you have given less no of arguments livescript generates new curried function for you (double)
As some of the comments above mentioned, the transpose of 1D arrays are 1D arrays, so one way to transpose a 1D array would be to convert the array to a matrix like so:
np.transpose(a.reshape(len(a), 1))
In C++, your source files are usually parsed from top to bottom in a single pass, so any variable or function must be declared before they can be used. There are some exceptions to this, like when defining functions inline in a class definition, but that's not the case for your code.
Either move the definition of integrate
above the one for getSkewNormal
, or add a forward declaration above getSkewNormal
:
double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
The same applies for sum
.
I was facing the same issue in bitbucket, and this worked for me:
line1
##<2 white spaces><enter>
line2
Another version...
Use strtol
, wrapping it inside a simple function to hide its complexity :
inline bool isInteger(const std::string & s)
{
if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false;
char * p;
strtol(s.c_str(), &p, 10);
return (*p == 0);
}
strtol
?As far as I love C++, sometimes the C API is the best answer as far as I am concerned:
strtol
seems quite raw at first glance, so an explanation will make the code simpler to read :
strtol
will parse the string, stopping at the first character that cannot be considered part of an integer. If you provide p
(as I did above), it sets p
right at this first non-integer character.
My reasoning is that if p
is not set to the end of the string (the 0 character), then there is a non-integer character in the string s
, meaning s
is not a correct integer.
The first tests are there to eliminate corner cases (leading spaces, empty string, etc.).
This function should be, of course, customized to your needs (are leading spaces an error? etc.).
See the description of strtol
at: http://en.cppreference.com/w/cpp/string/byte/strtol.
See, too, the description of strtol
's sister functions (strtod
, strtoul
, etc.).
vector.clear()
should work for you. In case you want to shrink the capacity of the vector
along with clear then
std::vector<T>(v).swap(v);
The problem may come from running the project from visual studio on IIS while being on the wrong opened tab on visual studio, so the solution is either opening the right tab (the webform you want to test on your browser) or as others suggested in the other answers, right click on the webform that you want to set as a homepage then click on 'Set As A Start Page'.
If l
is your list and X
is your value:
for i in range(len(l) + 1):
print l[:i] + [X] + l[i:]
You do not need to use substring at all since your format
doesn't hold that info.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";
Date fechaNueva = format.parse(fechaStr);
System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29
If you want to prevent resize by dragging sizegrips and by the maximize button and by maximize by doubleclick on the header text, than insert the following code in the load event of the form:
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle ' Prevent size grips
Me.MaximumSize = Me.Size ' Prevent maximize (also by doubleclick of header text)
Of course all choices of a formborderstyle beginning with Fixed will do.
You can try removing the width
and height
attributes on the svg root element, adding preserveAspectRatio="none" viewBox="0 0 1024 800"
instead. It makes a difference in Opera at least, assuming you wanted the svg to stretch to fill the entire region defined by the CSS styles.
Try this code. It will work
Uri smsUri = Uri.parse("tel:123456");
Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
intent.putExtra("sms_body", "sms text");
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
Hope this will help you.
Shift+F5 quickly clears the cache.
As you probably all ready know if you use the following line of code, your app will be rejected by Apple
NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];
here is a reference
http://ayeapi.blogspot.com/2009/12/sbformatphonenumber-is-lie.html
you can use the following information instead
NSString *phoneName = [[UIDevice currentDevice] name];
NSString *phoneUniqueIdentifier = [[UIDevice currentDevice] uniqueIdentifier];
and so on
@property(nonatomic,readonly,retain) NSString *name; // e.g. "My iPhone"
@property(nonatomic,readonly,retain) NSString *model; // e.g. @"iPhone", @"iPod Touch"
@property(nonatomic,readonly,retain) NSString *localizedModel; // localized version of model
@property(nonatomic,readonly,retain) NSString *systemName; // e.g. @"iPhone OS"
@property(nonatomic,readonly,retain) NSString *systemVersion; // e.g. @"2.0"
@property(nonatomic,readonly) UIDeviceOrientation orientation; // return current device orientation
@property(nonatomic,readonly,retain) NSString *uniqueIdentifier; // a string unique to each device based on various hardware info.
Hope this helps!
Have a look at this picture: Graphical Projections
The glOrtho
command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance.
I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus etc) using the following code every time the window is resized:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, windowWidth, windowHeight, 0.0f, 0.0f, 1.0f);
This will remap the OpenGL coordinates into the equivalent pixel values (X going from 0 to windowWidth and Y going from 0 to windowHeight). Note that I've flipped the Y values because OpenGL coordinates start from the bottom left corner of the window. So by flipping, I get a more conventional (0,0) starting at the top left corner of the window rather.
Note that the Z values are clipped from 0 to 1. So be careful when you specify a Z value for your vertex's position, it will be clipped if it falls outside that range. Otherwise if it's inside that range, it will appear to have no effect on the position except for Z tests.
Open Terminal
nano ~/.bash_profile
export ANDROID_HOME=/Users/qss/Library/Android/sdk
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
Control+S to save
Control+X to exit
Y to save changes
Update changes in terminal
source ~/.bash_profile
Validate Path:
echo $PATH
Confirm if all okay:
adb devices
The plugin's author says you should use "square brackets without the quotes", []
http://bassistance.de/2011/10/07/release-validation-plugin-1-9-0/
Release: Validation Plugin 1.9.0: "...Another change should make the setup of forms with hidden elements easier, these are now ignored by default (option “ignore” has “:hidden” now as default). In theory, this could break an existing setup. In the unlikely case that it actually does, you can fix it by setting the ignore-option to “[]” (square brackets without the quotes)."
To change this setting for all forms:
$.validator.setDefaults({
ignore: [],
// any other default options and/or rules
});
(It is not required that .setDefaults()
be within the document.ready
function)
OR for one specific form:
$(document).ready(function() {
$('#myform').validate({
ignore: [],
// any other options and/or rules
});
});
EDIT:
See this answer for how to enable validation on some hidden fields but still ignore others.
EDIT 2:
Before leaving comments that "this does not work", keep in mind that the OP is simply asking about the jQuery Validate plugin and his question has nothing to do with how ASP.NET, MVC, or any other Microsoft framework can alter this plugin's normal expected behavior. If you're using a Microsoft framework, the default functioning of the jQuery Validate plugin is over-written by Microsoft's unobtrusive-validation
plugin.
If you're struggling with the unobtrusive-validation
plugin, then please refer to this answer instead: https://stackoverflow.com/a/11053251/594235
Warning!
This is a list of random books of diverse quality. In the view of some people (with some justification), it is no longer a list of recommended books. Some of the listed books contain blatantly incorrect statements or teach wrong/harmful practices. People who are aware of such books can edit this answer to help improve it. See The C book list has gone haywire. What to do with it?, and also Deleted question audit 2018.
The C Programming Language (2nd Edition) - Brian W. Kernighan and Dennis M. Ritchie (1988). Still a good, short but complete introduction to C (C90, not C99 or later versions), written by the inventor of C. However, the language has changed and good C style has developed in the last 25 years, and there are parts of the book that show its age.
C: A Reference Manual (5th Edition) - Samuel P. Harbison and Guy R. Steele (2002). An excellent reference book on C, up to and including C99. It is not a tutorial, and probably unfit for beginners. It's great if you need to write a compiler for C, as the authors had to do when they started.
C Pocket Reference (O'Reilly) - Peter Prinz and Ulla Kirch-Prinz (2002).
The comp.lang.c FAQ - Steve Summit. Web site with answers to many questions about C.
Various versions of the C language standards can be found here. There is an online version of the draft C11 standard.
The new C standard - an annotated reference (Free PDF) - Derek M. Jones (2009). The "new standard" referred to is the old C99 standard rather than C11.
C Programming: A Modern Approach (2nd Edition) - K. N. King (2008). A good book for learning C.
Programming in C (4th Edition) - Stephen Kochan (2014). A good general introduction and tutorial.
C Primer Plus (5th Edition) - Stephen Prata (2004)
A Book on C - Al Kelley/Ira Pohl (1998).
The C Book (Free Online) - Mike Banahan, Declan Brady, and Mark Doran (1991).
C: How to Program (8th Edition) - Paul Deitel and Harvey M. Deitel (2015). Lots of good tips and best practices for beginners. The index is very good and serves as a decent reference (just not fully comprehensive, and very shallow).
Head First C - David Griffiths and Dawn Griffiths (2012).
Beginning C (5th Edition) - Ivor Horton (2013). Very good explanation of pointers, using lots of small but complete programs.
Sams Teach Yourself C in 21 Days - Bradley L. Jones and Peter Aitken (2002). Very good introductory stuff.
C In Easy Steps (5th Edition) - Mike McGrath (2018). It is a good book for learning and referencing C.
Effective C - Robert C Seacord (2020). A good introduction to modern C, including chapters on dynamic memory allocation, on program structure, and on debugging, testing and analysis. It has some pointers toward probable C2x features.
Modern C — Jens Gustedt (2017 1st Edn; 2020 2nd Edn). Covers C in 5 levels (encounter, acquaintance, cognition, experience, ambition) from beginning C to advanced C. It covers C11 and C17, including threads and atomic access, which few other books do. Not all compilers recognize these features in all environments.
C Interfaces and Implementations - David R. Hanson (1997). Provides information on how to define a boundary between an interface and implementation in C in a generic and reusable fashion. It also demonstrates this principle by applying it to the implementation of common mechanisms and data structures in C, such as lists, sets, exceptions, string manipulation, memory allocators, and more. Basically, Hanson took all the code he'd written as part of building Icon and lcc and pulled out the best bits in a form that other people could reuse for their own projects. It's a model of good C programming using modern design techniques (including Liskov's data abstraction), showing how to organize a big C project as a bunch of useful libraries.
The C Puzzle Book - Alan R. Feuer (1998)
The Standard C Library - P.J. Plauger (1992). It contains the complete source code to an implementation of the C89 standard library, along with extensive discussions about the design and why the code is designed as shown.
21st Century C: C Tips from the New School - Ben Klemens (2012). In addition to the C language, the book explains gdb, valgrind, autotools, and git. The comments on style are found in the last part (Chapter 6 and beyond).
Algorithms in C - Robert Sedgewick (1997). Gives you a real grasp of implementing algorithms in C. Very lucid and clear; will probably make you want to throw away all of your other algorithms books and keep this one.
Problem Solving and Program Design in C (6th Edition) - Jeri R. Hanly and Elliot B. Koffman (2009).
Data Structures - An Advanced Approach Using C - Jeffrey Esakov and Tom Weiss (1989).
C Unleashed - Richard Heathfield, Lawrence Kirby, et al. (2000). Not ideal, but it is worth intermediate programmers practicing problems written in this book. This is a good cookbook-like approach suggested by comp.lang.c contributors.
Expert C Programming: Deep C Secrets - Peter van der Linden (1994). Lots of interesting information and war stories from the Sun compiler team, but a little dated in places.
Advanced C Programming by Example - John W. Perry (1998).
Advanced Programming in the UNIX Environment - Richard W. Stevens and Stephen A. Rago (2013). Comprehensive description of how to use the Unix APIs from C code, but not so much about the mechanics of C coding.
Essential C (Free PDF) - Nick Parlante (2003). Note that this describes the C90 language at several points (e.g., in discussing //
comments and placement of variable declarations at arbitrary points in the code), so it should be treated with some caution.
C Programming FAQs: Frequently Asked Questions - Steve Summit (1995). This is the book of the web site listed earlier. It doesn't cover C99 or the later standards.
C in a Nutshell - Peter Prinz and Tony Crawford (2005). Excellent book if you need a reference for C99.
Functional C - Pieter Hartel and Henk Muller (1997). Teaches modern practices that are invaluable for low-level programming, with concurrency and modularity in mind.
The Practice of Programming - Brian W. Kernighan and Rob Pike (1999). A very good book to accompany K&R. It uses C++ and Java too.
C Traps and Pitfalls by A. Koenig (1989). Very good, but the C style pre-dates standard C, which makes it less recommendable these days.
Some have argued for the removal of 'Traps and Pitfalls' from this list because it has trapped some people into making mistakes; others continue to argue for its inclusion. Perhaps it should be regarded as an 'expert' book because it requires a moderately extensive knowledge of C to understand what's changed since it was published.
MISRA-C - industry standard published and maintained by the Motor Industry Software Reliability Association. Covers C89 and C99.
Although this isn't a book as such, many programmers recommend reading and implementing as much of it as possible. MISRA-C was originally intended as guidelines for safety-critical applications in particular, but it applies to any area of application where stable, bug-free C code is desired (who doesn't want fewer bugs?). MISRA-C is becoming the de facto standard in the whole embedded industry and is getting increasingly popular even in other programming branches. There are (at least) three publications of the standard (1998, 2004, and the current version from 2012). There is also a MISRA Compliance Guidelines document from 2016, and MISRA C:2012 Amendment 1 — Additional Security Guidelines for MISRA C:2012 (published in April 2016).
Note that some of the strictures in the MISRA rules are not appropriate to every context. For example, directive 4.12 states "Dynamic memory allocation shall not be used". This is appropriate in the embedded systems for which the MISRA rules are designed; it is not appropriate everywhere. (Compilers, for instance, generally use dynamic memory allocation for things like symbol tables, and to do without dynamic memory allocation would be difficult, if not preposterous.)
Archived lists of ACCU-reviewed books on Beginner's C (116 titles) from 2007 and Advanced C (76 titles) from 2008. Most of these don't look to be on the main site anymore, and you can't browse that by subject anyway.
There is a list of books and tutorials to be cautious about at the ISO 9899 Wiki, which is not itself formally associated with ISO or the C standard, but contains information about the C standard (though it hails the release of ISO 9899:2011 and does not mention the release of ISO 9899:2018).
Be wary of books written by Herbert Schildt. In particular, you should stay away from C: The Complete Reference (4th Edition, 2000), known in some circles as C: The Complete Nonsense.
Also do not use the book Let Us C (16th Edition, 2017) by Yashwant Kanetkar. Many people view it as an outdated book that teaches Turbo C and has lots of obsolete, misleading and incorrect material. For example, page 137 discusses the expected output from printf("%d %d %d\n", a, ++a, a++)
and does not categorize it as undefined behaviour as it should. It also consistently promotes unportable and buggy coding practices, such as using gets
, %[\n]s
in scanf
, storing return value of getchar
in a variable of type char
or using fflush
on stdin
.
Learn C The Hard Way (2015) by Zed Shaw. A book with mixed reviews. A critique of this book by Tim Hentenaar:
To summarize my views, which are laid out below, the author presents the material in a greatly oversimplified and misleading way, the whole corpus is a bundled mess, and some of the opinions and analyses he offers are just plain wrong. I've tried to view this book through the eyes of a novice, but unfortunately I am biased by years of experience writing code in C. It's obvious to me that either the author has a flawed understanding of C, or he's deliberately oversimplifying to the point where he's actually misleading the reader (intentionally or otherwise).
"Learn C The Hard Way" is not a book that I could recommend to someone who is both learning to program and learning C. If you're already a competent programmer in some other related language, then it represents an interesting and unusual exposition on C, though I have reservations about parts of the book. Jonathan Leffler
Other contributors, not necessarily credited in the revision history, include:
Alex Lockwood,
Ben Jackson,
Bubbles,
claws,
coledot,
Dana Robinson,
Daniel Holden,
desbest,
Dervin Thunk,
dwc,
Erci Hou,
Garen,
haziz,
Johan Bezem,
Jonathan Leffler,
Joshua Partogi,
Lucas,
Lundin,
Matt K.,
mossplix,
Matthieu M.,
midor,
Nietzche-jou,
Norman Ramsey,
r3st0r3,
ridthyself,
Robert S. Barnes,
Steve Summit,
Tim Ring,
Tony Bai,
VMAtm
You can use query string to pass value from one page to another..
1.pass the value using querystring
Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);
2.Retrive the value in the page u want by using any of these methods..
Method1:
string v = Request.QueryString["value"];
string n=Request.QueryString["number"];
Method2:
NameValueCollection v = Request.QueryString;
if (v.HasKeys())
{
string k = v.GetKey(0);
string n = v.Get(0);
if (k == "value")
{
lbltext.Text = n.ToString();
}
if (k == "value1")
{
lbltext.Text = "error occured";
}
}
NOTE:Method 2 is the fastest method.
I've used that option:
With Android Studio 3.2 and higher, you can quickly migrate an existing project to use AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.
You need to add type assertion .(string)
. It is necessary because the map is of type map[string]interface{}
:
host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)
Latest version of Docopt returns Opts object that has methods for conversion:
host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port
The accepted anwser using cmd.exe
and
for /F "tokens=*" %F in (file.txt) do whatever "%F" ...
works only for "normal" files. It fails miserably with huge files.
For big files, you may need to use Powershell and something like this:
[IO.File]::ReadLines("file.txt") | ForEach-Object { whatever "$_" }
or if you have enough memory:
foreach($line in [System.IO.File]::ReadLines("file.txt")) { whatever "$line" }
This worked for me with a 250 MB file containing over 2 million lines, where the for /F ...
command got stuck after a few thousand lines.
For the differences between foreach
and ForEach-Object
, see Getting to Know ForEach and ForEach-Object.
(credits: Read file line by line in PowerShell )
This JSFiddle project could help you to understand how modulus work: http://jsfiddle.net/elazar170/7hhnagrj
The modulus function works something like this:
function modulus(x,y){
var m = Math.floor(x / y);
var r = m * y;
return x - r;
}
I'm using .Net Core 2 MVC , and this one worked for me,
in the controller use
HttpContext.Request.Headers["Referer"];
for item in array: array2.append (item)
Or, in this case:
array2 += array
For a start simply add the following to your application.properties file
spring.security.user.name=user
spring.security.user.password=pass
NB: with no double quote
Run your application and enter the credentials (user, pass)
In an option you can use disabled="disabled"
, instead of on the select itself
You need to that in two steps, at least.
First, click on the ¶ symbol in the toolbar: you can see if you have CRLF
line endings or just LF
.
Click on the Replace button, and put \r\n
or \n
, depending on the kind of line ending. In the Search Mode section of the dialog, check Extended radio button (interpret \n
and such).
Then replace all occurrences with nothing (empty string).
You end with a big line...
Next, in the same Replace dialog, put your delimiter (</Row>
) for example and in the Replace With field, put the same with a line ending (</Row>\r\n
). Replace All, and you are done.
Sometime it is fixed by the Padding .. if you can play with that, then, it should fix your problem
<style type=text/css>
YourbuttonByID {Padding: 20px 80px; "for example" padding-left:50px;
padding-right:30px "to fix the text in the middle
without interfering with the text itself"}
</style>
It worked for me
Implicit waits are used to provide a default waiting time between each consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when the specified amount of time have elapsed after executing the previous test step/command.
Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed. Unlike Implicit waits, Explicit waits are applied for a particular instance only.
Brief syntax lesson
Cells(Row, Column)
identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)
.Cells(Row, Column)
identifies a cell within a sheet identified in a earlier With statement:
With ActiveSheet
:
.Cells(Row,Column)
:
End With
If you omit the dot, Cells(Row,Column)
is within the active worksheet. So wsh = ActiveWorkbook
wsh.Range
is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:
With ActiveSheet
:
.Range.
:
End With
Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:
With Sheets("xxxx")
:
.Range.
:
End With
because my code only works on sheet xxxx.
Cells(Row,Column)
identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value
is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value
is good.
Cells(Row,Column) like "*Miami*"
will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.
Cells(Row,Column).Value = "Miami"
will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:
Lcase(Cells(Row,Column).Value) = "miami"
My suggestions
Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami"
when I started typing this.
Use
If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
Cells(i, "C").Value = "BA"
if you want to accept, for example, "South Miami" and "Miami, North".
Use
If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
Cells(i, "C").Value = "BA"
if you want to accept, exactly, "Miami" and "Florida".
Use
If Lcase(Cells(i, "A").Value) = "miami" And _
Lcase(Cells(i, "D").Value) = "florida" Then
Cells(i, "C").Value = "BA"
if you don't care about case.
int *array = new int[n];
It declares a pointer to a dynamic array of type int
and size n
.
A little more detailed answer: new
allocates memory of size equal to sizeof(int) * n
bytes and return the memory which is stored by the variable array
. Also, since the memory is dynamically allocated using new
, you've to deallocate it manually by writing (when you don't need anymore, of course):
delete []array;
Otherwise, your program will leak memory of at least sizeof(int) * n
bytes (possibly more, depending on the allocation strategy used by the implementation).
Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.
One option is to replace table with CSS4 flex divs:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
That works in new browsers i.e. IE11+ see table at the bottom of the article.
The pseudo-elements generated by ::before and ::after are contained by the element's formatting box, and thus don't apply to replaced elements such as img, or to br elements.
If you want statically make columns not sortable. You can do this way
The macros defined in <inttypes.h>
are the most correct way to print values of types uint32_t
, uint16_t
, and so forth -- but they're not the only way.
Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf
format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)
An alternative is to cast the values to a predefined type and use the format for that type.
Types int
and unsigned int
are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t
or uint16_t
, respectively. Similarly, long
and unsigned long
are at least 32 bits wide, and long long
and unsigned long long
are at least 64 bits wide.
For example, I might write your program like this (with a few additional tweaks):
#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>
int main(void)
{
uint32_t a=12, a1;
uint16_t b=1, b1;
a1 = htonl(a);
printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
b1 = htons(b);
printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
return 0;
}
One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>
. Such an implementation most likely wouldn't have <stdint.h>
either, but the technique is useful for other integer types.
I tried changing year
to a different term, and it worked.
public_methods : {
get: function() {
return this._year;
},
set: function(newValue) {
if(newValue > this.originYear) {
this._year = newValue;
this.edition += newValue - this.originYear;
}
}
}
I currently have Xcode 4.6.3 and 5.0 installed. I used the following bash script to link 5.0 to the SDKs in the old version:
platforms_path="$1/Contents/Developer/Platforms";
if [ -d $platforms_path ]; then
for platform in `ls $platforms_path`
do
sudo ln -sf $platforms_path/$platform/Developer/SDKs/* $(xcode-select --print-path)/Platforms/$platform/Developer/SDKs;
done;
fi;
You just need to supply it with the path to the .app:
./xcode.sh /Applications/Xcode-463.app
Using Xamarin now we can develop iPhone applications in Windows machine itself with the help of Xamarin Live Player.
Using this Xamarin live player dev/deploy/debug cycle can now be done without an Apple system.
But to sign and release the app Apple system is required.
Find the reference here
I checked the reference nothing dodgy
SELECT *
FROM (
SELECT *
FROM users
WHERE 1
ORDER BY
rand()
LIMIT 20
) q
ORDER BY
name
This seems to do what you want:
numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data)
Here is another solution:
# The ellipsis is equivalent here to ":,:,:"...
numpy.vectorize(complex)(Data[...,0], Data[...,1])
And yet another simpler solution:
Data[...,0] + 1j * Data[...,1]
PS: If you want to save memory (no intermediate array):
result = 1j*Data[...,1]; result += Data[...,0]
devS' solution below is also fast.
Have you tried using the official JQueryUI implementation (not jQuery only) : ?
An anonymous class is extending or implementing while creating its object For example :
Interface in = new InterFace()
{
..............
}
Here anonymous class is implementing Interface.
Class cl = new Class(){
.................
}
here anonymous Class is extending a abstract Class.
I found that the best place to set up an ignore to the pesky .DS_Store
files is in the .git/info/exclude
file.
IntelliJ seems to do this automatically when you set up a git repository in it.
You need:
#include <string.h> /* memset */
#include <unistd.h> /* close */
in your code.
References: POSIX for close
, the C standard for memset
.
WAMP is an acronym for Windows (OS), Apache (web-server), MySQL (database), PHP (language).
XAMPP and WampServer are both free packages of WAMP, with additional applications/tools, put together by different people. There are also other WAMPs such as UniformServer. And there are commercial WAMPs such as WampDeveloper (what I use).
Their differences are in the format/structure of the package, the configurations, and the included management applications.
IIS is a web-server application just like Apache is, except it's made by Microsoft and is Windows only (Apache runs on both Windows and Linux). IIS is also more geared towards using ASP.NET (vs. PHP) and "SQL Server" (vs. MySQL), though it can use PHP and MySQL too.
Or, if using lo-dash: _.empty(value).
"Checks if value is empty. Arrays, strings, or arguments objects with a length of 0 and objects with no own enumerable properties are considered "empty"."
As of Java 7 (and Android API level 19):
System.lineSeparator()
Documentation: Java Platform SE 7
For older versions of Java, use:
System.getProperty("line.separator");
See https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html for other properties.
You need a Flask view that will receive POST data and an HTML form that will send it.
from flask import request
@app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>
It's a syntactically valid request, but not a satisfiable request. If you look further in that section you see:
If a syntactically valid byte-range-set includes at least one byte- range-spec whose first-byte-pos is less than the current length of the entity-body, or at least one suffix-byte-range-spec with a non- zero suffix-length, then the byte-range-set is satisfiable. Otherwise, the byte-range-set is unsatisfiable. If the byte-range-set is unsatisfiable, the server SHOULD return a response with a status of 416 (Requested range not satisfiable). Otherwise, the server SHOULD return a response with a status of 206 (Partial Content) containing the satisfiable ranges of the entity-body.
So I think in your example, the server should return a 416 since it's not a valid byte range for that file.
Got to this answer ? probably the answers above are to long ...
just type in :
echo "setenv M2_HOME $M2_HOME" | sudo tee -a /etc/launchd.conf
and restart your mac (thats it!)
restarting is annoying ? just use the command :
grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl
and restart IntelliJ IDEA
I was facing same issue, for me adding certificate to trust store solved this issue.
...you do not need to import any library. Just use the delete character:
BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),
this removes the newline and the space (^_^)*
With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt
in the root of your project. Then from the root of your project:
mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make
And for Debug
(again from the root of your project):
mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
Release
/ Debug
will add the appropriate flags for your compiler. There are also RelWithDebInfo
and MinSizeRel
build configurations.
You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT
variables, e.g.:
set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")
See CMAKE_BUILD_TYPE for more details.
As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.
Why don't you disable the button and enable it after you finish the event?
<input type="button" id="xx" onclick="checkEnableSubmit('true');yourFunction();">
<script type="text/javascript">
function checkEnableSubmit(status) {
document.getElementById("xx").disabled = status;
}
function yourFunction(){
//add your functionality
checkEnableSubmit('false');
}
</script>
Happy coding !!!
private void btnDelete_Click(object sender, EventArgs e)
{
if (e.ColumIndex == 10)// 10th column the button
{
dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
}
}
This solution can be delete a row (not selected, clicked row!) via "e" param.
string Folder = Directory.GetParent(path).Name;
Just add another join:
SELECT dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id,
images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
If you are struggling with the connection in the XAMPP environment I suggest uncommenting the following entry in the php.ini
file.
extension = odbc
I received an error without it: Uncaught pdoexception: could not find driver
Your static method should go from:
public static class SimpleUsing
{
public static void DoUsing(Action<MyDataContext> action)
{
using (MyDataContext db = new MyDataContext())
action(db);
}
}
To:
public static class SimpleUsing
{
public static TResult DoUsing<TResult>(Func<MyDataContext, TResult> action)
{
using (MyDataContext db = new MyDataContext())
return action(db);
}
}
This answer grew out of comments so I could provide code. For a complete elaboration, please see @sll's answer below.
For me, align="center"
was enough to center FOO
vertically:
<v-row align="center">
<v-col>FOO</v-col>
</row>
Here's a way I found. I'm on a Mac using Excel 2011.
If column B had the text values you want to be hyperlinks, put this formula in the cell C1 (or D1 or whatever as long as it's a free column): =HYPERLINK(B1,B1)
This will insert a hyperlink with the location as the link text and the "friendly name" as the link text. If you have another column that has a friendly name for each link, you could use that too.
Then, you could hide the text column if you didn't want to see it.
If you have a list of IDs of something, and the urls were all http://website.com/folder/ID
, such as:
A1 | B1
101 | http://website.com/folder/101
102 | http://website.com/folder/102
103 | http://website.com/folder/103
104 | http://website.com/folder/104
you could use something like =HYPERLINK("http://website.com/folder/"&A1,A1)
and you wouldn't need the list of urls. That was my situation and worked nicely.
According to this post: http://excelhints.com/2007/06/12/hyperlink-formula-in-excel/ this method will work in Excel 2007 as well.
I think the previous answers are correct, but here is another example (just a f.y.i, success() and error() are deprecated according to AngularJS Main page:
$http
.get('http://someendpoint/maybe/returns/JSON')
.then(function(response) {
return response.data;
}).catch(function(e) {
console.log('Error: ', e);
throw e;
}).finally(function() {
console.log('This finally block');
});
File file = context.getFilesDir();
file.mkdir();
String[] array = filePath.split("/");
for(int t = 0; t < array.length - 1; t++) {
file = new File(file, array[t]);
file.mkdir();
}
File f = new File(file,array[array.length- 1]);
RandomAccessFileOutputStream rvalue =
new RandomAccessFileOutputStream(f, append);
var date1 = new Date();
var date2 = new Date("2025/07/30 21:59:00");
//Customise date2 for your required future time
showDiff();
function showDiff(date1, date2){
var diff = (date2 - date1)/1000;
diff = Math.abs(Math.floor(diff));
var days = Math.floor(diff/(24*60*60));
var leftSec = diff - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
document.getElementById("showTime").innerHTML = "You have " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds before death.";
setTimeout(showDiff,1000);
}
for your HTML Code:
<div id="showTime"></div>
Have you considered using Javascript for this?
$('input').val($('input').val().replace(',', '.'));
How to fish and while using strict code. There are two prerequisite functions needed at the bottom of this post.
xml_add('before', id_('element_after'), '<span xmlns="http://www.w3.org/1999/xhtml">Some text.</span>');
xml_add('after', id_('element_before'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');
xml_add('inside', id_('element_parent'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');
Add multiple elements (namespace only needs to be on the parent element):
xml_add('inside', id_('element_parent'), '<div xmlns="http://www.w3.org/1999/xhtml"><input type="text" /><input type="button" /></div>');
Dynamic reusable code:
function id_(id) {return (document.getElementById(id)) ? document.getElementById(id) : false;}
function xml_add(pos, e, xml)
{
e = (typeof e == 'string' && id_(e)) ? id_(e) : e;
if (e.nodeName)
{
if (pos=='after') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e.nextSibling);}
else if (pos=='before') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
else if (pos=='inside') {e.appendChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true));}
else if (pos=='replace') {e.parentNode.replaceChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
//Add fragment and have it returned.
}
}
Easy: you wrap a <form>
around the element, call reset on the form, then remove the form using .unwrap()
. Unlike the .clone()
solutions otherwise in this thread, you end up with the same element at the end (including custom properties that were set on it).
Tested and working in Opera, Firefox, Safari, Chrome and IE6+. Also works on other types of form elements, with the exception of type="hidden"
.
window.reset = function(e) {
e.wrap('<form>').closest('form').get(0).reset();
e.unwrap();
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input id="file" type="file">
<br>
<input id="text" type="text" value="Original">
</form>
<button onclick="reset($('#file'))">Reset file</button>
<button onclick="reset($('#text'))">Reset text</button>
_x000D_
As Timo notes below, if you have the buttons to trigger the reset of the field inside of the <form>
, you must call .preventDefault()
on the event to prevent the <button>
from triggering a submit.
Does not work in IE 11 due to an unfixed bug. The text (file name) is cleared on the input, but its File
list remains populated.
This is how I implemented my URL builder. I have created one Service class to provide the params for the URL
public interface ParamsProvider {
String queryProvider(List<BasicNameValuePair> params);
String bodyProvider(List<BasicNameValuePair> params);
}
The Implementation of methods are below
@Component
public class ParamsProviderImp implements ParamsProvider {
@Override
public String queryProvider(List<BasicNameValuePair> params) {
StringBuilder query = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
query.append("?");
query.append(basicNameValuePair.toString());
first.set(false);
} else {
query.append("&");
query.append(basicNameValuePair.toString());
}
});
return query.toString();
}
@Override
public String bodyProvider(List<BasicNameValuePair> params) {
StringBuilder body = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
body.append(basicNameValuePair.toString());
first.set(false);
} else {
body.append("&");
body.append(basicNameValuePair.toString());
}
});
return body.toString();
}
}
When we need the query params for our URL, I simply call the service and build it. Example for that is below.
Class Mock{
@Autowired
ParamsProvider paramsProvider;
String url ="http://www.google.lk";
// For the query params price,type
List<BasicNameValuePair> queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("price", 100));
queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider
}
I don't know an easy method to convert a date object to any time zone, but if you want to convert it to the local time zone, you can just convert it with Date.prototype.getTime()
to the corresponding number of milliseconds, and back again.
date = new Date('2016-05-24T13:07:20');
date = new Date(date.getTime());
For example, date.getHours()
will now return 15
instead of 13
if you are, like me, in Austria (and it's summer).
I've read that the various datetime functions may exhibit non-standard behaviour in some browsers, so test this first. I can confirm that it works in Chrome.
The SimpleHelpers.FileEncoding Nuget package wraps a C# port of the Mozilla Universal Charset Detector into a dead-simple API:
var encoding = FileEncoding.DetectFileEncoding(txtFile);
The easiest solution in Bash:
$ s='"abc"'
$ echo $s
"abc"
$ echo "${s:1:-1}"
abc
This is called substring expansion (see Gnu Bash Manual and search for ${parameter:offset:length}
). In this example it takes the substring from s
starting at position 1 and ending at the second last position. This is due to the fact that if length
is a negative value it is interpreted as a backwards running offset from the end of parameter
.
This is another way to do this: use the Array#index
method.
It returns the index of the first occurrence of the element in the array.
For example:
a = ['cat','dog','horse']
if a.index('dog')
puts "dog exists in the array"
end
index()
can also take a block:
For example:
a = ['cat','dog','horse']
puts a.index {|x| x.match /o/}
This returns the index of the first word in the array that contains the letter 'o'.
A bit too late but I got the same issue and fixed it switching schemalocation into schemaLocation in the persistence.xml file (line 1).
Normally, the exe can be found in the debug folder, as suggested previously, but not in the release folder, that is disabled by default in my configuration. If you want to activate the release folder, you can do this: BUILD->Batch Build And activate the "build" checkbox in the release configuration. When you click the build button, the exe with some dependencies will be generated. Now you can copy and use it.
Say you have a list such as:
a = [9,8,7]
The following two methods are pretty compact ways to get a tuple with the minimum element and its index. Both take a similar time to process. I better like the zip method, but that is my taste.
element, index = min(list(zip(a, range(len(a)))))
min(list(zip(a, range(len(a)))))
(7, 2)
timeit min(list(zip(a, range(len(a)))))
1.36 µs ± 107 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
index, element = min(list(enumerate(a)), key=lambda x:x[1])
min(list(enumerate(a)), key=lambda x:x[1])
(2, 7)
timeit min(list(enumerate(a)), key=lambda x:x[1])
1.45 µs ± 78.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)