Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
Add this line to docker file
USER <your_user_name>
Use docker instruction USER
Add this into your httpd.conf file
Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore
If I understand correctly, you wish to have everything in one page and execute it from the same page.
You can use the following code to send mail from a single page, for example index.php
or contact.php
The only difference between this one and my original answer is the <form action="" method="post">
where the action has been left blank.
It is better to use header('Location: thank_you.php');
instead of echo
in the PHP handler to redirect the user to another page afterwards.
<?php
if(isset($_POST['submit'])){
$to = "[email protected]"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.
Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail()
function.
The PHP handler will also send a copy of the message to the person who filled in the form.
You can use two forward slashes //
in front of a line of code if you're not going to use it.
For example: // $subject2 = "Copy of your form submission";
will not execute.
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
(Uses info from HTML form and sends the Email)
<?php
if(isset($_POST['submit'])){
$to = "[email protected]"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
// You cannot use header and echo together. It's one or the other.
}
?>
To send as HTML:
If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.
Read the manual on mail()
to learn how to send emails as HTML:
Footnotes:
You have to specify the URL of the service that will handle the submitted data, using the action attribute.
As outlined at https://www.w3.org/TR/html5/forms.html under 4.10.1.3 Configuring a form to communicate with a server. For complete information, consult the page.
Therefore, action=""
will not work in HTML5.
The proper syntax would be:
action="handler.xxx"
or action="http://www.example.com/handler.xxx"
.Note that xxx
will be the extension of the type of file used to handle the process. This could be a .php
, .cgi
, .pl
, .jsp
file extension etc.
Consult the following Q&A on Stack if sending mail fails:
Try This :
document.getElementById(<element_ID>).readOnly=true;
You can include your header function wherever you like, as long as NO html and/or text has been printed to standard out.
For more information and usage: http://php.net/manual/en/function.header.php
I see in your code that you echo()
out some text in case of error or success. Don't do that: you can't. You can only redirect OR show the text. If you show the text you'll then fail to redirect.
Any changes you commit, like deleting all your project files, will still be in place after a pull. All a pull does is merge the latest changes from somewhere else into your own branch, and if your branch has deleted everything, then at best you'll get merge conflicts when upstream changes affect files you've deleted. So, in short, yes everything is up to date.
If you describe what outcome you'd like to have instead of "all files deleted", maybe someone can suggest an appropriate course of action.
Update:
GET THE MOST RECENT OF THE CODE ON MY SYSTEM
What you don't seem to understand is that you already have the most recent code, which is yours. If what you really want is to see the most recent of someone else's work that's on the master branch, just do:
git fetch upstream
git checkout upstream/master
Note that this won't leave you in a position to immediately (re)start your own work. If you need to know how to undo something you've done or otherwise revert changes you or someone else have made, then please provide details. Also, consider reading up on what version control is for, since you seem to misunderstand its basic purpose.
dplyr
does the trick
mtcars %>%
arrange(desc(mpg)) %>%
group_by(cyl) %>% slice(1:2)
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
2 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
3 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
5 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
6 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
If you use Homebrew on OS X, then you have a simpler solution:
$ brew install go --with-cc-common # Linux, Darwin, and Windows
or..
$ brew install go --with-cc-all # All the cross-compilers
Use reinstall
if you already have go
installed.
Usage:
select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');
Function:
CREATE OR REPLACE FUNCTION
replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR)
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN
SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY'
AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;
EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name ||
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';
RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;
END;
$$ LANGUAGE plpgsql;
Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.
If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)
<select chosen="{width: '100%'}" ng-
model="modelName" class="form-control input-
sm"
ng-
options="persons.persons as
persons.persons for persons in
jsonData"
ng-
change="anyFunction(anyParam)"
required>
<option value=""> </option>
</select>
<style>
.chosen-container .chosen-drop {
border-bottom: 0;
border-top: 1px solid #aaa;
top: auto;
bottom: 40px;
}
.chosen-container.chosen-with-drop .chosen-single {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-image: none;
}
.chosen-container.chosen-with-drop .chosen-drop {
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
box-shadow: none;
margin-bottom: -16px;
}
</style>
I've been looking at this problem for the better part of a day, and here's what I've come up with (credit to https://stackoverflow.com/a/5249214/196358 for pointing me in this direction).
(Note: I'm using flask-sqlalchemy, so my model declaration format is a bit different from straight sqlalchemy).
In my models.py
file:
import json
class Serializer(object):
__public__ = None
"Must be implemented by implementors"
def to_serializable_dict(self):
dict = {}
for public_key in self.__public__:
value = getattr(self, public_key)
if value:
dict[public_key] = value
return dict
class SWEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Serializer):
return obj.to_serializable_dict()
if isinstance(obj, (datetime)):
return obj.isoformat()
return json.JSONEncoder.default(self, obj)
def SWJsonify(*args, **kwargs):
return current_app.response_class(json.dumps(dict(*args, **kwargs), cls=SWEncoder, indent=None if request.is_xhr else 2), mimetype='application/json')
# stolen from https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py
and all my model objects look like this:
class User(db.Model, Serializer):
__public__ = ['id','username']
... field definitions ...
In my views I call SWJsonify wherever I would have called Jsonify
, like so:
@app.route('/posts')
def posts():
posts = Post.query.limit(PER_PAGE).all()
return SWJsonify({'posts':posts })
Seems to work pretty well. Even on relationships. I haven't gotten far with it, so YMMV, but so far it feels pretty "right" to me.
Suggestions welcome.
If you have one or more factor
variable(s) in your data that you want to make reproducible with dput(head(mydata))
, consider adding droplevels
to it, so that levels of factors that are not present in the minimized data set are not included in your dput
output, in order to make the example minimal:
dput(droplevels(head(mydata)))
If you are interested in html formatted email, make sure to pass Content-type: text/html;
in the header. Example:
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
For more details, check php mail function.
Even I faced the same problem in my XMPP notification application, receivers message needs to be added back to list view (implemented with ArrayList
). When I tried to add the receiver content through MessageListener
(separate thread), application quits with above error. I solved this by adding the content to my arraylist
& setListviewadapater
through runOnUiThread
method which is part of Activity class. This solved my problem.
The key was to do pod deintegrate
and rm *.workspace
file ! What a waste of time !
If you don't mind a third-party dependency, you should consider using my OS-Lib library. This makes reading/writing files and working with the filesystem very convenient:
// Make sure working directory exists and is empty
val wd = os.pwd/"out"/"splash"
os.remove.all(wd)
os.makeDir.all(wd)
// Read/write files
os.write(wd/"file.txt", "hello")
os.read(wd/"file.txt") ==> "hello"
// Perform filesystem operations
os.copy(wd/"file.txt", wd/"copied.txt")
os.list(wd) ==> Seq(wd/"copied.txt", wd/"file.txt")
with one-line helpers for reading bytes, reading chunks, reading lines, and many other useful/common operations
I had to add a Return-Path header in emails send by a Redmine instance. I agree with greatwolf only the sender can determine a correct (non default) Return-Path. The case is the following : E-mails are send with the default email address : [email protected] But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ). We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.
Here is example code showing how to compute a centered moving average and a trailing moving average using the rollmean
function from the zoo package.
library(tidyverse)
library(zoo)
some_data = tibble(day = 1:10)
# cma = centered moving average
# tma = trailing moving average
some_data = some_data %>%
mutate(cma = rollmean(day, k = 3, fill = NA)) %>%
mutate(tma = rollmean(day, k = 3, fill = NA, align = "right"))
some_data
#> # A tibble: 10 x 3
#> day cma tma
#> <int> <dbl> <dbl>
#> 1 1 NA NA
#> 2 2 2 NA
#> 3 3 3 2
#> 4 4 4 3
#> 5 5 5 4
#> 6 6 6 5
#> 7 7 7 6
#> 8 8 8 7
#> 9 9 9 8
#> 10 10 NA 9
Some scenarios don't always allow developers to switch scripting language.
My preference is definitely for JavaScript (and I have used it in new projects). However, maintaining older projects is still required and necessary. Unfortunately, these are written in VBScript.
So even though this solution doesn't offer true "try/catch" functionaility, the result is the same, and that's good enough for me to get the job done.
Create your file then return a reference to it with the correct header to trigger the Save As - edit the following as needed. Put your CSV data into $csvdata.
$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);
header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);
function call itself or use its own definition.
Not a technology podcast, but I really have to mention FreelanceRadio. A really great and sometimes hilarious resource. I'm listening to them in the morning, on the way to work. And sometimes feel really stupid just giggling by myself :P
Running the following helped resolve the issue:
npm config set strict-ssl false
I cannot comment on whether it will cause any other issues at this point in time.
public class GenerateEncryptedPassword {
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println("Please enter the password that needs to be encrypted :");
String input = sc.next();
try {
String encryptedPassword= AESencrp.encrypt(input);
System.out.println("Encrypted password generated is :"+encryptedPassword);
} catch (Exception ex) {
Logger.getLogger(GenerateEncryptedPassword.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I thought I would update this post a bit and say that alot of the iOS community has moved over to AFNetworking after ASIHTTPRequest
was abandoned. I highly recommend it. It's a great wrapper around NSURLConnection
and allows for asynchronous calls, and basically anything you might need.
This is a favorite Java interview question.
Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread e2 = new Thread(new EventThread("e2"));
t2.start();
while (true) {
try {
t1.join(); // 1
t2.join(); // 2 These lines (1,2) are in in public static void main
break;
}
}
t1.join()
means, t1 says something like "I want to finish first". Same is the case with t2
. No matter who started t1
or t2
thread (in this case the main
method), main will wait until t1
and t2
finish their task.
However, an important point to note down, t1
and t2
themselves can run in parallel irrespective of the join call sequence on t1
and t2
. It is the main/daemon
thread that has to wait.
Not out of the box in Sql Server Management Studio, but it is a feature of the very good SSMS Tools Pack
Just set the property of textbox that is
PasswordChar and set the *
as a property
of textbox. That will work for password.
passwordtextbox.PasswordChar = '*';
where passwordtextbox
is the text box name.
you can use this simple way
<select onchange="location = this.value;">
<option value="/finished">Finished</option>
<option value="/break">Break</option>
<option value="/issue">Issues</option>
<option value="/downtime">Downtime</option>
</select>
will redirect to route url you can direct to .html page or direct to some link just change value
in option.
Copied from the formal specification: ECMAScript 5.1 section 11.9.5
11.9.4 The Strict Equals Operator ( === )
The production EqualityExpression : EqualityExpression === RelationalExpression is evaluated as follows:
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref).
- Return the result of performing the strict equality comparison rval === lval. (See 11.9.6)
11.9.5 The Strict Does-not-equal Operator ( !== )
The production EqualityExpression : EqualityExpression !== RelationalExpression is evaluated as follows:
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref). Let r be the result of performing strict equality comparison rval === lval. (See 11.9.6)
- If r is true, return false. Otherwise, return true.
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
- Type(x) is Undefined, return true.
- Type(x) is Null, return true.
- Type(x) is Number, then
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0 and y is -0, return true.
- If x is -0 and y is +0, return true.
- Return false.
- If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
- If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
- Return true if x and y refer to the same object. Otherwise, return false.
just use preload="none"
in your video tag and video will stop autoplay when the page is loading.
Without GNU extension:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char str1[] = "First";
const char str2[] = "Second";
char *res;
res = malloc(strlen(str1) + strlen(str2) + 1);
if (!res) {
fprintf(stderr, "malloc() failed: insufficient memory!\n");
return EXIT_FAILURE;
}
strcpy(res, str1);
strcat(res, str2);
printf("Result: '%s'\n", res);
free(res);
return EXIT_SUCCESS;
}
Alternatively with GNU extension:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char str1[] = "First";
const char str2[] = "Second";
char *res;
if (-1 == asprintf(&res, "%s%s", str1, str2)) {
fprintf(stderr, "asprintf() failed: insufficient memory!\n");
return EXIT_FAILURE;
}
printf("Result: '%s'\n", res);
free(res);
return EXIT_SUCCESS;
}
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
Please add the correct mime-types to your code - at least these ones:
.jpeg -> image/jpeg
.gif -> image/gif
.png -> image/png
A list of mime-types can be found here.
Furthermore, simplify the code's logic and report an error number to help the first level support track down problems:
$allowedExts = array(
"pdf",
"doc",
"docx"
);
$allowedMimeTypes = array(
'application/msword',
'text/pdf',
'image/gif',
'image/jpeg',
'image/png'
);
$extension = end(explode(".", $_FILES["file"]["name"]));
if ( 20000 < $_FILES["file"]["size"] ) {
die( 'Please provide a smaller file [E/1].' );
}
if ( ! ( in_array($extension, $allowedExts ) ) ) {
die('Please provide another file type [E/2].');
}
if ( in_array( $_FILES["file"]["type"], $allowedMimeTypes ) )
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
}
else
{
die('Please provide another file type [E/3].');
}
This is the implementation coming from the Apache camel project:
/**
* Checks to see if a specific port is available.
*
* @param port the port to check for availability
*/
public static boolean available(int port) {
if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
throw new IllegalArgumentException("Invalid start port: " + port);
}
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
return false;
}
They are checking the DatagramSocket as well to check if the port is avaliable in UDP and TCP.
Hope this helps.
I ended up with this method for inserting a blob:
protected Boolean updateByteArrayInTable(String table, String value, byte[] byteArray, String expr)
{
try
{
SQLiteCommand mycommand = new SQLiteCommand(connection);
mycommand.CommandText = "update " + table + " set " + value + "=@image" + " where " + expr;
SQLiteParameter parameter = new SQLiteParameter("@image", System.Data.DbType.Binary);
parameter.Value = byteArray;
mycommand.Parameters.Add(parameter);
int rowsUpdated = mycommand.ExecuteNonQuery();
return (rowsUpdated>0);
}
catch (Exception)
{
return false;
}
}
For reading it back the code is:
protected DataTable executeQuery(String command)
{
DataTable dt = new DataTable();
try
{
SQLiteCommand mycommand = new SQLiteCommand(connection);
mycommand.CommandText = command;
SQLiteDataReader reader = mycommand.ExecuteReader();
dt.Load(reader);
reader.Close();
return dt;
}
catch (Exception)
{
return null;
}
}
protected DataTable getAllWhere(String table, String sort, String expr)
{
String cmd = "select * from " + table;
if (sort != null)
cmd += " order by " + sort;
if (expr != null)
cmd += " where " + expr;
DataTable dt = executeQuery(cmd);
return dt;
}
public DataRow getImage(long rowId) {
String where = KEY_ROWID_IMAGE + " = " + Convert.ToString(rowId);
DataTable dt = getAllWhere(DATABASE_TABLE_IMAGES, null, where);
DataRow dr = null;
if (dt.Rows.Count > 0) // should be just 1 row
dr = dt.Rows[0];
return dr;
}
public byte[] getImage(DataRow dr) {
try
{
object image = dr[KEY_IMAGE];
if (!Convert.IsDBNull(image))
return (byte[])image;
else
return null;
} catch(Exception) {
return null;
}
}
DataRow dri = getImage(rowId);
byte[] image = getImage(dri);
If you have two values yanked into two different registers (for example register a
and register b
) then you can simply set a variable c
and do the operation on it.
For example, :set c = str2float(@a) + str2float(@b)
and then you can paste the content of c
anywhere.
For example whilst in INSERT mode, CTRL + R
then type =
to enter into the expression register and just type c
after equal sign and hit ENTER. Done you should now have the total of a
and b
registers.
All these can be recorded in a macro and repeated over!
The str2float
function is used if you are working with floats, if you don't, you will get integers instead.
I am not sure if this is idiomatic but it worked for my case where I needed to add 2 numbers in a row and repeat it for 500 more lines.
I have a function next()
which will maybe inspire you.
function queue(target) {
var array = Array.prototype;
var queueing = [];
target.queue = queue;
target.queued = queued;
return target;
function queued(action) {
return function () {
var self = this;
var args = arguments;
queue(function (next) {
action.apply(self, array.concat.apply(next, args));
});
};
}
function queue(action) {
if (!action) {
return;
}
queueing.push(action);
if (queueing.length === 1) {
next();
}
}
function next() {
queueing[0](function (err) {
if (err) {
throw err;
}
queueing = queueing.slice(1);
if (queueing.length) {
next();
}
});
}
}
I got the same problems. I solved my problem by updating gradle.build for each sub-module to latest compiler version.
You can use scrollViewDidEndDecelerating
: for this
//@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
for (UICollectionViewCell *cell in [self.collectionView visibleCells]) {
NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
NSUInteger lastIndex = [indexPath indexAtPosition:[indexPath length] - 1];
NSLog(@"visible cell value %d",lastIndex);
}
}
In case you need a Distinct method on multiple properties, you can check out my PowerfulExtensions library. Currently it's in a very young stage, but already you can use methods like Distinct, Union, Intersect, Except on any number of properties;
This is how you use it:
using PowerfulExtensions.Linq;
...
var distinct = myArray.Distinct(x => x.A, x => x.B);
You can write a TCL script and establish SSH session to that Linux machine and issue commands automatically. Check http://wiki.tcl.tk/11542 for a short tutorial.
we can try this to get current script name without extension.
import os
script_name = os.path.splitext(os.path.basename(__file__))[0]
$('button').toggle(
function() {
$('#B').css('left', '0')
}, function() {
$('#B').css('left', '200px')
})
You can also see any animated version at http://jsfiddle.net/hThGb/2/
My situation and solution: I had created and enabled a HyperV ethernet adapter. For some reason, my main windows machine was using the "virtual" ethernet adapter instead of the 'hardware' adapter.
I disabled the virtual ethernet and my network settings to change the network public/privacy settings were revealed.
If you want to log errors from web-page, you should use WebChromeClient
and override its onConsoleMessage
:
webView.settings.apply {
javaScriptEnabled = true
javaScriptCanOpenWindowsAutomatically = true
domStorageEnabled = true
}
webView.webViewClient = WebViewClient()
webView.webChromeClient = MyWebChromeClient()
private class MyWebChromeClient : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
Timber.d("${consoleMessage.message()}")
Timber.d("${consoleMessage.lineNumber()} ${consoleMessage.sourceId()}")
return super.onConsoleMessage(consoleMessage)
}
}
Setting a -vendor
prefix that isn't supported in older browsers can cause them to throw an exception with .css
. Instead detect the supported prefix first:
// Start with a fall back
var newCss = { 'zoom' : ui.value };
// Replace with transform, if supported
if('WebkitTransform' in document.body.style)
{
newCss = { '-webkit-transform': 'scale(' + ui.value + ')'};
}
// repeat for supported browsers
else if('transform' in document.body.style)
{
newCss = { 'transform': 'scale(' + ui.value + ')'};
}
// Set the CSS
$('.user-text').css(newCss)
That works in old browsers. I've done scale
here but you could replace it with whatever other transform you wanted.
.Click() - Perform only click operation as like mouse click.
.Submit() - Perform Enter operation as like keyboard Enter event.
For Example. Consider a login page where it contains username and password and submit button.
On filling password if we want to login without clicking login button. we need to user .submit button on password where .click() operation does not work.[to login into application]
Brif.
driver.get("https:// anyURL");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.id("txtUserId")).sendKeys("[email protected]");
WebElement text = driver.findElement(By.id("txtPassword")); text.sendKeys("password");
Thread.sleep(1000);
text.click(); //This will not work - it will on perform click operation not submit operation
text.submit(); //This will perform submit operation has enter key
I tried all these answers, even closed Visual Studio and deleted all bin directories.
After starting it up again the MVC reference appeared to have a yellow exclamation mark on it, so I removed it and added it again.
Now it works, without copy local.
I made the following code so that even beginners can understand. Just copy the code and read comments. Note that message to be send is declared as a global variable which you can change just before sending the message. General changes can be done in Handler function.
multiplayerConnect.java
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class multiplayerConnect extends AppCompatActivity {
public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;
String bluetooth_message="00";
@SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
@Override
public void handleMessage(Message msg_type) {
super.handleMessage(msg_type);
switch (msg_type.what){
case MESSAGE_READ:
byte[] readbuf=(byte[])msg_type.obj;
String string_recieved=new String(readbuf);
//do some task based on recieved string
break;
case MESSAGE_WRITE:
if(msg_type.obj!=null){
ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
connectedThread.write(bluetooth_message.getBytes());
}
break;
case CONNECTED:
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
break;
case CONNECTING:
Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
break;
case NO_SOCKET_FOUND:
Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplayer_bluetooth);
initialize_layout();
initialize_bluetooth();
start_accepting_connection();
initialize_clicks();
}
public void start_accepting_connection()
{
//call this on button click as suited by you
AcceptThread acceptThread = new AcceptThread();
acceptThread.start();
Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Object[] objects = set_pairedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) objects[position];
ConnectThread connectThread = new ConnectThread(device);
connectThread.start();
Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
}
});
}
public void initialize_layout()
{
lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
lv_paired_devices.setAdapter(adapter_paired_devices);
}
public void initialize_bluetooth()
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
finish();
}
//Add these permisions before
// <uses-permission android:name="android.permission.BLUETOOTH" />
// <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
// <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else {
set_pairedDevices = bluetoothAdapter.getBondedDevices();
if (set_pairedDevices.size() > 0) {
for (BluetoothDevice device : set_pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
}
}
}
}
public class AcceptThread extends Thread
{
private final BluetoothServerSocket serverSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
} catch (IOException e) { }
serverSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null)
{
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(CONNECTED).sendToTarget();
}
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mHandler.obtainMessage(CONNECTING).sendToTarget();
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
// bluetooth_message = "Initial message"
// mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[2]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
multiplayer_bluetooth.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Challenge player"/>
<ListView
android:id="@+id/lv_paired_devices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</ListView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Make sure Device is paired"/>
</LinearLayout>
Yes you can as said by @tomer above. i want to add some point to @tomer answer.
router-outlet
where you want to load the second routing view in your view. (aux routing angular2.)In angular2 routing few important points are here.
for more info read out here and here.
import {RouteConfig, AuxRoute} from 'angular2/router';
@RouteConfig([
new AuxRoute({path: '/home', component: HomeCmp})
])
class MyApp {}
Try this
function setAttribs(elm, ob) {
//var r = [];
//var i = 0;
for (var z in ob) {
if (ob.hasOwnProperty(z)) {
try {
elm[z] = ob[z];
}
catch (er) {
elm.setAttribute(z, ob[z]);
}
}
}
return elm;
}
DEMO: HERE
using System.IO;
...
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
string contents = File.ReadAllText(file);
}
Note the above uses a .NET 4.0 feature; in previous versions replace EnumerateFiles
with GetFiles
). Also, replace File.ReadAllText
with your preferred way of reading xml files - perhaps XDocument
, XmlDocument
or an XmlReader
.
Have done a number of comparisons between left outer and inner joins and have not been able to find a consisten difference. There are many variables. Am working on a reporting database with thousands of tables many with a large number of fields, many changes over time (vendor versions and local workflow) . It is not possible to create all of the combinations of covering indexes to meet the needs of such a wide variety of queries and handle historical data. Have seen inner queries kill server performance because two large (millions to tens of millions of rows) tables are inner joined both pulling a large number of fields and no covering index exists.
The biggest issue though, doesn't seem to appeaer in the discussions above. Maybe your database is well designed with triggers and well designed transaction processing to ensure good data. Mine frequently has NULL values where they aren't expected. Yes the table definitions could enforce no-Nulls but that isn't an option in my environment.
So the question is... do you design your query only for speed, a higher priority for transaction processing that runs the same code thousands of times a minute. Or do you go for accuracy that a left outer join will provide. Remember that inner joins must find matches on both sides, so an unexpected NULL will not only remove data from the two tables but possibly entire rows of information. And it happens so nicely, no error messages.
You can be very fast as getting 90% of the needed data and not discover the inner joins have silently removed information. Sometimes inner joins can be faster, but I don't believe anyone making that assumption unless they have reviewed the execution plan. Speed is important, but accuracy is more important.
Others have answered "how" and quoted spec. Here is the real story of "why no <script/>
", after many hours digging into bug reports and mailing lists.
HTML 4
HTML 4 is based on SGML.
SGML has some shorttags, such as <BR//
, <B>text</>
, <B/text/
, or <OL<LI>item</LI</OL>
.
XML takes the first form, redefines the ending as ">" (SGML is flexible), so that it becomes <BR/>
.
However, HTML did not redfine, so <SCRIPT/>
should mean <SCRIPT>>
.
(Yes, the '>' should be part of content, and the tag is still not closed.)
Obviously, this is incompatible with XHTML and will break many sites (by the time browsers were mature enough to care about this), so nobody implemented shorttags and the specification advises against them.
Effectively, all 'working' self-ended tags are tags with prohibited end tag on technically non-conformant parsers and are in fact invalid. It was W3C which came up with this hack to help transitioning to XHTML by making it HTML-compatible.
And <script>
's end tag is not prohibited.
"Self-ending" tag is a hack in HTML 4 and is meaningless.
HTML 5
HTML5 has five types of tags and only 'void' and 'foreign' tags are allowed to be self-closing.
Because <script>
is not void (it may have content) and is not foreign (like MathML or SVG), <script>
cannot be self-closed, regardless of how you use it.
But why? Can't they regard it as foreign, make special case, or something?
HTML 5 aims to be backward-compatible with implementations of HTML 4 and XHTML 1.
It is not based on SGML or XML; its syntax is mainly concerned with documenting and uniting the implementations.
(This is why <br/>
<hr/>
etc. are valid HTML 5 despite being invalid HTML4.)
Self-closing <script>
is one of the tags where implementations used to differ.
It used to work in Chrome, Safari, and Opera; to my knowledge it never worked in Internet Explorer or Firefox.
This was discussed when HTML 5 was being drafted and got rejected because it breaks browser compatibility. Webpages that self-close script tag may not render correctly (if at all) in old browsers. There were other proposals, but they can't solve the compatibility problem either.
After the draft was released, WebKit updated the parser to be in conformance.
Self-closing <script>
does not happen in HTML 5 because of backward compatibility to HTML 4 and XHTML 1.
XHTML 1 / XHTML 5
When really served as XHTML, <script/>
is really closed, as other answers have stated.
Except that the spec says it should have worked when served as HTML:
XHTML Documents ... may be labeled with the Internet Media Type "text/html" [RFC2854], as they are compatible with most HTML browsers.
So, what happened?
People asked Mozilla to let Firefox parse conforming documents as XHTML regardless of the specified content header (known as content sniffing). This would have allowed self-closing scripts, and content sniffing was necessary anyway because web hosters were not mature enough to serve the correct header; IE was good at it.
If the first browser war didn't end with IE 6, XHTML may have been on the list, too. But it did end. And IE 6 has a problem with XHTML.
In fact IE did not support the correct MIME type at all, forcing everyone to use text/html
for XHTML because IE held major market share for a whole decade.
And also content sniffing can be really bad and people are saying it should be stopped.
Finally, it turns out that the W3C didn't mean XHTML to be sniffable: the document is both, HTML and XHTML, and Content-Type
rules.
One can say they were standing firm on "just follow our spec" and ignoring what was practical. A mistake that continued into later XHTML versions.
Anyway, this decision settled the matter for Firefox. It was 7 years before Chrome was born; there were no other significant browser. Thus it was decided.
Specifying the doctype alone does not trigger XML parsing because of following specifications.
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() ) );
I have a solution for this. First thing that add is already having a string value as input() function by default takes the input as string. Second thing that you can use append method to append value of add variable in your list.
Please do check my code I have done some modification : - {1} You can enter command in capital or small or mix {2} If user entered wrong command then your program will ask to input command again
inventory = ["sword","potion","armour","bow"] print(inventory) print("\ncommands : use (remove item) and pickup (add item)") selection=input("choose a command [use/pickup] : ") while True: if selection.lower()=="use": print(inventory) remove_item=input("What do you want to use? ") inventory.remove(remove_item) print(inventory) break
elif selection.lower()=="pickup":
print(inventory)
add_item=input("What do you want to pickup? ")
inventory.append(add_item)
print(inventory)
break
else:
print("Invalid Command. Please check your input")
selection=input("Once again choose a command [use/pickup] : ")
File-> Settings -> Keymap-> Complete Current Statement
I added ;
key in there. When typing ';' at the end of the line, it is auto-formatting.
UPDATE
I realized that this will cause some problems in some situations. Use Ctrl
+Shift
+Enter
instead. This key can be used in any position of cursor in a line. It will add ;
at the end of the line. Also this shortcut have some other useful features.
like:
public void someMethod()
after shortcut:
public void someMethod() {
// The cursor is here
}
so formatting on inserting ;
is not necessary.
You can (should) use CROSS JOIN
. Following query will be equivalent to yours:
SELECT
table1.columnA
, table2.columnA
FROM table1
CROSS JOIN table2
WHERE table1.columnA = 'Some value'
or you can even use INNER JOIN with some always true conditon:
FROM table1
INNER JOIN table2 ON 1=1
Modulo is the remainder, expressed as an integer, of a mathematical division expression.
So, lets say you have a pixel on a screen at position 90 where the screen is 100 pixels wide and add 20, it will wrap around to position 10. Why...because 90 + 20 = 110 therefore 110 % 100 = 10.
For me to understand it I consider the modulo is the integer representation of fractional number. Furthermore if you do the expression backwards and process the remainder as a fractional number and then added to the divisor it will give you your original answer.
Examples:
100
(A) --- = 14 mod 2
7
123
(B) --- = 8 mod 3
15
3
(C) --- = 0 mod 3
4
Reversed engineered to:
2 14(7) 2 98 2 100
(A) 14 mod 2 = 14 + --- = ----- + --- = --- + --- = ---
7 7 7 7 7 7
3 8(15) 3 120 3 123
(B) 8 mod 3 = 8 + --- = ----- + --- = --- + --- = ---
15 15 15 15 15 15
3 3
(B) 0 mod 3 = 0 + --- = ---
4 4
Arrays are always passed by reference if you use a[]
or *a
:
int* printSquares(int a[], int size, int e[]) {
for(int i = 0; i < size; i++) {
e[i] = i * i;
}
return e;
}
int* printSquares(int *a, int size, int e[]) {
for(int i = 0; i < size; i++) {
e[i] = i * i;
}
return e;
}
the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.
Either put it on one line or append on each line :o)
Sqlyog must be trimming white spaces on each line which explains why its working.
Example:
$qr2="INSERT INTO wp_bp_activity
(
user_id,
(this stuff)component,
(is) `type`,
(a) `action`,
(problem) content,
primary_link,
item_id,....
You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).
Alternative 1 Temporarily change your working directory
import os
os.chdir("**Put here the directory where you have the file with your function**")
from file import function
os.chdir("**Put here the directory where you were working**")
Alternative 2 Add the directory where you have your function to sys.path
import sys
sys.path.append("**Put here the directory where you have the file with your function**")
from file import function
You can try this too WARNING: this you should not do but since the question is asking for infinite loop with no end...this is how you could do it.
while [[ 0 -ne 1 ]]; do echo "it's looping"; sleep 2; done
I am doing like this in MSSQL
Getting Monthly Data:
SELECT YEAR(DATE_CREATED) [Year], MONTH(DATE_CREATED) [Month],
DATENAME(MONTH,DATE_CREATED) [Month Name], SUM(Num_of_Pictures) [Pictures Count]
FROM pictures_table
GROUP BY YEAR(DATE_CREATED), MONTH(DATE_CREATED),
DATENAME(MONTH, DATE_CREATED)
ORDER BY 1,2
Getting Monthly Data using PIVOT:
SELECT *
FROM (SELECT YEAR(DATE_CREATED) [Year],
DATENAME(MONTH, DATE_CREATED) [Month],
SUM(Num_of_Pictures) [Pictures Count]
FROM pictures_table
GROUP BY YEAR(DATE_CREATED),
DATENAME(MONTH, DATE_CREATED)) AS MontlySalesData
PIVOT( SUM([Pictures Count])
FOR Month IN ([January],[February],[March],[April],[May],
[June],[July],[August],[September],[October],[November],
[December])) AS MNamePivot
After scouring different solutions on SO, I found the following to be the simplest and cleanest solution for populating a Spinner
with custom Objects
. Here's the full implementation:
public class User{
public int ID;
public String name;
@Override
public String toString() {
return this.name; // What to display in the Spinner list.
}
}
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:spinnerMode="dialog" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Spinner android:id="@+id/user" />
</LinearLayout>
List<User> users = User.all(); // This example assumes you're getting all Users but adjust it for your Class and needs.
ArrayAdapter userAdapter = new ArrayAdapter(this, R.layout.spinner, users);
Spinner userSpinner = (Spinner) findViewById(R.id.user);
userSpinner.setAdapter(userAdapter);
userSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Get the value selected by the user
// e.g. to store it as a field or immediately call a method
User user = (User) parent.getSelectedItem();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
.aku {
transition: all .2s ease-in-out;
}
.aku:hover {
transform: scale(1.1);
}
Short version: it's marking that hash as attached to the current package namespace (so that that package provides its class implementation).
Here's a tidy solution where you provide the target date as a Calendar object.
// Used to translate the Month value of a JQuery calendar to the month value expected by a Calendar.
private static final Map<String,Integer> MONTH_TO_CALENDAR_INDEX = new HashMap<String,Integer>();
static {
MONTH_TO_CALENDAR_INDEX.put("January", 0);
MONTH_TO_CALENDAR_INDEX.put("February",1);
MONTH_TO_CALENDAR_INDEX.put("March",2);
MONTH_TO_CALENDAR_INDEX.put("April",3);
MONTH_TO_CALENDAR_INDEX.put("May",4);
MONTH_TO_CALENDAR_INDEX.put("June",5);
MONTH_TO_CALENDAR_INDEX.put("July",6);
MONTH_TO_CALENDAR_INDEX.put("August",7);
MONTH_TO_CALENDAR_INDEX.put("September",8);
MONTH_TO_CALENDAR_INDEX.put("October",9);
MONTH_TO_CALENDAR_INDEX.put("November",10);
MONTH_TO_CALENDAR_INDEX.put("December",11);
}
// ====================================================================================================
// setCalendarPicker
// ====================================================================================================
/**
* Sets the value of specified web element while assuming the element is a JQuery calendar.
* @param byOpen The By phrase that locates the control that opens the JQuery calendar when clicked.
* @param byPicker The By phrase that locates the JQuery calendar.
* @param targetDate The target date that you want set.
* @throws AssertionError if the method is unable to set the date.
*/
public void setCalendarPicker(By byOpen, By byPicker, Calendar targetDate) {
// Open the JQuery calendar.
WebElement opener = driver.findElement(byOpen);
opener.click();
// Locate the JQuery calendar.
WebElement picker = driver.findElement(byPicker);
// Calculate the target and current year-and-month as an integer where value = year*12+month.
// The difference between the two is the number of months we have to move ahead or backward.
int targetYearMonth = targetDate.get(Calendar.YEAR) * 12 + targetDate.get(Calendar.MONTH);
int currentYearMonth = Integer.valueOf(picker.findElement(By.className("ui-datepicker-year")).getText()) * 12
+ Integer.valueOf(MONTH_TO_CALENDAR_INDEX.get(picker.findElement(By.className("ui-datepicker-month")).getText()));
// Calculate the number of months we need to move the JQuery calendar.
int delta = targetYearMonth - currentYearMonth;
// As a sanity check, let's not allow more than 10 years so that we don't inadvertently spin in a loop for zillions of months.
if (Math.abs(delta) > 120) throw new AssertionError("Target date is more than 10 years away");
// Push the JQuery calendar forward or backward as appropriate.
if (delta > 0) {
while (delta-- > 0) picker.findElement(By.className("ui-icon-circle-triangle-e")).click();
} else if (delta < 0 ){
while (delta++ < 0) picker.findElement(By.className("ui-icon-circle-triangle-w")).click();
}
// Select the day within the month.
String dayOfMonth = String.valueOf(targetDate.get(Calendar.DAY_OF_MONTH));
WebElement tableOfDays = picker.findElement(By.cssSelector("tbody:nth-child(2)"));
for (WebElement we : tableOfDays.findElements(By.tagName("td"))) {
if (dayOfMonth.equals(we.getText())) {
we.click();
// Send a tab to completely leave this control. If the next control the user will access is another CalendarPicker,
// the picker might not get selected properly if we stay on the current control.
opener.sendKeys("\t");
return;
}
}
throw new AssertionError(String.format("Unable to select specified day"));
}
CloseableHttpClient
is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated.
The HttpClient
is an interface for this class and other classes.
You should then use the CloseableHttpClient
in your code, and create it using the HttpClientBuilder
. If you need to wrap the client to add specific behaviour you should use request and response interceptors instead of wrapping with the HttpClient
.
This answer was given in the context of httpclient-4.3.
If you wish to match only lines beginning with stop use
^stop
If you wish to match lines beginning with the word stop followed by a space
^stop\s
Or, if you wish to match lines beginning with the word stop but followed by either a space or any other non word character you can use (your regex flavor permitting)
^stop\W
On the other hand, what follows matches a word at the beginning of a string on most regex flavors (in these flavors \w matches the opposite of \W)
^\w
If your flavor does not have the \w shortcut, you can use
^[a-zA-Z0-9]+
Be wary that this second idiom will only match letters and numbers, no symbol whatsoever.
Check your regex flavor manual to know what shortcuts are allowed and what exactly do they match (and how do they deal with Unicode.)
Using the "file" command may be useful for this:
#!/bin/bash
check_file(){
if [ -z "${1}" ] ;then
echo "Please input something"
return;
fi
f="${1}"
result="$(file $f)"
if [[ $result == *"cannot open"* ]] ;then
echo "NO FILE FOUND ($result) ";
elif [[ $result == *"directory"* ]] ;then
echo "DIRECTORY FOUND ($result) ";
else
echo "FILE FOUND ($result) ";
fi
}
check_file "${1}"
Output examples :
$ ./f.bash login
DIRECTORY FOUND (login: directory)
$ ./f.bash ldasdas
NO FILE FOUND (ldasdas: cannot open `ldasdas' (No such file or directory))
$ ./f.bash evil.php
FILE FOUND (evil.php: PHP script, ASCII text)
FYI: the answers above work but you can use -s to help in weird situations by checking for a valid file first:
#!/bin/bash
check_file(){
local file="${1}"
[[ -s "${file}" ]] || { echo "is not valid"; return; }
[[ -d "${file}" ]] && { echo "is a directory"; return; }
[[ -f "${file}" ]] && { echo "is a file"; return; }
}
check_file ${1}
From command line to view react version, npm view react version
Change this line:
The 2 should be 0. Every count starts at 0.
//Aboutme.Text = String.Format("{2}", reader.GetString(0));//wrong
//Aboutme.Text = String.Format("{0}", reader.GetString(0));//correct
No, Bootstrap does not introduce special considerations for disabling a drop-down.
<select id="xxx" name="xxx" class="input-medium" disabled>
or
<select id="xxx" name="xxx" class="input-medium" disabled="disabled">
will work. I prefer to give attributes values (as in the second form; in XHTML, attributes must have a value), but the HTML spec says:
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
The key differences between read-only and disabled:*
The Disabled attribute
The Read Only Attribute
<SELECT>
, <OPTION>
, and <BUTTON>
elements do not have readonly attributes (although thy both have disabled attributes)*-blatant plagiarism from http://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/
You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):
Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
Write-Host $_.IP1
Write-Host $_.IP2
...
}
Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:
---
# this is just to avoid a call to |default on each iteration
- set_fact:
postconf_d: {}
- name: 'get postfix default configuration'
command: 'postconf -d'
register: command
# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >
{{
postconf_d |
combine(
dict([ item.partition('=')[::2]|map('trim') ])
)
with_items: command.stdout_lines
This will give the following output (stripped for the example):
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": "hash:/etc/aliases, nis:mail.aliases",
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
Going even further, parse the lists in the 'value':
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >-
{% set key, val = item.partition('=')[::2]|map('trim') -%}
{% if ',' in val -%}
{% set val = val.split(',')|map('trim')|list -%}
{% endif -%}
{{ postfix_default_main_cf | combine({key: val}) }}
with_items: command.stdout_lines
...
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": [
"hash:/etc/aliases",
"nis:mail.aliases"
],
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
A few things to notice:
in this case it's needed to "trim" everything (using the >-
in YAML and -%}
in Jinja), otherwise you'll get an error like:
FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\" {u'...
obviously the {% if ..
is far from bullet-proof
in the postfix case, val.split(',')|map('trim')|list
could have been simplified to val.split(', ')
, but I wanted to point out the fact you will need to |list
otherwise you'll get an error like:
"|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
Hope this can help.
if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
{
// Key exists
}
else
{
// Key doesn't exist
}
Well, my solution is sort of hack, but it works and I am using it.
1vw = 1% of viewport width
1vh = 1% of viewport height
1vmin = 1vw or 1vh, whichever is smaller
1vmax = 1vw or 1vh, whichever is larger
h1 {
font-size: 5.9vw;
}
h2 {
font-size: 3.0vh;
}
p {
font-size: 2vmin;
}
Here's my personal favorite, a logical bomb :)
::32/64Bit Switch
ECHO %PROCESSOR_ARCHITECTURE%|FINDSTR AMD64>NUL && SET ARCH=AMD64 || SET ARCH=x86
ECHO %ARCH%
PAUSE
With the AND's (&&
) and OR's (||
) this is a IF THEN ELSE
Batch Construct.
With this command I had poor image quality
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4
With this, almost without delay, I got good image quality.
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi
For Mac and Linux try this function in your aliases_bash file (located in /etc/aliases_bash for Mac folks, be sure to use sudo vim /etc/aliases_bash)
function adbtx {
userinput="$(sed 's/ /%s/g' <<< $1)"
adb shell input text "${userinput}";
}
export -f adbtx
Then in the command line enter:
adbtx 'Your text to emulator input'
'Your text to emulator input' will be input on the emulator text field.
Kudos to Eliot for his substitution string for sed.
TL;DR: You can't do relative imports from the file you execute since __main__
module is not a part of a package.
Absolute imports - import something available on sys.path
Relative imports - import something relative to the current module, must be a part of a package
If you're running both variants in exactly the same way, one of them should work. Here is an example that should help you understand what's going on. Let's add another main.py
file with the overall directory structure like this:
.
./main.py
./ryan/__init__.py
./ryan/config.py
./ryan/test.py
And let's update test.py
to see what's going on:
# config.py
debug = True
# test.py
print(__name__)
try:
# Trying to find module in the parent package
from . import config
print(config.debug)
del config
except ImportError:
print('Relative import failed')
try:
# Trying to find module on sys.path
import config
print(config.debug)
except ModuleNotFoundError:
print('Absolute import failed')
# main.py
import ryan.test
Let's run test.py
first:
$ python ryan/test.py
__main__
Relative import failed
True
Here "test" is the __main__
module and doesn't know anything about belonging to a package. However import config
should work, since the ryan
folder will be added to sys.path
.
Let's run main.py
instead:
$ python main.py
ryan.test
True
Absolute import failed
And here test is inside of the "ryan" package and can perform relative imports. import config
fails since implicit relative imports are not allowed in Python 3.
Hope this helped.
P.S.: If you're sticking with Python 3 there is no more need for __init__.py
files.
If you want to get specific columns using with()
in laravel eloquent then you can use code as below which is originally answered by @Adam in his answer here in response of this same question :
Post::with('user:id,username')->get();
So i have used it in my code but it was giving me error of 1052: Column 'id' in field list is ambiguous
, so if you guys are also facing same problem
Then for solving it you have to specify table name before the id column in with()
method as below code:
Post::with('user:user.id,username')->get();
Could you nest a div with margin-left: 50px;
and margin-right: 50px;
inside a <div>
with width: 100%;
?
It's almost always safer to use a library like lodash simply because of all the issues with cross-browser compatibilities and efficiency.
Efficiency because you can be guaranteed that at any given time, a hugely popular library like underscore will have the most efficient method of accomplishing a utility function like this.
_.includes([1, 2, 3], 3); // returns true
If you're concerned about the bulk that's being added to your application by including the whole library, know that you can include functionality separately:
var includes = require('lodash/collections/includes');
NOTICE: With older versions of lodash, this was _.contains()
rather than _.includes()
.
According to this snippet here, this approach should be good for long strings:
private string StringToHex(string hexstring)
{
StringBuilder sb = new StringBuilder();
foreach (char t in hexstring)
{
//Note: X for upper, x for lower case letters
sb.Append(Convert.ToInt32(t).ToString("x"));
}
return sb.ToString();
}
usage:
string result = StringToHex("Hello world"); //returns "48656c6c6f20776f726c64"
Another approach in one line
string input = "Hello world";
string result = String.Concat(input.Select(x => ((int)x).ToString("x")));
To answer the second part of your question - there are no pointers in PHP.
When working with objects, you generally pass by reference rather than by value - so in some ways this operates like a pointer, but is generally completely transparent.
This does depend on the version of PHP you are using.
I did a log file which prints data into text file using "Winston" log. The source code is here below,
const { createLogger, format, transports } = require('winston');
var fs = require('fs')
var logger = fs.createWriteStream('Data Log.txt', {`
flags: 'a'
})
const os = require('os');
var sleep = require('system-sleep');
var endOfLine = require('os').EOL;
var t = ' ';var s = ' ';var q = ' ';
var array1=[];
var array2=[];
var array3=[];
var array4=[];
array1[0] = 78;`
array1[1] = 56;
array1[2] = 24;
array1[3] = 34;
for (var n=0;n<4;n++)
{
array2[n]=array1[n].toString();
}
for (var k=0;k<4;k++)
{
array3[k]=Buffer.from(' ');
}
for (var a=0;a<4;a++)
{
array4[a]=Buffer.from(array2[a]);
}
for (m=0;m<4;m++)
{
array4[m].copy(array3[m],0);
}
logger.write('Date'+q);
logger.write('Time'+(q+' '))
logger.write('Data 01'+t);
logger.write('Data 02'+t);
logger.write('Data 03'+t);
logger.write('Data 04'+t)
logger.write(endOfLine);
logger.write(endOfLine);
enter code here`enter code here`
}
function mydata() //user defined function
{
logger.write(datechar+s);
logger.write(timechar+s);
for ( n = 0; n < 4; n++)
{
logger.write(array3[n]);
}
logger.write(endOfLine);
}
for (;;)
}
var now = new Date();
var dateFormat = require('dateformat');
var date = dateFormat(now,"isoDate");
var time = dateFormat(now, "h:MM:ss TT ");
var datechar = date.toString();
var timechar = time.toString();
mydata();
sleep(5*1000);
}
One more way would be to use dumpbin from the Visual Studio tools on DLL and look for the appropriate output
dumpbin.exe /HEADERS <your dll path>
FILE HEADER VALUE
14C machine (x86)
4 number of sections
5885AC36 time date stamp Mon Jan 23 12:39:42 2017
0 file pointer to symbol table
0 number of symbols
E0 size of optional header
2102 characteristics
Executable
32 bit word machine
DLL
Note: Above o/p is for 32bit dll
One more useful option with dumpbin.exe is /EXPORTS, It will show you the function exposed by the dll
dumpbin.exe /EXPORTS <PATH OF THE DLL>
I found a faster way of embedding:
2018 update:
For AdMob users, this causes AdMob version 12.0.0 (currently last version). It wrongly requests READ_PHONE_STATE permission, so even if your app doesn't require READ_PHONE_STATE permission in manifest, you won't be able to update your app in the Google Play Console (it will tell you to create a privacy policy page for your app, because your app requires this permission).
See this: https://developers.google.com/android/guides/releases#march_20_2018_-_version_1200
Also, they wrote they will publish an update to 12.0.1 fixing this soon.
Why Pandas ? Have you tried Standard Python ?
The use of standard library python. Pandas is subject to frequent updates, even with the recent release of the stable version.
Using the standard python library your code will always run.
One way of doing it is to have an idea of the way you want your data to be stored , and which questions you want to solve regarding the data. Then draw a schema of how you can organise your data (think tables) that will help you query the data, not necessarily normalisation.
You can make good use of :
Ram and HDD is becoming cheaper and cheaper with time and standard python 3 is widely available and stable.
The fondamental question you are trying to solve is "how to query large sets of data ?". The hdfs architecture is more or less what I am describing here (data modelling with data being stored on disk).
Let's say you have 1000 petabytes of data, there no way you will be able to store it in Dask or Pandas, your best chances here is to store it on disk and process it with generators.
Because the script will get executed first.. When the script will get executed, at that time controls are not getting loaded. So after loading controls you write a script.
It will work.
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
the other answers help to understand how to maintain such a session. Additionally, I want to provide a class which keeps the session maintained over different runs of a script (with a cache file). This means a proper "login" is only performed when required (timout or no session exists in cache). Also it supports proxy settings over subsequent calls to 'get' or 'post'.
It is tested with Python3.
Use it as a basis for your own code. The following snippets are release with GPL v3
import pickle
import datetime
import os
from urllib.parse import urlparse
import requests
class MyLoginSession:
"""
a class which handles and saves login sessions. It also keeps track of proxy settings.
It does also maintine a cache-file for restoring session data from earlier
script executions.
"""
def __init__(self,
loginUrl,
loginData,
loginTestUrl,
loginTestString,
sessionFileAppendix = '_session.dat',
maxSessionTimeSeconds = 30 * 60,
proxies = None,
userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',
debug = True,
forceLogin = False,
**kwargs):
"""
save some information needed to login the session
you'll have to provide 'loginTestString' which will be looked for in the
responses html to make sure, you've properly been logged in
'proxies' is of format { 'https' : 'https://user:pass@server:port', 'http' : ...
'loginData' will be sent as post data (dictionary of id : value).
'maxSessionTimeSeconds' will be used to determine when to re-login.
"""
urlData = urlparse(loginUrl)
self.proxies = proxies
self.loginData = loginData
self.loginUrl = loginUrl
self.loginTestUrl = loginTestUrl
self.maxSessionTime = maxSessionTimeSeconds
self.sessionFile = urlData.netloc + sessionFileAppendix
self.userAgent = userAgent
self.loginTestString = loginTestString
self.debug = debug
self.login(forceLogin, **kwargs)
def modification_date(self, filename):
"""
return last file modification date as datetime object
"""
t = os.path.getmtime(filename)
return datetime.datetime.fromtimestamp(t)
def login(self, forceLogin = False, **kwargs):
"""
login to a session. Try to read last saved session from cache file. If this fails
do proper login. If the last cache access was too old, also perform a proper login.
Always updates session cache file.
"""
wasReadFromCache = False
if self.debug:
print('loading or generating session...')
if os.path.exists(self.sessionFile) and not forceLogin:
time = self.modification_date(self.sessionFile)
# only load if file less than 30 minutes old
lastModification = (datetime.datetime.now() - time).seconds
if lastModification < self.maxSessionTime:
with open(self.sessionFile, "rb") as f:
self.session = pickle.load(f)
wasReadFromCache = True
if self.debug:
print("loaded session from cache (last access %ds ago) "
% lastModification)
if not wasReadFromCache:
self.session = requests.Session()
self.session.headers.update({'user-agent' : self.userAgent})
res = self.session.post(self.loginUrl, data = self.loginData,
proxies = self.proxies, **kwargs)
if self.debug:
print('created new session with login' )
self.saveSessionToCache()
# test login
res = self.session.get(self.loginTestUrl)
if res.text.lower().find(self.loginTestString.lower()) < 0:
raise Exception("could not log into provided site '%s'"
" (did not find successful login string)"
% self.loginUrl)
def saveSessionToCache(self):
"""
save session to a cache file
"""
# always save (to update timeout)
with open(self.sessionFile, "wb") as f:
pickle.dump(self.session, f)
if self.debug:
print('updated session cache-file %s' % self.sessionFile)
def retrieveContent(self, url, method = "get", postData = None, **kwargs):
"""
return the content of the url with respect to the session.
If 'method' is not 'get', the url will be called with 'postData'
as a post request.
"""
if method == 'get':
res = self.session.get(url , proxies = self.proxies, **kwargs)
else:
res = self.session.post(url , data = postData, proxies = self.proxies, **kwargs)
# the session has been updated on the server, so also update in cache
self.saveSessionToCache()
return res
A code snippet for using the above class may look like this:
if __name__ == "__main__":
# proxies = {'https' : 'https://user:pass@server:port',
# 'http' : 'http://user:pass@server:port'}
loginData = {'user' : 'usr',
'password' : 'pwd'}
loginUrl = 'https://...'
loginTestUrl = 'https://...'
successStr = 'Hello Tom'
s = MyLoginSession(loginUrl, loginData, loginTestUrl, successStr,
#proxies = proxies
)
res = s.retrieveContent('https://....')
print(res.text)
# if, for instance, login via JSON values required try this:
s = MyLoginSession(loginUrl, None, loginTestUrl, successStr,
#proxies = proxies,
json = loginData)
An alternative :
// shape
var shape = function(type){
this.type = type;
}
shape.prototype.display = function(){
console.log(this.type);
}
// circle
var circle = new shape('circle');
// override
circle.display = function(a,b){
// call implementation of the super class
this.__proto__.display.apply(this,arguments);
}
You can get the path of sdcard from this code:
File extStore = Environment.getExternalStorageDirectory();
Then specify the foldername and file name
for e.g:
"/LazyList/"+serialno.get(position).trim()+".jpg"
Access Token
for Mobile Number and Country Code
(Server Side OR Client Side)You can get the mobile number
with your access_token
with this API
https://graph.accountkit.com/v1.1/me/?access_token=xxxxxxxxxxxx. Maybe, once you have the mobile number
and the id
, you can work with it to verify the user with your server & database
.
xxxxxxxxxx
above is the Access Token
{
"id": "61940819992708",
"phone": {
"number": "+91XX82923912",
"country_prefix": "91",
"national_number": "XX82923912"
}
}
Auth Code
for Access Token
(Server Side)If you have an Auth Code
instead, you can first get the Access Token
with this API
- https://graph.accountkit.com/v1.1/access_token?grant_type=authorization_code&code=xxxxxxxxxx&access_token=AA|yyyyyyyyyy|zzzzzzzzzz
xxxxxxxxxx
, yyyyyyyyyy
and zzzzzzzzzz
above are the Auth Code
, App ID
and App Secret
respectively.
{
"id": "619XX819992708",
"access_token": "EMAWdcsi711meGS2qQpNk4XBTwUBIDtqYAKoZBbBZAEZCZAXyWVbqvKUyKgDZBniZBFwKVyoVGHXnquCcikBqc9ROF2qAxLRrqBYAvXknwND3dhHU0iLZCRwBNHNlyQZD",
"token_refresh_interval_sec": XX92000
}
server-side
since the API
requires the APP Secret
which is not meant to be shared
for security reasons
.Good Luck.
Use pg_dump, and later psql or pg_restore - depending whether you choose -Fp or -Fc options to pg_dump.
Example of usage:
ssh production
pg_dump -C -Fp -f dump.sql -U postgres some_database_name
scp dump.sql development:
rm dump.sql
ssh development
psql -U postgres -f dump.sql
On Chrome this has proven to work well for me.
<a href="newsletter_01.pdf" target="_new">Read more</a>
asarray(x)
is like array(x, copy=False)
Use asarray(x)
when you want to ensure that x
will be an array before any other operations are done. If x
is already an array then no copy would be done. It would not cause a redundant performance hit.
Here is an example of a function that ensure x
is converted into an array first.
def mysum(x):
return np.asarray(x).sum()
This worked well for me.
<Style x:Key="TransparentStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border>
<Border.Style>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="DarkGoldenrod"/>
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<Grid Background="Transparent">
<ContentPresenter></ContentPresenter>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Button Style="{StaticResource TransparentStyle}" VerticalAlignment="Top" HorizontalAlignment="Right" Width="25" Height="25"
Command="{Binding CloseWindow}">
<Button.Content >
<Grid Margin="0 0 0 0">
<Path Data="M0,7 L10,17 M0,17 L10,7" Stroke="Blue" StrokeThickness="2" HorizontalAlignment="Center" Stretch="None" />
</Grid>
</Button.Content>
</Button>
For .NET Core 2.2 you can publish the application and set the target to be a self-contained executable.
In Visual Studio right click your console application project. Select publish to folder and set the profile settings like so:
You'll find your compiled code with the .exe in the publish folder.
Note: This answer refers/adds to Sotirios Delimanolis's answer and comment.
I tried to get it to work with Map<Class, ParameterizedTypeReference<ResponseWrapper<?>>>
, as indicated in Sotirios's comment, but couldn't without an example.
In the end, I dropped the wildcard and parametrisation from ParameterizedTypeReference and used raw types instead, like so
Map<Class<?>, ParameterizedTypeReference> typeReferences = new HashMap<>();
typeReferences.put(MyClass1.class, new ParameterizedTypeReference<ResponseWrapper<MyClass1>>() { });
typeReferences.put(MyClass2.class, new ParameterizedTypeReference<ResponseWrapper<MyClass2>>() { });
...
ParameterizedTypeReference typeRef = typeReferences.get(clazz);
ResponseEntity<ResponseWrapper<T>> response = restTemplate.exchange(
uri,
HttpMethod.GET,
null,
typeRef);
and this finally worked.
If anyone has an example with parametrisation, I'd be very grateful to see it.
$(this).find('td')
will give you an array of td's in the tr.
roenving is correct BUT you need to change the test to:
if(element.nodeType == 1) { //code }
because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp
The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.
http://msdn.microsoft.com/en-us/library/ms378526.aspx
sqljdbc4.jar class library requires a Java Runtime Environment (JRE) of version 6.0 or later.
I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).
The following kills all the processes created by this user:
kill -9 -1
First off:
public class ProfileCollection implements Iterable<Profile> {
Second:
return m_Profiles.get(m_ActiveProfile);
Let's expand defer()
from Dario to be more reusable.
function defer(toWaitFor, method) {
if (window[toWaitFor]) {
method();
} else {
setTimeout(function () { defer(toWaitFor, method) }, 50);
}
}
Which is then run:
function waitFor() {
defer('jQuery', () => {console.log('jq done')});
defer('utag', () => {console.log('utag done')});
}
The essential difference between /*
and /
is that a servlet with mapping /*
will be selected before any servlet with an extension mapping (like *.html
), while a servlet with mapping /
will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").
In particular, a /*
mapping will always be selected before a /
mapping. Having either prevents any requests from reaching the container's own default servlet.
Either will be selected only after servlet mappings which are exact matches (like /foo/bar
) and those which are path mappings longer than /*
(like /foo/*
). Note that the empty string mapping is an exact match for the context root (http://host:port/context/
).
See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.
Decimal has a fixed precision while float has variable precision.
EDIT (failed to read entire question): Float(53) (aka real) is a double-precision (64-bit) floating point number in SQL Server. Regular Float is a single-precision (32-bit) floating point number. Double is a good combination of precision and simplicty for a lot of calculations. You can create a very high precision number with decimal -- up to 136-bit -- but you also have to be careful that you define your precision and scale correctly so that it can contain all your intermediate calculations to the necessary number of digits.
This function will round either be order of magnitude (right to left) or by digits the same way that format treats floating point decimal places (left to right:
def intround(n, p):
''' rounds an intger. if "p"<0, p is a exponent of 10; if p>0, left to right digits '''
if p==0: return n
if p>0:
ln=len(str(n))
p=p-ln+1 if n<0 else p-ln
return (n + 5 * 10**(-p-1)) // 10**-p * 10**-p
>>> tgt=5555555
>>> d=2
>>> print('\t{} rounded to {} places:\n\t{} right to left \n\t{} left to right'.format(
tgt,d,intround(tgt,-d), intround(tgt,d)))
Prints
5555555 rounded to 2 places:
5555600 right to left
5600000 left to right
You can also use Decimal class:
import decimal
import sys
def ri(i, prec=6):
ic=long if sys.version_info.major<3 else int
with decimal.localcontext() as lct:
if prec>0:
lct.prec=prec
else:
lct.prec=len(str(decimal.Decimal(i)))+prec
n=ic(decimal.Decimal(i)+decimal.Decimal('0'))
return n
On Python 3 you can reliably use round with negative places and get a rounded integer:
def intround2(n, p):
''' will fail with larger floating point numbers on Py2 and require a cast to an int '''
if p>0:
return round(n, p-len(str(n))+1)
else:
return round(n, p)
On Python 2, round will fail to return a proper rounder integer on larger numbers because round always returns a float:
>>> round(2**34, -5)
17179900000.0 # OK
>>> round(2**64, -5)
1.84467440737096e+19 # wrong
The other 2 functions work on Python 2 and 3
I have implemented @satchmorun's suggestion here: https://github.com/andresesfm/angular-underscore-module
To use it:
Make sure you have included underscore.js in your project
<script src="bower_components/underscore/underscore.js">
Get it:
bower install angular-underscore-module
Add angular-underscore-module.js to your main file (index.html)
<script src="bower_components/angular-underscore-module/angular-underscore-module.js"></script>
Add the module as a dependency in your App definition
var myapp = angular.module('MyApp', ['underscore'])
To use, add as an injected dependency to your Controller/Service and it is ready to use
angular.module('MyApp').controller('MyCtrl', function ($scope, _) {
...
//Use underscore
_.each(...);
...
Intent intent = new Intent(activity1.this, activity2.class);
intent.putExtra("message", message);
startActivity(intent);
In activity2, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
fast onliner for 'dictionary'-objects:
function isEmptyDict(d){for (var k in d) return false; return true}
Here is a screenshot of me fixing this. I've encountered it many times, and it's always due to this config-related jazz:
Event Log
(bottom right)Configure
of the Android Framework detected notificationIf you do this and your icon still isn't lit up, then you probably need to set up the emulator still. I would recommend investigating the SDK Manager
if so.
Well using find is the best option here
just simply use like this
$(".class").click(function(){
$("this").find('.subclass').css("visibility","visible");
})
and if there are many classes with the same name class its always better to give the class name of parent class like this
$(".parent .class").click(function(){
$("this").find('.subclass').css("visibility","visible");
})
Another option, in addition to using OPENQUERY and xp_cmdshell, is to use SQLCLR (SQL Server's "CLR Integration" feature). Not only is the SQLCLR option more secure than those other two methods, but there is also the potential benefit of being able to call the stored procedure in the current session such that it would have access to any session-based objects or settings, such as:
This can be achieved by using "context connection = true;" as the ConnectionString. Just keep in mind that all other restrictions placed on T-SQL User-Defined Functions will be enforced (i.e. cannot have any side-effects).
If you use a regular connection (i.e. not using the context connection), then it will operate as an independent call, just like it does when using the OPENQUERY and xp_cmdshell methods.
HOWEVER, please keep in mind that if you will be using a function that calls a stored procedure (regardless of which of the 3 noted methods you use) in a statement that affects more than 1 row, then the behavior cannot be expected to run once per row. As @MartinSmith mentioned in a comment on @MatBailie's answer, the Query Optimizer does not guarantee either the timing or number of executions of functions. But if you are using it in a SET @Variable = function();
statement or SELECT * FROM function();
query, then it should be ok.
An example of using a .NET / C# SQLCLR user-defined function to execute a stored procedure is shown in the following article (which I wrote):
Stairway to SQLCLR Level 2: Sample Stored Procedure and Function
To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.
You must use std namespace. If this code in main.cpp you should write
using namespace std;
If this declaration is in header, then you shouldn't include namespace and just write
std::string level;
For me both answers worked.
<Context docBase="/tmp/wars/hpong" path="" reloadable="true" />
<Service name="Catalina2"> <Connector port="8070" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8743" /> <Engine name="Catalina2" defaultHost="localhost"> <Host name="localhost" unpackWARs="true" autoDeploy="true"> <Context path="" docBase="/tmp/wars/hpong" reloadable="true"> <WatchedResource>WEB-INF/web.xml</WatchedResource> </Context> </Host> </Engine> </Service>
Note: when you declare docBase under context then ignore appBase at Host.
ROOT.war
and place it under webapps. So now unmatched url requests from other wars(contextpaths) will land into this war. This is better way to handle ROOT ("/**") context path. The second option is (double) loading the wars from Webapps folder as well. Also it only needs uncompressed war folder which is a headache.
ES2015 UPDATE
ES2015 have String#includes
method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true
if the needle is found in haystack else returns false
.
ng-if="haystack.includes(needle)"
Here, needle
is the string that is to be searched in haystack
.
See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.
You can use String#indexOf
to get the index of the needle in haystack.
The index can be compared with -1
to check whether needle is found in haystack.
ng-if="haystack.indexOf(needle) > -1"
For Angular(2+)
*ngIf="haystack.includes(needle)"
find and replace:
utf8mb4_unicode_520_ci
with
utf8_general_ci
in whole sql file
The object doesn't have 30 properties. It has one, which is an array that has 30 elements. You need the number of elements in that array.
In my case it was pretty much what Mayank Shukla's top answer says. The only detail was that my state was lacking completely the property I was defining.
For example, if you have this state:
state = {
"a" : "A",
"b" : "B",
}
If you're expanding your code, you might want to add a new prop so, someplace else in your code you might create a new property c
whose value is not only undefined on the component's state but the property itself is undefined.
To solve this just make sure to add c
into your state and give it a proper initial value.
e.g.,
state = {
"a" : "A",
"b" : "B",
"c" : "C", // added and initialized property!
}
Hope I was able to explain my edge case.
I run it (eg.): top -b | egrep -w 'java|mysqld'
You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?
Steps to fix this issue (In Windows) -
%appdata%
press enter %appdata%
> npm folderng.cmd
in your favorite editor--max_old_space_size=8192
to the IF and ELSE blockYour node.cmd
file looks like this after the change:
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
)
\l - Display database
\c - Connect to database
\dn - List schemas
\dt - List tables inside public schemas
\dt schema1. - List tables inside particular schemas. For eg: 'schema1'.
I have had the same problem and thanks to the posts here I have solved it. I knew that I have around a hundred files and I needed to run it for *.js files only.
find . -type f -name '*.js' -print0 | xargs -0 dos2unix
Thank you all for your help.
Based on what you provided, it is pretty simple for what you need to do and you even have a number of ways to go about doing it. You'll need something that'll let you post a body with your request. Almost any programming language can do this as well as command line tools like cURL.
One you have your tool decided, you'll need to create your JSON body and submit it to the server.
An example using cURL would be (all in one line, minus the \
at the end of the first line):
curl -v -H "Content-Type: application/json" -X POST \
-d '{"name":"your name","phonenumber":"111-111"}' http://www.abc.com/details
The above command will create a request that should look like the following:
POST /details HTTP/1.1
Host: www.abc.com
Content-Type: application/json
Content-Length: 44
{"name":"your name","phonenumber":"111-111"}
I would suggest you to checkout https://vlio20.github.io/angular-datepicker/
I had the same problem. My fix was to add headers to my PHP script which are present only when in dev environment.
This allows cross-domain requests:
header("Access-Control-Allow-Origin: *");
This tells the preflight request that it is OK for the client to send any headers it wants:
header("Access-Control-Allow-Headers: *");
This way there is no need to modify the request.
If you have sensitive data in your dev database that might potentially be leaked, then you might think twice about this.
How about:
firstNonNull = FluentIterable.from(
Lists.newArrayList( a, b, c, ... ) )
.firstMatch( Predicates.notNull() )
.or( someKnownNonNullDefault );
Java ArrayList conveniently allows null entries and this expression is consistent regardless of the number of objects to be considered. (In this form, all the objects considered need to be of the same type.)
Use this regular expression to match square brackets or single quotes:
/[\[\]']+/g
Replace with the empty string.
console.log("['abc','xyz']".replace(/[\[\]']+/g,''));
_x000D_
Here is the code that you need to put in your Account Controller in MVC5 and later to get the list of roles of a user:
csharp
public async Task<ActionResult> RoleAdd(string UserID)
{
return View(await
UserManager.GetRolesAsync(UserID)).OrderBy(s => s).ToList());
}
There is no need to use Roles.GetRolesForUser()
and enable the Role Manager Feature.
for mariadb install libmariadbclient-dev instead of libmysqlclient-dev
sudo apt-get install libmariadbclient-dev
Making more general the @showdev answer.
var getObjectByValue = function (array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
};
Example:
getObjectByValue(data, "code", "DZ" );
It's method syntax (which I find easier to read) but this might do it
Updated post comment
Use .FirstOrDefault()
instead of .First()
With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment
var groupByReference = context.Measurements
.GroupBy(m => m.Reference)
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
// Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
// .ThenBy(x => x.Avg)
.Take(numOfEntries)
.ToList();
First of all, install PrtSc Library using pip3.
import PrtSc.PrtSc as Screen
screenshot=PrtSc.PrtSc(True,'filename.png')
Update for PHP 7 (thanks shock_gone_wild)
PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:
$var = $var ?? "default";
Before PHP 7
No, there is no special operator or special syntax for this. However, you could use the ternary operator:
$var = isset($var) ? $var : "default";
Or like this:
isset($var) ?: $var = 'default';
Setting the -fx-text-fill
works for me.
See below:
if (passed) {
resultInfo.setText("Passed!");
resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
resultInfo.setText("Failed!");
resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}
if I got it right, you can try
for item in [x for x in checklist if x not in mylist]:
print (item)
I have no idea about the year of publication of the question; it might be old now. So, I expect my answer to be more of a reference for future similar questions after my post.
I don't know if anybody out there has already given an answer similar to the one I am about to give, which might result -I think- being the simplest, most direct and most effective: If someone has already given it, I apologize, but I haven't seen it. Here, my answer using CStr instead of TEXT:
Asuming cell A1 contains a date, and using VBA code:
Dim strDate As String 'Convert to string the value contained in A1 (a date) strDate = CStr([A1].Value)
You can, thereafter, manipulate it as any ordinary string using string functions (MID, LEFT, RIGHT, LEN, CONCATENATE (&), etc.)
$('.update-cart').click(function(e) {
updateCartWidget();
e.stopPropagation();
e.preventDefault();
});
$('.update-cart').click(function() {
updateCartWidget();
return false;
});
The following methods achieve the exact same thing.
Yes, you can do this use this below code it may help you.
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
display : block;_x000D_
padding : 10px;_x000D_
text-align : center;_x000D_
border: 5px solid #000;_x000D_
margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
<div class="childDiv1">_x000D_
First Div Child_x000D_
</div>_x000D_
<div class="childDiv2">_x000D_
Second Div Child_x000D_
</div>_x000D_
<div class="childDiv3">_x000D_
Third Div Child_x000D_
</div>_x000D_
<div class="childDiv4">_x000D_
Fourth Div Child_x000D_
</div>_x000D_
</div>
_x000D_
Yes, it will be possible and it won't be that difficult. All what's needed at this point to start with is some kind of converter that will turn MSIL into Dalvik bytecode. Since both formats are open-sourced and well documented, there won't be any problem with it.
So, writing Android applications in C# or VB.NET will be possible, question is how much of .NET framework standard libraries will be supported. But that's another issue.
Oscar Reyes wrote:
I'm pretty sure if google hand ANY interest in .net, they would've design something while Android was in the first stages, not now when they are in production stages. I don't mean it is not possible, what I'm saying is they're not interested. Maybe in mmm hhhh 10 yrs.
Actually what they've already designed is very compatible with Java and .NET
They can't do everything at once, but if you look into Android SDK, there is a tool called dx. This tool converts Java bytecode into Dalvik bytecode, so in other words, you can run programs written in Java on Android with no effort today. Now the same tool is needed for .NET.
Considering how similar .NET and Java are, it's really a matter of time.
ddimitrov wrote:
The .Net->Java->Dalvik translation can be done even now (http://dev.mainsoft.com/), but I think you underestimate the lack of .Net libraries. Of course somebody can port Mono, but it's definitely a non-trivial effort.
No need to port Mono. Android already has VM and some basic API. All what's needed is CIL->Dalvik converter and tiny .NET wrapper for Android API (and maybe some basic implementation of some standard .NET classes). That's it.
Update: .NET already works on Android - you will need product called Monodroid (http://monodroid.net) as stated above.
You'll see people using the Timer class to do this. Unfortunately, it isn't always accurate. Your best bet is to get the system time when the user enters input, calculate a target system time, and check if the system time has exceeded the target system time. If it has, then break out of the loop.
INSERT INTO Destination SELECT * FROM Source;
See SQL As Understood By SQLite: INSERT for a formal definition.
The ScriptManager
is a web control that you register in the page using
<asp:ScriptManager ID="ScriptManger1" runat="Server" />
inside the Form tag
I fixed it using following configuration.
Listen 85
<VirtualHost *:85>
DocumentRoot "C:/xampp/htdocs/LaraBlog/public"
<Directory "C:/xampp/htdocs/CommunicationApp/public">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View decor = getWindow().getDecorView();
if (shouldChangeStatusBarTintToDark) {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
} else {
// We want to change tint color to white again.
// You can also record the flags in advance so that you can turn UI back completely if
// you have set other flags before, such as translucent or full screen.
decor.setSystemUiVisibility(0);
}
}
Column(
children: <Widget>[
Text('Leading text widget'),
ListView(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: <Widget>[
ListTile(
leading: Icon(Icons.map),
title: Text('Map'),
),
ListTile(
leading: Icon(Icons.photo_album),
title: Text('Album'),
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Phone'),
),
],
),
Text('More widget'),
],
);
just use
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
properties in listView
This issue of circular dependencies of two module
Module 1:import Module 2
Module 2:import Module 1
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
How about:
return (returnValue == "1");
or as suggested below:
return (returnValue != "0");
The correct one will depend on what you are looking for as a success result.
Use SemaphoreSlim.WaitAsync
method.
await mySemaphoreSlim.WaitAsync();
try {
await Stuff();
} finally {
mySemaphoreSlim.Release();
}
For those we need the Swift version of the answer of @Jeff Thompson:
// Get a current time for where you want to start measuring from
var date = NSDate()
// do work...
// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
var timePassed_ms: Double = date.timeIntervalSinceNow * -1000.0
I hope this help you.
<?php
$names = array("firstname"=>"maurice",
"lastname"=>"muteti",
"contact"=>"7844433339");
foreach ($names as $name => $value) {
echo $name." ".$value."</br>";
}
print_r($names);
?>
The first option gives you more flexibilty:
var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);
And of course .html('*')
overrides the content while .append('*')
doesn't, but I guess, this wasn't your question.
Another good practice is prefixing your jQuery variables with $
:
Is there any specific reason behind using $ with variable in jQuery
Placing quotes around the "class"
property name will make it more compatible with less flexible browsers.
There are two ways to add the NOT NULL Columns to the table :
ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''
ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''
It means that you have to have PHP installed as a module in Apache, instead of starting it as a CGI script.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/tct_postpone_hour"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:gravity="center_vertical|center_horizontal"
android:text="1"
android:textSize="24dp" />
</RelativeLayout>
makes number one align in center both horizontal and vertical.
In my own experience where I needed to try and find out what some old VB6 programs were doing, I turned to Process Explorer (Sysinternals). I did the following:
This didn't show the actual functions, but it listed their names, folders of where files were being copied from and to and if it accessed a DB it would also display the connection string. Enough to help you get an idea, but may be useless for complex programs. The programs I was looking at were pretty basic (no pun intended).
YMMV.
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
I had the same problem and none of suggestions helped. But I found an interesting reason for that, on a physical device, Galaxy Tab.
When USB storage is on, external storage read and write permissions don't have any effect. Just turn off USB storage, and with the correct permissions, you'll have the problem solved.
Python doesn't really have either concept.
It uses duck typing, which removed the need for interfaces (at least for the computer :-))
Python <= 2.5: Base classes obviously exist, but there is no explicit way to mark a method as 'pure virtual', so the class isn't really abstract.
Python >= 2.6: Abstract base classes do exist (http://docs.python.org/library/abc.html). And allow you to specify methods that must be implemented in subclasses. I don't much like the syntax, but the feature is there. Most of the time it's probably better to use duck typing from the 'using' client side.
best way is
button.setBackgroundResource(android.R.drawable.ic_delete);
OR this for Drawable left and something like that for right etc.
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
and
getResources().getDrawable()
is now deprecated
There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too hard.
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
While there are two excellent answers telling you how to do it, I feel that another answer is missing: In most cases you shouldn't do it at all.
Arrays are cumbersome, in most cases you are better off using the Collection API.
With Collections, you can add and remove elements and there are specialized Collections for different functionality (index-based lookup, sorting, uniqueness, FIFO-access, concurrency etc.).
While it's of course good and important to know about Arrays and their usage, in most cases using Collections makes APIs a lot more manageable (which is why new libraries like Google Guava hardly use Arrays at all).
So, for your scenario, I'd prefer a List of Lists, and I'd create it using Guava:
List<List<String>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("abc","def","ghi"));
listOfLists.add(Lists.newArrayList("jkl","mno","pqr"));
I ran into this problem too, a lot of people seem to recommend force reloading your page, which won't fix the issue in cases such as if you're running it on a server. I believe the optimal solution in this scenario is to timestamp your css.
<link rel="stylesheet" href="{% static 'home/radioStyles.css' %}?{% now 'U' %}" type="text/css"/>
Where adding ?{% now 'U' %} to the end of your css file would fix this issue.
<link rel="stylesheet" type="text/css" href="style.css?Wednesday 2nd February 2020 12PM" />
Where ?Wednesday 2nd February 2020 12PM
(current date) seems to fix the issue, I also noticed just putting the time fixes it too.
Simple jQuery solution:
$("textarea").keyup(function() {
var scrollHeight = $(this).prop('scrollHeight') - parseInt($(this).css("paddingTop")) - parseInt($(this).css("paddingBottom"));
if (scrollHeight > $(this).height()) {
$(this).height(scrollHeight + "px");
}
});
HTML:
<textarea rows="2" style="padding: 20px; overflow: hidden; resize: none;"></textarea>
Overflow should be hidden. Resize is none if you do not want to make it resizable by mouse.
You could parse the JSON to an object, then create your malformed JSON from the ajavscript object. This may not be the best performance-wise, tho.
Otherwise, if you only need to make very small changes to the string, just treat it as a string, and mangle it using standard javascript.
Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.
Try the following code:
var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()
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" );
}
}
Using DatabaseUtils.queryNumEntries()
:
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
or (more inefficiently)
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
In Activity:
int profile_counts = db.getProfilesCount();
db.close();
private String[] getStringArray(JSONArray jsonArray) throws JSONException {_x000D_
if (jsonArray != null) {_x000D_
String[] stringsArray = new String[jsonArray.length()];_x000D_
for (int i = 0; i < jsonArray.length(); i++) {_x000D_
stringsArray[i] = jsonArray.getString(i);_x000D_
}_x000D_
return stringsArray;_x000D_
} else_x000D_
return null;_x000D_
}
_x000D_
Recently I learned of the following syntax:
DELETE (SELECT *
FROM productfilters pf
INNER JOIN product pr
ON pf.productid = pr.id
WHERE pf.id >= 200
AND pr.NAME = 'MARK')
I think it looks much cleaner then other proposed code.
According to this article application/xml is preferred.
EDIT
I did a little follow-up on the article.
The author claims that the encoding declared in XML processing instructions, like:
<?xml version="1.0" encoding="UTF-8"?>
can be ignored when text/xml
media type is used.
They support the thesis with the definition of text/*
MIME type family specification in RFC 2046, specifically the following fragment:
4.1.2. Charset Parameter
A critical parameter that may be specified in the Content-Type field
for "text/plain" data is the character set. This is specified with a
"charset" parameter, as in:
Content-type: text/plain; charset=iso-8859-1
Unlike some other parameter values, the values of the charset
parameter are NOT case sensitive. The default character set, which
must be assumed in the absence of a charset parameter, is US-ASCII.
The specification for any future subtypes of "text" must specify
whether or not they will also utilize a "charset" parameter, and may
possibly restrict its values as well. For other subtypes of "text"
than "text/plain", the semantics of the "charset" parameter should be
defined to be identical to those specified here for "text/plain",
i.e., the body consists entirely of characters in the given charset.
In particular, definers of future "text" subtypes should pay close
attention to the implications of multioctet character sets for their
subtype definitions.
According to them, such difficulties can be avoided when using application/xml
MIME type. Whether it's true or not, I wouldn't go as far as to avoid text/xml
. IMHO, it's best just to follow the semantics of human-readability(non-readability) and always remember to specify the charset.
Swift 3.
// Remove all cache
URLCache.shared.removeAllCachedResponses()
// Delete any associated cookies
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used
conda install [-y] package">=version"
conda install [-y] package'>=low_version, <=high_version'
conda install [-y] "package>=low_version, <high_version"
conda install -y torchvision">=0.3.0"
conda install openpyxl'>=2.4.10,<=2.6.0'
conda install "openpyxl>=2.4.10,<3.0.0"
where option -y, --yes Do not ask for confirmation.
Here is a summary:
Format Sample Specification Results
Exact qtconsole==4.5.1 4.5.1
Fuzzy qtconsole=4.5 4.5.0, 4.5.1, ..., etc.
>=, >, <, <= "qtconsole>=4.5" 4.5.0 or higher
qtconsole"<4.6" less than 4.6.0
OR "qtconsole=4.5.1|4.5.2" 4.5.1, 4.5.2
AND "qtconsole>=4.3.1,<4.6" 4.3.1 or higher but less than 4.6.0
Potion of the above information credit to Conda Cheat Sheet
Tested on conda 4.7.12
Windows 7, 8 & 10
This is dead easy since Windows 7. In File Explorer, right click anywhere and create a new file. Type the new filename as .something.
(notice the appended period) and press enter twice, job done.
So instead of being prompted with
You must type a file name.
You will instead be prompted with
If you change a file name extension, the file might become unusable.
Note: If you're having issues then please ensure you have "file name extensions" visible, you can activate this under the "View" menu in File Explorer. Also, this method works for folders too.
A neat trick for fast rounding is to add .5 before you cast your decimal to an int.
decimal d = 10.1m;
d += .5m;
int i = (int)d;
Still leaves i=10
, but
decimal d = 10.5m;
d += .5m;
int i = (int)d;
Would round up so that i=11
.
I found it pretty easy like this
using System;
using System.Data;
using System.IO;
using Excel;
public DataTable ExcelToDataTableUsingExcelDataReader(string storePath)
{
FileStream stream = File.Open(storePath, FileMode.Open, FileAccess.Read);
string fileExtension = Path.GetExtension(storePath);
IExcelDataReader excelReader = null;
if (fileExtension == ".xls")
{
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (fileExtension == ".xlsx")
{
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
var test = result.Tables[0];
return result.Tables[0];
}
Note: you need to install SharpZipLib package for this
Install-Package SharpZipLib
neat and clean! ;)
You can do this with the reshape()
function, or with the melt()
/ cast()
functions in the reshape package. For the second option, example code is
library(reshape)
cast(dat1, name ~ numbers)
Or using reshape2
library(reshape2)
dcast(dat1, name ~ numbers)
If you are sending alphanumeric data try changing
'Content-Type': 'multipart/form-data'
to
'Content-Type': 'application/x-www-form-urlencoded'
If you are sending non-alphanumeric data try to remove 'Content-Type' at all.
If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)
We call it the "ant" menu. Guess it was a good time to change since everyone had just gotten used to the hamburger.
This is what I use:
#if DBG
#include <stdio.h>
#define DBGPRINT printf
#else
#define DBGPRINT(...) /**/
#endif
It has the nice benefit to handle printf properly, even without additional arguments. In case DBG ==0, even the dumbest compiler gets nothing to chew upon, so no code is generated.
One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)
The correct solution is
Dim copyToRow: copyToRow = 5
Rows(copyToRow & ":" & copyToRow).Select
The VARCHAR
datatype is synonymous with the VARCHAR2
datatype. To avoid possible changes in behavior, always use the VARCHAR2
datatype to store variable-length character strings.
If your database runs on a single-byte character set (e.g. US7ASCII
, WE8MSWIN1252
or WE8ISO8859P1
) it does not make any difference whether you use VARCHAR2(x BYTE)
or VARCHAR2(x CHAR)
.
It makes only a difference when your DB runs on multi-byte character set (e.g. AL32UTF8
or AL16UTF16
). You can simply see it in this example:
CREATE TABLE my_table (
VARCHAR2_byte VARCHAR2(1 BYTE),
VARCHAR2_char VARCHAR2(1 CHAR)
);
INSERT INTO my_table (VARCHAR2_char) VALUES ('€');
1 row created.
INSERT INTO my_table (VARCHAR2_char) VALUES ('ü');
1 row created.
INSERT INTO my_table (VARCHAR2_byte) VALUES ('€');
INSERT INTO my_table (VARCHAR2_byte) VALUES ('€')
Error at line 10
ORA-12899: value too large for column "MY_TABLE"."VARCHAR2_BYTE" (actual: 3, maximum: 1)
INSERT INTO my_table (VARCHAR2_byte) VALUES ('ü')
Error at line 11
ORA-12899: value too large for column "MY_TABLE"."VARCHAR2_BYTE" (actual: 2, maximum: 1)
VARCHAR2(1 CHAR)
means you can store up to 1 character, no matter how many byte it has. In case of Unicode one character may occupy up to 4 bytes.
VARCHAR2(1 BYTE)
means you can store a character which occupies max. 1 byte.
If you don't specify either BYTE
or CHAR
then the default is taken from NLS_LENGTH_SEMANTICS
session parameter.
Unless you have Oracle 12c where you can set MAX_STRING_SIZE=EXTENDED
the limit is VARCHAR2(4000 CHAR)
However, VARCHAR2(4000 CHAR)
does not mean you are guaranteed to store up to 4000 characters. The limit is still 4000 bytes, so in worst case you may store only up to 1000 characters in such field.
See this example (€
in UTF-8 occupies 3 bytes):
CREATE TABLE my_table2(VARCHAR2_char VARCHAR2(4000 CHAR));
BEGIN
INSERT INTO my_table2 VALUES ('€€€€€€€€€€');
FOR i IN 1..7 LOOP
UPDATE my_table2 SET VARCHAR2_char = VARCHAR2_char ||VARCHAR2_char;
END LOOP;
END;
/
SELECT LENGTHB(VARCHAR2_char) , LENGTHC(VARCHAR2_char) FROM my_table2;
LENGTHB(VARCHAR2_CHAR) LENGTHC(VARCHAR2_CHAR)
---------------------- ----------------------
3840 1280
1 row selected.
UPDATE my_table2 SET VARCHAR2_char = VARCHAR2_char ||VARCHAR2_char;
UPDATE my_table2 SET VARCHAR2_char = VARCHAR2_char ||VARCHAR2_char
Error at line 1
ORA-01489: result of string concatenation is too long
See also Examples and limits of BYTE and CHAR semantics usage (NLS_LENGTH_SEMANTICS) (Doc ID 144808.1)
Do you mean that you've got code like
if(map.containsKey(key)) doSomethingWith(map.get(key))
all over the place ? Then you should simply check whether map.get(key)
returned null and that's it.
By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey
is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.
I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:
template <template<class> class H, class S>
void f(const H<S> &value) {
}
Here, H
is a template, but I wanted this function to deal with all specializations of H
.
NOTE: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).
I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that std::vector
doesn't have a typedef value_type
.
So how would you write a function which can create variables of the right type for the vectors elements? This would work.
template <template<class, class> class V, class T, class A>
void f(V<T, A> &v) {
// This can be "typename V<T, A>::value_type",
// but we are pretending we don't have it
T temp = v.back();
v.pop_back();
// Do some work on temp
std::cout << temp << std::endl;
}
NOTE: std::vector
has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.
which you can use like this:
f<std::vector, int>(v); // v is of type std::vector<int> using any allocator
or better yet, we can just use:
f(v); // everything is deduced, f can deal with a vector of any type!
UPDATE: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing auto
. Now the same function can be written as:
template <class Cont>
void f(Cont &v) {
auto temp = v.back();
v.pop_back();
// Do some work on temp
std::cout << temp << std::endl;
}
which is how I'd prefer to write this type of code.
If you're checking for a function that is a jQuery plugin, you need to use $.fn.myfunction
if (typeof $.fn.mask === 'function') {
$('.zip').mask('00000');
}
it is better to use CONCAT function in PostgreSQL for concatenation
eg : select CONCAT(first_name,last_name) from person where pid = 136
if you are using column_a || ' ' || column_b for concatenation for 2 column , if any of the value in column_a or column_b is null query will return null value. which may not be preferred in all cases.. so instead of this
||
use
CONCAT
it will return relevant value if either of them have value
string.Format("{0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow)
returns 2017-02-10T08:12:39.483Z
Have you tried:
tr.classname { margin-bottom:5em; }
Alternatively, each td can be adjusted as well:
td.classname { margin-bottom:5em; }
or
td.classname { padding-bottom:5em; }
f=/home/cox/myapp.apk #or $1 if input from terminal.
#backup env var
backup=$LD_LIBRARY_PATH
LD_LIBRARY_PATH=/vendor/lib:/system/lib
myTemp=/sdcard/temp.apk
adb push $f $myTemp
adb shell pm install -r $myTemp
#restore env var
LD_LIBRARY_PATH=$backup
This works for me. I run this on ubuntu 12.04, on shell terminal.
I had the same problem like you. Here's my error code.
@Component
public class GetExprsAndEnvId {
@Value("hello")
private String Mysecret;
public GetExprsAndEnvId() {
System.out.println("construct");
}
public void print(){
System.out.println(this.Mysecret);
}
public String getMysecret() {
return Mysecret;
}
public void setMysecret(String mysecret) {
Mysecret = mysecret;
}
}
This is no problem like this, but we need to use it like this:
@Autowired
private GetExprsAndEnvId getExprsAndEnvId;
not like this:
getExprsAndEnvId = new GetExprsAndEnvId();
Here, the field annotated with @Value is null because Spring doesn't know about the copy of GetExprsAndEnvId that is created with new and didn't know to how to inject values in it.
In Opera 12 when you bind using the plain JavaScript, 'oTransitionEnd' will work:
document.addEventListener("oTransitionEnd", function(){
alert("Transition Ended");
});
however if you bind through jQuery, you need to use 'otransitionend'
$(document).bind("otransitionend", function(){
alert("Transition Ended");
});
In case you are using Modernizr or bootstrap-transition.js you can simply do a change:
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
You can find some info here as well http://www.ianlunn.co.uk/blog/articles/opera-12-otransitionend-bugs-and-workarounds/
Error Code:
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.29/version: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect . This error may also indicate that the docker daemon is not running.
Solutions:
1) For Windows 7 Command Window(cmd.exe), open cmd.exe with run as administrator and execute following command:
docker-machine env --shell cmd default
You will receive following output:
SET DOCKER_TLS_VERIFY=1
SET DOCKER_HOST=tcp://192.168.99.100:2376
SET DOCKER_CERT_PATH=C:\Users\USER_NAME\.docker\machine\machines\default
SET DOCKER_MACHINE_NAME=default
SET COMPOSE_CONVERT_WINDOWS_PATHS=true
REM Run this command to configure your shell:
REM @FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i
Copy the command below and execute on cmd:
@FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i
And then execute following command to control:
docker version
2) For Windows 7 Powershell, open powershell.exe with run as administrator and execute following command:
docker-machine env --shell=powershell | Invoke-Expression
And then execute following command to control:
docker version
3) If you reopen cmd or powershell, you should repeat the related steps again.
I haven't seen my own way of doing it before, so, try this out. It is way easier to follow and has a much smaller footprint:
if([bool]([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -notcontains "S-1-5-32-544") {
Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
}
Very simply, if the current Powershell session was called with administrator privileges, the Administrator Group well-known SID will show up in the Groups when you grab the current identity. Even if the account is a member of that group, the SID won't show up unless the process was invoked with elevated credentials.
Nearly all of these answers are a variation on Microsoft's Ben Armstrong's immensely popular method of how to accomplish it while not really grasping what it is actually doing and how else to emulate the same routine.
Thanks for this - I was having a similar issue, as I'm trying to programatically relate objects will hierarchical class names, even though those names might not necessarily be known to my script.
In my script, I want an <a>
tag to turn help text on/off by giving the <a>
tag [some_class]
plus the class of toggle
, and then giving it's help text the class of [some_class]_toggle
. This code is successfully finding the related elements using jQuery:
$("a.toggle").toggle(function(){toggleHelp($(this), false);}, function(){toggleHelp($(this), true);});
function toggleHelp(obj, mode){
var classList = obj.attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item.indexOf("_toggle") > 0) {
var targetClass = "." + item.replace("_toggle", "");
if(mode===false){$(targetClass).removeClass("off");}
else{$(targetClass).addClass("off");}
}
});
}
Short ONELINER:
<input onkeypress="return /[a-z]/i.test(event.key)" >
_x000D_
For all unicode letters try this regexp: /\p{L}/u
(but ... this) - and here is working example :)
You might want to try the contains
selector:
if ($("#field > div.field-item:contains('someText')").length) {
$("#somediv").addClass("thisClass");
}
Also, as other mentioned, you must use == or === rather than =.
The following should work:
pip install pywin32
But it didn't for me. I fixed this by downloading and installing the exe from here:
Another option to stream images from a webcam to a browser is via mjpeg. This is just a series of jpeg images that most modern browsers support as part of the tag. Here's a sample server written in c#:
https://www.codeproject.com/articles/371955/motion-jpeg-streaming-server
This works well over a LAN, but not as well over the internet as mjpeg is not as effcient as other video codecs (h264, VP8 etc..)
How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids
, but Perl complains.
Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open
returned an error, and make sure you are using use strict; use warnings;
.
my ($ids, $nIds)
is a list, right? With two elements?
It's a (very special) function call. $ids,$nIds
is a list with two elements.
You can use JavaScript like... Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id="data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
you make the use of the HTML Helper and have
@using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="@Url.Action("MyAction", "MyController")" >
Html.BeginForm
has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm()
will create a POST
form that points to your current controller and current action. As an example, let's say you have a controller called Posts
and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>
@using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
@Url.ActionLink("go to list", "Index")
}
@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;
.
I want to change or update my ContactNo to 8018070999 where there is 8018070777 using Case statement
update [Contacts] set contactNo=(case
when contactNo=8018070777 then 8018070999
else
contactNo
end)
LTRIM(RTRIM(FCT_TYP_CD)) & ') AND (' & LTRIM(RTRIM(DEP_TYP_ID)) & ')'
I think you're missing a )
on both of the trims. Some SQL versions support just TRIM which does both L and R trims...
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException
if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db
object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved
method of your service as follows:
Intent intent = new Intent("com.android.ServiceStopped");
sendBroadcast(intent);
and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.
Check on yourCheckBox.Value
?
When using setAttribute
and getRequestDispatcher
on doGet
, make sure that you are accessing your pages with the urlPatterns ("/login" for example) defined for your servlet. If you do it with "/login.jsp" your doGet
won't get called so none of your attributes will be available.
The most efficient way (before django 1.2) is this:
if orgs.count() == 0:
# no results
else:
# alrigh! let's continue...
I'm a bit late to the party, however there's an important note:
Your scripts might be in the right order but watch out for any async
s in your script tag (like this)
<script type="text/javascript" src="js/bootstrap.js" async></script>
This might be causing the issue. Especially if you have this async
set only for Production environments this can get really frustrating to reason about.