How to check for a valid URL in Java?
Judging by the source code for URI
, the
public URL(URL context, String spec, URLStreamHandler handler)
constructor does more validation than the other constructors. You might try that one, but YMMV.
How to use Scanner to accept only valid int as input
Use Scanner.hasNextInt()
:
Returns true
if the next token in this scanner's input can be interpreted as an int
value in the default radix using the nextInt()
method. The scanner does not advance past any input.
Here's a snippet to illustrate:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt()) sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
You don't have to parseInt
or worry about NumberFormatException
. Note that since the hasNextXXX
methods don't advance past any input, you may have to call next()
if you want to skip past the "garbage", as shown above.
Related questions
Testing pointers for validity (C/C++)
Preventing a crash caused by the caller sending in an invalid pointer is a good way to make silent bugs that are hard to find.
Isn't it better for the programmer using your API to get a clear message that his code is bogus by crashing it rather than hiding it?
Regex for Mobile Number Validation
This regex is very short and sweet for working.
/^([+]\d{2})?\d{10}$/
Ex: +910123456789 or 0123456789
-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length
This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.
if you want to add the space between than you can use the
[ ]
here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex
/^([+]\d{2}[ ])?\d{10}$/
Ex: +91 0123456789
Thanks ask any question if you have.
C# Validating input for textbox on winforms
Description
There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating
event.
The Validating
event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true
the TextBox doesn't lose the focus.
MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order
Enter
GotFocus
Leave
Validating
Validated
LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
Enter
GotFocus
LostFocus
Leave
Validating
Validated
Sample Validating Event
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text != "something")
e.Cancel = true;
}
Update
You can use the ErrorProvider
to visualize that your TextBox is not valid.
Check out Using Error Provider Control in Windows Forms and C#
More Information
How do I remove javascript validation from my eclipse project?
I was able to exclude the jquery.mobile 1.1.1 in Juno by selecting Add Multiple next to the Exlusion Patterns, which brings up the tree, then drilling down to the jquery-mobile folder and selecting that.
This corrected all the warnings for the library!
Radio button validation in javascript
document.forms[ 'forms1' ].onsubmit = function() {
return [].some.call( this.elements, function( el ) {
return el.type === 'radio' ? el.checked : false
} )
}
Just something out of my head. Not sure the code is working.
Better way to check variable for null or empty string?
to be more robust (tabulation, return…), I define:
function is_not_empty_string($str) {
if (is_string($str) && trim($str, " \t\n\r\0") !== '')
return true;
else
return false;
}
// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
var_export($value);
if (is_not_empty_string($value))
print(" is a none empty string!\n");
else
print(" is not a string or is an empty string\n");
}
sources:
Java Regex to Validate Full Name allow only Spaces and Letters
please try this regex (allow only Alphabets and space)
"[a-zA-Z][a-zA-Z ]*"
if you want it for IOS then,
NSString *yourstring = @"hello";
NSString *Regex = @"[a-zA-Z][a-zA-Z ]*";
NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
if ([TestResult evaluateWithObject:yourstring] == true)
{
// validation passed
}
else
{
// invalid name
}
Simple JavaScript Checkbox Validation
If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:
html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">
script:
<script type="text/Javascript">
function deleteData() {
if(!document.getElementById('Delete').checked){
alert('Checkbox not checked');
return false;
}
</script>
HTML5 form required attribute. Set custom validation message?
The easiest and cleanest way I've found is to use a data attribute to store your custom error. Test the node for validity and handle the error by using some custom html.
le javascript
if(node.validity.patternMismatch)
{
message = node.dataset.patternError;
}
and some super HTML5
<input type="text" id="city" name="city" data-pattern-error="Please use only letters for your city." pattern="[A-z ']*" required>
What is a regular expression which will match a valid domain name without a subdomain?
I know that this is a bit of an old post, but all of the regular expressions here are missing one very important component: the support for IDN domain names.
IDN domain names start with xn--. They enable extended UTF-8 characters in domain names. For example, did you know "?.com" is a valid domain name? Yeah, "love heart dot com"! To validate the domain name, you need to let http://xn--c6h.com/ pass the validation.
Note, to use this regex, you will need to convert the domain to lower case, and also use an IDN library to ensure you encode domain names to ACE (also known as "ASCII Compatible Encoding"). One good library is GNU-Libidn.
idn(1) is the command line interface to the internationalized domain name library. The following example converts the host name in UTF-8 into ACE encoding. The resulting URL https://nic.xn--flw351e/ can then be used as ACE-encoded equivalent of https://nic.??/.
$ idn --quiet -a nic.??
nic.xn--flw351e
This magic regular expression should cover most domains (although, I am sure there are many valid edge cases that I have missed):
^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\.(xn--)?([a-z0-9\-]{1,61}|[a-z0-9-]{1,30}\.[a-z]{2,})$
When choosing a domain validation regex, you should see if the domain matches the following:
- xn--stackoverflow.com
- stackoverflow.xn--com
- stackoverflow.co.uk
If these three domains do not pass, your regular expression may be not allowing legitimate domains!
Check out The Internationalized Domain Names Support page from Oracle's International Language Environment Guide for more information.
Feel free to try out the regex here: http://www.regexr.com/3abjr
ICANN keeps a list of tlds that have been delegated which can be used to see some examples of IDN domains.
Edit:
^(((?!-))(xn--|_{1,1})?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?([a-z0-9][a-z0-9\-]{0,60}|[a-z0-9-]{1,30}\.[a-z]{2,})$
This regular expression will stop domains that have '-' at the end of a hostname as being marked as being valid. Additionally, it allows unlimited subdomains.
Regular expression for first and last name
For simplicities sake, you can use:
(.*)\s(.*)
The thing I like about this is that the last name is always after the first name, so if you're going to enter this matched groups into a database, and the name is John M. Smith, the 1st group will be
John M., and the 2nd group will be Smith.
Javascript validation: Block special characters
For special characters:
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.formname.fieldname.value.length; i++) {
if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
ZIP Code (US Postal Code) validation
Are you referring to address validation? Like the previous answer by Mike, you need to cater for the othe 95%.
What you can do is when the user select's their country, then enable validation. Address validation and zipcode validation are 2 different things. Validating the ZIP is just making sure its integer. Address validation is validating the actual address for accuracy, preferably for mailing.
Min / Max Validator in Angular 2 Final
Apparently, Angular had the max/min directives for template driven forms at some point but had to remove them in v4.2.0. You can read about the regression that caused the removal here: https://github.com/angular/angular/issues/17491
For now the only working solution that I know of is to use custom directive as @amd suggested. Here's how to use it with Bootstrap 4.
min-validator.directive.ts
import { Directive, Input } from '@angular/core'
import { NG_VALIDATORS, Validator, AbstractControl, Validators } from '@angular/forms'
@Directive({
selector: '[min]',
providers: [{ provide: NG_VALIDATORS, useExisting: MinDirective, multi: true }]
})
export class MinDirective implements Validator {
@Input() min: number;
validate(control: AbstractControl): { [key: string]: any } {
return Validators.min(this.min)(control)
}
}
And in your template:
<input type="number" [min]="minAge" #age="ngModel" [(ngModel)]="person.age" class="form-control" [ngClass]="{'is-invalid':age.invalid}">
<div *ngIf="age.invalid && (age.dirty || age.touched)" class="invalid-feedback">You need to be older than {{minAge}} to participate</div>
Hope this helps!
What is jQuery Unobtrusive Validation?
With the unobtrusive way:
- You don't have to call the validate() method.
- You specify requirements using data attributes (data-val, data-val-required, etc.)
Jquery Validate Example:
<input type="text" name="email" class="required">
<script>
$(function () {
$("form").validate();
});
</script>
Jquery Validate Unobtrusive Example:
<input type="text" name="email" data-val="true"
data-val-required="This field is required.">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
asp.net validation to make sure textbox has integer values
<script language="javascript" type="text/javascript">
function fixedlength(textboxID, keyEvent, maxlength) {
//validation for digits upto 'maxlength' defined by caller function
if (textboxID.value.length > maxlength) {
textboxID.value = textboxID.value.substr(0, maxlength);
}
else if (textboxID.value.length < maxlength || textboxID.value.length == maxlength) {
textboxID.value = textboxID.value.replace(/[^\d]+/g, '');
return true;
}
else
return false;
}
</script>
<asp:TextBox ID="txtNextVisit" runat="server" MaxLength="2" onblur="return fixedlength(this, event, 2);" onkeypress="return fixedlength(this, event, 2);" onkeyup="return fixedlength(this, event, 2);"></asp:TextBox>
Laravel password validation rule
I have had a similar scenario in Laravel and solved it in the following way.
The password contains characters from at least three of the following five categories:
- English uppercase characters (A – Z)
- English lowercase characters (a – z)
- Base 10 digits (0 – 9)
- Non-alphanumeric (For example: !, $, #, or %)
- Unicode characters
First, we need to create a regular expression and validate it.
Your regular expression would look like this:
^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$
I have tested and validated it on this site. Yet, perform your own in your own manner and adjust accordingly. This is only an example of regex, you can manipluated the way you want.
So your final Laravel code should be like this:
'password' => 'required|
min:6|
regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/|
confirmed',
Update
As @NikK in the comment mentions, in Laravel 5.5 and newer the the password value should encapsulated in array Square brackets like
'password' => ['required',
'min:6',
'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/',
'confirmed']
I have not testing it on Laravel 5.5 so I am trusting @NikK hence I have moved to working with c#/.net these days and have no much time for Laravel.
Note:
- I have tested and validated it on both the regular expression site and a Laravel 5 test environment and it works.
- I have used min:6, this is optional but it is always a good practice to have a security policy that reflects different aspects, one of which is minimum password length.
- I suggest you to use password confirmed to ensure user typing correct password.
- Within the 6 characters our regex should contain at least 3 of a-z or A-Z and number and special character.
- Always test your code in a test environment before moving to production.
- Update: What I have done in this answer is just example of regex password
Some online references
Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:
Validate phone number using javascript
This is by far the easiest way I have found to use javascript regex to check phone number format. this particular example checks if it is a 10 digit number.
<input name="phone" pattern="^\d{10}$" type="text" size="50">
The input field gets flagged when submit button is clicked if the pattern doesn't match the value, no other css or js required.
How to validate IP address in Python?
Consider IPv4 address as "ip".
if re.match(r'^((\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$', ip):
print "Valid IP"
else:
print "Invalid IP"
Check if date is in the past Javascript
function isPrevDate() {
alert("startDate is " + Startdate);
if(Startdate.length != 0 && Startdate !='') {
var start_date = Startdate.split('-');
alert("Input date: "+ start_date);
start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
alert("start date arrray format " + start_date);
var a = new Date(start_date);
//alert("The date is a" +a);
var today = new Date();
var day = today.getDate();
var mon = today.getMonth()+1;
var year = today.getFullYear();
today = (mon+"/"+day+"/"+year);
//alert(today);
var today = new Date(today);
alert("Today: "+today.getTime());
alert("a : "+a.getTime());
if(today.getTime() > a.getTime() )
{
alert("Please select Start date in range");
return false;
} else {
return true;
}
}
}
What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone
Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.
Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.
As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.
MVC Return Partial View as JSON
You can extract the html string from the PartialViewResult object, similar to the answer to this thread:
Render a view as a string
PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.
Using the code from the thread above, you would be able to use:
public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
if (ModelState.IsValid)
{
if(Request.IsAjaxRequest())
return PartialView("NotEvil", model);
return View(model)
}
if(Request.IsAjaxRequest())
{
return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
}
return View(model);
}
Validating input using java.util.Scanner
Overview of Scanner.hasNextXXX
methods
java.util.Scanner
has many hasNextXXX
methods that can be used to validate input. Here's a brief overview of all of them:
hasNext()
- does it have any token at all?
hasNextLine()
- does it have another line of input?
- For Java primitives
- Regular expression-based
Scanner
is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern)
, which lets you define what pattern separates your tokens. There are also find
and skip
methods that ignores delimiters.
The following discussion will keep the regex as simple as possible, so the focus remains on Scanner
.
Example 1: Validating positive ints
Here's a simple example of using hasNextInt()
to validate positive int
from the input.
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
Here's an example session:
Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5
Note how much easier Scanner.hasNextInt()
is to use compared to the more verbose try/catch
Integer.parseInt
/NumberFormatException
combo. By contract, a Scanner
guarantees that if it hasNextInt()
, then nextInt()
will peacefully give you that int
, and will not throw any NumberFormatException
/InputMismatchException
/NoSuchElementException
.
Related questions
Example 2: Multiple hasNextXXX
on the same token
Note that the snippet above contains a sc.next()
statement to advance the Scanner
until it hasNextInt()
. It's important to realize that none of the hasNextXXX
methods advance the Scanner
past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!
This has two consequences:
- If you need to skip the "garbage" input that fails your
hasNextXXX
test, then you need to advance the Scanner
one way or another (e.g. next()
, nextLine()
, skip
, etc).
- If one
hasNextXXX
test fails, you can still test if it perhaps hasNextYYY
!
Here's an example of performing multiple hasNextXXX
tests.
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
System.out.println(
sc.hasNextInt() ? "(int) " + sc.nextInt() :
sc.hasNextLong() ? "(long) " + sc.nextLong() :
sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
"(String) " + sc.next()
);
}
Here's an example session:
5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit
Note that the order of the tests matters. If a Scanner
hasNextInt()
, then it also hasNextLong()
, but it's not necessarily true
the other way around. More often than not you'd want to do the more specific test before the more general test.
Example 3 : Validating vowels
Scanner
has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);
Here's an example session:
Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e
In regex, as a Java string literal, the pattern "[aeiou]"
is what is called a "character class"; it matches any of the letters a
, e
, i
, o
, u
. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner
.
API links
Related questions
References
Example 4: Using two Scanner
at once
Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner
, where the second Scanner
takes the nextLine()
from the first Scanner
as input. Here's an example:
Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
Scanner lineSc = new Scanner(sc.nextLine());
int sum = 0;
while (lineSc.hasNextInt()) {
sum += lineSc.nextInt();
}
System.out.println("Sum is " + sum);
}
Here's an example session:
Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit
In addition to Scanner(String)
constructor, there's also Scanner(java.io.File)
among others.
Summary
Scanner
provides a rich set of features, such as hasNextXXX
methods for validation.
- Proper usage of
hasNextXXX/nextXXX
in combination means that a Scanner
will NEVER throw an InputMismatchException
/NoSuchElementException
.
- Always remember that
hasNextXXX
does not advance the Scanner
past any input.
- Don't be shy to create multiple
Scanner
if necessary. Two simple Scanner
is often better than one overly complex Scanner
.
- Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any
Scanner
method that takes a String pattern
argument is regex-based.
- Tip: an easy way to turn any
String
into a literal pattern is to Pattern.quote
it.
What's the valid way to include an image with no src?
<img src="invis.gif" />
Where invis.gif is a single pixel transparent gif. This won't break in future browser versions and has been working in legacy browsers since the '90s.
png should work too but in my tests, the gif was 43 bytes and the png was 167 bytes so the gif won.
p.s. don't forget an alt tag, validators like them too.
How does the SQL injection from the "Bobby Tables" XKCD comic work?
It drops the students table.
The original code in the school's program probably looks something like
q = "INSERT INTO Students VALUES ('" + FNMName.Text + "', '" + LName.Text + "')";
This is the naive way to add text input into a query, and is very bad, as you will see.
After the values from the first name, middle name textbox FNMName.Text (which is Robert'); DROP TABLE STUDENTS; --
) and the last name textbox LName.Text (let's call it Derper
) are concatenated with the rest of the query, the result is now actually two queries separated by the statement terminator (semicolon). The second query has been injected into the first. When the code executes this query against the database, it will look like this
INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --', 'Derper')
which, in plain English, roughly translates to the two queries:
Add a new record to the Students table with a Name value of 'Robert'
and
Delete the Students table
Everything past the second query is marked as a comment: --', 'Derper')
The '
in the student's name is not a comment, it's the closing string delimiter. Since the student's name is a string, it's needed syntactically to complete the hypothetical query. Injection attacks only work when the SQL query they inject results in valid SQL.
Edited again as per dan04's astute comment
How do I make an input field accept only letters in javaScript?
If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:
function validate() {
if (document.myForm.name.value == "") {
alert("Enter a name");
document.myForm.name.focus();
return false;
}
if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
alert("Invalid characters");
document.myForm.name.focus();
return false;
}
}
Best way to check if a Data Table has a null value in it
You can null/blank/space Etc value using LinQ
Use Following Query
var BlankValueRows = (from dr1 in Dt.AsEnumerable()
where dr1["Columnname"].ToString() == ""
|| dr1["Columnname"].ToString() == ""
|| dr1["Columnname"].ToString() == ""
select Columnname);
Here Replace Columnname with table column name and "" your search item in above code we looking null value.
Regex date validation for yyyy-mm-dd
A simple one would be
\d{4}-\d{2}-\d{2}
Debuggex Demo
but this does not restrict month to 1-12 and days from 1 to 31.
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
RegEx for valid international mobile phone number
Even if you write a regular expression that matches exactly the subset "valid phone numbers" out of strings, there is no way to guarantee (by way of a regular expression) that they are valid mobile phone numbers. In several countries, mobile phone numbers are indistinguishable from landline phone numbers without at least a number plan lookup, and in some cases, even that won't help. For example, in Sweden, lots of people have "ported" their regular, landline-like phone number to their mobile phone. It's still the same number as they had before, but now it goes to a mobile phone instead of a landline.
Since valid phone numbers consist only of digits, I doubt that rolling your own would risk missing some obscure case of phone number at least. If you want to have better certainty, write a generator that takes a list of all valid country codes, and requires one of them at the beginning of the phone number to be matched by the generated regular expression.
Validate decimal numbers in JavaScript - IsNumeric()
I found simple solution, probably not best but it's working fine :)
So, what I do is next, I parse string to Int and check if length size of new variable which is now int type is same as length of original string variable. Logically if size is the same it means string is fully parsed to int and that is only possible if string is "made" only of numbers.
var val=1+$(e).val()+'';
var n=parseInt(val)+'';
if(val.length == n.length )alert('Is int');
You can easily put that code in function and instead of alert use return true if int.
Remember, if you use dot or comma in string you are checking it's still false cos you are parsing to int.
Note: Adding 1+ on e.val so starting zero wouldn't be removed.
How to check whether a given string is valid JSON in Java
String jsonInput = "{\"mob no\":\"9846716175\"}";//Read input Here
JSONReader reader = new JSONValidatingReader();
Object result = reader.read(jsonInput);
System.out.println("Validation Success !!");
Please download stringtree-json library
How do you perform address validation?
Fixaddress.com service is available that provides following services,
1) Address Validation.
2) Address Correction.
3) Address spell correcting.
4) Correct addresses phonetic mistakes.
Fixaddress.com uses USPS and Tiger data as reference data.
For more detail visit below link,
http://www.fixaddress.com/
How to validate date with format "mm/dd/yyyy" in JavaScript?
Find in the below code which enables to perform the date validation for any of the supplied format to validate start/from and end/to dates. There could be some better approaches but have come up with this. Note supplied date format and date string go hand in hand.
<script type="text/javascript">
function validate() {
var format = 'yyyy-MM-dd';
if(isAfterCurrentDate(document.getElementById('start').value, format)) {
alert('Date is after the current date.');
} else {
alert('Date is not after the current date.');
}
if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
alert('Date is before current date.');
} else {
alert('Date is not before current date.');
}
if(isCurrentDate(document.getElementById('start').value, format)) {
alert('Date is current date.');
} else {
alert('Date is not a current date.');
}
if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Start/Effective Date cannot be greater than End/Expiration Date');
} else {
alert('Valid dates...');
}
if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('End/Expiration Date cannot be less than Start/Effective Date');
} else {
alert('Valid dates...');
}
if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Dates are equals...');
} else {
alert('Dates are not equals...');
}
if (isDate(document.getElementById('start').value, format)) {
alert('Is valid date...');
} else {
alert('Is invalid date...');
}
}
/**
* This method gets the year index from the supplied format
*/
function getYearIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'YYYY'
|| tokens[0] === 'yyyy') {
return 0;
} else if (tokens[1]=== 'YYYY'
|| tokens[1] === 'yyyy') {
return 1;
} else if (tokens[2] === 'YYYY'
|| tokens[2] === 'yyyy') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the year string located at the supplied index
*/
function getYear(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the month index from the supplied format
*/
function getMonthIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'MM'
|| tokens[0] === 'mm') {
return 0;
} else if (tokens[1] === 'MM'
|| tokens[1] === 'mm') {
return 1;
} else if (tokens[2] === 'MM'
|| tokens[2] === 'mm') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the month string located at the supplied index
*/
function getMonth(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the date index from the supplied format
*/
function getDateIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'DD'
|| tokens[0] === 'dd') {
return 0;
} else if (tokens[1] === 'DD'
|| tokens[1] === 'dd') {
return 1;
} else if (tokens[2] === 'DD'
|| tokens[2] === 'dd') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the date string located at the supplied index
*/
function getDate(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method returns true if date1 is before date2 else return false
*/
function isBefore(date1, date2, format) {
// Validating if date1 date is greater than the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
> new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method returns true if date1 is after date2 else return false
*/
function isAfter(date1, date2, format) {
// Validating if date2 date is less than the date1 date
if (new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()
< new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
) {
return true;
}
return false;
}
/**
* This method returns true if date1 is equals to date2 else return false
*/
function isEquals(date1, date2, format) {
// Validating if date1 date is equals to the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
=== new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date is
* equals to the current date.
*/
function isCurrentDate(date, format) {
// Validating if the supplied date is the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
=== new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is before the current date.
*/
function isBeforeCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
< new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is after the current date.
*/
function isAfterCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
> new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method splits the supplied date OR format based
* on non alpha numeric characters in the supplied string.
*/
function splitDateFormat(dateFormat) {
// Spliting the supplied string based on non characters
return dateFormat.split(/\W/);
}
/*
* This method validates if the supplied value is a valid date.
*/
function isDate(date, format) {
// Validating if the supplied date string is valid and not a NaN (Not a Number)
if (!isNaN(new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))))) {
return true;
}
return false;
}
</script>
Below is the HTML snippet
<input type="text" name="start" id="start" size="10" value="" />
<br/>
<input type="text" name="end" id="end" size="10" value="" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate();" />
Javascript - validation, numbers only
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.
Validation of radio button group using jQuery validation plugin
As per Brandon's answer. But if you're using ASP.NET MVC which uses unobtrusive validation, you can add the data-val attribute to the first one. I also like to have labels for each radio button for usability.
<span class="field-validation-valid" data-valmsg-for="color" data-valmsg-replace="true"></span>
<p><input type="radio" name="color" id="red" value="R" data-val="true" data-val-required="Please choose one of these options:"/> <label for="red">Red</label></p>
<p><input type="radio" name="color" id="green" value="G"/> <label for="green">Green</label></p>
<p><input type="radio" name="color" id="blue" value="B"/> <label for="blue">Blue</label></p>
show validation error messages on submit in angularjs
http://jsfiddle.net/LRD5x/30/ A simple solution.
HTML
<form ng-submit="sendForm($event)" ng-class={submitted:submitted}>
JS
$scope.sendForm = function($event) {
$event.preventDefault()
$scope.submitted = true
};
CSS
.submitted input.ng-invalid:not(:focus) {
background-color: #FA787E;
}
input.ng-invalid ~ .alert{
display:none;
}
.submitted input.ng-invalid ~ .alert{
display:block;
}
WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery
Further to the accepted answer, I ran into issues with code elsewhere on my site requiring jQuery along with the Migrate Plugin.
When the required mapping is added to Global.asax, when loading a page requiring unobtrusive validation (for example a page with the ChangePassword ASP control), the mapped script resource conflicts with the already-loaded jQuery and migrate scripts.
Adding the migrate plugin as a second mapping solves the issue:
// required for UnobtrusiveValidationMode introduced since ASP.NET 4.5
var jQueryScriptDefinition = new ScriptResourceDefinition
{
Path = "~/Plugins/Common/jquery-3.3.1.min.js", DebugPath = "~/Plugins/Common/jquery-3.3.1.js", LoadSuccessExpression = "typeof(window.jQuery) !== 'undefined'"
};
var jQueryMigrateScriptDefinition = new ScriptResourceDefinition
{
Path = "~/Plugins/Common/jquery-migrate-3.0.1.min.js", DebugPath = "~/Plugins/Common/jquery-migrate-3.0.1.js", LoadSuccessExpression = "typeof(window.jQuery) !== 'undefined'"
};
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", jQueryScriptDefinition);
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", jQueryMigrateScriptDefinition);
JavaScript file upload size validation
I use one main Javascript function that I had found at Mozilla Developer Network site https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications, along with another function with AJAX and changed according to my needs. It receives a document element id regarding the place in my html code where I want to write the file size.
<Javascript>
function updateSize(elementId) {
var nBytes = 0,
oFiles = document.getElementById(elementId).files,
nFiles = oFiles.length;
for (var nFileId = 0; nFileId < nFiles; nFileId++) {
nBytes += oFiles[nFileId].size;
}
var sOutput = nBytes + " bytes";
// optional code for multiples approximation
for (var aMultiples = ["K", "M", "G", "T", "P", "E", "Z", "Y"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
sOutput = " (" + nApprox.toFixed(3) + aMultiples[nMultiple] + ")";
}
return sOutput;
}
</Javascript>
<HTML>
<input type="file" id="inputFileUpload" onchange="uploadFuncWithAJAX(this.value);" size="25">
</HTML>
<Javascript with XMLHttpRequest>
document.getElementById('spanFileSizeText').innerHTML=updateSize("inputFileUpload");
</XMLHttpRequest>
Cheers
How to add form validation pattern in Angular 2?
custom validation step by step
Html template
<form [ngFormModel]="demoForm">
<input
name="NotAllowSpecialCharacters"
type="text"
#demo="ngForm"
[ngFormControl] ="demoForm.controls['spec']"
>
<div class='error' *ngIf="demo.control.touched">
<div *ngIf="demo.control.hasError('required')"> field is required.</div>
<div *ngIf="demo.control.hasError('invalidChar')">Special Characters are not Allowed</div>
</div>
</form>
Component App.ts
import {Control, ControlGroup, FormBuilder, Validators, NgForm, NgClass} from 'angular2/common';
import {CustomValidator} from '../../yourServices/validatorService';
under class
define
demoForm: ControlGroup;
constructor( @Inject(FormBuilder) private Fb: FormBuilder ) {
this.demoForm = Fb.group({
spec: new Control('', Validators.compose([Validators.required, CustomValidator.specialCharValidator])),
})
}
under {../../yourServices/validatorService.ts}
export class CustomValidator {
static specialCharValidator(control: Control): { [key: string]: any } {
if (control.value) {
if (!control.value.match(/[-!$%^&*()_+|~=`{}\[\]:";#@'<>?,.\/]/)) {
return null;
}
else {
return { 'invalidChar': true };
}
}
}
}
MaxLength Attribute not generating client-side validation attributes
I had this same problem and I was able to solve it by implementing the IValidatableObject interface in my view model.
public class RegisterViewModel : IValidatableObject
{
/// <summary>
/// Error message for Minimum password
/// </summary>
public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters";
/// <summary>
/// Minimum acceptable password length
/// </summary>
public const int PasswordMinimumLength = 8;
/// <summary>
/// Gets or sets the password provided by the user.
/// </summary>
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
/// <summary>
/// Only need to validate the minimum length
/// </summary>
/// <param name="validationContext">ValidationContext, ignored</param>
/// <returns>List of validation errors</returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errorList = new List<ValidationResult>();
if ((Password?.Length ?? 0 ) < PasswordMinimumLength)
{
errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List<string>() {"Password"}));
}
return errorList;
}
}
The markup in the Razor is then...
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" }
<div class="password-helper">Must contain: 8 characters, 1 upper-case, 1 lower-case
</div>
@Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" })
</div>
This works really well. If I attempt to use [StringLength] instead then the rendered HTML is just not correct. The validation should render as:
<span class="text-danger field-validation-invalid field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true"><span id="Password-error" class="">The Password should be a minimum of 8 characters long.</span></span>
With the StringLengthAttribute the rendered HTML shows as a ValidationSummary which is not correct. The funny thing is that when the validator fails the submit is still blocked!
How to validate a date?
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}
HTML/JavaScript: Simple form validation on submit
I use this really simple small JavaScript library to validate a complete form in one single line of code:
jsFormValidator.App.create().Validator.applyRules('Login');
Check here: jsFormValidator
The benefit of this tool is that you just write a JSON object which describe your validation rules. There isn't any need to put in a line like:
<input type=text name="username" data-validate placeholder="Username">
data-validate
is injected in all the input fields of your form, but when using jsFormValidator, you don't require this heavy syntax and the validation will be applied to your form in one shot, without the need to touch your HTML code.
Right HTTP status code to wrong input
409 Conflict
could be an acceptable solution.
According to: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
The doc continues with an example:
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
In my case, I would like to PUT a string, that must be unique, to a database via an API. Before adding it to the database, I am checking that it is not already in the database.
If it is, I will return "Error: The string is already in the database", 409
.
I believe this is what the OP wanted: an error code suitable for when the data does not pass the server's criteria.
Validating IPv4 addresses with regexp
const char*ipv4_regexp = "\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\."
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\."
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\."
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b";
I adapted the regular expression taken from JGsoft RegexBuddy library to C language (regcomp/regexec) and I found out it works but there's a little problem in some OS like Linux.
That regular expression accepts ipv4 address like 192.168.100.009 where 009 in Linux is considered an octal value so the address is not the one you thought.
I changed that regular expression as follow:
const char* ipv4_regex = "\\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\."
"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\."
"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\."
"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\b";
using that regular expressione now 192.168.100.009 is not a valid ipv4 address while 192.168.100.9 is ok.
I modified a regular expression for multicast address too and it is the following:
const char* mcast_ipv4_regex = "\\b(22[4-9]|23[0-9])\\."
"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\."
"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]?)\\."
"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\b";
I think you have to adapt the regular expression to the language you're using to develop your application
I put an example in java:
package utility;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NetworkUtility {
private static String ipv4RegExp = "\\b(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d?)\\b";
private static String ipv4MulticastRegExp = "2(?:2[4-9]|3\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d?|0)){3}";
public NetworkUtility() {
}
public static boolean isIpv4Address(String address) {
Pattern pattern = Pattern.compile(ipv4RegExp);
Matcher matcher = pattern.matcher(address);
return matcher.matches();
}
public static boolean isIpv4MulticastAddress(String address) {
Pattern pattern = Pattern.compile(ipv4MulticastRegExp);
Matcher matcher = pattern.matcher(address);
return matcher.matches();
}
}
checking if number entered is a digit in jquery
String.prototype.isNumeric = function() {
var s = this.replace(',', '.').replace(/\s+/g, '');
return s == 0 || (s/s);
}
usage
'9.1'.isNumeric() -> 1
'0xabc'.isNumeric() -> 1
'10,1'.isNumeric() -> 1
'str'.isNumeric() -> NaN
Checking if form has been submitted - PHP
For general check if there was a POST
action use:
if (!empty($_POST))
EDIT: As stated in the comments, this method won't work for in some cases (e.g. with check boxes and button without a name). You really should use:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
How to add a RequiredFieldValidator to DropDownList control?
If you are using a data source, here's another way to do it without code behind.
Note the following key points:
- The
ListItem
of Value="0"
is on the source page, not added in code
- The
ListItem
in the source will be overwritten if you don't include
AppendDataBoundItems="true"
in the DropDownList
InitialValue="0"
tells the validator that this is the value that
should fire that validator (as pointed out in other answers)
Example:
<asp:DropDownList ID="ddlType" runat="server" DataSourceID="sdsType"
DataValueField="ID" DataTextField="Name" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="--Please Select--" Selected="True"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvType" runat="server" ControlToValidate="ddlType"
InitialValue="0" ErrorMessage="Type required"></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="sdsType" runat="server"
ConnectionString='<%$ ConnectionStrings:TESTConnectionString %>'
SelectCommand="SELECT ID, Name FROM Type"></asp:SqlDataSource>
ASP.NET MVC Conditional validation
I've been using this amazing nuget that does dynamic annotations ExpressiveAnnotations
You could validate any logic you can dream of:
public string Email { get; set; }
public string Phone { get; set; }
[RequiredIf("Email != null")]
[RequiredIf("Phone != null")]
[AssertThat("AgreeToContact == true")]
public bool? AgreeToContact { get; set; }
Decimal or numeric values in regular expression validation
I had the same problem, but I also wanted ".25" to be a valid decimal number. Here is my solution using JavaScript:
function isNumber(v) {
// [0-9]* Zero or more digits between 0 and 9 (This allows .25 to be considered valid.)
// ()? Matches 0 or 1 things in the parentheses. (Allows for an optional decimal point)
// Decimal point escaped with \.
// If a decimal point does exist, it must be followed by 1 or more digits [0-9]
// \d and [0-9] are equivalent
// ^ and $ anchor the endpoints so tthe whole string must match.
return v.trim().length > 0 && v.trim().match(/^[0-9]*(\.[0-9]+)?$/);
}
Where my trim() method is
String.prototype.trim = function() {
return this.replace(/(^\s*|\s*$)/g, "");
};
Matthew DesVoigne
jQuery Validate Plugin - Trigger validation of single field
If you want to validate individual form field, but don't want for UI to be triggered and display any validation errors, you may consider to use Validator.check() method which returns if given field passes validation or not.
Here is example
var validator = $("#form").data('validator');
if(validator.check('#element')){
/*field is valid*/
}else{
/*field is not valid (but no errors will be displayed)*/
}
How to validate an email address using a regular expression?
For a vivid demonstration, the following monster is pretty good but still does not correctly recognize all syntactically valid email addresses: it recognizes nested comments up to four levels deep.
This is a job for a parser, but even if an address is syntactically valid, it still may not be deliverable. Sometimes you have to resort to the hillbilly method of "Hey, y'all, watch ee-us!"
// derivative of work with the following copyright and license:
// Copyright (c) 2004 Casey West. All rights reserved.
// This module is free software; you can redistribute it and/or
// modify it under the same terms as Perl itself.
// see http://search.cpan.org/~cwest/Email-Address-1.80/
private static string gibberish = @"
(?-xism:(?:(?-xism:(?-xism:(?-xism:(?-xism:(?-xism:(?-xism:\
s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^
\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))
|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)+
|\s+)*[^\x00-\x1F\x7F()<>\[\]:;@\,.<DQ>\s]+(?-xism:(?-xism:\
s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^
\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))
|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)+
|\s+)*)|(?-xism:(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-xism:(
?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?
:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x
0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*<DQ>(?-xism:(?-xism:[
^\\<DQ>])|(?-xism:\\(?-xism:[^\x0A\x0D])))+<DQ>(?-xism:(?-xi
sm:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xis
m:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\
]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+)*\s*\)\
s*)+|\s+)*))+)?(?-xism:(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?
-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:
\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[
^\x0A\x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*<(?-xism:(?-xi
sm:(?-xism:(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^(
)\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(
?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))
|)+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*(?-xism:[^\x00-\x1F\x7F()<
>\[\]:;@\,.<DQ>\s]+(?:\.[^\x00-\x1F\x7F()<>\[\]:;@\,.<DQ>\s]
+)*)(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))
|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:
(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s
*\)\s*))+)*\s*\)\s*)+|\s+)*)|(?-xism:(?-xism:(?-xism:\s*\((?
:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x
0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xi
sm:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*
<DQ>(?-xism:(?-xism:[^\\<DQ>])|(?-xism:\\(?-xism:[^\x0A\x0D]
)))+<DQ>(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\
]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-x
ism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+
)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*))\@(?-xism:(?-xism:(?-xism:(
?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?
-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^
()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+)*\s
*\)\s*)+|\s+)*(?-xism:[^\x00-\x1F\x7F()<>\[\]:;@\,.<DQ>\s]+(
?:\.[^\x00-\x1F\x7F()<>\[\]:;@\,.<DQ>\s]+)*)(?-xism:(?-xism:
\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[
^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+)
)|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)
+|\s+)*)|(?-xism:(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-xism:
(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((
?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\
x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*\[(?:\s*(?-xism:(?-x
ism:[^\[\]\\])|(?-xism:\\(?-xism:[^\x0A\x0D])))+)*\s*\](?-xi
sm:(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:
\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(
?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+
)*\s*\)\s*)+|\s+)*)))>(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-
xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\
s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^
\x0A\x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*))|(?-xism:(?-x
ism:(?-xism:(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^
()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*
(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D])
)|)+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*(?-xism:[^\x00-\x1F\x7F()
<>\[\]:;@\,.<DQ>\s]+(?:\.[^\x00-\x1F\x7F()<>\[\]:;@\,.<DQ>\s
]+)*)(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+)
)|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism
:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\
s*\)\s*))+)*\s*\)\s*)+|\s+)*)|(?-xism:(?-xism:(?-xism:\s*\((
?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\
x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-x
ism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)
*<DQ>(?-xism:(?-xism:[^\\<DQ>])|(?-xism:\\(?-xism:[^\x0A\x0D
])))+<DQ>(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\
\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-
xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)
+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*))\@(?-xism:(?-xism:(?-xism:
(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(
?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[
^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+)*\
s*\)\s*)+|\s+)*(?-xism:[^\x00-\x1F\x7F()<>\[\]:;@\,.<DQ>\s]+
(?:\.[^\x00-\x1F\x7F()<>\[\]:;@\,.<DQ>\s]+)*)(?-xism:(?-xism
:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:
[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+
))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*
)+|\s+)*)|(?-xism:(?-xism:(?-xism:\s*\((?:\s*(?-xism:(?-xism
:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\(
(?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A
\x0D]))|)+)*\s*\)\s*))+)*\s*\)\s*)+|\s+)*\[(?:\s*(?-xism:(?-
xism:[^\[\]\\])|(?-xism:\\(?-xism:[^\x0A\x0D])))+)*\s*\](?-x
ism:(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism
:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:\s*(?-xism:(?-xism:
(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|)+)*\s*\)\s*))
+)*\s*\)\s*)+|\s+)*))))(?-xism:\s*\((?:\s*(?-xism:(?-xism:(?
>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0D]))|(?-xism:\s*\((?:
\s*(?-xism:(?-xism:(?>[^()\\]+))|(?-xism:\\(?-xism:[^\x0A\x0
D]))|)+)*\s*\)\s*))+)*\s*\)\s*)*)"
.Replace("<DQ>", "\"")
.Replace("\t", "")
.Replace(" ", "")
.Replace("\r", "")
.Replace("\n", "");
private static Regex mailbox =
new Regex(gibberish, RegexOptions.ExplicitCapture);
Rails 2.3.4 Persisting Model on Validation Failure
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
ASP.NET Custom Validator Client side & Server Side validation not firing
Your CustomValidator
will only fire when the TextBox
isn't empty.
If you need to ensure that it's not empty then you'll need a RequiredFieldValidator
too.
Note: If the input control is empty,
no validation functions are called and
validation succeeds. Use a
RequiredFieldValidator control to
require the user to enter data in the
input control.
EDIT:
If your CustomValidator
specifies the ControlToValidate
attribute (and your original example does) then your validation functions will only be called when the control isn't empty.
If you don't specify ControlToValidate
then your validation functions will be called every time.
This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator
, you could omit the ControlToValidate
attribute from the CustomValidator
and setup your validation functions to do something like this:
Client Side code (Javascript):
function TextBoxDCountyClient(sender, args) {
var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
if (v == '') {
args.IsValid = false; // field is empty
}
else {
// do your other validation tests here...
}
}
Server side code (C#):
protected void TextBoxDTownCity_Validate(
object source, ServerValidateEventArgs args)
{
string v = TextBoxDTownCity.Text;
if (v == string.Empty)
{
args.IsValid = false; // field is empty
}
else
{
// do your other validation tests here...
}
}
How to validate an email address in JavaScript
HTML5 itself has email validation. If your browser supports HTML5 then you can use the following code.
<form><input type="email" placeholder="[email protected]" required>
<input type="submit">
</form>
jsFiddle link
From the HTML5 spec:
A valid e-mail address is a string that matches the email
production of the following ABNF, the character set for which is Unicode.
email = 1*( atext / "." ) "@" label *( "." label )
label = let-dig [ [ ldh-str ] let-dig ] ; limited to a length of 63 characters by RFC 1034 section 3.5
atext = < as defined in RFC 5322 section 3.2.3 >
let-dig = < as defined in RFC 1034 section 3.5 >
ldh-str = < as defined in RFC 1034 section 3.5 >
This requirement is a willful violation of RFC 5322, which defines a syntax for e-mail addresses that is simultaneously too strict (before the "@" character), too vague (after the "@" character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.
The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
ASP.NET email validator regex
I don't validate email address format anymore (Ok I check to make sure there is an at sign and a period after that). The reason for this is what says the correctly formatted address is even their email? You should be sending them an email and asking them to click a link or verify a code. This is the only real way to validate an email address is valid and that a person is actually able to recieve email.
Remove values from select list based on condition
with pure javascript
var condition = true; // your condition
if(condition) {
var theSelect = document.getElementById('val');
var options = theSelect.getElementsByTagName('OPTION');
for(var i=0; i<options.length; i++) {
if(options[i].innerHTML == 'Apple' || options[i].innerHTML == 'Cars') {
theSelect.removeChild(options[i]);
i--; // options have now less element, then decrease i
}
}
}
not tested with IE (if someone can confirm it...)
How to Call a JS function using OnClick event
Inline code takes higher precedence than the other ones. To call your other function func () call it from the f1 ().
Inside your function, add a line,
function fun () {
// Your code here
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
fun ();
}
Rewriting your whole code,
<!DOCTYPE html>
<html>
<head>
<script>
function fun()
{
alert("hello");
//validation code to see State field is mandatory.
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
fun ();
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
State: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
</form>
<table><tr><td id="Save" onclick="f1()">click</td></tr></table>
</body>
</html>
How do you do dynamic / dependent drop downs in Google Sheets?
Edit: The answer below may be satisfactory, but it has some drawbacks:
There is a noticeable pause for the running of the script. I'm on a 160 ms latency, and it's enough to be annoying.
It works by building a new range each time you edit a given row. This gives an 'invalid contents' to previous entries some of the time
I hope others can clean this up somewhat.
Here's another way to do it, that saves you a ton of range naming:
Three sheets in the worksheet: call them Main, List, and DRange (for dynamic range.)
On the Main sheet, column 1 contains a timestamp. This time stamp is modified onEdit.
On List your categories and subcategories are arranged as a simple list. I'm using this for plant inventory at my tree farm, so my list looks like this:
Group | Genus | Bot_Name
Conifer | Abies | Abies balsamea
Conifer | Abies | Abies concolor
Conifer | Abies | Abies lasiocarpa var bifolia
Conifer | Pinus | Pinus ponderosa
Conifer | Pinus | Pinus sylvestris
Conifer | Pinus | Pinus banksiana
Conifer | Pinus | Pinus cembra
Conifer | Picea | Picea pungens
Conifer | Picea | Picea glauca
Deciduous | Acer | Acer ginnala
Deciduous | Acer | Acer negundo
Deciduous | Salix | Salix discolor
Deciduous | Salix | Salix fragilis
...
Where | indicates separation into columns.
For convenience I also used the headers as names for named ranges.
DRrange A1 has the formula
=Max(Main!A2:A1000)
This returns the most recent timestamp.
A2 to A4 have variations on:
=vlookup($A$1,Inventory!$A$1:$E$1000,2,False)
with the 2 being incremented for each cell to the right.
On running A2 to A4 will have the currently selected Group, Genus and Species.
Below each of these, is a filter command something like this:
=unique(filter(Bot_Name,REGEXMATCH(Bot_Name,C1)))
These filters will populate a block below with matching entries to the contents of the top cell.
The filters can be modified to suit your needs, and to the format of your list.
Back to Main: Data validation in Main is done using ranges from DRange.
The script I use:
function onEdit(event) {
//SETTINGS
var dynamicSheet='DRange'; //sheet where the dynamic range lives
var tsheet = 'Main'; //the sheet you are monitoring for edits
var lcol = 2; //left-most column number you are monitoring; A=1, B=2 etc
var rcol = 5; //right-most column number you are monitoring
var tcol = 1; //column number in which you wish to populate the timestamp
//
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn(); //scol is the column number of the edited cell
if (scol >= lcol && scol <= rcol) {
s.getRange(r.getRow(), tcol).setValue(new Date());
for(var looper=scol+1; looper<=rcol; looper++) {
s.getRange(r.getRow(),looper).setValue(""); //After edit clear the entries to the right
}
}
}
}
Original Youtube presentation that gave me most of the onEdit timestamp component:
https://www.youtube.com/watch?v=RDK8rjdE85Y
Check if inputs are empty using jQuery
Great collection of answers, would like to add that you can also do this using the :placeholder-shown
CSS selector. A little cleaner to use IMO, especially if you're already using jQ and have placeholders on your inputs.
_x000D_
_x000D_
if ($('input#cust-descrip').is(':placeholder-shown')) {_x000D_
console.log('Empty');_x000D_
}_x000D_
_x000D_
$('input#cust-descrip').on('blur', '', function(ev) {_x000D_
if (!$('input#cust-descrip').is(':placeholder-shown')) {_x000D_
console.log('Has Text!');_x000D_
}_x000D_
else {_x000D_
console.log('Empty!');_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="form-control" id="cust-descrip" autocomplete="off" placeholder="Description">
_x000D_
_x000D_
_x000D_
You can also make use of the :valid
and :invalid
selectors if you have inputs that are required. You can use these selectors if you are using the required attribute on an input.
How do I turn off the mysql password validation?
On some installations, you cannot execute this command until you have reset the root password. You cannot reset the root password, until you execute this command. Classic Catch-22.
One solution not mention by other responders is to temporarily disable the plugin via mysql configuration. In any my.cnf
, in the [mysqld]
section, add:
skip-validate_password=1
and restart the server. Change the password, and set the value back to 0, and restart again.
How can I listen to the form submit event in javascript?
Based on your requirements you can also do the following without libraries like jQuery:
Add this to your head:
window.onload = function () {
document.getElementById("frmSubmit").onsubmit = function onSubmit(form) {
var isValid = true;
//validate your elems here
isValid = false;
if (!isValid) {
alert("Please check your fields!");
return false;
}
else {
//you are good to go
return true;
}
}
}
And your form may still look something like:
<form id="frmSubmit" action="/Submit">
<input type="submit" value="Submit" />
</form>
Regular expression for URL validation (in JavaScript)
try with this:
var RegExp =/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;
Sql script to find invalid email addresses
SELECT * FROM people WHERE email NOT LIKE '%_@__%.__%'
Anything more complex will likely return false negatives and run slower.
Validating e-mail addresses in code is virtually impossible.
EDIT: Related questions
How to validate white spaces/empty spaces? [Angular 2]
To validate white space in starting in an input you can just call change event and do inline function for that.
_x000D_
_x000D_
<input type="text" class="form-control"
placeholder="First Name without white space in starting"
name="firstName"
#firstName="ngModel"
[(ngModel)]="user.FirstName"
(change) ="user.FirstName = user.FirstName.trim()"
required/>
_x000D_
_x000D_
_x000D_
Easy way to test a URL for 404 in PHP?
I found this answer here:
if(($twitter_XML_raw=file_get_contents($timeline))==false){
// Retrieve HTTP status code
list($version,$status_code,$msg) = explode(' ',$http_response_header[0], 3);
// Check the HTTP Status code
switch($status_code) {
case 200:
$error_status="200: Success";
break;
case 401:
$error_status="401: Login failure. Try logging out and back in. Password are ONLY used when posting.";
break;
case 400:
$error_status="400: Invalid request. You may have exceeded your rate limit.";
break;
case 404:
$error_status="404: Not found. This shouldn't happen. Please let me know what happened using the feedback link above.";
break;
case 500:
$error_status="500: Twitter servers replied with an error. Hopefully they'll be OK soon!";
break;
case 502:
$error_status="502: Twitter servers may be down or being upgraded. Hopefully they'll be OK soon!";
break;
case 503:
$error_status="503: Twitter service unavailable. Hopefully they'll be OK soon!";
break;
default:
$error_status="Undocumented error: " . $status_code;
break;
}
Essentially, you use the "file get contents" method to retrieve the URL, which automatically populates the http response header variable with the status code.
Check if input value is empty and display an alert
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
AngularJS: How do I manually set input to $valid in controller?
You cannot directly change a form's validity. If all the descendant inputs are valid, the form is valid, if not, then it is not.
What you should do is to set the validity of the input element. Like so;
addItem.capabilities.$setValidity("youAreFat", false);
Now the input (and so the form) is invalid.
You can also see which error causes invalidation.
addItem.capabilities.errors.youAreFat == true;
Disable validation of HTML5 form elements
I just wanted to add that using the novalidate attribute in your form will only prevent the browser from sending the form. The browser still evaluates the data and adds the :valid and :invalid pseudo classes.
I found this out because the valid and invalid pseudo classes are part of the HTML5 boilerplate stylesheet which I have been using. I just removed the entries in the CSS file that related to the pseudo classes. If anyone finds another solution please let me know.
How can I check if a single character appears in a string?
static String removeOccurences(String a, String b)
{
StringBuilder s2 = new StringBuilder(a);
for(int i=0;i<b.length();i++){
char ch = b.charAt(i);
System.out.println(ch+" first index"+a.indexOf(ch));
int lastind = a.lastIndexOf(ch);
for(int k=new String(s2).indexOf(ch);k > 0;k=new String(s2).indexOf(ch)){
if(s2.charAt(k) == ch){
s2.deleteCharAt(k);
System.out.println("val of s2 : "+s2.toString());
}
}
}
System.out.println(s1.toString());
return (s1.toString());
}
.NET 4.0 has a new GAC, why?
Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.
In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.
The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.
To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.
Source
Why?
It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.
See the following information in MSDN about the GAC changes in 4.0.
For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application
The CLR version used for both .NET
Framework 2.0 and .NET Framework 3.5
is CLR 2.0. As a result of this, there
was no need in the previous two
framework releases to split the GAC.
The problem of breaking older (in this
case, .NET 2.0) applications
resurfaces in Net Framework 4.0 at
which point CLR 4.0 released. Hence,
to avoid interference issues between
CLR 2.0 and CLR 4.0, the GAC is now
split into private GACs for each
runtime.
As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.
Sorting object property by values
To find frequency of each element and sort it by frequency/values.
_x000D_
_x000D_
let response = ["apple", "orange", "apple", "banana", "orange", "banana", "banana"];
let frequency = {};
response.forEach(function(item) {
frequency[item] = frequency[item] ? frequency[item] + 1 : 1;
});
console.log(frequency);
let intents = Object.entries(frequency)
.sort((a, b) => b[1] - a[1])
.map(function(x) {
return x[0];
});
console.log(intents);
_x000D_
_x000D_
_x000D_
Outputs:
{ apple: 2, orange: 2, banana: 3 }
[ 'banana', 'apple', 'orange' ]
W3WP.EXE using 100% CPU - where to start?
We had this on a recursive query that was dumping tons of data to the output - have you double checked everything does exit and no infinite loops exist?
Might try to narrow it down with a single page - we found ANTS to not be much help in that same case either - what we ended up doing was running the site hit a page watch the CPU - hit the next page watch CPU - very methodical and time consuming but if you cant find it with some code tracing you might be out of luck -
We were able to use IIS log files to track it to a set of pages that were suspect -
Hope that helps !
Toggle display:none style with JavaScript
Give the UL an ID and use the getElementById function:
<html>
<body>
<script>
function toggledisplay(elementID)
{
(function(style) {
style.display = style.display === 'none' ? '' : 'none';
})(document.getElementById(elementID).style);
}
</script>
<a href="#" title="Show Tags" onClick="toggledisplay('changethis');">Show All Tags</a>
<ul class="subforums" id="changethis" style="overflow-x: visible; overflow-y: visible; ">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
PostgreSQL query to list all table names?
Open up the postgres terminal with the databse you would like:
psql dbname (run this line in a terminal)
then, run this command in the postgres environment
\d
This will describe all tables by name. Basically a list of tables by name ascending.
Then you can try this to describe a table by fields:
\d tablename.
Hope this helps.
How to loop through file names returned by find?
I like to use find which is first assigned to variable and IFS switched to new line as follow:
FilesFound=$(find . -name "*.txt")
IFSbkp="$IFS"
IFS=$'\n'
counter=1;
for file in $FilesFound; do
echo "${counter}: ${file}"
let counter++;
done
IFS="$IFSbkp"
As commented by @Konrad Rudolph this will not work with "new lines" in file name. I still think it is handy as it covers most of the cases when you need to loop over command output.
JavaScript hide/show element
_x000D_
_x000D_
function showStuff(id, text, btn) {_x000D_
document.getElementById(id).style.display = 'block';_x000D_
// hide the lorem ipsum text_x000D_
document.getElementById(text).style.display = 'none';_x000D_
// hide the link_x000D_
btn.style.display = 'none';_x000D_
}
_x000D_
<td class="post">_x000D_
_x000D_
<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>_x000D_
<span id="answer1" style="display: none;">_x000D_
<textarea rows="10" cols="115"></textarea>_x000D_
</span>_x000D_
_x000D_
<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>_x000D_
</td>
_x000D_
_x000D_
_x000D_
Using multiple delimiters in awk
I see many perfect answers are up on the board, but still would like to upload my piece of code too,
awk -F"/" '{print $3 " " $5 " " $7}' sam | sed 's/ cat.* =//g'
Count length of array and return 1 if it only contains one element
A couple other options:
Use the comma operator to create an array:
$cars = ,"bmw"
$cars.GetType().FullName
# Outputs: System.Object[]
Use array subexpression syntax:
$cars = @("bmw")
$cars.GetType().FullName
# Outputs: System.Object[]
If you don't want an object array you can downcast to the type you want e.g. a string array.
[string[]] $cars = ,"bmw"
[string[]] $cars = @("bmw")
How to extract numbers from string in c?
Make a state machine that operates on one basic principle: is the current character a number.
- When transitioning from non-digit to digit, you initialize your current_number := number.
- when transitioning from digit to digit, you "shift" the new digit in:
current_number := current_number * 10 + number;
- when transitioning from digit to non-digit, you output the current_number
- when from non-digit to non-digit, you do nothing.
Optimizations are possible.
Failed to find Build Tools revision 23.0.1
As the error says
Failed to find build Tools revision 23.0.1
This means that in your project you have used
buildToolsVersion "23.0.3"
So,You need to download the exact same version this makes the error disappear
**Step 1:**
GO to Tools and click SDK Manager
**Step 2:**
you can see SDK Platforms ,SDK Tools and SDK update Sites
**Step3:**
Click SDK Tools and click show package details
**Step 4:**
Select the version that you have mentioned in your Project
These Steps has solved my issue.
Executing <script> injected by innerHTML after AJAX call
Here is the script that will evaluates all script tags in the text.
function evalJSFromHtml(html) {
var newElement = document.createElement('div');
newElement.innerHTML = html;
var scripts = newElement.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
eval(script.innerHTML);
}
}
Just call this function after you receive your HTML from server. Be warned: using eval
can be dangerous.
Demo:
http://plnkr.co/edit/LA7OPkRfAtgOhwcAnLrl?p=preview
XSL substring and indexOf
Here is some one liner xpath 1.0 expressions for IndexOf( $text, $searchString ):
If you need the position of the FIRST character of the sought string, or 0 if it is not present:
contains($text,$searchString)*(1 + string-length(substring-before($text,$searchString)))
If you need the position of the first character AFTER the found string, or 0 if it is not present:
contains($text,$searchString)*(1 + string-length(substring-before($text,$searchString)) + string-length($searchString))
Alternatively if you need the position of the first character AFTER the found string, or length+1 if it is not present:
1 + string-length($right) - string-length(substring-after($right,$searchString))
That should cover most cases that you need.
Note: The multiplication by contains( ... ) causes the true or false result of the contains( ... ) function to be converted to 1 or 0, which elegantly provides the "0 when not found" part of the logic.
SQL Server stored procedure creating temp table and inserting value
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
How to make a .jar out from an Android Studio project
In the Android Studio IDE, access the "Run Anything bar" by:
CTRL+CTRL +gradle CreateFullJarRelease
+ENTER
After that you'll find your artefact in this folder in your project
Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar
OR
Gradle has already a Task
for that, in the gradle side-menu, under the other
folder.
Then scroll down to createFullJarRelease
and click it.
After that you'll find your artefact in this folder in your project
Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar
How to load a resource from WEB-INF directory of a web archive
Here is how it works for me with no Servlet use.
Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml
In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )
Now let's use class loader:
InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
What is the difference between an IntentService and a Service?
service: It runs in the background on your system. For example,
- If you went to a hotel and you give your order for a soup to a server
- The server gets your order and sends to chef
- You don't know how the soup is made in the kitchen and what processes are required for making the soup
- Once your order is ready, the server brings you the soup.
background process: chef making soup
IntentService:- it's consecutive service.. (i.e) when you order many food items at a time to server but the server delivers those items one by one and not deliver them all at once.
mysql update multiple columns with same now()
If you really need to be sure that now()
has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update
but last_update
hasn't been updated yet)
you could do something like:
mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;
anyway I think that mysql is clever enough to ask for now()
only once per query.
Bootstrap 4 Dropdown Menu not working?
It's an issue with popper.js
file. What I found at the official site was that bundle files include popper in itself but not jquery. I managed to fix it by adding link to these files:
bootstrap.bundle.js
bootstrap.bundle.min.js
I removed popper.js
however since it comes within the bundle file.
How to Retrieve value from JTextField in Java Swing?
Just use event.getSource()
frim within actionPerformed
Cast it to the component
for Ex, if you need combobox
JComboBox comboBox = (JComboBox) event.getSource();
JTextField txtField = (JTextField) event.getSource();
use appropriate api to get the value,
for Ex.
Object selected = comboBox.getSelectedItem(); etc.
SELECT INTO a table variable in T-SQL
OK, Now with enough effort i am able to insert into @table using the below :
INSERT @TempWithheldTable SELECT
a.SuspendedReason,
a.SuspendedNotes,
a.SuspendedBy ,
a.ReasonCode FROM OPENROWSET( BULK 'C:\DataBases\WithHeld.csv', FORMATFILE =
N'C:\DataBases\Format.txt',
ERRORFILE=N'C:\Temp\MovieLensRatings.txt'
) AS a;
The main thing here is selecting columns to insert .
URL Encoding using C#
I think people here got sidetracked by the UrlEncode message. URLEncoding is not what you want -- you want to encode stuff that won't work as a filename on the target system.
Assuming that you want some generality -- feel free to find the illegal characters on several systems (MacOS, Windows, Linux and Unix), union them to form a set of characters to escape.
As for the escape, a HexEscape should be fine (Replacing the characters with %XX). Convert each character to UTF-8 bytes and encode everything >128 if you want to support systems that don't do unicode. But there are other ways, such as using back slashes "\" or HTML encoding """. You can create your own. All any system has to do is 'encode' the uncompatible character away. The above systems allow you to recreate the original name -- but something like replacing the bad chars with spaces works also.
On the same tangent as above, the only one to use is
Uri.EscapeDataString
-- It encodes everything that is needed for OAuth, it doesn't encode the things that OAuth forbids encoding, and encodes the space as %20 and not + (Also in the OATH Spec) See: RFC 3986. AFAIK, this is the latest URI spec.
Difference of two date time in sql server
CREATE FUNCTION getDateDiffHours(@fdate AS datetime,@tdate as datetime)
RETURNS varchar (50)
AS
BEGIN
DECLARE @cnt int
DECLARE @cntDate datetime
DECLARE @dayDiff int
DECLARE @dayDiffWk int
DECLARE @hrsDiff decimal(18)
DECLARE @markerFDate datetime
DECLARE @markerTDate datetime
DECLARE @fTime int
DECLARE @tTime int
DECLARE @nfTime varchar(8)
DECLARE @ntTime varchar(8)
DECLARE @nfdate datetime
DECLARE @ntdate datetime
-------------------------------------
--DECLARE @fdate datetime
--DECLARE @tdate datetime
--SET @fdate = '2005-04-18 00:00:00.000'
--SET @tdate = '2005-08-26 15:06:07.030'
-------------------------------------
DECLARE @tempdate datetime
--setting weekends
SET @fdate = dbo.getVDate(@fdate)
SET @tdate = dbo.getVDate(@tdate)
--RETURN @fdate
SET @fTime = datepart(hh,@fdate)
SET @tTime = datepart(hh,@tdate)
--RETURN @fTime
if datediff(hour,@fdate, @tdate) <= 9
RETURN(convert(varchar(50),0) + ' Days ' + convert(varchar(50),datediff(hour,@fdate, @tdate))) + ' Hours'
else
--setting working hours
SET @nfTime = dbo.getV00(convert(varchar(2),datepart(hh,@fdate))) + ':' +dbo.getV00(convert(varchar(2),datepart(mi,@fdate))) + ':'+ dbo.getV00(convert(varchar(2),datepart(ss,@fdate)))
SET @ntTime = dbo.getV00(convert(varchar(2),datepart(hh,@tdate))) + ':' +dbo.getV00(convert(varchar(2),datepart(mi,@tdate))) + ':'+ dbo.getV00(convert(varchar(2),datepart(ss,@tdate)))
IF @fTime > 17
begin
set @nfTime = '17:00:00'
end
else
begin
IF @fTime < 8
set @nfTime = '08:00:00'
end
IF @tTime > 17
begin
set @ntTime = '17:00:00'
end
else
begin
IF @tTime < 8
set @ntTime = '08:00:00'
end
-- used for working out whole days
SET @nfdate = dateadd(day,1,@fdate)
SET @ntdate = @tdate
SET @nfdate = convert(varchar,datepart(yyyy,@nfdate)) + '-' + convert(varchar,datepart(mm,@nfdate)) + '-' + convert(varchar,datepart(dd,@nfdate))
SET @ntdate = convert(varchar,datepart(yyyy,@ntdate)) + '-' + convert(varchar,datepart(mm,@ntdate)) + '-' + convert(varchar,datepart(dd,@ntdate))
SET @cnt = 0
SET @dayDiff = 0
SET @cntDate = @nfdate
SET @dayDiffWk = convert(decimal(18,2),@ntdate-@nfdate)
--select @nfdate,@ntdate
WHILE @cnt < @dayDiffWk
BEGIN
IF (NOT DATENAME(dw, @cntDate) = 'Saturday') AND (NOT DATENAME(dw, @cntDate) = 'Sunday')
BEGIN
SET @dayDiff = @dayDiff + 1
END
SET @cntDate = dateadd(day,1,@cntDate)
SET @cnt = @cnt + 1
END
--SET @dayDiff = convert(decimal(18,2),@ntdate-@nfdate) --datediff(day,@nfdate,@ntdate)
--SELECT @dayDiff
set @fdate = convert(varchar,datepart(yyyy,@fdate)) + '-' + convert(varchar,datepart(mm,@fdate)) + '-' + convert(varchar,datepart(dd,@fdate)) + ' ' + @nfTime
set @tdate = convert(varchar,datepart(yyyy,@tdate)) + '-' + convert(varchar,datepart(mm,@tdate)) + '-' + convert(varchar,datepart(dd,@tdate)) + ' ' + @ntTime
set @markerFDate = convert(varchar,datepart(yyyy,@fdate)) + '-' + convert(varchar,datepart(mm,@fdate)) + '-' + convert(varchar,datepart(dd,@fdate)) + ' ' + '17:00:00'
set @markerTDate = convert(varchar,datepart(yyyy,@tdate)) + '-' + convert(varchar,datepart(mm,@tdate)) + '-' + convert(varchar,datepart(dd,@tdate)) + ' ' + '08:00:00'
--select @fdate,@tdate
--select @markerFDate,@markerTDate
set @hrsDiff = convert(decimal(18,2),datediff(hh,@fdate,@markerFDate))
--select @hrsDiff
set @hrsDiff = @hrsDiff + convert(int,datediff(hh,@markerTDate,@tdate))
--select @fdate,@tdate
IF convert(varchar,datepart(yyyy,@fdate)) + '-' + convert(varchar,datepart(mm,@fdate)) + '-' + convert(varchar,datepart(dd,@fdate)) = convert(varchar,datepart(yyyy,@tdate)) + '-' + convert(varchar,datepart(mm,@tdate)) + '-' + convert(varchar,datepart(dd,@tdate))
BEGIN
--SET @hrsDiff = @hrsDiff - 9
Set @hrsdiff = datediff(hour,@fdate,@tdate)
END
--select FLOOR((@hrsDiff / 9))
IF (@hrsDiff / 9) > 0
BEGIN
SET @dayDiff = @dayDiff + FLOOR(@hrsDiff / 9)
SET @hrsDiff = @hrsDiff - FLOOR(@hrsDiff / 9)*9
END
--select convert(varchar(50),@dayDiff) + ' Days ' + convert(varchar(50),@hrsDiff) + ' Hours'
RETURN(convert(varchar(50),@dayDiff) + ' Days ' + convert(varchar(50),@hrsDiff)) + ' Hours'
END
Plotting power spectrum in python
if rate is the sampling rate(Hz), then np.linspace(0, rate/2, n)
is the frequency array of every point in fft. You can use rfft
to calculate the fft in your data is real values:
import numpy as np
import pylab as pl
rate = 30.0
t = np.arange(0, 10, 1/rate)
x = np.sin(2*np.pi*4*t) + np.sin(2*np.pi*7*t) + np.random.randn(len(t))*0.2
p = 20*np.log10(np.abs(np.fft.rfft(x)))
f = np.linspace(0, rate/2, len(p))
plot(f, p)
signal x contains 4Hz & 7Hz sin wave, so there are two peaks at 4Hz & 7Hz.
phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client
Every once in a while, and this isn't often, but every once in a while, there's a typo in your password. A subtle difference between an upper and lower case letter, for example. I went through many, many of these solutions.
I had simply mistyped the password, and it was saved to my browser, so I didn't think to check it again.
Since this error CAN be caused by a missed password, just double-check before you go on this quest.
String.strip() in Python
No, it is better practice to leave them out.
Without strip(), you can have empty keys and values:
apples<tab>round, fruity things
oranges<tab>round, fruity things
bananas<tab>
Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.
How to Change Margin of TextView
TextView does not support setMargins. Android docs say:
Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.
AngularJS multiple filter with custom filter function
In view file (HTML or EJS)
<div ng-repeat="item in vm.itemList | filter: myFilter > </div>
and In Controller
$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}
CSS - how to make image container width fixed and height auto stretched
No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.
You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.
Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto
is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100%
like this fiddle.
img {
width: 100%;
height: auto;
}
http://jsfiddle.net/D8uUd/1/
form serialize javascript (no framework)
I could be crazy but I'm finding these answers seriously bloated. Here's my solution
function serialiseForm(form) {
var input = form.getElementsByTagName("input");
var formData = {};
for (var i = 0; i < input.length; i++) {
formData[input[i].name] = input[i].value;
}
return formData = JSON.stringify(formData);
}
How to find the number of days between two dates
As @Forte L. mentioned you can do the following as well;
SELECT dtCreated
, bActive
, dtLastPaymentAttempt
, dtLastUpdated
, dtLastVisit
, DATEDIFF(day, dtCreated, dtLastUpdated) Difference
FROM Customers
WHERE (bActive = 'true')
AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))
Concept behind putting wait(),notify() methods in Object class
This is just my 2 cents on this question...not sure if this holds true in its entirety.
Each Object has a monitor and waitset --> set of threads (this is probably more at OS level). This means the monitor and the waitset can be seen as private members of an object. Having wait() and notify() methods in Thread class would mean giving public access to the waitset or using get-set methods to modify the waitset. You wouldnt want to do that because thats bad designing.
Now given that the Object knows the thread/s waiting for its monitor, it should be the job of the Object to go and awaken those threads waiting for it rather than an Object of thread class going and awakening each one of them (which would be possible only if the thread class object is given access to the waitset). However, it is not the job of a particular thread to go and awaken each of the waiting threads. (This is exactly what would happened if all these methods were inside the Thread class). Its job is just to release the lock and move ahead with its own task. A thread works independently and does not need to know whihc other threads are waiting for the objects monitor (it is an unnecessary detail for the thread class object). If it started awakening each thread on its own.. it is moving from away its core functionality and that is to carry out its own task. When you think about a scene where there might 1000's of threads.. you can assume how much of a performance impact it can create. Hence, given that Object Class knows who is waiting on it, it can carry out the job awakening the waiting threads and the thread which sent notify() can carry out with its further processing.
To give an analogy (perhaps not the right one but cant think of anything else). When we have a power outage, we call a customer representative of that company because she knows the right people to contact to fix it. You as a consumer are not allowed to know who are the engineers behind it and even if you know, you cannot possibly call each one of them and tell them of your troubles (that is not ur duty. Your duty is to inform them about the outage and the CR's job is to go and notify(awaken) the right engineers for it).
Let me know if this sounds right... (I do have the ability to confuse sometimes with my words).
C programming in Visual Studio
You can use Visual Studio for C, but if you are serious about learning the newest C available, I recommend using something like Code::Blocks with MinGW-TDM version, which you can get a 32 bit version of. I use version 5.1 which supports the newest C and C++. Another benefit is that it is a better platform for creating software that can be easily ported to other platforms. If you were, for example, to code in C, using the SDL library, you could create software that could be recompiled with little to no changes to the code, on Linux, Apple and many mobile devices. The way Microsoft has been going these days, I think this is definitely the better route to take.
What is the "assert" function?
There are three main reasons for using the assert() function over the normal if else and printf
assert() function is mainly used in the debugging phase, it is tedious to write if else with a printf statement everytime you want to test a condition which might not even make its way in the final code.
In large software deployments , assert comes very handy where you can make the compiler ignore the assert statements using the NDEBUG macro defined before linking the header file for assert() function.
assert() comes handy when you are designing a function or some code and want to get an idea as to what limits the code will and not work and finally include an if else for evaluating it basically playing with assumptions.
Show a div with Fancybox
I use approach with appending "singleton" link for element you want to show in fancybox. This is code, what I use with some minor edits:
function showElementInPopUp(elementId) {
var fancyboxAnchorElementId = "fancyboxTriggerFor_" + elementId;
if ($("#"+fancyboxAnchorElementId).length == 0) {
$("body").append("<a id='" + fancyboxAnchorElementId + "' href='#" + elementId+ "' style='display:none;'></a>");
$("#"+fancyboxAnchorElementId).fancybox();
}
$("#" + fancyboxAnchorElementId).click();
}
Additional explanation:
If you show fancybox with "content" option, it will duplicate DOM, which is inside elements. Sometimes this is not OK. In my case I needed to have the same elements, because they were used in form.
Prevent line-break of span element
Put this in your CSS:
white-space:nowrap;
Get more information here: http://www.w3.org/wiki/CSS/Properties/white-space
white-space
The white-space
property declares how white space inside the element is handled.
Values
normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.
pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.
nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.
pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
inherit
Takes the same specified value as the property for the element's parent.
How do I bind a List<CustomObject> to a WPF DataGrid?
if you do not expect that your list
will be recreated then you can use the same approach as you've used for Asp.Net (instead of DataSource
this property in WPF is usually named ItemsSource
):
this.dataGrid1.ItemsSource = list;
But if you would like to replace your list
with new collection instance then you should consider using databinding
.
Convert a Unicode string to a string in Python (containing extra symbols)
No answere worked for my case, where I had a string variable containing unicode chars, and no encode-decode explained here did the work.
If I do in a Terminal
echo "no me llama mucho la atenci\u00f3n"
or
python3
>>> print("no me llama mucho la atenci\u00f3n")
The output is correct:
output: no me llama mucho la atención
But working with scripts loading this string variable didn't work.
This is what worked on my case, in case helps anybody:
string_to_convert = "no me llama mucho la atenci\u00f3n"
print(json.dumps(json.loads(r'"%s"' % string_to_convert), ensure_ascii=False))
output: no me llama mucho la atención
What's the difference between compiled and interpreted language?
What’s the difference between compiled and interpreted language?
The difference is not in the language; it is in the implementation.
Having got that out of my system, here's an answer:
In a compiled implementation, the original program is translated into native machine instructions, which are executed directly by the hardware.
In an interpreted implementation, the original program is translated into something else. Another program, called "the interpreter", then examines "something else" and performs whatever actions are called for. Depending on the language and its implementation, there are a variety of forms of "something else". From more popular to less popular, "something else" might be
Binary instructions for a virtual machine, often called bytecode, as is done in Lua, Python, Ruby, Smalltalk, and many other systems (the approach was popularized in the 1970s by the UCSD P-system and UCSD Pascal)
A tree-like representation of the original program, such as an abstract-syntax tree, as is done for many prototype or educational interpreters
A tokenized representation of the source program, similar to Tcl
The characters of the source program, as was done in MINT and TRAC
One thing that complicates the issue is that it is possible to translate (compile) bytecode into native machine instructions. Thus, a successful intepreted implementation might eventually acquire a compiler. If the compiler runs dynamically, behind the scenes, it is often called a just-in-time compiler or JIT compiler. JITs have been developed for Java, JavaScript, Lua, and I daresay many other languages. At that point you can have a hybrid implementation in which some code is interpreted and some code is compiled.
JSON date to Java date?
Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).
So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
produces a format that can parse both "2013-03-11T01:38:18.309Z"
and "2013-03-11T01:38:18.309+0000"
and will give you the same result.
Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.
I actually have more trouble on the JavaScript side to deal with both formats.
Trying to get property of non-object in
<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>
or
$sidemenus = mysql_fetch_array($results);
then
<?php echo $sidemenu['mname']."<br />";?>
Vue.js - How to properly watch for nested data
Another way to add that I used to 'hack' this solution was to do this:
I set up a seperate computed
value that would simply return the nested object value.
data : function(){
return {
my_object : {
my_deep_object : {
my_value : "hello world";
}.
},
};
},
computed : {
helper_name : function(){
return this.my_object.my_deep_object.my_value;
},
},
watch : {
helper_name : function(newVal, oldVal){
// do this...
}
}
Sorting table rows according to table header column using javascript or jquery
I've been working on a function to work within a library for a client, and have been having a lot of trouble keeping the UI responsive during the sorts (even with only a few hundred results).
The function has to resort the entire table each AJAX pagination, as new data may require injection further up. This is what I had so far:
- jQuery library required.
table
is the ID of the table being sorted.
- The table attributes
sort-attribute
, sort-direction
and the column attribute column
are all pre-set.
Using some of the details above I managed to improve performance a bit.
function sorttable(table) {
var context = $('#' + table), tbody = $('#' + table + ' tbody'), sortfield = $(context).data('sort-attribute'), c, dir = $(context).data('sort-direction'), index = $(context).find('thead th[data-column="' + sortfield + '"]').index();
if (!sortfield) {
sortfield = $(context).data('id-attribute');
};
switch (dir) {
case "asc":
tbody.find('tr').sort(function (a, b) {
var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
// if a < b return 1
return sortvala < sortvalb ? 1
// else if a > b return -1
: sortvala > sortvalb ? -1
// else they are equal - return 0
: 0;
}).appendTo(tbody);
break;
case "desc":
default:
tbody.find('tr').sort(function (a, b) {
var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
// if a < b return 1
return sortvala > sortvalb ? 1
// else if a > b return -1
: sortvala < sortvalb ? -1
// else they are equal - return 0
: 0;
}).appendTo(tbody);
break;
}
In principle the code works perfectly, but it's painfully slow... are there any ways to improve performance?
Handling of non breaking space: <p> </p> vs. <p> </p>
How about a workaround?
In my case I took the value of the textarea in a jQuery variable, and changed all "<p> "
to <p class="clear">
and clear class to have certain height and margin, as the following example:
jQuery
tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p> /g, '<p class="clear">');
the val is then saved to the database with the new val.
CSS
p.clear{height: 2px; margin-bottom: 3px;}
You can adjust the height & margin as you wish.
And since 'p' is a display: block element. it should give you the expected output.
Hope that helps!
When do you use Git rebase instead of Git merge?
It's simple. With rebase you say to use another branch as the new base for your work.
If you have, for example, a branch master
, you create a branch to implement a new feature, and say you name it cool-feature
, of course the master branch is the base for your new feature.
Now at a certain point you want to add the new feature you implemented in the master
branch. You could just switch to master
and merge the cool-feature
branch:
$ git checkout master
$ git merge cool-feature
But this way a new dummy commit is added. If you want to avoid spaghetti-history you can rebase:
$ git checkout cool-feature
$ git rebase master
And then merge it in master
:
$ git checkout master
$ git merge cool-feature
This time, since the topic branch has the same commits of master plus the commits with the new feature, the merge will be just a fast-forward.
creating an array of structs in c++
You can't use an initialization-list for a struct
after it's been initialized. You've already default-initialized the two Customer
structs when you declared the array customerRecords
. Therefore you're going to have either use member-access syntax to set the value of the non-static data members, initialize the structs using a list of initialization lists when you declare the array itself, or you can create a constructor for your struct and use the default operator=
member function to initialize the array members.
So either of the following could work:
Customer customerRecords[2];
customerRecords[0].uid = 25;
customerRecords[0].name = "Bob Jones";
customerRecords[1].uid = 25;
customerRecords[1].namem = "Jim Smith";
Or if you defined a constructor for your struct like:
Customer::Customer(int id, string input_name): uid(id), name(input_name) {}
You could then do:
Customer customerRecords[2];
customerRecords[0] = Customer(25, "Bob Jones");
customerRecords[1] = Customer(26, "Jim Smith");
Or you could do the sequence of initialization lists that Tuomas used in his answer. The reason his initialization-list syntax works is because you're actually initializing the Customer
structs at the time of the declaration of the array, rather than allowing the structs to be default-initialized which takes place whenever you declare an aggregate data-structure like an array.
Where does one get the "sys/socket.h" header/source file?
Since you've labeled the question C++, you might be interested in using boost::asio, ACE, or some other cross-platform socket library for C++ or for C. Some other cross-platform libraries may be found in the answers to C++ sockets library for cross-platform and Cross platform Networking API.
Assuming that using a third party cross-platform sockets library is not an option for you...
The header <sys/socket.h> is defined in IEEE Std. 1003.1 (POSIX), but sadly Windows is non-compliant with the POSIX standard. The MinGW compiler is a port of GCC for compiling Windows applications, and therefore does not include these POSIX system headers. If you install GCC using Cygwin, then it will include these system headers to emulate a POSIX environment on Windows. Be aware, however, that if you use Cygwin for sockets that a.) you will need to put the cygwin DLL in a place where your application can read it and b.) Cygwin headers and Windows headers don't interact very well (so if you plan on including windows.h
, then you probably don't want to be including sys/socket.h
).
My personal recommendation would be to download a copy of VirtualBox, download a copy of Ubuntu, install Ubuntu into VirtualBox, and then do your coding and testing on Ubuntu. Alternatively, I am told that Microsoft sells a "UNIX subsystem" and that it is pre-installed on certain higher-end editions of Windows, although I have no idea how compliant this system is (and, if it is compliant, with which edition of the UNIX standard it is compliant). Winsockets are also an option, although they can behave in subtly different ways than their POSIX counterparts, even though the signatures may be similar.
Assert an object is a specific type
Solution for JUnit 5
The documentation says:
However, JUnit Jupiter’s org.junit.jupiter.Assertions
class does not provide an assertThat()
method like the one found in JUnit 4’s org.junit.Assert
class which accepts a Hamcrest Matcher
. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.
Example for Hamcrest:
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
class HamcrestAssertionDemo {
@Test
void assertWithHamcrestMatcher() {
SubClass subClass = new SubClass();
assertThat(subClass, instanceOf(BaseClass.class));
}
}
Example for AssertJ:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class AssertJDemo {
@Test
void assertWithAssertJ() {
SubClass subClass = new SubClass();
assertThat(subClass).isInstanceOf(BaseClass.class);
}
}
Note that this assumes you want to test behaviors similar to instanceof
(which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.
Assigning multiple styles on an HTML element
In HTML the style tag has the following syntax:
style="property1:value1;property2:value2"
so in your case:
<h2 style="text-align:center;font-family:tahoma">TITLE</h2>
Hope this helps.
Node.js/Express.js App Only Works on Port 3000
The following works if you have something like this in your app.js:
http.createServer(app).listen(app.get('port'),
function(){
console.log("Express server listening on port " + app.get('port'));
});
Either explicitly hardcode your code to use the port you want, like:
app.set('port', process.env.PORT || 3000);
This code means set your port to the environment variable PORT
or if that is undefined
then set it to the literal 3000
.
Or, use your environment to set the port. Setting it via the environment is used to help delineate between PRODUCTION
and DEVELOPMENT
and also a lot of Platforms as a Service use the environment to set the port according to their specs as well as internal Express configs. The following sets an environment key=value pair and then launches your app.
$ PORT=8080 node app.js
In reference to your code example, you want something like this:
var express = require("express");
var app = express();
// sets port 8080 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 8080);
app.get('/', function(req, res){
res.send('hello world');
});
// Only works on 3000 regardless of what I set environment port to or how I set
// [value] in app.set('port', [value]).
// app.listen(3000);
app.listen(app.get('port'));
how to execute php code within javascript
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result
class.
Populating a dictionary using for loops (python)
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
Best way to parse command-line parameters?
I am from Java world, I like args4j because its simple, specification is more readable( thanks to annotations) and produces nicely formatted output.
Here is my example snippet:
Specification
import org.kohsuke.args4j.{CmdLineException, CmdLineParser, Option}
object CliArgs {
@Option(name = "-list", required = true,
usage = "List of Nutch Segment(s) Part(s)")
var pathsList: String = null
@Option(name = "-workdir", required = true,
usage = "Work directory.")
var workDir: String = null
@Option(name = "-master",
usage = "Spark master url")
var masterUrl: String = "local[2]"
}
Parse
//var args = "-listt in.txt -workdir out-2".split(" ")
val parser = new CmdLineParser(CliArgs)
try {
parser.parseArgument(args.toList.asJava)
} catch {
case e: CmdLineException =>
print(s"Error:${e.getMessage}\n Usage:\n")
parser.printUsage(System.out)
System.exit(1)
}
println("workDir :" + CliArgs.workDir)
println("listFile :" + CliArgs.pathsList)
println("master :" + CliArgs.masterUrl)
On invalid arguments
Error:Option "-list" is required
Usage:
-list VAL : List of Nutch Segment(s) Part(s)
-master VAL : Spark master url (default: local[2])
-workdir VAL : Work directory.
./xx.py: line 1: import: command not found
If you run a script directly e.g., ./xx.py
and your script has no shebang such as #!/usr/bin/env python
at the very top then your shell may execute it as a shell script. POSIX says:
If the execl() function fails due to an error equivalent to the
[ENOEXEC] error defined in the System Interfaces volume of
POSIX.1-2008, the shell shall execute a command equivalent to having a
shell invoked with the pathname resulting from the search as its first
operand, with any remaining arguments passed to the new shell, except
that the value of "$0" in the new shell may be set to the command
name. If the executable file is not a text file, the shell may bypass
this command execution. In this case, it shall write an error message,
and shall return an exit status of 126.
Note: you may get ENOEXEC
if your text file has no shebang.
Without the shebang, you shell tries to run your Python script as a shell script that leads to the error: import: command not found
.
Also, if you run your script as python xx.py
then you do not need the shebang. You don't even need it to be executable (+x
). Your script is interpreted by python
in this case.
On Windows, shebang is not used unless pylauncher is installed. It is included in Python 3.3+.
How to create a file with a given size in Linux?
Use fallocate
if you don't want to wait for disk.
Example:
fallocate -l 100G BigFile
Usage:
Usage:
fallocate [options] <filename>
Preallocate space to, or deallocate space from a file.
Options:
-c, --collapse-range remove a range from the file
-d, --dig-holes detect zeroes and replace with holes
-i, --insert-range insert a hole at range, shifting existing data
-l, --length <num> length for range operations, in bytes
-n, --keep-size maintain the apparent size of the file
-o, --offset <num> offset for range operations, in bytes
-p, --punch-hole replace a range with a hole (implies -n)
-z, --zero-range zero and ensure allocation of a range
-x, --posix use posix_fallocate(3) instead of fallocate(2)
-v, --verbose verbose mode
-h, --help display this help
-V, --version display version
How do I create a link to add an entry to a calendar?
You can have the program create an .ics (iCal) version of the calendar and then you can import this .ics into whichever calendar program you'd like: Google, Outlook, etc.
I know this post is quite old, so I won't bother inputting any code. But please comment on this if you'd like me to provide an outline of how to do this.
Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install
My MAC OS Crashed recently. I reinstalled macOS 10.7.4 and Xcode 4.5. But all provisioning profiles were showing the following message in organizer
.
Valid Signing identity not found
I struggled to find help for a couple of days. Later I realized that if you have migrated from one system to another(or formatted your system), you need to export your private key from your keychain from your old system to the new system (or new OS installed).
One can also export your developer profile/team developer profile in organizer.
Organizer > Teams > Developer Profile > Export
Hope it helps.
What REALLY happens when you don't free after malloc?
If a program forgets to free a few Megabytes before it exits the operating system will free them. But if your program runs for weeks at a time and a loop inside the program forgets to free a few bytes in each iteration you will have a mighty memory leak that will eat up all the available memory in your computer unless you reboot it on a regular basis => even small memory leaks might be bad if the program is used for a seriously big task even if it originally wasn't designed for one.
How to find where javaw.exe is installed?
It worked to me:
String javaHome = System.getProperty("java.home");
File f = new File(javaHome);
f = new File(f, "bin");
f = new File(f, "javaw.exe"); //or f = new File(f, "javaws.exe"); //work too
System.out.println(f + " exists: " + f.exists());
Replace values in list using Python
>>> L = range (11)
>>> [ x if x%2 == 1 else None for x in L ]
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
Does Python have an argc argument?
dir(sys)
says no. len(sys.argv)
works, but in Python it is better to ask for forgiveness than permission, so
#!/usr/bin/python
import sys
try:
in_file = open(sys.argv[1], "r")
except:
sys.exit("ERROR. Can't read supplied filename.")
text = in_file.read()
print(text)
in_file.close()
works fine and is shorter.
If you're going to exit anyway, this would be better:
#!/usr/bin/python
import sys
text = open(sys.argv[1], "r").read()
print(text)
I'm using print()
so it works in 2.7 as well as Python 3.
how to play video from url
Check whether your phone supports the video format or not.Even I had the problem when playing a 3gp file but it played a mp4 file perfectly.
How to achieve ripple animation using support library?
Sometimes you have a custom background, in that cases a better solution is use android:foreground="?selectableItemBackground"
Update
If you want ripple effect with rounded corners and custom background you can use this:
background_ripple.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/ripple_color">
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
<corners android:radius="5dp" />
</shape>
</item>
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
<corners android:radius="5dp" />
</shape>
</item>
layout.xml
<Button
android:id="@+id/btn_play"
android:background="@drawable/background_ripple"
app:backgroundTint="@color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/play_now" />
I used this on API >= 21
AttributeError: 'module' object has no attribute
Not sure how but the below change sorted my issue:
i was having the name of file and import name same for eg i had file name as emoji.py and i was trying to import emoji. But changing the name of file solved the issue .
Hope so it helps
How to get values from IGrouping
More clarified version of above answers:
IEnumerable<IGrouping<int, ClassA>> groups = list.GroupBy(x => x.PropertyIntOfClassA);
foreach (var groupingByClassA in groups)
{
int propertyIntOfClassA = groupingByClassA.Key;
//iterating through values
foreach (var classA in groupingByClassA)
{
int key = classA.PropertyIntOfClassA;
}
}
How to pass in password to pg_dump?
Backup over ssh with password using temporary .pgpass credentials and push to S3:
#!/usr/bin/env bash
cd "$(dirname "$0")"
DB_HOST="*******.*********.us-west-2.rds.amazonaws.com"
DB_USER="*******"
SSH_HOST="[email protected]_domain.com"
BUCKET_PATH="bucket_name/backup"
if [ $# -ne 2 ]; then
echo "Error: 2 arguments required"
echo "Usage:"
echo " my-backup-script.sh <DB-name> <password>"
echo " <DB-name> = The name of the DB to backup"
echo " <password> = The DB password, which is also used for GPG encryption of the backup file"
echo "Example:"
echo " my-backup-script.sh my_db my_password"
exit 1
fi
DATABASE=$1
PASSWORD=$2
echo "set remote PG password .."
echo "$DB_HOST:5432:$DATABASE:$DB_USER:$PASSWORD" | ssh "$SSH_HOST" "cat > ~/.pgpass; chmod 0600 ~/.pgpass"
echo "backup over SSH and gzip the backup .."
ssh "$SSH_HOST" "pg_dump -U $DB_USER -h $DB_HOST -C --column-inserts $DATABASE" | gzip > ./tmp.gz
echo "unset remote PG password .."
echo "*********" | ssh "$SSH_HOST" "cat > ~/.pgpass"
echo "encrypt the backup .."
gpg --batch --passphrase "$PASSWORD" --cipher-algo AES256 --compression-algo BZIP2 -co "$DATABASE.sql.gz.gpg" ./tmp.gz
# Backing up to AWS obviously requires having your credentials to be set locally
# EC2 instances can use instance permissions to push files to S3
DATETIME=`date "+%Y%m%d-%H%M%S"`
aws s3 cp ./"$DATABASE.sql.gz.gpg" s3://"$BUCKET_PATH"/"$DATABASE"/db/"$DATETIME".sql.gz.gpg
# s3 is cheap, so don't worry about a little temporary duplication here
# "latest" is always good to have because it makes it easier for dev-ops to use
aws s3 cp ./"$DATABASE.sql.gz.gpg" s3://"$BUCKET_PATH"/"$DATABASE"/db/latest.sql.gz.gpg
echo "local clean-up .."
rm ./tmp.gz
rm "$DATABASE.sql.gz.gpg"
echo "-----------------------"
echo "To decrypt and extract:"
echo "-----------------------"
echo "gpg -d ./$DATABASE.sql.gz.gpg | gunzip > tmp.sql"
echo
Just substitute the first couple of config lines with whatever you need - obviously.
For those not interested in the S3 backup part, take it out - obviously.
This script deletes the credentials in .pgpass
afterward because in some environments, the default SSH user can sudo without a password, for example an EC2 instance with the ubuntu
user, so using .pgpass
with a different host account in order to secure those credential, might be pointless.
How to emulate a do-while loop in Python?
for a do - while loop containing try statements
loop = True
while loop:
generic_stuff()
try:
questionable_stuff()
# to break from successful completion
# loop = False
except:
optional_stuff()
# to break from unsuccessful completion -
# the case referenced in the OP's question
loop = False
finally:
more_generic_stuff()
alternatively, when there's no need for the 'finally' clause
while True:
generic_stuff()
try:
questionable_stuff()
# to break from successful completion
# break
except:
optional_stuff()
# to break from unsuccessful completion -
# the case referenced in the OP's question
break
INSERT INTO @TABLE EXEC @query with SQL Server 2000
DECLARE @q nvarchar(4000)
SET @q = 'DECLARE @tmp TABLE (code VARCHAR(50), mount MONEY)
INSERT INTO @tmp
(
code,
mount
)
SELECT coa_code,
amount
FROM T_Ledger_detail
SELECT *
FROM @tmp'
EXEC sp_executesql @q
If you want in dynamic query
How to get the height of a body element
Set
html { height: 100%; }
body { min-height: 100%; }
instead of height: 100%
.
The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.
How to determine the current iPhone/device model?
SWIFT 3.1
my two cents for simply calling utsname:
func platform() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let size = Int(_SYS_NAMELEN) // is 32, but posix AND its init is 256....
let s = withUnsafeMutablePointer(to: &systemInfo.machine) {p in
p.withMemoryRebound(to: CChar.self, capacity: size, {p2 in
return String(cString: p2)
})
}
return s
}
as other did, but a bit cleaner about all the intricacy of C/Swift and back.
):
Returns values such as "x86_64"
IndentationError expected an indented block
If you are using a mac and sublime text 3, this is what you do.
Go to your /Packages/User/
and create a file called Python.sublime-settings
.
Typically /Packages/User
is inside your ~/Library/Application Support/Sublime Text 3/Packages/User/Python.sublime-settings
if you are using mac os x.
Then you put this in the Python.sublime-settings
.
{
"tab_size": 4,
"translate_tabs_to_spaces": false
}
Credit goes to Mark Byer's answer, sublime text 3 docs and python style guide.
This answer is mostly for readers who had the same issue and stumble upon this and are using sublime text 3 on Mac OS X.
How to increase font size in a plot in R?
In case you want to increase the font of the labels of the histogram when setting labels=TRUE
bp=hist(values, labels = FALSE,
main='Histogram',
xlab='xlab',ylab='ylab', cex.main=2, cex.lab=2,cex.axis=2)
text(x=bp$mids, y=bp$counts, labels=bp$counts ,cex=2,pos=3)
How to print jquery object/array
_x000D_
_x000D_
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];_x000D_
var data = arrofobject.map(arrofobject => arrofobject);_x000D_
console.log(data)
_x000D_
_x000D_
_x000D_
for more details please look at jQuery.map()
Passing multiple values for a single parameter in Reporting Services
this worked for a distinct set of strings ( e.g. "START", "END", "ERROR", "SUCCESS" )
1)define a Report-Parameter ( e.g. @log_status ) and check "Allow multiple values"
2) define a dataset
3) open the dataset-properties window
3a) in the Query-Tab enter your query: e.g.
select * from your_table where (CHARINDEX(your_column, @log_status,0) > 0)
3b) in the Parameters-Tab enter your Parameter, e.g.
Parametername: @log_status ; Parametervalue: <<Expr>>
3c) for the Expr click on the "fx"-Button and enter:
=join(Parameters!log_status.Value,",")
finished! ( it's similar to Ed Harper's solution, but sorry to say this didn't work for me )
String to LocalDate
As you use Joda Time, you should use DateTimeFormatter
:
final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);
If using Java 8 or later, then refer to hertzi's answer
Python display text with font & color?
There are 2 possibilities. In either case PyGame has to be initialized by pygame.init
.
import pygame
pygame.init()
Use either the pygame.font
module and create a pygame.font.SysFont
or pygame.font.Font
object. render()
a pygame.Surface
with the text and blit
the Surface to the screen:
my_font = pygame.font.SysFont(None, 50)
text_surface = myfont.render("Hello world!", True, (255, 0, 0))
screen.blit(text_surface, (10, 10))
Or use the pygame.freetype
module. Create a pygame.freetype.SysFont()
or pygame.freetype.Font
object. render()
a pygame.Surface
with the text or directly render_to()
the text to the screen:
my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)
my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))
See also Text and font
Minimal pygame.font
example: repl.it/@Rabbid76/PyGame-Text
import pygame
pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
text = font.render('Hello World', True, (255, 0, 0))
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
window.blit(text, text.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
Minimal pygame.freetype
example: repl.it/@Rabbid76/PyGame-FreeTypeText
import pygame
import pygame.freetype
pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()
ft_font = pygame.freetype.SysFont('Times New Roman', 80)
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
text_rect = ft_font.get_rect('Hello World')
text_rect.center = window.get_rect().center
ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0))
pygame.display.flip()
pygame.quit()
exit()
jquery clear input default value
Just a shorthand
$(document).ready(function() {
$(".input").val("Email Address");
$(".input").on("focus click", function(){
$(this).val("");
});
});
</script>
how to use substr() function in jquery?
Extract characters from a string:
var str = "Hello world!";
var res = str.substring(1,4);
The result of res
will be:
ell
http://www.w3schools.com/jsref/jsref_substring.asp
$('.dep_buttons').mouseover(function(){
$(this).text().substring(0,25);
if($(this).text().length > 30) {
$(this).stop().animate({height:"150px"},150);
}
$(".dep_buttons").mouseout(function(){
$(this).stop().animate({height:"40px"},150);
});
});
How to pull specific directory with git
Tried and tested this works !
mkdir <directory name> ; //Same directory name as the one you want to pull
cd <directory name>;
git remote add origin <GIT_URL>;
git checkout -b '<branch name>';
git config core.sparsecheckout true;
echo <directory name>/ >> .git/info/sparse-checkout;
git pull origin <pull branch name>
Hope this was helpful!
How to continue the code on the next line in VBA
If you want to insert this formula =SUMIFS(B2:B10,A2:A10,F2)
into cell G2, here is how I did it.
Range("G2")="=sumifs(B2:B10,A2:A10," & _
"F2)"
To split a line of code, add an ampersand, space and underscore.
bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js
On moving a .html template to a wordpress one, I found this "popper required" popping up regularly :)
Two reasons it happened for me: and the console error can be deceptive:
The error in the console can send you down the wrong path. It MIGHT not be the real issue. First reason for me was the order in which you have set your .js files to load. In html easy, put them in the same order as the theme template. In Wordpress, you need to enqueue them in the right order, but also set a priority if they don't appear in the right order,
Second thing is are the .js files in the header or the footer. Moving them to the footer can solve the issue - it did for me, after a day of trying to debug the issue. Usually doesn't matter, but for a complex page with lots of js libraries, it might!
Overriding the java equals() method - not working?
In Java, the equals()
method that is inherited from Object
is:
public boolean equals(Object other);
In other words, the parameter must be of type Object
. This is called overriding; your method public boolean equals(Book other)
does what is called overloading to the equals()
method.
The ArrayList
uses overridden equals()
methods to compare contents (e.g. for its contains()
and equals()
methods), not overloaded ones. In most of your code, calling the one that didn't properly override Object
's equals was fine, but not compatible with ArrayList
.
So, not overriding the method correctly can cause problems.
I override equals the following everytime:
@Override
public boolean equals(Object other){
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof MyClass)) return false;
MyClass otherMyClass = (MyClass)other;
...test other properties here...
}
The use of the @Override
annotation can help a ton with silly mistakes.
Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it the wrong way, you will get a compile error.
When to use margin vs padding in CSS
TL;DR: By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.
To me, the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't.
Consider two elements one above the other each with padding of 1em
. This padding is considered to be part of the element and is always preserved.
So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element.
Thus the content of the two elements will end up being 2em
apart.
Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap.
So in this example, you will end up with the content of the first element followed by 1em
of combined margin followed by the content of the second element. So the content of the two elements is only 1em
apart.
This can be really useful when you know that you want to say 1em
of spacing around an element, regardless of what element it is next to.
The other two big differences are that padding is included in the click region and background color/image, but not the margin.
_x000D_
_x000D_
div.box > div { height: 50px; width: 50px; border: 1px solid black; text-align: center; }_x000D_
div.padding > div { padding-top: 20px; }_x000D_
div.margin > div { margin-top: 20px; }
_x000D_
<h3>Default</h3>_x000D_
<div class="box">_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
<div>C</div>_x000D_
</div>_x000D_
_x000D_
<h3>padding-top: 20px</h3>_x000D_
<div class="box padding">_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
<div>C</div>_x000D_
</div>_x000D_
_x000D_
<h3>margin-top: 20px; </h3>_x000D_
<div class="box margin">_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
<div>C</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Element count of an array in C++
No that would still produce the right value because you must define the array to be either all elements of a single type or pointers to a type. In either case the array size is known at compile time so sizeof(arr) / sizeof(arr[0]) always returns the element count.
Here is an example of how to use this correctly:
int nonDynamicArray[ 4 ];
#define nonDynamicArrayElementCount ( sizeof(nonDynamicArray) / sizeof(nonDynamicArray[ 0 ]) )
I'll go one further here to show when to use this properly. You won't use it very often. It is primarily useful when you want to define an array specifically so you can add elements to it without changing a lot of code later. It is a construct that is primarily useful for maintenance. The canonical example (when I think about it anyway ;-) is building a table of commands for some program that you intend to add more commands to later. In this example to maintain/improve your program all you need to do is add another command to the array and then add the command handler:
char *commands[] = { // <--- note intentional lack of explicit array size
"open",
"close",
"abort",
"crash"
};
#define kCommandsCount ( sizeof(commands) / sizeof(commands[ 0 ]) )
void processCommand( char *command ) {
int i;
for ( i = 0; i < kCommandsCount; ++i ) {
// if command == commands[ i ] do something (be sure to compare full string)
}
}
https with WCF error: "Could not find base address that matches scheme https"
I had this exact same problem. Except my solution was to add an "s" to the binding value.
Old:
binding="mexHttpBinding"
New:
binding="mexHttpsBinding"
web.config snippet:
<services>
<service behaviorConfiguration="ServiceBehavior" name="LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService">
<endpoint behaviorConfiguration="AspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding"
contract="LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService" />
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
</service>
How to use a dot "." to access members of dictionary?
The language itself doesn't support this, but sometimes this is still a useful requirement. Besides the Bunch recipe, you can also write a little method which can access a dictionary using a dotted string:
def get_var(input_dict, accessor_string):
"""Gets data from a dictionary using a dotted accessor-string"""
current_data = input_dict
for chunk in accessor_string.split('.'):
current_data = current_data.get(chunk, {})
return current_data
which would support something like this:
>> test_dict = {'thing': {'spam': 12, 'foo': {'cheeze': 'bar'}}}
>> output = get_var(test_dict, 'thing.spam.foo.cheeze')
>> print output
'bar'
>>
Download TS files from video stream
I came up with an efficient parralelized one-line that concatenate a sequence of .ts
files into one .mp4
file using GNU Parallel:
parallel -k curl https://example.com/video/seg-{}-f4-v1-a1.ts ::: {1..279} >> result.mp4
The key is to replace the variant part of your url with {}
and to set {a..b}
with the lower and upper bound. That's it!
Using "word-wrap: break-word" within a table
table-layout: fixed
will get force the cells to fit the table (and not the other way around), e.g.:
<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
table-layout: fixed;">
<tr>
<td>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
</td>
</tr>
</table>
SQL order string as number
This will handle negative numbers, fractions, string, everything:
ORDER BY ISNUMERIC(col) DESC, Try_Parse(col AS decimal(10,2)), col;
Python dictionary replace values
via dict.update() function
In case you need a declarative solution, you can use dict.update()
to change values in a dict.
Either like this:
my_dict.update({'key1': 'value1', 'key2': 'value2'})
or like this:
my_dict.update(key1='value1', key2='value2')
via dictionary unpacking
Since Python 3.5 you can also use dictionary unpacking for this:
my_dict = { **my_dict, 'key1': 'value1', 'key2': 'value2'}
Note: This creates a new dictionary.
via merge operator or update operator
Since Python 3.9 you can also use the merge operator on dictionaries:
my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}
Note: This creates a new dictionary.
Or you can use the update operator:
my_dict |= {'key1': 'value1', 'key2': 'value2'}
concatenate variables
Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:
rem The retail files set
set FILES_SET="(*.exe *.dll"
rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"
rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%
rem Append the closing bracket
set FILES_SET=%FILES_SET%)
echo %FILES_SET%
Cheers...
HTTP URL Address Encoding in Java
I've created a new project to help construct HTTP URLs. The library will automatically URL encode path segments and query parameters.
You can view the source and download a binary at https://github.com/Widen/urlbuilder
The example URL in this question:
new UrlBuilder("search.barnesandnoble.com", "booksearch/first book.pdf").toString()
produces
http://search.barnesandnoble.com/booksearch/first%20book.pdf
Testing the type of a DOM element in JavaScript
You can use typeof(N)
to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.
In that case, use the elem.tagName
or elem.nodeName
property.
if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.
React Native absolute positioning horizontal centre
It's very simple really. Use percentage for width
and left
properties. For example:
logo : {
position: 'absolute',
top : 50,
left: '30%',
zIndex: 1,
width: '40%',
height: 150,
}
Whatever width
is, left
equals (100% - width)/2
Use ffmpeg to add text subtitles
I tried using MP4Box for this task, but it couldn't handle the M4V I was dealing with. I had success embedding the SRT as soft subtitles with ffmpeg with the following command line:
ffmpeg -i input.m4v -i input.srt -vcodec copy -acodec copy -scodec copy -map 0:0 -map 0:1 -map 1:0 -y output.mkv
Like you I had to use an MKV output file - I wasn't able to create an M4V file.
Difference between Git and GitHub
In the SVN analogy, Git replaces SVN, while GitHub replaces SourceForge :P
If this project of yours is new, then you can still commit to your local Git, then you can push to GitHub later on. You will need to add your GitHub repo as a 'remote repository' in your Git setup.
They seem to have something for Eclipse users : http://eclipse.github.com/
Otherwise, if you are new to Git : http://git-scm.com/book
How to use a client certificate to authenticate and authorize in a Web API
Looking at the source code I also think there must be some issue with the private key.
What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.
If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.
(see source code from class SecureChannnel, method EnsurePrivateKey)
So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.
You can activate Network Tracing to try to debug this. It will give you output like this:
- Trying to find a matching certificate in the certificate store
- Cannot find the certificate in either the LocalMachine store or the CurrentUser store.
Eclipse can't find / load main class
Renaming the main class should be enough (and easiest):
- Go to your class and set cursor to your class name;
- ALT + Shift + R and rename the class (build if not done automatically);
- You should be able to run it now;
- Rename the class to the old name if you want;
How do you check that a number is NaN in JavaScript?
I've created this little function that works like a charm.
Instead of checking for NaN which seems to be counter intuitive, you check for a number. I'm pretty sure I am not the first to do it this way, but I thought i'd share.
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
What are sessions? How do they work?
Simple Explanation by analogy
Imagine you are in a bank, trying to get some money out of your account. But it's dark; the bank is pitch black: there's no light and you can't see your hand in front of your face. You are surrounded by another 20 people. They all look the same. And everybody has the same voice. And everyone is a potential bad guy. In other words, HTTP is stateless.
This bank is a funny type of bank - for the sake of argument here's how things work:
- you wait in line (or on-line) and you talk to the teller: you make a request to withdraw money, and then
- you have to wait briefly on the sofa, and 20 minutes later
- you have to go and actually collect your money from the teller.
But how will the teller tell you apart from everyone else?
The teller can't see or readily recognise you, remember, because the lights are all out. What if your teller gives your $10,000 withdrawal to someone else - the wrong person?! It's absolutely vital that the teller can recognise you as the one who made the withdrawal, so that you can get the money (or resource) that you asked for.
Solution:
When you first appear to the teller, he or she tells you something in secret:
"When ever you are talking to me," says the teller, "you should first identify yourlself as GNASHEU329 - that way I know it's you".
Nobody else knows the secret passcode.
Example of How I Withdrew Cash:
So I decide to go to and chill out for 20 minutes and then later i go to the teller and say "I'd like to collect my withdrawal"
The teller asks me: "who are you??!"
"It's me, Mr George Banks!"
"Prove it!"
And then I tell them my passcode: GNASHEU329
"Certainly Mr Banks!"
That basically is how a session works. It allows one to be uniquely identified in a sea of millions of people. You need to identify yourself every time you deal with the teller.
If you got any questions or are unclear - please post comment and i will try to clear it up for you. The following is not strictly speaking, completely accurate in its terminology, but I hope it's helpful to you in understanding concepts.
Explanation via Pictures:
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
VBA - how to conditionally skip a for loop iteration
You can use a kind of continue
by using a nested Do ... Loop While False
:
'This sample will output 1 and 3 only
Dim i As Integer
For i = 1 To 3: Do
If i = 2 Then Exit Do 'Exit Do is the Continue
Debug.Print i
Loop While False: Next i
Error In PHP5 ..Unable to load dynamic library
Even though several other answers suggest it, installing more unnecessary software is generally not the best solution. Instead, you should fix the underlying problem. The reason these messages appear is because you are trying to load those extensions, but they are not installed. So the easy solution is simply to tell PHP to stop trying to load them:
First, find out which files are trying to load the above extensions:
$ grep -Hrv ";" /etc/php5 | grep -E "extension(\s+)?="
Example output for Ubuntu:
/etc/php5/mods-available/gd.ini:extension=gd.so
/etc/php5/mods-available/pdo_sqlite.ini:extension=pdo_sqlite.so
/etc/php5/mods-available/pdo.ini:extension=pdo.so
/etc/php5/mods-available/pdo_mysql.ini:extension=pdo_mysql.so
/etc/php5/mods-available/mysqli.ini:extension=mysqli.so
/etc/php5/mods-available/mysql.ini:extension=mysql.so
/etc/php5/mods-available/curl.ini:extension=curl.so
/etc/php5/mods-available/sqlite3.ini:extension=sqlite3.so
/etc/php5/conf.d/mcrypt.ini:extension=mcrypt.so
/etc/php5/conf.d/imagick.ini:extension=imagick.so
/etc/php5/apache2/php.ini:extension=http.so
Now just find the files that are loading the extensions that are causing the errors and comment out those lines with a ;
. For some reason this happened to me with the default install of Ubuntu, so hopefully this helps someone else.
How to use moment.js library in angular 2 typescript app?
I would go with following:
npm install moment --save
To your systemjs.config.js
file's map
array add:
'moment': 'node_modules/moment'
to packages
array add:
'moment': { defaultExtension: 'js' }
In your component.ts use:
import * as moment from 'moment/moment';
and that's it. You can use from your component's class:
today: string = moment().format('D MMM YYYY');
How can I perform a str_replace in JavaScript, replacing text in JavaScript?
Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:
Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.
For a simple test run on the JS perf page, I've documented some of the results:
_x000D_
_x000D_
<script>_x000D_
// Setup_x000D_
var startString = "xxxxxxxxxabcxxxxxxabcxx";_x000D_
var endStringRegEx = undefined;_x000D_
var endStringString = undefined;_x000D_
var endStringRegExNewStr = undefined;_x000D_
var endStringRegExNew = undefined;_x000D_
var endStringStoredRegEx = undefined; _x000D_
var re = new RegExp("abc", "g");_x000D_
</script>_x000D_
_x000D_
<script>_x000D_
// Tests_x000D_
endStringRegEx = startString.replace(/abc/g, "def") // Regex_x000D_
endStringString = startString.replace("abc", "def", "g") // String_x000D_
endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String_x000D_
endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp_x000D_
endStringStoredRegEx = startString.replace(re, "def") // saved regex_x000D_
</script>
_x000D_
_x000D_
_x000D_
The results for Chrome 68 are as follows:
String replace: 9,936,093 operations/sec
Saved regex: 5,725,506 operations/sec
Regex: 5,529,504 operations/sec
New Regex String: 3,571,180 operations/sec
New Regex: 3,224,919 operations/sec
From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace
only replaces the first instance of the matched character. Its only possible to replace all instances with //g
. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_');
or worse while (name.includes(' ')) { name = name.replace(' ', '_') }
Strings and character with printf
If you want to display a single character then you can also use name[0]
instead of using pointer.
It will serve your purpose but if you want to display full string using %c
, you can try this:
#include<stdio.h>
void main()
{
char name[]="siva";
int i;
for(i=0;i<4;i++)
{
printf("%c",*(name+i));
}
}
How do I add indices to MySQL tables?
It's worth noting that multiple field indexes can drastically improve your query performance. So in the above example we assume ProductID is the only field to lookup but were the query to say ProductID = 1 AND Category = 7 then a multiple column index helps. This is achieved with the following:
ALTER TABLE `table` ADD INDEX `index_name` (`col1`,`col2`)
Additionally the index should match the order of the query fields. In my extended example the index should be (ProductID,Category) not the other way around.
Change keystore password from no password to a non blank password
this way worked better for me:
echo y | keytool -storepasswd -storepass 123456 -keystore /tmp/IT-Root-CA.keystore -import -alias IT-Root-CA -file /etc/pki/ca-trust/source/anchors/IT-Root-CA.crt
machine running:
[root@rhel80-68]# cat /etc/redhat-release
Red Hat Enterprise Linux release 8.1 (Ootpa)
Jenkins fails when running "service start jenkins"
In my case, the port 8080 was taken by some other service (Apache Airflow).
So I edit the HTTP port in this file:
sudo vi /etc/default/jenkins
And then started the service and it worked:
sudo service jenkins start
I was on Ubuntu 18.04 and installed openjdk-8
Change selected value of kendo ui dropdownlist
You have to use Kendo UI DropDownList select
method (documentation in here).
Basically you should:
// get a reference to the dropdown list
var dropdownlist = $("#Instrument").data("kendoDropDownList");
If you know the index you can use:
// selects by index
dropdownlist.select(1);
If not, use:
// selects item if its text is equal to "test" using predicate function
dropdownlist.select(function(dataItem) {
return dataItem.symbol === "test";
});
JSFiddle example here
check if "it's a number" function in Oracle
Function for mobile number of length 10 digits and starting from 9,8,7 using regexp
create or replace FUNCTION VALIDATE_MOBILE_NUMBER
(
"MOBILE_NUMBER" IN varchar2
)
RETURN varchar2
IS
v_result varchar2(10);
BEGIN
CASE
WHEN length(MOBILE_NUMBER) = 10
AND MOBILE_NUMBER IS NOT NULL
AND REGEXP_LIKE(MOBILE_NUMBER, '^[0-9]+$')
AND MOBILE_NUMBER Like '9%' OR MOBILE_NUMBER Like '8%' OR MOBILE_NUMBER Like '7%'
then
v_result := 'valid';
RETURN v_result;
else
v_result := 'invalid';
RETURN v_result;
end case;
END;
Python code to remove HTML tags from a string
Using a regex
Using a regex, you can clean everything inside <>
:
import re
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
Some HTML texts can also contain entities that are not enclosed in brackets, such as '&nsbm
'. If that is the case, then you might want to write the regex as
cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
This link contains more details on this.
Using BeautifulSoup
You could also use BeautifulSoup
additional package to find out all the raw text.
You will need to explicitly set a parser when calling BeautifulSoup
I recommend "lxml"
as mentioned in alternative answers (much more robust than the default one (html.parser
) (i.e. available without additional install).
from bs4 import BeautifulSoup
cleantext = BeautifulSoup(raw_html, "lxml").text
But it doesn't prevent you from using external libraries, so I recommend the first solution.
EDIT: To use lxml
you need to pip install lxml
.
std::thread calling method of class
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
ActiveRecord find and only return selected columns
In Rails 2
l = Location.find(:id => id, :select => "name, website, city", :limit => 1)
...or...
l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])
This reference doc gives you the entire list of options you can use with .find
, including how to limit by number, id, or any other arbitrary column/constraint.
In Rails 3 w/ActiveRecord Query Interface
l = Location.where(["id = ?", id]).select("name, website, city").first
Ref: Active Record Query Interface
You can also swap the order of these chained calls, doing .select(...).where(...).first
- all these calls do is construct the SQL query and then send it off.
Limit Get-ChildItem recursion depth
Try this function:
Function Get-ChildItemToDepth {
Param(
[String]$Path = $PWD,
[String]$Filter = "*",
[Byte]$ToDepth = 255,
[Byte]$CurrentDepth = 0,
[Switch]$DebugMode
)
$CurrentDepth++
If ($DebugMode) {
$DebugPreference = "Continue"
}
Get-ChildItem $Path | %{
$_ | ?{ $_.Name -Like $Filter }
If ($_.PsIsContainer) {
If ($CurrentDepth -le $ToDepth) {
# Callback to this function
Get-ChildItemToDepth -Path $_.FullName -Filter $Filter `
-ToDepth $ToDepth -CurrentDepth $CurrentDepth
}
Else {
Write-Debug $("Skipping GCI for Folder: $($_.FullName) " + `
"(Why: Current depth $CurrentDepth vs limit depth $ToDepth)")
}
}
}
}
source
$(document).ready equivalent without jQuery
This question was asked quite a long time ago. For anyone just seeing this question, there is now a site called "you might not need jquery" which breaks down - by level of IE support required - all the functionality of jquery and provides some alternative, smaller libraries.
IE8 document ready script according to you might not need jquery
function ready(fn) {
if (document.readyState != 'loading')
fn();
else if (document.addEventListener)
document.addEventListener('DOMContentLoaded', fn);
else
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?
This enables you to write something like:
void doSomething() {
List<String>list = new ArrayList<String>();
//do something
}
Later on, you might want to change it to:
void doSomething() {
List<String>list = new LinkedList<String>();
//do something
}
without having to change the rest of the method.
However, if you want to use a CopyOnWriteArrayList
for example, you would need to declare it as such, and not as a List if you wanted to use its extra methods (addIfAbsent for example):
void doSomething() {
CopyOnWriteArrayList<String>list = new CopyOnWriteArrayList<String>();
//do something, for example:
list.addIfAbsent("abc");
}
adding comment in .properties files
The property file task is for editing properties files. It contains all sorts of nice features that allow you to modify entries. For example:
<propertyfile file="build.properties">
<entry key="build_number"
type="int"
operation="+"
value="1"/>
</propertyfile>
I've incremented my build_number
by one. I have no idea what the value was, but it's now one greater than what it was before.
- Use the
<echo>
task to build a property file instead of <propertyfile>
. You can easily layout the content and then use <propertyfile>
to edit that content later on.
Example:
<echo file="build.properties">
# Default Configuration
source.dir=1
dir.publish=1
# Source Configuration
dir.publish.html=1
</echo>
- Create separate properties files for each section. You're allowed a comment header for each type. Then, use to batch them together into one single file:
Example:
<propertyfile file="default.properties"
comment="Default Configuration">
<entry key="source.dir" value="1"/>
<entry key="dir.publish" value="1"/>
<propertyfile>
<propertyfile file="source.properties"
comment="Source Configuration">
<entry key="dir.publish.html" value="1"/>
<propertyfile>
<concat destfile="build.properties">
<fileset dir="${basedir}">
<include name="default.properties"/>
<include name="source.properties"/>
</fileset>
</concat>
<delete>
<fileset dir="${basedir}">
<include name="default.properties"/>
<include name="source.properties"/>
</fileset>
</delete>
Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext
I've had a similar issue with this error. In my case, I was entering the incorrect password for the Keystore.
I changed the password for the Keystore to match what I was entering (I didn't want to change the password I was entering), but it still gave the same error.
keytool -storepasswd -keystore keystore.jks
Problem was that I also needed to change the Key's password within the Keystore.
When I initially created the Keystore, the Key was created with the same password as the Keystore (I accepted this default option). So I had to also change the Key's password as follows:
keytool -keypasswd -alias my.alias -keystore keystore.jks
How do I embed a mp4 movie into my html?
If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.
<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>
How to calculate time difference in java?
Java 8
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime1= LocalDateTime.parse("2014-11-25 19:00:00", formatter);
LocalDateTime dateTime2= LocalDateTime.parse("2014-11-25 16:00:00", formatter);
long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
long diffInSeconds = java.time.Duration.between(dateTime1, dateTime2).getSeconds();
long diffInMinutes = java.time.Duration.between(dateTime1, dateTime2).toMinutes();
Java double.MAX_VALUE?
Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).
This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.
Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).
How to download all dependencies and packages to directory
Somewhat simplified (and what worked for me) way that worked for me (based on all the above)
Note that dependencies hierarchy can go deeper then one level
Get dependencies of your package
$ apt-cache depends mongodb | grep Depends:
Depends: mongodb-dev
Depends: mongodb-server
Get urls:
sudo apt-get --print-uris --yes -d --reinstall install mongodb-org mongodb-org-server mongodb-org-shell mongodb-org-tools | grep "http://" | awk '{print$1}' | xargs -I'{}' echo {} | tee files.list
wget --input-file files.list
Accessing a Dictionary.Keys Key through a numeric index
You could always do this:
string[] temp = new string[mydict.count];
mydict.Keys.CopyTo(temp, 0)
int LastCount = mydict[temp[mydict.count - 1]]
But I wouldn't recommend it. There's no guarantee that the last inserted key will be at the end of the array. The ordering for Keys on MSDN is unspecified, and subject to change. In my very brief test, it does seem to be in order of insertion, but you'd be better off building in proper bookkeeping like a stack--as you suggest (though I don't see the need of a struct based on your other statements)--or single variable cache if you just need to know the latest key.
Command to get time in milliseconds
date
command didnt provide milli seconds on OS X, so used an alias from python
millis(){ python -c "import time; print(int(time.time()*1000))"; }
OR
alias millis='python -c "import time; print(int(time.time()*1000))"'
EDIT: following the comment from @CharlesDuffy.
Forking any child process takes extra time.
$ time date +%s%N
1597103627N
date +%s%N 0.00s user 0.00s system 63% cpu 0.006 total
Python is still improving it's VM start time, and it is not as fast as ahead-of-time compiled code (such as date
).
On my machine, it took about 30ms - 60ms (that is 5x-10x of 6ms taken by date
)
$ time python -c "import time; print(int(time.time()*1000))"
1597103899460
python -c "import time; print(int(time.time()*1000))" 0.03s user 0.01s system 83% cpu 0.053 total
I figured awk
is lightweight than python
, so awk
takes in the range of 6ms to 12ms (i.e. 1x to 2x of date):
$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
1597103729525
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}' 0.00s user 0.00s system 74% cpu 0.010 total
adding css class to multiple elements
Try using:
.button input, .button a {
// css stuff
}
Also, read up on CSS.
Edit: If it were me, I'd add the button class to the element, not to the parent tag.
Like so:
HTML:
<a href="#" class='button'>BUTTON TEXT</a>
<input type="submit" class='button' value='buttontext' />
CSS:
.button {
// css stuff
}
For specific css stuff use:
input.button {
// css stuff
}
a.button {
// css stuff
}
File input 'accept' attribute - is it useful?
It's been a few years, and Chrome at least makes use of this attribute. This attribute is very useful from a usability standpoint as it will filter out the unnecessary files for the user, making their experience smoother. However, the user can still select "all files" from the type (or otherwise bypass the filter), thus you should always validate the file where it is actually used; If you're using it on the server, validate it there before using it. The user can always bypass any client-side scripting.
Redis: How to access Redis log file
vi /usr/local/etc/redis.conf
Look for dir, logfile
# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /usr/local/var/db/redis/
# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile "redis_log"
So the log file is created at /usr/local/var/db/redis/redis_log
with the name redis_log
You can also try MONITOR
command from redis-cli
to review the number of commands executed.
Make page to tell browser not to cache/preserve input values
Are you explicitly setting the values as blank? For example:
<input type="text" name="textfield" value="">
That should stop browsers putting data in where it shouldn't. Alternatively, you can add the autocomplete
attribute to the form tag:
<form autocomplete="off" ...></form>
How to rollback or commit a transaction in SQL Server
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
Creating a .p12 file
I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.
I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!
Generate 2048-bit RSA private key:
openssl genrsa -out key.pem 2048
Generate a Certificate Signing Request:
openssl req -new -sha256 -key key.pem -out csr.csr
Generate a self-signed x509 certificate suitable for use on web servers.
openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem
Create SSL identity file in PKCS12 as mentioned here
openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem
Unit testing with Spring Security
You are quite right to be concerned - static method calls are particularly problematic for unit testing as you cannot easily mock your dependencies. What I am going to show you is how to let the Spring IoC container do the dirty work for you, leaving you with neat, testable code. SecurityContextHolder is a framework class and while it may be ok for your low-level security code to be tied to it, you probably want to expose a neater interface to your UI components (i.e. controllers).
cliff.meyers mentioned one way around it - create your own "principal" type and inject an instance into consumers. The Spring <aop:scoped-proxy/> tag introduced in 2.x combined with a request scope bean definition, and the factory-method support may be the ticket to the most readable code.
It could work like following:
public class MyUserDetails implements UserDetails {
// this is your custom UserDetails implementation to serve as a principal
// implement the Spring methods and add your own methods as appropriate
}
public class MyUserHolder {
public static MyUserDetails getUserDetails() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
if (a == null) {
return null;
} else {
return (MyUserDetails) a.getPrincipal();
}
}
}
public class MyUserAwareController {
MyUserDetails currentUser;
public void setCurrentUser(MyUserDetails currentUser) {
this.currentUser = currentUser;
}
// controller code
}
Nothing complicated so far, right? In fact you probably had to do most of this already. Next, in your bean context define a request-scoped bean to hold the principal:
<bean id="userDetails" class="MyUserHolder" factory-method="getUserDetails" scope="request">
<aop:scoped-proxy/>
</bean>
<bean id="controller" class="MyUserAwareController">
<property name="currentUser" ref="userDetails"/>
<!-- other props -->
</bean>
Thanks to the magic of the aop:scoped-proxy tag, the static method getUserDetails will be called every time a new HTTP request comes in and any references to the currentUser property will be resolved correctly. Now unit testing becomes trivial:
protected void setUp() {
// existing init code
MyUserDetails user = new MyUserDetails();
// set up user as you wish
controller.setCurrentUser(user);
}
Hope this helps!
Adding a collaborator to my free GitHub account?
Yes the set of instructions above are outdated. For the new GitHub the Settings button must be clicked.
Also the person you try to add as a collaborator must have an existing GitHub account. In other words he should have signed up on GitHub first because it is not possible to send collaboration requests merely by typing in the email address of the collaborator.
onClick not working on mobile (touch)
better to use touchstart
event with .on()
jQuery method:
$(window).load(function() { // better to use $(document).ready(function(){
$('.List li').on('click touchstart', function() {
$('.Div').slideDown('500');
});
});
And i don't understand why you are using $(window).load()
method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready()
method which does not wait for each element on the page to be loaded first.
numpy max vs amax vs maximum
For completeness, in Numpy there are four maximum related functions. They fall into two different categories:
np.amax/np.max
, np.nanmax
: for single array order statistics
- and
np.maximum
, np.fmax
: for element-wise comparison of two arrays
NaNs propagator np.amax/np.max
and its NaN ignorant counterpart np.nanmax
.
np.max
is just an alias of np.amax
, so they are considered as one function.
>>> np.max.__name__
'amax'
>>> np.max is np.amax
True
np.max
propagates NaNs while np.nanmax
ignores NaNs.
>>> np.max([np.nan, 3.14, -1])
nan
>>> np.nanmax([np.nan, 3.14, -1])
3.14
NaNs propagator np.maximum
and its NaNs ignorant counterpart np.fmax
.
Both functions require two arrays as the first two positional args to compare with.
# x1 and x2 must be the same shape or can be broadcast
np.maximum(x1, x2, /, ...);
np.fmax(x1, x2, /, ...)
np.maximum
propagates NaNs while np.fmax
ignores NaNs.
>>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
array([ nan, nan, 2.72])
>>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
array([-inf, 3.14, 2.72])
The element-wise functions are np.ufunc
(Universal Function), which means they have some special properties that normal Numpy function don't have.
>>> type(np.maximum)
<class 'numpy.ufunc'>
>>> type(np.fmax)
<class 'numpy.ufunc'>
>>> #---------------#
>>> type(np.max)
<class 'function'>
>>> type(np.nanmax)
<class 'function'>
And finally, the same rules apply to the four minimum related functions:
np.amin/np.min
, np.nanmin
;
- and
np.minimum
, np.fmin
.
Python class inherits object
Yes, it's historical. Without it, it creates an old-style class.
If you use type()
on an old-style object, you just get "instance". On a new-style object you get its class.
kill -3 to get java thread dump
In Jboss you can perform the following
nohup $JBOSS_HOME/bin/run.sh -c yourinstancename $JBOSS_OPTS >> console-$(date +%Y%m%d).out 2>&1 < /dev/null &
kill -3 <java_pid>
This will redirect your output/threadump to the file console specified in the above command.
blur() vs. onblur()
I guess it's just because the onblur event is called as a result of the input losing focus, there isn't a blur action associated with an input, like there is a click action associated with a button
no pg_hba.conf entry for host
For those who have the similar problem trying to connect to local db and trying like
con = psycopg2.connect(database="my_db", user="my_name", password="admin")
, try to pass the additional parameter, so the following saved me a day:
con = psycopg2.connect(database="my_db", user="my_name", password="admin", host="localhost")
How to compare two dates?
datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2)
will return True
.
datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2)
will return datetime.timedelta(-1)
.
datetime.date(2011, 1, 1) + datetime.date(2011, 1, 2)
will return datetime.timedelta(1)
.
see the docs.
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
I have perfect answer for all this : I tried so many solution not able to get finally myself able to manage , please find detail answer below:
$.ajax({
traditional: true,
url: "/Conroller/MethodTest",
type: "POST",
contentType: "application/json; charset=utf-8",
data:JSON.stringify(
[
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
]),
success: function (data) {
$scope.DisplayError(data.requestStatus);
}
});
Controler
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
public JsonResult MethodTest(IEnumerable<Thing> datav)
{
//now datav is having all your values
}
Making TextView scrollable on Android
If you want text to be scrolled within the textview, then you can follow the following:
First you should have to subclass textview.
And then use that.
Following is an example of a subclassed textview.
public class AutoScrollableTextView extends TextView {
public AutoScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setEllipsize(TruncateAt.MARQUEE);
setMarqueeRepeatLimit(-1);
setSingleLine();
setHorizontallyScrolling(true);
}
public AutoScrollableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setEllipsize(TruncateAt.MARQUEE);
setMarqueeRepeatLimit(-1);
setSingleLine();
setHorizontallyScrolling(true);
}
public AutoScrollableTextView(Context context) {
super(context);
setEllipsize(TruncateAt.MARQUEE);
setMarqueeRepeatLimit(-1);
setSingleLine();
setHorizontallyScrolling(true);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if(focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void onWindowFocusChanged(boolean focused) {
if(focused)
super.onWindowFocusChanged(focused);
}
@Override
public boolean isFocused() {
return true;
}
}
Now, you have to use that in the XML in this way:
<com.yourpackagename.AutoScrollableTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is very very long text to be scrolled"
/>
That's it.