UITableView example for Swift
// UITableViewCell set Identify "Cell"
// UITableView Name is tableReport
UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var tableReport: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Report Name"
return cell;
}
}
What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?
I will put a small comparison table here (just to have it somewhere):
Servlet is mapped as /test%3F/*
and the application is deployed under /app
.
http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a
Method URL-Decoded Result
----------------------------------------------------
getContextPath() no /app
getLocalAddr() 127.0.0.1
getLocalName() 30thh.loc
getLocalPort() 8480
getMethod() GET
getPathInfo() yes /a?+b
getProtocol() HTTP/1.1
getQueryString() no p+1=c+d&p+2=e+f
getRequestedSessionId() no S%3F+ID
getRequestURI() no /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL() no http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme() http
getServerName() 30thh.loc
getServerPort() 8480
getServletPath() yes /test?
getParameterNames() yes [p 2, p 1]
getParameter("p 1") yes c d
In the example above the server is running on the localhost:8480
and the name 30thh.loc
was put into OS hosts
file.
Comments
"+" is handled as space only in the query string
Anchor "#a" is not transferred to the server. Only the browser can work with it.
If the url-pattern
in the servlet mapping does not end with *
(for example /test
or *.jsp
), getPathInfo()
returns null
.
If Spring MVC is used
Method getPathInfo()
returns null
.
Method getServletPath()
returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b
Be careful with URL encoded parts of @RequestMapping
and @RequestParam
in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.
How to create an XML document using XmlDocument?
What about:
#region Using Statements
using System;
using System.Xml;
#endregion
class Program {
static void Main( string[ ] args ) {
XmlDocument doc = new XmlDocument( );
//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
XmlElement root = doc.DocumentElement;
doc.InsertBefore( xmlDeclaration, root );
//(2) string.Empty makes cleaner code
XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
doc.AppendChild( element1 );
XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
element1.AppendChild( element2 );
XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text1 = doc.CreateTextNode( "text" );
element3.AppendChild( text1 );
element2.AppendChild( element3 );
XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text2 = doc.CreateTextNode( "other text" );
element4.AppendChild( text2 );
element2.AppendChild( element4 );
doc.Save( "D:\\document.xml" );
}
}
(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?
The result is:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>other text</level2>
</level1>
</body>
But I recommend you to use LINQ to XML which is simpler and more readable like here:
#region Using Statements
using System;
using System.Xml.Linq;
#endregion
class Program {
static void Main( string[ ] args ) {
XDocument doc = new XDocument( new XElement( "body",
new XElement( "level1",
new XElement( "level2", "text" ),
new XElement( "level2", "other text" ) ) ) );
doc.Save( "D:\\document.xml" );
}
}
Find child element in AngularJS directive
jQlite (angular's "jQuery" port) doesn't support lookup by classes.
One solution would be to include jQuery in your app.
Another is using QuerySelector
or QuerySelectorAll
:
link: function(scope, element, attrs) {
console.log(element[0].querySelector('.list-scrollable'))
}
We use the first item in the element
array, which is the HTML element. element.eq(0)
would yield the same.
FIDDLE
background: fixed no repeat not working on mobile
This is what i do and it works everythere :)
.container {
background: url(${myImage})
background-attachment: fixed;
background-size: cover;
transform: scale(1.1, 1.1);
}
then...
@media only screen and (max-width: 768px){
background-size: 100% 100vh;
}
How to read if a checkbox is checked in PHP?
To check if a checkbox is checked use empty()
When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.
Check if checkbox is checked with empty as followed:
//Check if checkbox is checked
if(!empty($_POST['checkbox'])){
#Checkbox selected code
} else {
#Checkbox not selected code
}
How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)
Textarea resize control is available via the CSS3 resize property:
textarea { resize: both; } /* none|horizontal|vertical|both */
textarea.resize-vertical{ resize: vertical; }
textarea.resize-none { resize: none; }
Allowable values self-explanatory: none
(disables textarea resizing), both
, vertical
and horizontal
.
Notice that in Chrome, Firefox and Safari the default is both
.
If you want to constrain the width and height of the textarea element, that's not a problem: these browsers also respect max-height
, max-width
, min-height
, and min-width
CSS properties to provide resizing within certain proportions.
Code example:
_x000D_
_x000D_
#textarea-wrapper {_x000D_
padding: 10px;_x000D_
background-color: #f4f4f4;_x000D_
width: 300px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea {_x000D_
min-height:50px;_x000D_
max-height:120px;_x000D_
width: 290px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea.vertical { _x000D_
resize: vertical;_x000D_
}
_x000D_
<div id="textarea-wrapper">_x000D_
<label for="resize-default">Textarea (default):</label>_x000D_
<textarea name="resize-default" id="resize-default"></textarea>_x000D_
_x000D_
<label for="resize-vertical">Textarea (vertical):</label>_x000D_
<textarea name="resize-vertical" id="resize-vertical" class="vertical">Notice this allows only vertical resize!</textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Doing a join across two databases with different collations on SQL Server and getting an error
A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.
It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)
select
sone_field collate DATABASE_DEFAULT
from
table_1
inner join
table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever
How to use git merge --squash?
You want to merge with the squash option. That's if you want to do it one branch at a time.
git merge --squash feature1
If you want to merge all the branches at the same time as single commits, then first rebase interactively and squash each feature then octopus merge:
git checkout feature1
git rebase -i master
Squash into one commit then repeat for the other features.
git checkout master
git merge feature1 feature2 feature3 ...
That last merge is an "octopus merge" because it's merging a lot of branches at once.
Hope this helps
Check if an HTML input element is empty or has no value entered by user
Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:
if (document.getElementById('customx') == ""){
DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.
How to add a search box with icon to the navbar in Bootstrap 3?
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<meta name="description" content="">_x000D_
<meta name="author" content="">_x000D_
_x000D_
<title>3 Col Portfolio - Start Bootstrap Template</title>_x000D_
_x000D_
<!-- Bootstrap Core CSS -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>_x000D_
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<!-- Navigation -->_x000D_
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
<div class="container">_x000D_
<!-- Brand and toggle get grouped for better mobile display -->_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Start Bootstrap</a>_x000D_
</div>_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav">_x000D_
<li>_x000D_
<a href="#">About</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Services</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Contact</a>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="navbar-form navbar-right">_x000D_
<div class="input-group">_x000D_
<input type="text" name="keyword" placeholder="search..." class="form-control">_x000D_
<span class="input-group-btn">_x000D_
<button class="btn btn-default">Go</button>_x000D_
</span>_x000D_
</div>_x000D_
</form>_x000D_
</div>_x000D_
<!-- /.navbar-collapse -->_x000D_
</div>_x000D_
<!-- /.container -->_x000D_
</nav>_x000D_
_x000D_
<!-- Page Content -->_x000D_
<div class="container">_x000D_
_x000D_
<!-- Page Header -->_x000D_
<div class="row">_x000D_
<div class="col-lg-12">_x000D_
<h1 class="page-header">Page Heading_x000D_
<small>Secondary Text</small>_x000D_
</h1>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<hr>_x000D_
_x000D_
<!-- Pagination -->_x000D_
<div class="row text-center">_x000D_
<div class="col-lg-12">_x000D_
<ul class="pagination">_x000D_
<li>_x000D_
<a href="#">«</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#">1</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">2</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">3</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">4</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">5</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">»</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
</div>_x000D_
<!-- Footer -->_x000D_
<footer>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>About</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-home"></i> Your company address here_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-earphone"></i> 0982.808.065_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-envelope"></i> [email protected]_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-flag"></i> <a href="#">Fan page</a>_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-time"></i> 08:00-18:00 Monday to Friday_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>Support</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#" class="link">Terms of Service</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Privacy policy</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Warranty commitment</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Site map</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>Other</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod_x000D_
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo_x000D_
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse_x000D_
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
</footer>_x000D_
_x000D_
<!-- /.container -->_x000D_
_x000D_
<!-- jQuery -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Bootstrap Core JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_
@JsonProperty annotation on field as well as getter/setter
My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:
For eg. consider a slight modification of your case:
@JsonProperty("fileName")
private String fileName;
@JsonProperty("fileName")
public String getFileName()
{
return fileName;
}
@JsonProperty("fileName1")
public void setFileName(String fileName)
{
this.fileName = fileName;
}
Both fileName
field, and method getFileName
, have the correct property name of fileName
and setFileName
has a different one fileName1
, in this case Jackson will look for a fileName1
attribute in json at the point of deserialization and will create a attribute called fileName1
at the point of serialization.
Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName
, it would just pick one of them as the attribute(FILENAME
), and had any on of the three differed, it would have thrown an exception:
java.lang.IllegalStateException: Conflicting property name definitions
Reading a column from CSV file using JAVA
You are not changing the value of line. It should be something like this.
import java.io.BufferedReader;
import java.io.FileReader;
public class InsertValuesIntoTestDb {
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception {
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("test.csv"));
while((line = br.readLine()) != null){
String[] b = line.split(splitBy);
System.out.println(b[0]);
}
br.close();
}
}
readLine returns each line and only returns null when there is nothing left. The above code sets line and then checks if it is null.
How to convert a ruby hash object to JSON?
Add the following line on the top of your file
require 'json'
Then you can use:
car = {:make => "bmw", :year => "2003"}
car.to_json
Alternatively, you can use:
JSON.generate({:make => "bmw", :year => "2003"})
How can I remove a pytz timezone from a datetime object?
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
How to access Anaconda command prompt in Windows 10 (64-bit)
How to add anaconda installation directory to your PATH variables
1. open environmental variables window
Do this by either going to my computer and then right clicking the background for the context menu > "properties". On the left side open "advanced system settings" or just search for "env..." in start menu ([Win]+[s] keys).
Then click on environment variables
If you struggle with this step read this explanation.
2. Edit Path in the user environmental variables section and add three new entries:
D:\path\to\anaconda3
D:\path\to\anaconda3\Scripts
D:\path\to\anaconda3\Library\bin
D:\path\to\anaconda3
should be the folder where you have installed anaconda
Click [OK] on all opened windows.
If you did everything correctly, you can test a conda
command by opening a new powershell window.
conda --version
This should output something like: conda 4.8.2
Is there an XSL "contains" directive?
Sure there is! For instance:
<xsl:if test="not(contains($hhref, '1234'))">
<li>
<a href="{$hhref}" title="{$pdate}">
<xsl:value-of select="title"/>
</a>
</li>
</xsl:if>
The syntax is: contains(stringToSearchWithin, stringToSearchFor)
java- reset list iterator to first element of the list
Best would be not using LinkedList
at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)
Use ArrayList
, and iterate with
int len = list.size();
for (int i = 0; i < len; i++) {
Element ele = list.get(i);
}
Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:
iter = list.listIterator();
(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)
Vibrate and Sound defaults on notification
Its work fine to me,You can try it.
protected void displayNotification() {
Log.i("Start", "notification");
// Invoking the default notification service //
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder.setAutoCancel(true);
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You have "+unMber_unRead_sms +" new message.");
mBuilder.setTicker("New message from PayMe..");
mBuilder.setSmallIcon(R.drawable.icon2);
// Increase notification number every time a new notification arrives //
mBuilder.setNumber(unMber_unRead_sms);
// Creates an explicit intent for an Activity in your app //
Intent resultIntent = new Intent(this, FreesmsLog.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(FreesmsLog.class);
// Adds the Intent that starts the Activity to the top of the stack //
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// mBuilder.setOngoing(true);
Notification note = mBuilder.build();
note.defaults |= Notification.DEFAULT_VIBRATE;
note.defaults |= Notification.DEFAULT_SOUND;
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on. //
mNotificationManager.notify(notificationID, mBuilder.build());
}
How to get char from string by index?
First make sure the required number is a valid index for the string from beginning or end , then you can simply use array subscript notation.
use len(s)
to get string length
>>> s = "python"
>>> s[3]
'h'
>>> s[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[0]
'p'
>>> s[-1]
'n'
>>> s[-6]
'p'
>>> s[-7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>>
Remove last specific character in a string c#
Or you can convert it into Char Array first by:
string Something = "1,5,12,34,";
char[] SomeGoodThing=Something.ToCharArray[];
Now you have each character indexed
:
SomeGoodThing[0] -> '1'
SomeGoodThing[1] -> ','
Play around it
Twitter Bootstrap - how to center elements horizontally or vertically
For future visitors to this question:
If you are trying to center an image in a div but the image won't center, this could describe your problem:
jsFiddle DEMO of the problem
<div class="col-sm-4 text-center">
<img class="img-responsive text-center" src="myPic.jpg" />
</div>
The img-responsive
class adds a display:block
instruction to the image tag, which stops text-align:center
(text-center
class) from working.
SOLUTION:
<div class="col-sm-4">
<img class="img-responsive center-block" src="myPic.jpg" />
</div>
jsFiddle of the solution
Adding the center-block
class overrides the display:block
instruction put in by using the img-responsive
class.
Without the img-responsive
class, the image would center just by adding text-center
class
Update:
Also, you should know the basics of flexbox and how to use it, since Bootstrap4 now uses it natively.
Here is an excellent, fast-paced video tutorial by Brad Schiff
Here is a great cheat sheet
How to disable an input type=text?
You can also by jquery:
$('#foo')[0].disabled = true;
Working example:
_x000D_
_x000D_
$('#foo')[0].disabled = true;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input id="foo" placeholder="placeholder" value="value" />
_x000D_
_x000D_
_x000D_
T-SQL: Deleting all duplicate rows but keeping one
You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:
WITH cte AS (
SELECT[foo], [bar],
row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
FROM TABLE
)
DELETE cte WHERE [rn] > 1
Play around with it and see what you get.
(Edit: In an attempt to be helpful, someone edited the ORDER BY
clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc
)
ASP.NET MVC on IIS 7.5
Yet another reason this can happen - your RouteConfig.cs
or WebApiConfig.cs
are invalid.
In my case, I had a route defined as such (note the parenthesis instead of curly brace):
...
routeTemplate: "api/(something}"
...
How do I use .toLocaleTimeString() without displaying seconds?
Here's a function that will do it, with comments that explain:
function displayNiceTime(date){
// getHours returns the hours in local time zone from 0 to 23
var hours = date.getHours()
// getMinutes returns the minutes in local time zone from 0 to 59
var minutes = date.getMinutes()
var meridiem = " AM"
// convert to 12-hour time format
if (hours > 12) {
hours = hours - 12
meridiem = ' PM'
}
else if (hours === 0){
hours = 12
}
// minutes should always be two digits long
if (minutes < 10) {
minutes = "0" + minutes.toString()
}
return hours + ':' + minutes + meridiem
}
Since, as others have noted, toLocaleTimeString() can be implemented differently in different browsers, this way gives better control.
To learn more about the Javascript Date object, this is a good resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
This is the solution, which is worked for me.
<p:commandButton id="b1" value="Save" process="userGroupSetupForm"
actionListener="#{userGroupSetupController.saveData()}"
update="growl userGroupList userGroupSetupForm" />
Here, process="userGroupSetupForm" atrribute is mandatory for Ajax call. actionListener is calling a method from @ViewScope Bean. Also updating growl message, Datatable: userGroupList and Form: userGroupSetupForm.
C++ Dynamic Shared Library on Linux
Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library
Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.
If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.
How to properly compare two Integers in Java?
==
checks for reference equality, however when writing code like:
Integer a = 1;
Integer b = 1;
Java is smart enough to reuse the same immutable for a
and b
, so this is true: a == b
. Curious, I wrote a small example to show where java stops optimizing in this way:
public class BoxingLol {
public static void main(String[] args) {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
Integer a = i;
Integer b = i;
if (a != b) {
System.out.println("Done: " + i);
System.exit(0);
}
}
System.out.println("Done, all values equal");
}
}
When I compile and run this (on my machine), I get:
Done: 128
Maximum length for MD5 input/output
You can have any length, but of course, there can be a memory issue on the computer if the String input is too long. The output is always 32 characters.
How to create range in Swift?
I created the following extension:
extension String {
func substring(from from:Int, to:Int) -> String? {
if from<to && from>=0 && to<self.characters.count {
let rng = self.startIndex.advancedBy(from)..<self.startIndex.advancedBy(to)
return self.substringWithRange(rng)
} else {
return nil
}
}
}
example of use:
print("abcde".substring(from: 1, to: 10)) //nil
print("abcde".substring(from: 2, to: 4)) //Optional("cd")
print("abcde".substring(from: 1, to: 0)) //nil
print("abcde".substring(from: 1, to: 1)) //nil
print("abcde".substring(from: -1, to: 1)) //nil
Attaching click to anchor tag in angular
I have encountered this issue in Angular 5 which still followed the link. The solution was to have the function return false
in order to prevent the page being refreshed:
html
<a href="" (click)="openChangePasswordForm()">Change expired password</a>
ts
openChangePasswordForm(): boolean {
console.log("openChangePasswordForm called!");
return false;
}
How to remove listview all items
if you used List object and passed to the adapter you can remove the value from the List object and than call the notifyDataSetChanged() using adapter object.
for e.g.
List<String> list = new ArrayList<String>();
ArrayAdapter adapter;
adapter = new ArrayAdapter<String>(DeleteManyTask.this,
android.R.layout.simple_list_item_1,
(String[])list.toArray(new String[0]));
listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter);
listview.setAdapter(listAdapter);
for remove do this way
list.remove(index); //or
list.clear();
adpater.notifyDataSetChanged();
or without list object remove item from list.
adapter.clear();
adpater.notifyDataSetChanged();
Copy multiple files with Ansible
- name: find inq.Linux*
find: paths="/appl/scripts/inq" recurse=yes patterns="inq.Linux*"
register: find_files
- name: set fact
set_fact:
all_files:
- "{{ find_files.files | map(attribute='path') | list }}"
when: find_files > 0
- name: copy files
copy:
src: "{{ item }}"
dest: /destination/
with_items: "{{ all_files }}"
when: find_files > 0
how to set imageview src?
What you are looking for is probably this:
ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"
int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);
Let me know if this was helpful :)
How to flatten only some dimensions of a numpy array
A slight generalization to Alexander's answer - np.reshape can take -1 as an argument, meaning "total array size divided by product of all other listed dimensions":
e.g. to flatten all but the last dimension:
>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)
WMI "installed" query different from add/remove programs list?
Installed products consist of installed software elements and features so it's worth checking wmic alias's for PRODUCT as well as checking SOFTWAREELEMENT and SOFTWAREFEATURE:
wmic product get name,version
wmic softwareelement get name,version
wmic softwarefeature get name,version
PostgreSQL CASE ... END with multiple conditions
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
Is there a destructor for Java?
I used to mainly deal with C++ and that is what lead me to the search of a destructor as well. I am using JAVA a lot now. What I did, and it may not be the best case for everyone, but I implemented my own destructor by reseting all the values to either 0 or there default through a function.
Example:
public myDestructor() {
variableA = 0; //INT
variableB = 0.0; //DOUBLE & FLOAT
variableC = "NO NAME ENTERED"; //TEXT & STRING
variableD = false; //BOOL
}
Ideally this won't work for all situations, but where there are global variables it will work as long as you don't have a ton of them.
I know I am not the best Java programmer, but it seems to be working for me.
Difference between setTimeout with and without quotes and parentheses
With the parentheses:
setTimeout("alertMsg()", 3000); // It work, here it treat as a function
Without the quotes and the parentheses:
setTimeout(alertMsg, 3000); // It also work, here it treat as a function
And the third is only using quotes:
setTimeout("alertMsg", 3000); // It not work, here it treat as a string
_x000D_
_x000D_
function alertMsg1() {_x000D_
alert("message 1");_x000D_
}_x000D_
function alertMsg2() {_x000D_
alert("message 2");_x000D_
}_x000D_
function alertMsg3() {_x000D_
alert("message 3");_x000D_
}_x000D_
function alertMsg4() {_x000D_
alert("message 4");_x000D_
}_x000D_
_x000D_
// this work after 2 second_x000D_
setTimeout(alertMsg1, 2000);_x000D_
_x000D_
// This work immediately_x000D_
setTimeout(alertMsg2(), 4000);_x000D_
_x000D_
// this fail_x000D_
setTimeout('alertMsg3', 6000);_x000D_
_x000D_
// this work after 8second_x000D_
setTimeout('alertMsg4()', 8000);
_x000D_
_x000D_
_x000D_
In the above example first alertMsg2() function call immediately (we
give the time out 4S but it don't bother) after that alertMsg1() (A
time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but
the alertMsg3() is not working because we place it within the quotes
without parties so it is treated as a string.
How to get a subset of a javascript object's properties
If you are using ES6 there is a very concise way to do this using destructuring. Destructuring allows you to easily add on to objects using a spread, but it also allows you to make subset objects in the same way.
const object = {
a: 'a',
b: 'b',
c: 'c',
d: 'd',
}
// Remove "c" and "d" fields from original object:
const {c, d, ...partialObject} = object;
const subset = {c, d};
console.log(partialObject) // => { a: 'a', b: 'b'}
console.log(subset) // => { c: 'c', d: 'd'};
Apache Tomcat Not Showing in Eclipse Server Runtime Environments
You need to go to Help>Eclipse Marketplace . Then type server in the search box it will display Eclipse JST Server Adapters (Apache Tomcat,...) .Select that one and install it .Then go back to Window>Preferences>Server>Runtime Environnement, click add choose Apache tomcat version then add the installation directory .
How can I parse a YAML file in Python
#!/usr/bin/env python
import sys
import yaml
def main(argv):
with open(argv[0]) as stream:
try:
#print(yaml.load(stream))
return 0
except yaml.YAMLError as exc:
print(exc)
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
For loop in Objective-C
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(@"%d", i);
}
On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.
for (NSString* currentString in myArrayOfStrings)
{
NSLog(@"%@", currentString);
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [myArrayOfStrings count]; i++)
{
NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}
The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.
Hope this helps.
Find kth smallest element in a binary search tree in Optimum way
public int ReturnKthSmallestElement1(int k)
{
Node node = Root;
int count = k;
int sizeOfLeftSubtree = 0;
while(node != null)
{
sizeOfLeftSubtree = node.SizeOfLeftSubtree();
if (sizeOfLeftSubtree + 1 == count)
return node.Value;
else if (sizeOfLeftSubtree < count)
{
node = node.Right;
count -= sizeOfLeftSubtree+1;
}
else
{
node = node.Left;
}
}
return -1;
}
this is my implementation in C# based on the algorithm above just thought I'd post it so people can understand better it works for me
thank you IVlad
PHP Fatal error: Cannot redeclare class
You have a class of the same name declared more than once. Maybe via multiple includes. When including other files you need to use something like
include_once "something.php";
to prevent multiple inclusions. It's very easy for this to happen, though not always obvious, since you could have a long chain of files being included by one another.
How to Deserialize XML document
See if this helps:
[Serializable()]
[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
{
[XmlArrayItem(typeof(Car))]
public Car[] Car { get; set; }
}
.
[Serializable()]
public class Car
{
[System.Xml.Serialization.XmlElement()]
public string StockNumber{ get; set; }
[System.Xml.Serialization.XmlElement()]
public string Make{ get; set; }
[System.Xml.Serialization.XmlElement()]
public string Model{ get; set; }
}
And failing that use the xsd.exe program that comes with visual studio to create a schema document based on that xml file, and then use it again to create a class based on the schema document.
Binding a WPF ComboBox to a custom list
You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.
Have you set the DataContext to your ConnectionViewModel object?
I copied you code and made some minor modifications, and it seems to work fine.
I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.
Here is my XAML content:
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel>
<Button Click="Button_Click">asdf</Button>
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}" />
</StackPanel>
</Grid>
</Window>
And here is my code-behind:
namespace WpfApplication6
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ConnectionViewModel vm = new ConnectionViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((ConnectionViewModel)DataContext).PhonebookEntry = "test";
}
}
public class PhoneBookEntry
{
public string Name { get; set; }
public PhoneBookEntry(string name)
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
public class ConnectionViewModel : INotifyPropertyChanged
{
public ConnectionViewModel()
{
IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
list.Add(new PhoneBookEntry("test"));
list.Add(new PhoneBookEntry("test2"));
_phonebookEntries = new CollectionView(list);
}
private readonly CollectionView _phonebookEntries;
private string _phonebookEntry;
public CollectionView PhonebookEntries
{
get { return _phonebookEntries; }
}
public string PhonebookEntry
{
get { return _phonebookEntry; }
set
{
if (_phonebookEntry == value) return;
_phonebookEntry = value;
OnPropertyChanged("PhonebookEntry");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.
Maybe there is an issue with the CollectionView? I noticed a warning in the output console:
System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.
Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.
How to remove old Docker containers
UPDATED 2021 (NEWEST)
docker container prune
This - 2017 (OLD) way
To remove ALL STOPPED CONTAINERS
docker rm $(docker ps -a -q)
To remove ALL CONTAINERS (STOPPED AND NON STOPPED)
docker rm -f $(docker ps -a -q)
MySQL DROP all tables, ignoring foreign keys
One-step solution without copying returned value from SQL Select query using procedure.
SET FOREIGN_KEY_CHECKS = 0
SET @TABLES = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name,'`') INTO @TABLES FROM information_schema.tables
WHERE table_schema = 'databaseName';
SET @TABLES = CONCAT('DROP TABLE IF EXISTS ', @TABLES);
PREPARE stmt FROM @TABLES;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1
how to run the command mvn eclipse:eclipse
I don't think one needs it any more. The latest versions of Eclipse have Maven plugin enabled. So you will just need to import a Maven project into Eclipse and no more as an existing project. Eclipse will create the needed .project, .settings, .classpath files based on your pom.xml and environment settings (installed Java version, etc.) . The earlier versions of Eclipse needed to have run the command mvn eclipse:eclipse
which produced the same result.
difference between System.out.println() and System.err.println()
It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:
public class PrintQueue {
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
System.out.println("out");
System.err.println("err");
}
}
}
If you compile and run the program, you will see that the order of outputs in console is mixed up.
An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.
Even in this code snippet you can see that the order is mixed up sometimes:
public class PrintQueue {
public static void main(String[] args) {
System.out.println("out");
System.err.println("err");
}
}
re.sub erroring with "Expected string or bytes-like object"
I suppose better would be to use re.match() function. here is an example which may help you.
import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]
sentences
Keep CMD open after BAT file executes
start cmd /k
did the magic for me. I actually used it for preparing cordova phonegap app it runs the command, shows the result and waits for the user to close it. Below is the simple example
start cmd /k echo Hello, World!
What I did use in my case
start cmd /k cordova prepare
Update
You could even have a title for this by using
start "My Title" echo Hello, World!
Script parameters in Bash
Use the variables "$1"
, "$2"
, "$3"
and so on to access arguments. To access all of them you can use "$@"
, or to get the count of arguments $#
(might be useful to check for too few or too many arguments).
How to remove origin from git repository
Fairly straightforward:
git remote rm origin
As for the filter-branch
question - just add --prune-empty
to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:
git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD
Enabling refreshing for specific html elements only
Try this:
_x000D_
_x000D_
function reload(){_x000D_
var container = document.getElementById("yourDiv");_x000D_
var content = container.innerHTML;_x000D_
container.innerHTML= content; _x000D_
_x000D_
//this line is to watch the result in console , you can remove it later _x000D_
console.log("Refreshed"); _x000D_
}
_x000D_
<a href="javascript: reload()">Click to Reload</a>_x000D_
<div id="yourDiv">The content that you want to refresh/reload</div>
_x000D_
_x000D_
_x000D_
Hope it works. Let me know
C# Parsing JSON array of objects
string jsonData1=@"[{""name"":""0"",""price"":""40"",""count"":""1"",""productId"":""4"",""catid"":""4"",""productTotal"":""40"",""orderstatus"":""0"",""orderkey"":""123456789""}]";
string jsonData = jsonData1.Replace("\"", "");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
JArray array= JArray.Parse(jsonData);
couldnot parse , if the vaule is a string..
look at name : meals , if name : 1 then it will parse
How can I make an "are you sure" prompt in a Windows batchfile?
First, open the terminal.
Then, type
cd ~
touch .sure
chmod 700 .sure
Next, open .sure and paste this inside.
#!/bin/bash --init-file
PS1='> '
alias y='
$1
exit
'
alias n='Taskkill /IM %Terminal% /f'
echo ''
echo 'Are you sure? Answer y or n.'
echo ''
After that, close the file.
~/.sure ; ENTER COMMAND HERE
This will give you a prompt of are you sure before continuing the command.
Abstract Class vs Interface in C++
Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.
class IInterface()
{
Public:
Virtual ~IInterface(){};
…
}
Class ClassImpl : public IInterface
{
…
}
Int main()
{
IInterface* pInterface = new ClassImpl();
…
delete pInterface; // Wrong in OO Programming, correct in C++.
}
How do you create nested dict in Python?
This thing is empty nested list from which ne will append data to empty dict
ls = [['a','a1','a2','a3'],['b','b1','b2','b3'],['c','c1','c2','c3'],
['d','d1','d2','d3']]
this means to create four empty dict inside data_dict
data_dict = {f'dict{i}':{} for i in range(4)}
for i in range(4):
upd_dict = {'val' : ls[i][0], 'val1' : ls[i][1],'val2' : ls[i][2],'val3' : ls[i][3]}
data_dict[f'dict{i}'].update(upd_dict)
print(data_dict)
The output
{'dict0': {'val': 'a', 'val1': 'a1', 'val2': 'a2', 'val3': 'a3'},
'dict1': {'val': 'b', 'val1': 'b1', 'val2': 'b2', 'val3': 'b3'},'dict2':
{'val': 'c', 'val1': 'c1', 'val2': 'c2', 'val3': 'c3'}, 'dict3': {'val': 'd', 'val1': 'd1', 'val2': 'd2', 'val3': 'd3'}}
Replace multiple characters in a C# string
string ToBeReplaceCharacters = @"~()@#$%&+,'"<>|;\/*?";
string fileName = "filename;with<bad:separators?";
foreach (var RepChar in ToBeReplaceCharacters)
{
fileName = fileName.Replace(RepChar.ToString(), "");
}
Functional programming vs Object Oriented programming
If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.
In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.
How to load an ImageView by URL in Android?
Try this way,hope this will help you to solve your problem.
Here I explain about how to use "AndroidQuery" external library for load image from url/server in asyncTask manner with also cache loaded image to device file or cache area.
- Download "AndroidQuery" library from here
- Copy/Paste this jar to project lib folder and add this library to project build-path
- Now I show demo to how to use it.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageFromUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<ProgressBar
android:id="@+id/pbrLoadImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private AQuery aQuery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aQuery = new AQuery(this);
aQuery.id(R.id.imageFromUrl).progress(R.id.pbrLoadImage).image("http://itechthereforeiam.com/wp-content/uploads/2013/11/android-gone-packing.jpg",true,true);
}
}
Note : Here I just implemented common method to load image from url/server but you can use various types of method which can be provided by "AndroidQuery"to load your image easily.
Differences between strong and weak in Objective-C
To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.
-(void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(@"myView tag is = %ld", myView.tag);
}
In above method scope of myView variable is limited to displayLocalVariable method, once the method gets finished myView variable which is holding the UIView object will get deallocated from the memory.
Now what if we want to hold the myView variable throughout our view controller's life cycle. For this we can create the property named as usernameView which will have Strong reference to the variable myView(see @property(nonatomic,strong) UIView* usernameView;
and self.usernameView = myView;
in below code), as below,
@interface LoginViewController ()
@property(nonatomic,strong) UIView* usernameView;
@property(nonatomic,weak) UIView* dummyNameView;
- (void)displayLocalVariable;
@end
@implementation LoginViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(void)viewWillAppear:(BOOL)animated
{
[self displayLocalVariable];
}
- (void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(@"myView tag is = %ld", myView.tag);
self.usernameView = myView;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
Now in above code you can see myView has been assigned to self.usernameView and self.usernameView is having a strong reference(as we declared in interface using @property) to myView. Hence myView will not get deallocated from memory till self.usernameView is alive.
Now consider assigning myName to dummyNameView which is a Weak reference, self.dummyNameView = myView;
Unlike Strong reference Weak will hold the myView only till there is Strong reference to myView. See below code to understand Weak reference,
-(void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(@"myView tag is = %ld", myView.tag);
self.dummyNameView = myView;
}
In above code there is Weak reference to myView(i.e. self.dummyNameView is having Weak reference to myView) but there is no Strong reference to myView, hence self.dummyNameView will not be able to hold the myView value.
Now again consider the below code,
-(void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(@"myView tag is = %ld", myView.tag);
self.usernameView = myView;
self.dummyNameView = myView;
}
In above code self.usernameView has a Strong reference to myView, hence self.dummyNameView will now have a value of myView even after method ends since myView has a Strong reference associated with it.
Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated till it's retain count reaches to 0.
Hope this helps.
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Try this:
$('#parent').on('click', '#child', function() {
// Code
});
From the $.on()
documentation:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on()
.
Your #child
element doesn't exist when you call $.on()
on it, so the event isn't bound (unlike $.live()
). #parent
, however, does exist, so binding the event to that is fine.
The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent
from #child
.
random.seed(): What does it do?
random.seed(a, version)
in python is used to initialize the pseudo-random number generator (PRNG).
PRNG is algorithm that generates sequence of numbers approximating the properties of random numbers. These random numbers can be reproduced using the seed value. So, if you provide seed value, PRNG starts from an arbitrary starting state using a seed.
Argument a
is the seed value. If the a value is None
, then by default, current system time is used.
and version
is An integer specifying how to convert the a parameter into a integer. Default value is 2.
import random
random.seed(9001)
random.randint(1, 10) #this gives output of 1
# 1
If you want the same random number to be reproduced then provide the same seed again
random.seed(9001)
random.randint(1, 10) # this will give the same output of 1
# 1
If you don't provide the seed, then it generate different number and not 1 as before
random.randint(1, 10) # this gives 7 without providing seed
# 7
If you provide different seed than before, then it will give you a different random number
random.seed(9002)
random.randint(1, 10) # this gives you 5 not 1
# 5
So, in summary, if you want the same random number to be reproduced, provide the seed. Specifically, the same seed.
SQL injection that gets around mysql_real_escape_string()
Consider the following query:
$iId = mysql_real_escape_string("1 OR 1=1");
$sSql = "SELECT * FROM table WHERE id = $iId";
mysql_real_escape_string()
will not protect you against this.
The fact that you use single quotes (' '
) around your variables inside your query is what protects you against this. The following is also an option:
$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";
How to finish current activity in Android
I tried using this example but it failed miserably. Every time I use to invoke finish()/ finishactivity() inside a handler, I end up with this menacing java.lang.IllegalAccess Exception
. i'm not sure how did it work for the one who posed the question.
Instead the solution I found was that create a method in your activity such as
void kill_activity()
{
finish();
}
Invoke this method from inside the run method of the handler. This worked like a charm for me. Hope this helps anyone struggling with "how to close an activity from a different thread?".
Query for array elements inside JSON type
jsonb
in Postgres 9.4+
You can use the same query as below, just with jsonb_array_elements()
.
But rather use the jsonb
"contains" operator @>
in combination with a matching GIN index on the expression data->'objects'
:
CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);
SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';
Since the key objects
holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.
More explanation and options:
json
in Postgres 9.3+
Unnest the JSON array with the function json_array_elements()
in a lateral join in the FROM
clause and test for its elements:
SELECT data::text, obj
FROM reports r, json_array_elements(r.data#>'{objects}') obj
WHERE obj->>'src' = 'foo.png';
db<>fiddle here
Old sqlfiddle
The CTE (WITH
query) just substitutes for a table reports
.
Or, equivalent for just a single level of nesting:
SELECT *
FROM reports r, json_array_elements(r.data->'objects') obj
WHERE obj->>'src' = 'foo.png';
->>
, ->
and #>
operators are explained in the manual.
Both queries use an implicit JOIN LATERAL
.
Closely related:
VB.NET Inputbox - How to identify when the Cancel Button is pressed?
Here is what I did and it worked perfectly for what I was looking to do:
Dim StatusDate As String
StatusDate = InputBox("What status date do you want to pull?", "Enter Status Date", " ")
If StatusDate = " " Then
MessageBox.Show("You must enter a Status date to continue.")
Exit Sub
ElseIf StatusDate = "" Then
Exit Sub
End If
This key was to set the default value of the input box to be an actual space, so a user pressing just the OK button would return a value of " " while pressing cancel returns ""
From a usability standpoint, the defaulted value in the input box starts highlighted and is cleared when a user types so the experience is no different than if the box had no value.
Java: how to add image to Jlabel?
the shortest code is :
JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));
stringPictureURL is PATH of image .
How to find GCD, LCM on a set of numbers
int lcm = 1;
int y = 0;
boolean flag = false;
for(int i=2;i<=n;i++){
if(lcm%i!=0){
for(int j=i-1;j>1;j--){
if(i%j==0){
flag =true;
y = j;
break;
}
}
if(flag){
lcm = lcm*i/y;
}
else{
lcm = lcm*i;
}
}
flag = false;
}
here, first for loop is for getting every numbers starting from '2'. then if statement check whether the number(i) divides lcm if it does then it skip that no. and if it doesn't then next for loop is for finding a no. which can divides the number(i) if this happens we don't need that no. we only wants its extra factor. so here if the flag is true this means there already had some factors of no. 'i' in lcm. so we divide that factors and multiply the extra factor to lcm. If the number isn't divisible by any of its previous no. then when simply multiply it to the lcm.
How to get my Android device Internal Download Folder path
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
How to get the index of an element in an IEnumerable?
The whole point of getting things out as IEnumerable is so you can lazily iterate over the contents. As such, there isn't really a concept of an index. What you are doing really doesn't make a lot of sense for an IEnumerable. If you need something that supports access by index, put it in an actual list or collection.
split string only on first instance - java
String[] func(String apple){
String[] tmp = new String[2];
for(int i=0;i<apple.length;i++){
if(apple.charAt(i)=='='){
tmp[0]=apple.substring(0,i);
tmp[1]=apple.substring(i+1,apple.length);
break;
}
}
return tmp;
}
//returns string_ARRAY_!
i like writing own methods :)
Can't stop rails server
killall -9 ruby
will kill all the ruby processes, and at-least on my machine, rails servers appear as ruby processes. killall -9 rails
is much more specific and doesn't work for older versions of rails servers (it gives a 'rails:no process found' because the process is named ruby)
Encountered this problem a while ago. After submitting a form in activeadmin, the rails server just hanged and I was unable to kill it using normal means (even after ctrl+z it was still running in the background). Learner's answer helped, but this command doesn't need process id.
Groovy / grails how to determine a data type?
To determine the class of an object simply call:
someObject.getClass()
You can abbreviate this to someObject.class
in most cases. However, if you use this on a Map
it will try to retrieve the value with key 'class'. Because of this, I always use getClass()
even though it's a little longer.
If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:
(somObject instanceof Date)
or to check if the class of an object is exactly a particular class (not a subclass of it), use:
(somObject.getClass() == Date)
Can I draw rectangle in XML?
try this
<TableRow
android:layout_width="match_parent"
android:layout_marginTop="5dp"
android:layout_height="wrap_content">
<View
android:layout_width="15dp"
android:layout_height="15dp"
android:background="#3fe1fa" />
<TextView
android:textSize="12dp"
android:paddingLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="1700 Market Street"
android:id="@+id/textView8" />
</TableRow>
output
Running Python code in Vim
You can extends for any language with 1 keybinding with augroup command, for example:
augroup rungroup
autocmd!
autocmd BufRead,BufNewFile *.go nnoremap <F5> :exec '!go run' shellescape(@%, 1)<cr>
autocmd BufRead,BufNewFile *.py nnoremap <F5> :exec '!python' shellescape(@%, 1)<cr>
augroup END
Java: is there a map function?
There is no notion of a function in the JDK as of java 6.
Guava has a Function interface though and the
Collections2.transform(Collection<E>, Function<E,E2>)
method provides the functionality you require.
Example:
// example, converts a collection of integers to their
// hexadecimal string representations
final Collection<Integer> input = Arrays.asList(10, 20, 30, 40, 50);
final Collection<String> output =
Collections2.transform(input, new Function<Integer, String>(){
@Override
public String apply(final Integer input){
return Integer.toHexString(input.intValue());
}
});
System.out.println(output);
Output:
[a, 14, 1e, 28, 32]
These days, with Java 8, there is actually a map function, so I'd probably write the code in a more concise way:
Collection<String> hex = input.stream()
.map(Integer::toHexString)
.collect(Collectors::toList);
iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons
You should use Asset Catalog:
I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.
Note: No need to make any entry in info.plist file :) And no any other configuration.
In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.
Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon.
If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution.
After uploading all required dimensions, you shouldn't get any warning.
How do I use a delimiter with Scanner.useDelimiter in Java?
For example:
String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);
This will let you use Enter as a delimiter.
Thus, if you input:
Hello world (ENTER)
it will print 'Hello World'.
PHP json_encode json_decode UTF-8
if you get "unexpected Character" error you should check if there is a BOM (Byte Order Marker saved into your utf-8 json.
You can either remove the first character or save if without BOM.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
how to count length of the JSON array element
First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :
obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;
Mongoimport of json file
Using mongoimport you can able to achieve the same
mongoimport --db test --collection user --drop --file ~/downloads/user.json
where,
test - Database name
user - collection name
user.json - dataset file
--drop
is drop the collection if already exist.
How to pass html string to webview on android
Passing null would be better. The full codes is like:
WebView wv = (WebView)this.findViewById(R.id.myWebView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadDataWithBaseURL(null, "<html>...</html>", "text/html", "utf-8", null);
Creating multiple log files of different content with log4j
I had this question, but with a twist - I was trying to log different content to different files. I had information for a LowLevel debug log, and a HighLevel user log. I wanted the LowLevel to go to only one file, and the HighLevel to go to both a file, and a syslogd.
My solution was to configure the 3 appenders, and then setup the logging like this:
log4j.threshold=ALL
log4j.rootLogger=,LowLogger
log4j.logger.HighLevel=ALL,Syslog,HighLogger
log4j.additivity.HighLevel=false
The part that was difficult for me to figure out was that the 'log4j.logger' could have multiple appenders listed. I was trying to do it one line at a time.
Hope this helps someone at some point!
Selenium C# WebDriver: Wait until element is present
Using the solution provided by Mike Kwan may have an impact in overall testing performance, since the implicit wait will be used in all FindElement calls.
Many times you'll want the FindElement to fail right away when an element is not present (you're testing for a malformed page, missing elements, etc.). With the implicit wait these operations would wait for the whole timeout to expire before throwing the exception. The default implicit wait is set to 0 seconds.
I've written a little extension method to IWebDriver that adds a timeout (in seconds) parameter to the FindElement()
method. It's quite self-explanatory:
public static class WebDriverExtensions
{
public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => drv.FindElement(by));
}
return driver.FindElement(by);
}
}
I didn't cache the WebDriverWait object as its creation is very cheap, this extension may be used simultaneously for different WebDriver objects, and I only do optimizations when ultimately needed.
Usage is straightforward:
var driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://localhost/mypage");
var btn = driver.FindElement(By.CssSelector("#login_button"));
btn.Click();
var employeeLabel = driver.FindElement(By.CssSelector("#VCC_VSL"), 10);
Assert.AreEqual("Employee", employeeLabel.Text);
driver.Close();
Alter column in SQL Server
I think you want this syntax:
ALTER TABLE tb_TableName
add constraint cnt_Record_Status Default '' for Record_Status
Based on some of your comments, I am going to guess that you might already have null
values in your table which is causing the alter of the column to not null
to fail. If that is the case, then you should run an UPDATE
first. Your script will be:
update tb_TableName
set Record_Status = ''
where Record_Status is null
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL
ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
See SQL Fiddle with demo
CSV in Python adding an extra carriage return, on Windows
Python 3:
The official csv
documentation recommends open
ing the file with newline=''
on all platforms to disable universal newlines translation:
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
...
The CSV writer terminates each line with the lineterminator
of the dialect, which is \r\n
for the default excel
dialect on all platforms.
Python 2:
On Windows, always open your files in binary mode ("rb"
or "wb"
), before passing them to csv.reader
or csv.writer
.
Although the file is a text file, CSV is regarded a binary format by the libraries involved, with \r\n
separating records. If that separator is written in text mode, the Python runtime replaces the \n
with \r\n
, hence the \r\r\n
observed in the file.
See this previous answer.
Byte Array to Hex String
If you have a numpy array, you can do the following:
>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'
Count number of records returned by group by
The simplest solution is to use a derived table:
Select Count(*)
From (
Select ...
From TempTable
Group By column_1, column_2, column_3, column_4
) As Z
Another solution is to use a Count Distinct:
Select ...
, ( Select Count( Distinct column_1, column_2, column_3, column_4 )
From TempTable ) As CountOfItems
From TempTable
Group By column_1, column_2, column_3, column_4
downcast and upcast
That is correct. When you do that you are casting it it into an employee
object, so that means you cannot access anything manager specific.
Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast like this:
if (employee is Manager)
{
Manager m = (Manager)employee;
//do something with it
}
or with the as
operator like this:
Manager m = (employee as Manager);
if (m != null)
{
//do something with it
}
If anything is unclear I'll be happy to correct it!
Get Last Part of URL PHP
The absolute simplest way to accomplish this, is with basename()
echo basename('http://domain.com/artist/song/music-videos/song-title/9393903');
Which will print
9393903
Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.
Git Push error: refusing to update checked out branch
Maybe your remote repo is in the branch which you want to push. You can try to checkout another branch in your remote machine. I did this, than these error disappeared, and I pushed success to my remote repo. Notice that I use ssh to connect my own server instead of github.com.
How can I disable ReSharper in Visual Studio and enable it again?
If resharper is completely missing from the options menu, it could be because the extension itself has been disabled.
In Visual Studio 2017 ReSharper 2018.X.X can be enabled and disabled by going to Help
> Manage Visual Studio Performance
. Then select JetBrains ReSharper ...
under Extensions
.
In Visual Studio 2019, you would go under Extensions->Manage Extensions->Installed
What are all the uses of an underscore in Scala?
An excellent explanation of the uses of the underscore is Scala _ [underscore] magic.
Examples:
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything other than one and two"
}
expr match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}
List(1,2,3,4,5).foreach(print(_))
// Doing the same without underscore:
List(1,2,3,4,5).foreach( a => print(a))
In Scala, _
acts similar to *
in Java while importing packages.
// Imports all the classes in the package matching
import scala.util.matching._
// Imports all the members of the object Fun (static import in Java).
import com.test.Fun._
// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }
In Scala, a getter and setter will be implicitly defined for all non-private vars in a object. The getter name is same as the variable name and _=
is added for the setter name.
class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}
Usage:
val t = new Test
t.age = 5
println(t.age)
If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable.
class Test {
def fun = {
// Some code
}
val funLike = fun _
}
Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined
This creates a new module/app:
var myApp = angular.module('myApp',[]);
While this accesses an already created module (notice the omission of the second argument):
var myApp = angular.module('myApp');
Since you use the first approach on both scripts you are basically overriding the module you previously created.
On the second script being loaded, use var myApp = angular.module('myApp');
.
Remove specific commit
There are four ways of doing so:
Clean way, reverting but keep in log the revert:
git revert --strategy resolve <commit>
Harsh way, remove altogether only the last commit:
git reset --soft "HEAD^"
Note: Avoid git reset --hard
as it will also discard all changes in files since the last commit. If --soft
does not work, rather try --mixed
or --keep
.
Rebase (show the log of the last 5 commits and delete the lines you don't want, or reorder, or squash multiple commits in one, or do anything else you want, this is a very versatile tool):
git rebase -i HEAD~5
And if a mistake is made:
git rebase --abort
Quick rebase: remove only a specific commit using its id:
git rebase --onto commit-id^ commit-id
Alternatives: you could also try:
git cherry-pick commit-id
Yet another alternative:
git revert --no-commit
As a last resort, if you need full freedom of history editing (eg, because git don't allow you to edit what you want to), you can use this very fast open source application: reposurgeon.
Note: of course, all these changes are done locally, you should git push
afterwards to apply the changes to the remote. And in case your repo doesn't want to remove the commit ("no fast-forward allowed", which happens when you want to remove a commit you already pushed), you can use git push -f
to force push the changes.
Note2: if working on a branch and you need to force push, you should absolutely avoid git push --force
because this may overwrite other branches (if you have made changes in them, even if your current checkout is on another branch). Prefer to always specify the remote branch when you force push: git push --force origin your_branch
.
When & why to use delegates?
Say you want to write a procedure to integrate some real-valued function f (x) over some interval [a, b]. Say we want to use the 3-Point Gaussian method to do this (any will do, of course).
Ideally we want some function that looks like:
// 'f' is the integrand we want to integrate over [a, b] with 'n' subintervals.
static double Gauss3(Integrand f, double a, double b, int n) {
double res = 0;
// compute result
// ...
return res;
}
So we can pass in any Integrand
, f, and get its definite integral over the closed interval.
Just what type should Integrand
be?
Without Delegates
Well, without delegates, we'd need some sort of interface with a single method, say eval
declared as follows:
// Interface describing real-valued functions of one variable.
interface Integrand {
double eval(double x);
}
Then we'd need to create a whole bunch of classes implementing this interface, as follows:
// Some function
class MyFunc1 : Integrand {
public double eval(double x) {
return /* some_result */ ;
}
}
// Some other function
class MyFunc2 : Integrand {
public double eval(double x) {
return /* some_result */ ;
}
}
// etc
Then to use them in our Gauss3 method, we need to invoke it as follows:
double res1 = Gauss3(new MyFunc1(), -1, 1, 16);
double res2 = Gauss3(new MyFunc2(), 0, Math.PI, 16);
And Gauss3 needs to do the look like the following:
static double Gauss3(Integrand f, double a, double b, int n) {
// Use the integrand passed in:
f.eval(x);
}
So we need to do all that just to use our arbitrary functions in Guass3
.
With Delegates
public delegate double Integrand(double x);
Now we can define some static (or not) functions adhering to that prototype:
class Program {
public delegate double Integrand(double x);
// Define implementations to above delegate
// with similar input and output types
static double MyFunc1(double x) { /* ... */ }
static double MyFunc2(double x) { /* ... */ }
// ... etc ...
public static double Gauss3(Integrand f, ...) {
// Now just call the function naturally, no f.eval() stuff.
double a = f(x);
// ...
}
// Let's use it
static void Main() {
// Just pass the function in naturally (well, its reference).
double res = Gauss3(MyFunc1, a, b, n);
double res = Gauss3(MyFunc2, a, b, n);
}
}
No interfaces, no clunky .eval stuff, no object instantiation, just simple function-pointer like usage, for a simple task.
Of course, delegates are more than just function pointers under the hood, but that's a separate issue (function chaining and events).
Django MEDIA_URL and MEDIA_ROOT
This if for Django 1.10:
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
How to list containers in Docker
To show only running containers use the given command:
docker ps
To show all containers use the given command:
docker ps -a
To show the latest created container (includes all states) use the given command:
docker ps -l
To show n last created containers (includes all states) use the given command:
docker ps -n=-1
To display total file sizes use the given command:
docker ps -s
The content presented above is from docker.com.
In the new version of Docker, commands are updated, and some management commands are added:
docker container ls
It is used to list all the running containers.
docker container ls -a
And then, if you want to clean them all,
docker rm $(docker ps -aq)
It is used to list all the containers created irrespective of its state.
And to stop all the Docker containers (force)
docker rm -f $(docker ps -a -q)
Here the container is the management command.
Any reason to prefer getClass() over instanceof when generating .equals()?
It depends if you consider if a subclass of a given class is equals to its parent.
class LastName
{
(...)
}
class FamilyName
extends LastName
{
(..)
}
here I would use 'instanceof', because I want a LastName to be compared to FamilyName
class Organism
{
}
class Gorilla extends Organism
{
}
here I would use 'getClass', because the class already says that the two instances are not equivalent.
golang why don't we have a set datastructure
Partly, because Go doesn't have generics (so you would need one set-type for every type, or fall back on reflection, which is rather inefficient).
Partly, because if all you need is "add/remove individual elements to a set" and "relatively space-efficient", you can get a fair bit of that simply by using a map[yourtype]bool
(and set the value to true
for any element in the set) or, for more space efficiency, you can use an empty struct as the value and use _, present = the_setoid[key]
to check for presence.
Where does the iPhone Simulator store its data?
To Open the dictories where you App are that you build in xCode on the simulators, do the following:
- open a Finder windor ( smiley face icon )
- then click GO -> Go to Folder
- type: ~/Library/Application Support/iPhone Simulator
- The Directories are the iOS version of the different Simulators
- The Sub Directories are the Apps install on the simulator
- The Documents folder is where the user generated content which gets backup up onto iCloud
How to get current instance name from T-SQL
To get the list of server and instance that you're connected to:
select * from Sys.Servers
To get the list of databases that connected server has:
SELECT * from sys.databases;
How to reload / refresh model data from the server programmatically?
You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:
function PersonListCtrl($scope, $http) {
$scope.loadData = function () {
$http.get('/persons').success(function(data) {
$scope.persons = data;
});
};
//initial load
$scope.loadData();
}
then in your markup
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="loadData()">Refresh</button>
</div>
As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:
for example (just puedo code) in your controller:
$scope.addPerson = function() {
$scope.persons.push({ name: 'Test Monkey' });
};
Then you could use that in your view or whatever you'd want to do.
How do you change the server header returned by nginx?
After I read Parthian Shot's answer, I dig into /usr/sbin/nginx
binary file. Then I found out that the file contains these three lines.
Server: nginx/1.12.2
Server: nginx/1.12.2
Server: nginx
Basically first two of them are meant for server_tokens on;
directive (Server version included).
Then I change the search criteria to match those lines within the binary file.
sed -i 's/Server: nginx/Server: thing/' `which nginx`
After I dig farther I found out that the error message produced by nginx is also included in this file.
<hr><center>nginx</center>
There are three of them, one without the version, two of them included the version. So I run the following command to replace nginx string within the error message.
sed -i 's/center>nginx/center>thing/' `which nginx`
PySpark: withColumn() with two conditions and three outcomes
There are a few efficient ways to implement this. Let's start with required imports:
from pyspark.sql.functions import col, expr, when
You can use Hive IF
function inside expr:
new_column_1 = expr(
"""IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)
or when
+ otherwise
:
new_column_2 = when(
col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)
Finally you could use following trick:
from pyspark.sql.functions import coalesce, lit
new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))
With example data:
df = sc.parallelize([
("orange", "apple"), ("kiwi", None), (None, "banana"),
("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])
you can use this as follows:
(df
.withColumn("new_column_1", new_column_1)
.withColumn("new_column_2", new_column_2)
.withColumn("new_column_3", new_column_3))
and the result is:
+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple| 0| 0| 0|
| kiwi| null| 3| 3| 3|
| null|banana| 3| 3| 3|
| mango| mango| 1| 1| 1|
| null| null| 3| 3| 3|
+------+------+------------+------------+------------+
How to make cross domain request
If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather).
I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.
Query Mongodb on month, day, year... of a datetime
Use the $expr
operator which allows the use of aggregation expressions within the query language. This will give you the power to use the Date Aggregation Operators in your query as follows:
month = 11
db.mydatabase.mycollection.find({
"$expr": {
"$eq": [ { "$month": "$date" }, month ]
}
})
or
day = 17
db.mydatabase.mycollection.find({
"$expr": {
"$eq": [ { "$dayOfMonth": "$date" }, day ]
}
})
You could also run an aggregate operation with the aggregate()
function that takes in a $redact
pipeline:
month = 11
db.mydatabase.mycollection.aggregate([
{
"$redact": {
"$cond": [
{ "$eq": [ { "$month": "$date" }, month ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
For the other request
day = 17
db.mydatabase.mycollection.aggregate([
{
"$redact": {
"$cond": [
{ "$eq": [ { "$dayOfMonth": "$date" }, day ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
Using OR
month = 11
day = 17
db.mydatabase.mycollection.aggregate([
{
"$redact": {
"$cond": [
{
"$or": [
{ "$eq": [ { "$month": "$date" }, month ] },
{ "$eq": [ { "$dayOfMonth": "$date" }, day ] }
]
},
"$$KEEP",
"$$PRUNE"
]
}
}
])
Using AND
var month = 11,
day = 17;
db.collection.aggregate([
{
"$redact": {
"$cond": [
{
"$and": [
{ "$eq": [ { "$month": "$createdAt" }, month ] },
{ "$eq": [ { "$dayOfMonth": "$createdAt" }, day ] }
]
},
"$$KEEP",
"$$PRUNE"
]
}
}
])
The $redact
operator incorporates the functionality of $project
and $match
pipeline and will return all documents match the condition using $$KEEP
and discard from the pipeline those that don't match using the $$PRUNE
variable.
SQL Server - Convert date field to UTC
I'm a bit late to the game but I needed to do something like this on SQL 2012, I haven't fully tested it yet but here is what I came up with.
CREATE FUNCTION SMS.fnConvertUTC
(
@DateCST datetime
)
RETURNS DATETIME
AS
BEGIN
RETURN
CASE
WHEN @DateCST
BETWEEN
CASE WHEN @DateCST > '2007-01-01'
THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-MAR-14 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-MAR-14 02:00' ) + 1
ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-APR-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-APR-07 02:00' ) + 1 END
AND
CASE WHEN @DateCST > '2007-01-01'
THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-NOV-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-NOV-07 02:00' ) + 1
ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-OCT-31 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-OCT-31 02:00' ) + 1 END
THEN DATEADD(HOUR,4,@DateCST)
ELSE DATEADD(HOUR,5,@DateCST)
END
END
Above someone posted a static list DST dates so I wrote the below query to compare this code's output to that list... so far it looks correct.
;WITH DT AS
(
SELECT MyDate = GETDATE()
UNION ALL
SELECT MyDate = DATEADD(YEAR,-1,MyDate) FROM DT
WHERE DATEADD(YEAR,-1,MyDate) > DATEADD(YEAR, -30, GETDATE())
)
SELECT
SpringForward = CASE
WHEN MyDate > '2007-01-01'
THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-MAR-14 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-MAR-14 02:00' ) + 1
ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-APR-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-APR-07 02:00' ) + 1 END
, FallBackward = CASE
WHEN MyDate > '2007-01-01'
THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-NOV-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-NOV-07 02:00' ) + 1
ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-OCT-31 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-OCT-31 02:00' ) + 1 END
FROM DT
ORDER BY 1 DESC
SpringForward FallBackward
---------------- ----------------
2020-03-08 02:00 2020-11-01 02:00
2019-03-10 02:00 2019-11-03 02:00
2018-03-11 02:00 2018-11-04 02:00
2017-03-12 02:00 2017-11-05 02:00
2016-03-13 02:00 2016-11-06 02:00
2015-03-08 02:00 2015-11-01 02:00
2014-03-09 02:00 2014-11-02 02:00
2013-03-10 02:00 2013-11-03 02:00
2012-03-11 02:00 2012-11-04 02:00
2011-03-13 02:00 2011-11-06 02:00
2010-03-14 02:00 2010-11-07 02:00
2009-03-08 02:00 2009-11-01 02:00
2008-03-09 02:00 2008-11-02 02:00
2007-03-11 02:00 2007-11-04 02:00
2006-04-02 02:00 2006-10-29 02:00
2005-04-03 02:00 2005-10-30 02:00
2004-04-04 02:00 2004-10-31 02:00
2003-04-06 02:00 2003-10-26 02:00
2002-04-07 02:00 2002-10-27 02:00
2001-04-01 02:00 2001-10-28 02:00
2000-04-02 02:00 2000-10-29 02:00
1999-04-04 02:00 1999-10-31 02:00
1998-04-05 02:00 1998-10-25 02:00
1997-04-06 02:00 1997-10-26 02:00
1996-04-07 02:00 1996-10-27 02:00
1995-04-02 02:00 1995-10-29 02:00
1994-04-03 02:00 1994-10-30 02:00
1993-04-04 02:00 1993-10-31 02:00
1992-04-05 02:00 1992-10-25 02:00
1991-04-07 02:00 1991-10-27 02:00
(30 row(s) affected)
Create a folder and sub folder in Excel VBA
This works like a charm in AutoCad VBA and I grabbed it from an excel forum. I don't know why you all make it so complicated?
FREQUENTLY ASKED QUESTIONS
Question: I'm not sure if a particular directory exists already. If it doesn't exist, I'd like to create it using VBA code. How can I do this?
Answer: You can test to see if a directory exists using the VBA code below:
(Quotes below are omitted to avoid confusion of programming code)
If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then
MkDir "c:\TOTN\Excel\Examples"
End If
http://www.techonthenet.com/excel/formulas/mkdir.php
Maven: how to override the dependency added by a library
The accepted answer is correct but I'd like to add my two cents. I've run into a problem where I had a project A that had a project B as a dependency. Both projects use slf4j but project B uses log4j while project A uses logback.
Project B uses slf4j 1.6.1, while project A uses slf4j 1.7.5 (due to the already included logback 1.2.3 dependency).
The problem: Project A couldn't find a function that exists on slf4j 1.7.5, after checking eclipe's dependency hierarchy tab I found out that during build it was using slf4j 1.6.1 from project B, instead of using logback's slf4j 1.7.5.
I solved the issue by changing the order of the dependencies on project A pom, when I moved project B entry below the logback entry then maven started to build the project using slf4j 1.7.5.
Edit:
Adding the slf4j 1.7.5 dependency before Project B dependency worked too.
How to send an HTTPS GET Request in C#
Add ?var1=data1&var2=data2
to the end of url to submit values to the page via GET:
using System.Net;
using System.IO;
string url = "https://www.example.com/scriptname.php?var1=hello";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
How to repeat a char using printf?
printf("%.*s\n",n,(char *) memset(buffer,c,n));
n
<= sizeof(buffer)
[ maybe also n < 2^16]
However the optimizer may change it to puts(buffer)
and then the lack of EoS will .....
And the assumption is that memset is an assembler instruction (but still a loop be it on
chip).
Strictly seen there is no solution given you precondition 'No loop'.
How do I mock an open used in a with statement (using the Mock framework in Python)?
To patch the built-in open() function with unittest:
This worked for a patch to read a json config.
class ObjectUnderTest:
def __init__(self, filename: str):
with open(filename, 'r') as f:
dict_content = json.load(f)
The mocked object is the io.TextIOWrapper object returned by the open() function
@patch("<src.where.object.is.used>.open",
return_value=io.TextIOWrapper(io.BufferedReader(io.BytesIO(b'{"test_key": "test_value"}'))))
def test_object_function_under_test(self, mocker):
How to block users from closing a window in Javascript?
Take a look at onBeforeUnload
.
It wont force someone to stay but it will prompt them asking them whether they really want to leave, which is probably the best cross browser solution you can manage. (Similar to this site if you attempt to leave mid-answer.)
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. Are you sure?";
}
</script>
Edit: Most browsers no longer allow a custom message for onbeforeunload
.
See this bug report from the 18th of February, 2016.
onbeforeunload dialogs are used for two things on the Modern Web:
1. Preventing users from inadvertently losing data.
2. Scamming users.
In an attempt to restrict their use for the latter while not stopping the former, we are going to not display the string provided by the webpage. Instead, we are going to use a generic string.
Firefox already does this[...]
Setting HTTP headers
I had the same issue as described above the solutions given above are correct, the set up I have is as follows
1) Angularjs for the Client
2) Beego framework for GO server
Please following these points
1) CORS settings must be enabled only on GO server
2) Do NOT add any type of headers in angularJS except for this
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}])
In you GO server add the CORS settings before the request starts to get processed so that the preflight request receives a 200 OK after which the the OPTIONS method will get converted to GET,POST,PUT or what ever is your request type.
Adding devices to team provisioning profile
- Login to your iPhone provisioning portal through developer.apple.com
- Add the UDID in devices
- Go to Provisioning Profile sections. Click on your provisioning profile, click on Edit.
- In Device section select your added device and generate provisioning certificate again.
- Download it and double click. It will automatically added in your Xcode.
- To check UDID present in .ipa file or not. Generate .ipa file and upload on diawi.com, get diawi link and hit on Safari browser. You can check their how many UDID are integrated in generated .ipa.
How to Set JPanel's Width and Height?
Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);
Angular 2: How to call a function after get a response from subscribe http.post
You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.
saveData(data:DepartmentModel){
return this.ds.sendDepartmentOnSubmit(data).
subscribe(response=>this.status=response,
()=>{},
()=>this.departmentModel={DepartmentId:0});
}
Collision resolution in Java HashMap
When multiple keys end up in same hash code which is present in same bucket.
When the same key has different values then the old value will be replaced with new value.
Liked list converted to balanced Binary tree from java 8 version on wards in worst case scenario.
Collision happen when 2 distinct keys generate the same hashcode() value.
When there are more collisions then there it will leads to worst performance of hashmap.
Objects which are are equal according to the equals method must return the same hashCode value.
When both objects return the same has code then they will be moved into the same bucket.
Assign a synthesizable initial value to a reg in Verilog
The always @* would never trigger as no Right hand arguments change. Why not use a wire with assign?
module top (
input wire clk,
output wire [7:0] led
);
wire [7:0] data_reg ;
assign data_reg = 8'b10101011;
assign led = data_reg;
endmodule
If you actually want a flop where you can change the value, the default would be in the reset clause.
module top
(
input clk,
input rst_n,
input [7:0] data,
output [7:0] led
);
reg [7:0] data_reg ;
always @(posedge clk or negedge rst_n) begin
if (!rst_n)
data_reg <= 8'b10101011;
else
data_reg <= data ;
end
assign led = data_reg;
endmodule
Hope this helps
Converting Date and Time To Unix Timestamp
Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...
let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);
to prove it:
let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);
enjoy!
Using Default Arguments in a Function
This is case, when object are better - because you can set up your object to hold x and y , set up defaults etc.
Approach with array is near to create object ( In fact, object is bunch of parameters and functions which will work over object, and function taking array will work over some bunch ov parameters )
Cerainly you can always do some tricks to set null or something like this as default
hibernate: LazyInitializationException: could not initialize proxy
We encountered this error as well. What we did to solve the issue is we added a lazy=false in the Hibernate mapping file.
It appears we had a class A that's inside a Session that loads another class B. We are trying to access the data on class B but this class B is detached from the session.
In order for us to access this Class B, we had to specify in the class A's Hibernate mapping file the lazy=false attribute. For example,
<many-to-one name="classA"
class="classB"
lazy="false">
<column name="classb_id"
sql-type="bigint(10)"
not-null="true"/>
</many-to-one>
Call php function from JavaScript
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
Plain Javascript
In this very basic example, we send a request to myAjax.php
when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output
.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
Gets byte array from a ByteBuffer in java
Depends what you want to do.
If what you want is to retrieve the bytes that are remaining (between position and limit), then what you have will work. You could also just do:
ByteBuffer bb =..
byte[] b = new byte[bb.remaining()];
bb.get(b);
which is equivalent as per the ByteBuffer javadocs.
How to unmount a busy device
Multiple mounts inside a folder
An additional reason could be a secondary mount inside your primary mount folder, e.g. after you worked on an SD card for an embedded device:
# mount /dev/sdb2 /mnt # root partition which contains /boot
# mount /dev/sdb1 /mnt/boot # boot partition
Unmounting /mnt will fail:
# umount /mnt
umount: /mnt: target is busy.
First we have to unmount the boot folder and then the root:
# umount /mnt/boot
# umount /mnt