trigger('submit') does not work.beacuse onSubmit method does not get fired. the following code works for me, call onSubmit method when using this code :
$("form").find(':submit').click();
I think the source of confusion is the distinction between a node's attribute and the corresponding property.
You're using:
$("a.button").parents("form").attr("onsubmit")
You're directly reading the onsubmit
attribute's value (which must be a string). Instead, you should access the onsubmit
property of the node:
$("a.button").parents("form").prop("onsubmit")
Here's a quick test:
<form id="form1" action="foo1.htm" onsubmit="return valid()"></form>
<script>
window.onload = function () {
var form1 = document.getElementById("form1");
function log(s) {
document.write("<div>" + s + "</div>");
}
function info(v) {
return "(" + typeof v + ") " + v;
}
log("form1 onsubmit property: " + info(form1.onsubmit));
log("form1 onsubmit attribute: " + info(form1.getAttribute("onsubmit")));
};
</script>
This yields:
form1 onsubmit property: (function) function onsubmit(event) { return valid(); } form1 onsubmit attribute: (string) return valid()
You can pass the event as argument to the function and then prevent the default behaviour.
var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(event){
event.preventDefault();
alert('it works!');
}
return <form onSubmit={this.doSomething}>
<button>Click me</button>
</form>;
}
});
My answer, I believe, will be Intellij specific.
I had rebuilt clean, even going as far as to manually delete the "out" and "target" dirs. Intellij has a "invalidate caches and restart", which sometimes clears odd errors. This time it didn't work. The dependency versions all looked correct in the project settings->modules menu.
The final answer was to manually delete my problem dependency from my local maven repo. An old version of bouncycastle was the culprit(I knew I had just changed versions and that would be the problem) and although the old version showed up no where in what was being built, it solved my problem. I was using intellij version 14 and then upgraded to 15 during this process.
Partial import from lodash should work in angular 4.1.x using following notation:
let assign = require('lodash/assign');
Or use 'lodash-es' and import in module:
import { assign } from 'lodash-es';
Actually I would say the 1st preference would be an external style sheet (External CSS), the 2nd preference would be writing CSS in style tags in the header section of the current page (Internal CSS)
<style type="text/css">
<!-- CSS goes here -->
</style>
And as a 3rd option - or last resort rather - I'd use CSS in the tags themselves (Inline CSS).
Here is how I got it to work in IE8:
Use Guava.
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;
public abstract class GenericClass<T> {
private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) { };
private final Type type = typeToken.getType(); // or getRawType() to return Class<? super T>
public Type getType() {
return type;
}
public static void main(String[] args) {
GenericClass<String> example = new GenericClass<String>() { };
System.out.println(example.getType()); // => class java.lang.String
}
}
A while back, I posted some full-fledge examples including abstract classes and subclasses here.
Note: this requires that you instantiate a subclass of GenericClass
so it can bind the type parameter correctly. Otherwise it'll just return the type as T
.
Make as shown.
$(document).ready(function(){_x000D_
$('#myModal').modal('show');_x000D_
_x000D_
$('#myBtn').on('click', function(){_x000D_
$('#myModal').modal('show');_x000D_
});_x000D_
_x000D_
});_x000D_
<br/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Activate Modal with JavaScript</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
If I understand your issue this should work
&emsp—the em space; this should be a very wide space, typically as much as four real spaces. &ensp—the en space; this should be a somewhat wide space, roughly two regular spaces. &thinsp—this will be a narrow space, even more narrow than a regular space.
Sources: http://hea-www.harvard.edu/~fine/Tech/html-sentences.html
You can see all the version of a module with npm view
.
eg: To list all versions of bootstrap including beta.
npm view bootstrap versions
But if the version list is very big it will truncate. An --json
option will print all version including beta versions as well.
npm view bootstrap versions --json
If you want to list only the stable versions not the beta then use singular version
npm view bootstrap@* versions
Or
npm view bootstrap@* versions --json
And, if you want to see only latest version then here you go.
npm view bootstrap version
You can loop the array with a for loop and the object properties with for-in loops.
for (var i=0; i<result.length; i++)
for (var name in result[i]) {
console.log("Item name: "+name);
console.log("Source: "+result[i][name].sourceUuid);
console.log("Target: "+result[i][name].targetUuid);
}
Most of the time your background color is different from the background of your table. Since there are spaces between the cells, those spaces will create the illusion of lines with the color of the background behind the table.
The solution is to get rid of those spaces.
Inside the table tag write:
cellspacing="0"
As stated by Harry Joy, you can do it on the onclick
attr like so:
<input type="button" onclick="func1();func2();" value="Call2Functions" />
Or, in your JS like so:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1();
func2();
};
Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):
var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
func1 = Call2FunctionsEle.onclick;
Call2FunctionsEle.onclick = function()
{
if( typeof func1 === 'function' )
{
func1();
}
func2();
};
If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1.apply( this, arguments );
func2.apply( this, arguments );
};
In Ubuntu and Debian, you can apt-get install moreutils
. This contains a utility called mispipe
that returns the exit status of the first command in the pipe.
The problem is that --exclude="*"
says to exclude (for example) the 1260000000/
directory, so rsync
never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include
.
I think the closest thing to what you want is this:
rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
(which will include all directories, and all files matching file_11*.jpg
, but no other files), or maybe this:
rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
(same concept, but much pickier about the directories it will include).
You can also put DOM elements, like div
on top of the canvas that would represent your canvas elements and be positioned the same way.
Now you can attach event listeners to these divs and run the necessary actions.
You try this.
I have already tried it in my django template.
It will work fine. Just remove the curly braces pair {{ and }} from {{source}}.
I have also added <table> tag and that's it.
After modification your code will look something like below.
{% for source in sources %}
<table>
<tr>
<td>{{ source }}</td>
<td>
{% if title == source %}
Just now!
{% endif %}
</td>
</tr>
</table>
{% endfor %}
My dictionary looks like below,
{'title':"Rishikesh", 'sources':["Hemkesh", "Malinikesh", "Rishikesh", "Sandeep", "Darshan", "Veeru", "Shwetabh"]}
and OUTPUT looked like below once my template got rendered.
Hemkesh
Malinikesh
Rishikesh Just now!
Sandeep
Darshan
Veeru
Shwetabh
I think that the best approach is to use protocol-oriented programming if you are using Swift.
First of all you must create a KeyboardCapable
protocol, that gives to any UIViewController conforming it the ability to register and unregister keyboard observers:
import Foundation
import UIKit
protocol KeyboardCapable: KeyboardAnimatable {
func keyboardWillShow(notification: NSNotification)
func keyboardWillHide(notification: NSNotification)
}
extension KeyboardCapable where Self: UIViewController {
func registerKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil)
}
func unregisterKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
}
You've notice the extraneous KeyboardAnimatable
keyword on the above piece of code. It's just the name of the next protocol we need to create:
import Foundation
import UIKit
protocol KeyboardAnimatable {
}
extension KeyboardAnimatable where Self: UIViewController {
func performKeyboardShowFullViewAnimation(withKeyboardHeight height: CGFloat, andDuration duration: NSTimeInterval) {
UIView.animateWithDuration(duration, animations: { () -> Void in
self.view.frame = CGRectMake(view.frame.origin.x, -height, view.bounds.width, view.bounds.height)
}, completion: nil)
}
func performKeyboardHideFullViewAnimation(withDuration duration: NSTimeInterval) {
UIView.animateWithDuration(duration, animations: { () -> Void in
self.view.frame = CGRectMake(view.frame.origin.x, 0.0, view.bounds.width, view.bounds.height)
}, completion: nil)
}
}
This KeyboardAnimatable
protocol, gives all UIViewController conforming it two methods that will animate the whole view up and down, respectively.
Okay so if KeyboardCapable
conforms to KeyboardAnimatable
, all UIViewController conforming to KeyboardCapable
, also conforms to KeyboardAnimatable
. That's cool.
Let's see a UIViewController
conforming KeyboardCapable
, and reacting to keyboard events:
import Foundation
import UIKit
class TransferConfirmViewController: UIViewController, KeyboardCapable {
//MARK: - LIFE CYCLE
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
registerKeyboardNotifications()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
unregisterKeyboardNotifications()
}
//MARK: - NOTIFICATIONS
//MARK: Keyboard
func keyboardWillShow(notification: NSNotification) {
let keyboardHeight = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().height
let animationDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
performKeyboardShowFullViewAnimation(withKeyboardHeight: keyboardHeight, andDuration: animationDuration)
}
func keyboardWillHide(notification: NSNotification) {
let animationDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
performKeyboardHideFullViewAnimation(withDuration: animationDuration)
}
}
Now your UIViewController
will respond to keyboard events and will animate in consequence.
Note: If you want a custom animation instead of push or pull the view, you must define custom methods on KeyboardAnimatable
protocol or perform them on KeyboardCapable
functions. It's up to you.
I tried to recreate the situation...
WebMethod
called Function1
expecting the following params: Function1(Contact Contact, string description, int amount)
Where Contact
is just a model that has getters and setters for id
and name
like in your case.
You can download the .NET sample WS at:
https://www.dropbox.com/s/6pz1w94a52o5xah/11593623.zip
This is what you need to do at PHP side:
(Tested and working)
<?php
// Create Contact class
class Contact {
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
}
// Initialize WS with the WSDL
$client = new SoapClient("http://localhost:10139/Service1.asmx?wsdl");
// Create Contact obj
$contact = new Contact(100, "John");
// Set request params
$params = array(
"Contact" => $contact,
"description" => "Barrel of Oil",
"amount" => 500,
);
// Invoke WS method (Function1) with the request params
$response = $client->__soapCall("Function1", array($params));
// Print WS response
var_dump($response);
?>
print_r($params)
you will see the following output, as your WS would expect:Array ( [Contact] => Contact Object ( [id] => 100 [name] => John ) [description] => Barrel of Oil [amount] => 500 )
(As you can see, Contact
object is not null
nor the other params. That means your request was successfully done from PHP side)
object(stdClass)[3] public 'Function1Result' => string 'Detailed information of your request! id: 100, name: John, description: Barrel of Oil, amount: 500' (length=98)
Happy Coding!
here is the proxy setting
git config --global http.proxy http://<username>:<pass>@<ip>:<port>
git config --global https.proxy http://<username>:<pass>@<ip>:<port>
Double-quoted strings are more elegant because you don't have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).
However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string--even if you surround it with braces!
//syntax error!!
//$s = "Hello {trim($world)}!"
//the only option
$s = "Hello " . trim($world) . "!";
Here's a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00
(a half an hour duration):
#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta
def time_diff(start, end):
if isinstance(start, datetime_time): # convert to datetime
assert isinstance(end, datetime_time)
start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
if start <= end: # e.g., 10:33:26-11:15:49
return end - start
else: # end < start e.g., 23:55:00-00:25:00
end += timedelta(1) # +day
assert end > start
return end - start
for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
print(time_diff(s, e))
assert time_diff(s, e) == time_diff(s.time(), e.time())
0:42:23
0:30:00
time_diff()
returns a timedelta object that you can pass (as a part of the sequence) to a mean()
function directly e.g.:
#!/usr/bin/env python
from datetime import timedelta
def mean(data, start=timedelta(0)):
"""Find arithmetic average."""
return sum(data, start) / len(data)
data = [timedelta(minutes=42, seconds=23), # 0:42:23
timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds
The mean()
result is also timedelta()
object that you can convert to seconds (td.total_seconds()
method (since Python 2.7)), hours (td / timedelta(hours=1)
(Python 3)), etc.
One situation where it is quite useful to be able to handle the x-button click event is when you are using a Form that is an MDI container. The reason is that the closeing and closed events are raised first with children and lastly with the parent. So in one scenario a user clicks the x-button to close the application and the MDI parent asks for a confirmation to proceed. In case he decides to not close the application but carry on whatever he is doing the children will already have processed the closing event potentially lost information/work whatever. One solution is to intercept the WM_CLOSE message from the Windows message loop in your main application form (i.e. which closed, terminates the application) like so:
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0010) // WM_CLOSE
{
// If we don't want to close this window
if (ShowConfirmation("Are you sure?") != DialogResult.Yes) return;
}
base.WndProc(ref m);
}
For beginners, the accepted answer is correct, but a little terse if you're not that familiar with either VSC or Regex.
So, in case this is your first contact with either:
To find and modify text,
In the "Find" step, you can use regex with "capturing groups," e.g. I want to find (group1) and (group2)
, using parentheses. This would find the same text as I want to find group1 and group2
, but with the difference that you can then reference group1
and group2
in the next step:
In the "Replace" step, you can refer to the capturing groups via $1
, $2
etc, so you could change the sentence to I found $1 and $2 having a picnic
, which would output I found group1 and group2 having a picnic.
Notes:
Instead of just a string, anything inside or outside the ()
can be a regular expression.
$0
refers to the whole match
Match duplicate comma-delimited items:
(?<=,|^)([^,]*)(,\1)+(?=,|$)
This regex can be used to split the values of a comma delimitted list. List elements may be quoted, unquoted or empty. Commas inside a pair of quotation marks are not matched.
,(?!(?<=(?:^|,)\s*"(?:[^"]|""|\\")*,)(?:[^"]|""|\\")*"\s*(?:,|$))
Bugs caused by missing predefined folder for store compiled class file which is normally is /out folder by default. You can give a try to close Intellij > Import Project > From existing source. This will solve this problem.
app = Flask(__name__, static_folder="your path to static")
If you have templates in your root directory, placing the app=Flask(name) will work if the file that contains this also is in the same location, if this file is in another location, you will have to specify the template location to enable Flask to point to the location
You can not simply ping in Java as it relies on ICMP, which is sadly not supported in Java
http://mindprod.com/jgloss/ping.html
Use sockets instead
Hope it helps
With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress
I know this is old but I've used a function similar to this...
deleteRow: function (ctrl) {
//remove the row from the table
$(ctrl).closest('tr').remove();
}
... with markup like this ...
<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>
...and it works fine
If you're using Xamarin, I found a guide on their official forum explaining how to do this:
Hereafter, you might also need to update the Google Play Services from the Google Play Store.
Hope this helps for anyone else who has troubles finding the documentation.
I noticed that Internet Explorer 11 gets incredibly slow when slicing the data like Jeremy suggested. This is true for Chrome, but Internet Explorer seems to have a problem when passing the sliced data to the Blob-Constructor. On my machine, passing 5 MB of data makes Internet Explorer crash and memory consumption is going through the roof. Chrome creates the blob in no time.
Run this code for a comparison:
var byteArrays = [],
megaBytes = 2,
byteArray = new Uint8Array(megaBytes*1024*1024),
block,
blobSlowOnIE, blobFastOnIE,
i;
for (i = 0; i < (megaBytes*1024); i++) {
block = new Uint8Array(1024);
byteArrays.push(block);
}
//debugger;
console.profile("No Slices");
blobSlowOnIE = new Blob(byteArrays, { type: 'text/plain'});
console.profileEnd();
console.profile("Slices");
blobFastOnIE = new Blob([byteArray], { type: 'text/plain'});
console.profileEnd();
So I decided to include both methods described by Jeremy in one function. Credits go to him for this.
function base64toBlob(base64Data, contentType, sliceSize) {
var byteCharacters,
byteArray,
byteNumbers,
blobData,
blob;
contentType = contentType || '';
byteCharacters = atob(base64Data);
// Get BLOB data sliced or not
blobData = sliceSize ? getBlobDataSliced() : getBlobDataAtOnce();
blob = new Blob(blobData, { type: contentType });
return blob;
/*
* Get BLOB data in one slice.
* => Fast in Internet Explorer on new Blob(...)
*/
function getBlobDataAtOnce() {
byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
byteArray = new Uint8Array(byteNumbers);
return [byteArray];
}
/*
* Get BLOB data in multiple slices.
* => Slow in Internet Explorer on new Blob(...)
*/
function getBlobDataSliced() {
var slice,
byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
slice = byteCharacters.slice(offset, offset + sliceSize);
byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
byteArray = new Uint8Array(byteNumbers);
// Add slice
byteArrays.push(byteArray);
}
return byteArrays;
}
}
You can also use a formula in excel in order to convert this type of date to a date type excel can read:
=DATEVALUE(CONCATENATE(MID(A1,8,3),MID(A1,4,4),RIGHT(A1,4)))
And you get: 12/7/2016
from: Wed Dec 07 00:00:00 UTC 2016
To everyone using:
Get-WMIObject win32_product
You should be aware that this will run a self-heal on every single MSI application installed on the PC. If you were to check eventvwr it will say it has finished reconfiguring each product.
In this case i use the following (a mixture of Yan Sklyarenko's method):
$Reg = @( "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*", "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" )
$InstalledApps = Get-ItemProperty $Reg -EA 0
$WantedApp = $InstalledApps | Where { $_.DisplayName -like "*<part of product>*" }
Now if you were to type:
$WantedApp.PSChildName
You would be given the following:
PS D:\SCCM> $WantedApp.PSChildName
{047904BA-C065-40D5-969A-C7D91CA93D62}
If your organization uses loads of MST's whilst installing applications you would want to avoid running self-heals encase they revert some crucial settings.
git rev-list --all | xargs -n 5 git grep EXPRESSION
is a tweak to Jeet's solution, so it shows results while it searches and not just at the end (which can take a long time in a large repository).
Here is some code from above added with actual action code (point 1 and 2);
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in
// 1. remove object from your array
scannedItems.remove(at: indexPath.row)
// 2. reload the table, otherwise you get an index out of bounds crash
self.tableView.reloadData()
completionHandler(true)
}
deleteAction.backgroundColor = .systemOrange
let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
configuration.performsFirstActionWithFullSwipe = true
return configuration
}
var empty = $("#cartContent").html().trim().length == 0;
I am using this method to read Contacts
public static List<ContactItem> readPhoneContacts(Context context) {
List<ContactItem> contactItems = new ArrayList<ContactItem>();
try {
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, "upper("+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");
/*context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",
new String[] { id },
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");*/
Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list
if (contactsCount > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
ContactItem contactItem = new ContactItem();
contactItem.setContactName(contactName);
//the below cursor will give you details for multiple contacts
Cursor pCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
// continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list
while (pCursor.moveToNext()) {
int phoneType = pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
//String isStarred = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
String phoneNo = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//you will get all phone numbers according to it's type as below switch case.
//Logs.e will print the phone number along with the name in DDMS. you can use these details where ever you want.
switch (phoneType) {
case Phone.TYPE_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
break;
case Phone.TYPE_OTHER:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
break;
default:
break;
}
}
contactItem.setSelectedAddress(getContactPostalAddress(pCursor));
pCursor.close();
contactItems.add(contactItem);
}
}
cursor.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return contactItems;
}//loadContacts
you can try adding
$db['db_debug'] = FALSE;
in "your database file".php after that you can modify your database as you like.
You may use the String.split()
method:
String[] tokens = str.split(",");
After that, use Double.parseDouble()
method to parse the string value to a double.
double latitude = Double.parseDouble(tokens[0]);
double longitude = Double.parseDouble(tokens[1]);
Similar parse methods exist in the other wrapper classes as well - Integer
, Boolean
, etc.
If you want to avoid concatenating all commands into a single command with ;
or &&
you can also get true multi-line scripts using a heredoc:
command:
- sh
- "-c"
- |
/bin/bash <<'EOF'
# Normal script content possible here
echo "Hello world"
ls -l
exit 123
EOF
This is handy for running existing bash scripts, but has the downside of requiring both an inner and an outer shell instance for setting up the heredoc.
For changing the direction of swipe you can use
reverselayout attribute = true.
In Kotlin,
val layoutManager = LinearLayoutManager(this@MainActivity,LinearLayoutManager.HORIZONTAL,true)
recyclerview.layoutManager = layoutManager
In Java,
LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,true);
recyclerview.setLayoutManager(layoutManager);
Actually it reverses the layout.
If it shows like below
1.2..3....10
it will change to
10.9..8....1
For creating Horizontal RecyclerView there are many ways.
I had a similar issue where I wanted to represent HTML as JSON in the following way:
string
Example:
<div>
<span>text</span>Text2
</div>
becomes
[
'div',
{},
['span', {}, 'text'],
'Text2'
]
I wrote a function which handles transforming a DOM Element into this kind of JS structure. You can find this function at the end of this answer. The function is written in Typescript. You can use the Typescript playground to convert it to clean JavaScript.
Furthermore, if you need to parse an html string into DOM, assign to .innerHtml
:
let element = document.createElement('div')
element.innerHtml = htmlString
Also, this one is common knowledge but if you need a JSON string output, use JSON.stringify
.
/**
* A NodeDescriptor stands for either an (HTML) Element, or for a text node
*/
export type NodeDescriptor = ElementDescriptor | string
/**
* Array representing an HTML Element. It consists of:
*
* - The (tag) name of the element
* - An object, mapping attribute keys to attribute values
* - The (inlined) list of children nodes
*/
export type ElementDescriptor = [
string,
Record<string, string>,
...NodeDescriptor[]
]
export let htmlToJs = (element: Element, trim = true): ElementDescriptor => {
let convertElement = (element: Element): ElementDescriptor => {
let attributeObject: Record<string, string> = {}
for (let { name, value } of element.attributes) {
attributeObject[name] = value
}
let childArray: NodeDescriptor[] = []
for (let node of element.childNodes) {
let converter = htmlToJsDispatch[node.nodeType]
if (converter) {
let descriptor = converter(node as any)
let skip = false
if (trim && typeof descriptor === 'string') {
descriptor = descriptor.trim()
if (descriptor === '') skip = true
}
if (!skip) childArray.push(descriptor)
}
}
return [element.tagName.toLowerCase(), attributeObject, ...childArray]
}
let htmlToJsDispatch = {
[element.ELEMENT_NODE]: convertElement,
[element.TEXT_NODE]: (node: Text): string => node.data,
}
return convertElement(element)
}
Setting margins on table cells doesn't really have any effect as far as I know. The true CSS equivalent for cellspacing
is border-spacing
- but it doesn't work in Internet Explorer.
You can use border-collapse: collapse
to reliably set cell spacing to 0 as mentioned, but for any other value I think the only cross-browser way is to keep using the cellspacing
attribute.
It is not so easy to give out specific addresses to people say for a conference or a specific project or product. It could be more secure to prevent hacking such as SQL injection attacks etc.
Assuming the renderDetailItem method has the following signature...
(rowData, sectionID, rowID, highlightRow)
Try doing this...
<TouchableHighlight key={rowID} underlayColor='#dddddd'>
If you are familiar with using System.Windows.Forms class then you can just add a reference of System.Windows.Forms class to your project:
Solution Explorer -> References -> Add References... -> ( Assemblies : Framework ) -> scroll down and check System.Windows.Forms assembly -> OK.
Now you can add using System.Windows.Forms; statement and use screen in your wpf project just like before.
According to Authentication on google: OAuth2 keeps returning 'invalid_grant'
"You should reuse the access token you get after the first successful authentication. You will get an invalid_grant error if your previous token has not expired yet. Cache it somewhere so you can reuse it."
hope it helps
First give your input type submit a name, like this name='submitform'
.
and then put this in your php file
if (isset($_POST['submitform']))
{
?>
<script type="text/javascript">
window.location = "http://www.google.com/";
</script>
<?php
}
Don't forget to change the url to yours.
As others have mentioned you need a users/show.json view, but there are options to consider for the templating language...
ERB
Works out of the box. Great for HTML, but you'll quickly find it's awful for JSON.
Good solution. Have to add a dependency and learn its DSL.
Same deal as RABL: Good solution. Have to add a dependency and learn its DSL.
Plain Ruby
Ruby is awesome at generating JSON and there's nothing new to learn as you can call to_json
on a Hash or an AR object. Simply register the .rb extension for templates (in an initializer):
ActionView::Template.register_template_handler(:rb, :source.to_proc)
Then create the view users/show.json.rb:
@user.to_json
For more info on this approach see http://railscasts.com/episodes/379-template-handlers
Just use:
param.AddWithValue("@Date_Of_Birth",DOB);
That will take care of all your problems.
Could anyone help explain why
In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.
The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.
or give a solution for the code on windows? Thanks so much!
Choose a data type whose size is not platform dependent. You can find the list at https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in the most sensible choice would probably be np.int64
What's the big deal with this.. The cleanest way to do this is
var currentDate=new Date().toLocaleString().slice(0,10);
You can also use
HttpRuntime.AppDomainAppVirtualPath
**multiple delete not working**
function delete_selection()
{
$id_array = array();
$selection = $this->input->post("selection", TRUE);
$id_array = explode("|", $selection);
foreach ($id_array as $item):
if ($item != ''):
//DELETE ROW
$this->db->where('entry_id', $item);
$this->db->delete('helpline_entry');
endif;
endforeach;
}
Prerequisite:
Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control
Aria does not change anything visually. (Aria is scared of designers too).
aria-label
aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users
How To Use:
<input type="edit" aria-label="search" placeholder="search">
There is no visual change in application. But screen readers can understand the purpose of control
aria-labelledby
Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually
Approach 1:
<span id="sd">Search</span>
<input type="text" aria-labelledby="sd">
Approach 2:
aria-labelledby can also be used to combine two labels for screen reader users
<span id="de">Billing Address</span>
<span id="sd">First Name</span>
<input type="text" aria-labelledby="de sd">
So the way I would solve this problem is to make sure the two datetimes are in the right timezone.
I can see that you are using datetime.now()
which will return the systems current time, with no tzinfo set.
tzinfo is the information attached to a datetime to let it know what timezone it is in. If you are using naive datetime you need to be consistent through out your system. I would highly recommend only using datetime.utcnow()
seeing as somewhere your are creating datetime that have tzinfo associated with them, what you need to do is make sure those are localized (has tzinfo associated) to the correct timezone.
Take a look at Delorean, it makes dealing with this sort of thing much easier.
As SLaks answered, the native
keyword is for calling native code.
It also used by GWT for implementing javascript methods.
You can use this code...
public class Main {
public static void main(String args[]) {
String[] names = {"First", "Second", "Third"};//You Can Add More Names
double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
List<Customer> customers = new ArrayList<Customer>();
int i = 0;
while (i < names.length) {
customers.add(new Customer(names[i], amount[i]));
i++;
}
}
}
The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
It doesn't matter what the content-type is.
Extension at post below.
you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.
Not IsNull(Fields!W_O_Count.Value)
netstat -p -l | grep $PORT
and lsof -i :$PORT
solutions are good but I prefer fuser $PORT/tcp
extension syntax to POSIX (which work for coreutils
) as with pipe:
pid=`fuser $PORT/tcp`
it prints pure pid so you can drop sed
magic out.
One thing that makes fuser
my lover tools is ability to send signal to that process directly (this syntax is also extension to POSIX):
$ fuser -k $port/tcp # with SIGKILL
$ fuser -k -15 $port/tcp # with SIGTERM
$ fuser -k -TERM $port/tcp # with SIGTERM
Also -k is supported by FreeBSD: http://www.freebsd.org/cgi/man.cgi?query=fuser
Just an easy answer for the future which I found easy to use as a starter:
Similar to using end=''
to avoid a new line, you can use sep=''
to avoid the white spaces...for this question here, it would look like this:
print('Value is "', value, '"', sep = '')
May it help someone in the future.
MsgBox("Variable {0} " , variable)
If you don't mind a third party dependency, there is a class named Collectors2 in Eclipse Collections which contains methods returning Collectors for summing and summarizing BigDecimal and BigInteger. These methods take a Function as a parameter so you can extract a BigDecimal or BigInteger value from an object.
List<BigDecimal> list = mList(
BigDecimal.valueOf(0.1),
BigDecimal.valueOf(1.1),
BigDecimal.valueOf(2.1),
BigDecimal.valueOf(0.1));
BigDecimal sum =
list.stream().collect(Collectors2.summingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), sum);
BigDecimalSummaryStatistics statistics =
list.stream().collect(Collectors2.summarizingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), statistics.getSum());
Assert.assertEquals(BigDecimal.valueOf(0.1), statistics.getMin());
Assert.assertEquals(BigDecimal.valueOf(2.1), statistics.getMax());
Assert.assertEquals(BigDecimal.valueOf(0.85), statistics.getAverage());
Note: I am a committer for Eclipse Collections.
Since I haven't gotten any more feedback on this issue, I thought I'd just share what ended up being my solution:
As suggested by Barry in a comment to the original post, manually renaming the '...bin\Debug[ProjectName].exe' to something else (e.g. '[ProjectName]1.exe') is one work-around (I'm however not allowed to delete the file myself, and I must say I find that a bit weird as one would believe the same lock preventing deletion would also prevent renaming...). It's not a good solution, but it's reasonable fast (at least after you've done it a couple of times, it almost becomes a routine), and at least way faster than restarting Visual Studio which is what I did in the beginning.
In case somebody wonders, I could also add that I only see this problem semi-randomly. It usually happens after I've done some changes in the design mode of a form (but not always). It usually doesn't happen if I only change business-logic code or non-visual related code (but sometimes it does...). Frustrating indeed, but at least I have a hack that works for me - let's just hope that my next project doesn't face this problem as well...
@Barry: if you would like to get credit for your comment, please feel free to post it as an answer and I'll make sure to accept it :)
use below code, as this is 100% growth rate in case of 0 to any number :
IFERROR((NEW-OLD)/OLD,100%)
View.setOnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
v.alpha = 0f
v.invalidate()
}
MotionEvent.ACTION_UP -> {
v.alpha = 1f
v.invalidate()
}
}
false
}
You could use <jsp:include>
for this.
<jsp:include page="/servletURL" />
It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. Create a Servlet which does something like following in doGet()
method.
request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
and in /WEB-INF/result.jsp
<p>The result is ${result}</p>
Now call the Servlet by the URL which matches its <url-pattern>
in web.xml
, e.g. http://example.com/contextname/servletURL.
Do note that the JSP file is explicitly placed in /WEB-INF
folder. This will prevent the user from opening the JSP file individually. The user can only call the servlet in order to open the JSP file.
If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form action
.
<form action="servletURL" method="post">
Its doPost()
method will then be called.
You've started right - now you just need to fill the each student
structure in the array:
struct student
{
public int s_id;
public String s_name, c_name, dob;
}
class Program
{
static void Main(string[] args)
{
student[] arr = new student[4];
for(int i = 0; i < 4; i++)
{
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
arr[i].s_id = Int32.Parse(Console.ReadLine());
arr[i].s_name = Console.ReadLine();
arr[i].c_name = Console.ReadLine();
arr[i].s_dob = Console.ReadLine();
}
}
}
Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.
from urllib import request
def get(url):
with request.urlopen(url) as r:
return r.read()
def download(url, file=None):
if not file:
file = url.split('/')[-1]
with open(file, 'wb') as f:
f.write(get(url))
there's a better way
# Larger example
rows = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00)]
c.executemany('insert into stocks values (?,?,?,?,?)', rows)
connection.commit()
I have a large file in excel dealing with purchase and sale of mutual fund units. Number of rows in a worksheet exceeds 4000. I have no experience with VBA and would like to work with basic excel. Taking the cue from the solutions suggested above, I tried to solve the problem ( to insert blank rows automatically) in the following manner:
This method also may be tried by the readers.
Call list()
on the dictionary instead:
keys = list(test)
In Python 3, the dict.keys()
method returns a dictionary view object, which acts as a set. Iterating over the dictionary directly also yields keys, so turning a dictionary into a list results in a list of all the keys:
>>> test = {'foo': 'bar', 'hello': 'world'}
>>> list(test)
['foo', 'hello']
>>> list(test)[0]
'foo'
I don't know if this is the best way, but it has worked for me.
$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/path/to/file.php");
Update: It looks like the manual has been updated and the example I was referring to has been removed. See the edit to @flainez's answer above.
Original: Using @objc is the right way to do it even if you're not interoperating with Obj-C. It ensures that your protocol is being applied to a class and not an enum or struct. See "Checking for Protocol Conformance" in the manual.
In it's simplest form, use the answer of Georg Fritzsche
For a bit advanced, you can use this,
QString QString::arg ( int a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
Get the documentation and an example here..
Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement
In Objective C
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(tableView == firstTableView)
{
//code for first table view
[cell.contentView addSubview: someView];
}
if(tableview == secondTableView)
{
//code for secondTableView
[cell.contentView addSubview: someView];
}
return cell;
}
In Swift 3.0
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
if(tableView == firstTableView) {
//code for first table view
}
if(tableview == secondTableView) {
//code for secondTableView
}
return cell
}
public class DayFlipper extends ViewPager {
private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {
@Override
public int getCount() {
return DayFlipper.DAY_HISTORY;
}
@Override
public void startUpdate(View container) {
}
@Override
public Object instantiateItem(View container, int position) {
Log.d(TAG, "instantiateItem(): " + position);
Date d = DateHelper.getBot();
for (int i = 0; i < position; i++) {
d = DateHelper.getTomorrow(d);
}
d = DateHelper.normalize(d);
CubbiesView cv = new CubbiesView(mContext);
cv.setLifeDate(d);
((ViewPager) container).addView(cv, 0);
// add map
cv.setCubbieMap(mMap);
cv.initEntries(d);
adpter = FlipperAdapter.this;
return cv;
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((CubbiesView) object);
}
@Override
public void finishUpdate(View container) {
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((CubbiesView) object);
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
}
...
public void refresh() {
adapter().notifyDataSetChanged();
}
}
try this.
Make sure that the selected DB is the one where the table is. I was running the Script on Master
. In my case, I had to switch to hr_db
.
Rookie mistake but, could help someone.
I had the same problem while trying to run make
for a project after installing Boost version 1.66.0 on Ubuntu Trusty64. The error message was similar to (not exactly like) this one:
CMake Error at
/usr/local/Cellar/cmake/3.3.2/share/cmake/Modules/FindBoost.cmake:1245 (message):
Unable to find the requested Boost libraries.
Boost version: 0.0.0
Boost include path: /usr/include
Detected version of Boost is too old. Requested version was 1.36 (or newer).
Call Stack (most recent call first):
CMakeLists.txt:10 (FIND_PACKAGE)
Boost was definitely installed, but CMake couldn't detect it. After spending plenty of time tinkering with paths and environmental variables, I eventually ended up checking cmake
itself for options and found the following:
--check-system-vars = Find problems with variable usage in system files
So I ran the following in the directory at issue:
sudo cmake --check-system-vars
which returned:
Also check system files when warning about unused and uninitialized variables.
-- Boost version: 1.66.0
-- Found the following Boost libraries:
-- system
-- filesystem
-- thread
-- date_time
-- chrono
-- regex
-- serialization
-- program_options
-- Found Git: /usr/bin/git
-- Configuring done
-- Generating done
-- Build files have been written to: /home/user/myproject
and resolved the issue.
Install gcc.
If you're on linux, use the package manager.
If you're on Windows, use MinGW.
Press Alt+H(h) and then you'll see the shortcuts on the toolbar, press FC to operate color menu and press A(Automatic) for black or browse through other colors using arrow keys.
Another way is to tell the marshaller to always use a certain prefix
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
@Override
public String getPreferredPrefix(String arg0, String arg1, boolean arg2) {
return "ns1";
}
});'
$validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', ]);
if ($validator->fails()) { return $validator->errors(); }
The problem is that variables declared in one case
are still visible in the subsequent case
s unless an explicit { }
block is used, but they will not be initialized because the initialization code belongs to another case
.
In the following code, if foo
equals 1, everything is ok, but if it equals 2, we'll accidentally use the i
variable which does exist but probably contains garbage.
switch(foo) {
case 1:
int i = 42; // i exists all the way to the end of the switch
dostuff(i);
break;
case 2:
dostuff(i*2); // i is *also* in scope here, but is not initialized!
}
Wrapping the case in an explicit block solves the problem:
switch(foo) {
case 1:
{
int i = 42; // i only exists within the { }
dostuff(i);
break;
}
case 2:
dostuff(123); // Now you cannot use i accidentally
}
To further elaborate, switch
statements are just a particularly fancy kind of a goto
. Here's an analoguous piece of code exhibiting the same issue but using a goto
instead of a switch
:
int main() {
if(rand() % 2) // Toss a coin
goto end;
int i = 42;
end:
// We either skipped the declaration of i or not,
// but either way the variable i exists here, because
// variable scopes are resolved at compile time.
// Whether the *initialization* code was run, though,
// depends on whether rand returned 0 or 1.
std::cout << i;
}
Time Zone Handling
I just want to clarify, even though this has been commented so future people don't miss this very important distinction.
DateTime.strptime("1318996912",'%s') # => Wed, 19 Oct 2011 04:01:52 +0000
displays a return value in UTC and requires the seconds to be a String and outputs a UTC Time object, whereas
Time.at(1318996912) # => 2011-10-19 00:01:52 -0400
displays a return value in the LOCAL time zone, normally requires a FixNum argument, but the Time object itself is still in UTC even though the display is not.
So even though I passed the same integer to both methods, I seemingly two different results because of how the class' #to_s
method works. However, as @Eero had to remind me twice of:
Time.at(1318996912) == DateTime.strptime("1318996912",'%s') # => true
An equality comparison between the two return values still returns true. Again, this is because the values are basically the same (although different classes, the #==
method takes care of this for you), but the #to_s
method prints drastically different strings. Although, if we look at the strings, we can see they are indeed the same time, just printed in different time zones.
Method Argument Clarification
The docs also say "If a numeric argument is given, the result is in local time." which makes sense, but was a little confusing to me because they don't give any examples of non-integer arguments in the docs. So, for some non-integer argument examples:
Time.at("1318996912")
TypeError: can't convert String into an exact number
you can't use a String argument, but you can use a Time argument into Time.at
and it will return the result in the time zone of the argument:
Time.at(Time.new(2007,11,1,15,25,0, "+09:00"))
=> 2007-11-01 15:25:00 +0900
Benchmarks
After a discussion with @AdamEberlin on his answer, I decided to publish slightly changed benchmarks to make everything as equal as possible. Also, I never want to have to build these again so this is as good a place as any to save them.
Time.at(int).to_datetime ~ 2.8x faster
09:10:58-watsw018:~$ ruby -v
ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin18]
09:11:00-watsw018:~$ irb
irb(main):001:0> require 'benchmark'
=> true
irb(main):002:0> require 'date'
=> true
irb(main):003:0>
irb(main):004:0* format = '%s'
=> "%s"
irb(main):005:0> times = ['1318996912', '1318496913']
=> ["1318996912", "1318496913"]
irb(main):006:0> int_times = times.map(&:to_i)
=> [1318996912, 1318496913]
irb(main):007:0>
irb(main):008:0* datetime_from_strptime = DateTime.strptime(times.first, format)
=> #<DateTime: 2011-10-19T04:01:52+00:00 ((2455854j,14512s,0n),+0s,2299161j)>
irb(main):009:0> datetime_from_time = Time.at(int_times.first).to_datetime
=> #<DateTime: 2011-10-19T00:01:52-04:00 ((2455854j,14512s,0n),-14400s,2299161j)>
irb(main):010:0>
irb(main):011:0* datetime_from_strptime === datetime_from_time
=> true
irb(main):012:0>
irb(main):013:0* Benchmark.measure do
irb(main):014:1* 100_000.times {
irb(main):015:2* times.each do |i|
irb(main):016:3* DateTime.strptime(i, format)
irb(main):017:3> end
irb(main):018:2> }
irb(main):019:1> end
=> #<Benchmark::Tms:0x00007fbdc18f0d28 @label="", @real=0.8680500000045868, @cstime=0.0, @cutime=0.0, @stime=0.009999999999999998, @utime=0.86, @total=0.87>
irb(main):020:0>
irb(main):021:0* Benchmark.measure do
irb(main):022:1* 100_000.times {
irb(main):023:2* int_times.each do |i|
irb(main):024:3* Time.at(i).to_datetime
irb(main):025:3> end
irb(main):026:2> }
irb(main):027:1> end
=> #<Benchmark::Tms:0x00007fbdc3108be0 @label="", @real=0.33059399999910966, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.32000000000000006, @total=0.32000000000000006>
****edited to not be completely and totally incorrect in every way****
****added benchmarks****
When we use crontab
or the deprecated /etc/rc.local
file, we need a delay (e.g. sleep 10
, depending on the machine) to make sure that system services are available. Usually, systemd
(or upstart
) is used to manage which services start when the system boots. You can try use the similar configuration for this:
# /etc/systemd/system/docker-compose-app.service
[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service
[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up -d
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0
[Install]
WantedBy=multi-user.target
Or, if you want run without the -d
flag:
# /etc/systemd/system/docker-compose-app.service
[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service
[Service]
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0
Restart=on-failure
StartLimitIntervalSec=60
StartLimitBurst=3
[Install]
WantedBy=multi-user.target
Change the WorkingDirectory
parameter with your dockerized project path. And enable the service to start automatically:
systemctl enable docker-compose-app
Using @extend is a fine solution, but be aware that the compiled css will break up the class definition. Any classes that extends the same placeholder will be grouped together and the rules that aren't extended in the class will be in a separate definition. If several classes become extended, it can become unruly to look up a selector in the compiled css or the dev tools. Whereas a mixin will duplicate the mixin code and add any additional styles.
You can see the difference between @extend and @mixin in this sassmeister
Alternative solution: you can dump your db and restore that in different name. As I've experienced it's much quicker than db.copyDatabase()
.
$ mongodump -d old_db_name -o mongodump/
$ mongorestore -d new_db_name mongodump/old_db_name
http://docs.mongodb.org/manual/tutorial/backup-with-mongodump/
This is the current official recommended approach for database renames, given that copyDatabase
was removed in MongoDB 4.2:
The "copydb" command is deprecated, please use these two commands instead:
- mongodump (to back up data)
- mongorestore (to recover data from mongodump into a new namespace)
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
The accepted answer seems like it will search through the entire response message. This could give you false matches for cookie headers if the word "Set-Cookie" is at the beginning of a line. While it should be fine in most cases. The safer way might be to read through the message from the beginning until the first empty line which indicates the end of the message headers. This is just an alternate solution that should look for the first blank line and then use preg_grep on those lines only to find "Set-Cookie".
curl_setopt($ch, CURLOPT_HEADER, 1);
//Return everything
$res = curl_exec($ch);
//Split into lines
$lines = explode("\n", $res);
$headers = array();
$body = "";
foreach($lines as $num => $line){
$l = str_replace("\r", "", $line);
//Empty line indicates the start of the message body and end of headers
if(trim($l) == ""){
$headers = array_slice($lines, 0, $num);
$body = $lines[$num + 1];
//Pull only cookies out of the headers
$cookies = preg_grep('/^Set-Cookie:/', $headers);
break;
}
}
Another reason to use object
over iframe is that object
sub resources (when an <object>
performs HTTP
requests) are considered as passive/display
in terms of Mixed content
, which means it's more secure when you must have Mixed content
.
Mixed content means that when you have https
but your resource is from http
.
Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content
Go to "File" in android studio, Click "invalidate caches/Restart" and "Invalidate and Restart"
That also works
Somewhere in your controller (often the last line is a good place), put
console.log($scope);
If you want to see an inner/implicit scope, say inside an ng-repeat, something like this will work.
<li ng-repeat="item in items">
...
<a ng-click="showScope($event)">show scope</a>
</li>
Then in your controller
function MyCtrl($scope) {
...
$scope.showScope = function(e) {
console.log(angular.element(e.srcElement).scope());
}
}
Note that above we define the showScope() function in the parent scope, but that's okay... the child/inner/implicit scope can access that function, which then prints out the scope based on the event, and hence the scope associated with the element that fired the event.
@jm-'s suggestion also works, but I don't think it works inside a jsFiddle. I get this error on jsFiddle inside Chrome:
> angular.element($0).scope()
ReferenceError: angular is not defined
Try to this cors npm modules.
var cors = require('cors')
var app = express()
app.use(cors())
This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.
If you have imported an existing project, then just remove your source folders and then add them again to build path, and restart eclipse. Most of the times eclipse will keep showing the error till you restart.
In swift 3 use:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
That this works is not trivial at all! It's a property of the IEEE floating point representation that int°floor = ?·? if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.
This post explains why it works in that range.
In a double, you can represent 32bit integers without any problems. There cannot be any rounding issues. More precisely, doubles can represent all integers between and including 253 and -253.
Short explanation: A double can store up to 53 binary digits. When you require more, the number is padded with zeroes on the right.
It follows that 53 ones is the largest number that can be stored without padding. Naturally, all (integer) numbers requiring less digits can be stored accurately.
Adding one to 111(omitted)111 (53 ones) yields 100...000, (53 zeroes). As we know, we can store 53 digits, that makes the rightmost zero padding.
This is where 253 comes from.
More detail: We need to consider how IEEE-754 floating point works.
1 bit 11 / 8 52 / 23 # bits double/single precision
[ sign | exponent | mantissa ]
The number is then calculated as follows (excluding special cases that are irrelevant here):
-1sign × 1.mantissa ×2exponent - bias
where bias = 2exponent - 1 - 1, i.e. 1023 and 127 for double/single precision respectively.
Knowing that multiplying by 2X simply shifts all bits X places to the left, it's easy to see that any integer must have all bits in the mantissa that end up right of the decimal point to zero.
Any integer except zero has the following form in binary:
1x...x where the x-es represent the bits to the right of the MSB (most significant bit).
Because we excluded zero, there will always be a MSB that is one—which is why it's not stored. To store the integer, we must bring it into the aforementioned form: -1sign × 1.mantissa ×2exponent - bias.
That's saying the same as shifting the bits over the decimal point until there's only the MSB towards the left of the MSB. All the bits right of the decimal point are then stored in the mantissa.
From this, we can see that we can store at most 52 binary digits apart from the MSB.
It follows that the highest number where all bits are explicitly stored is
111(omitted)111. that's 53 ones (52 + implicit 1) in the case of doubles.
For this, we need to set the exponent, such that the decimal point will be shifted 52 places. If we were to increase the exponent by one, we cannot know the digit right to the left after the decimal point.
111(omitted)111x.
By convention, it's 0. Setting the entire mantissa to zero, we receive the following number:
100(omitted)00x. = 100(omitted)000.
That's a 1 followed by 53 zeroes, 52 stored and 1 added due to the exponent.
It represents 253, which marks the boundary (both negative and positive) between which we can accurately represent all integers. If we wanted to add one to 253, we would have to set the implicit zero (denoted by the x
) to one, but that's impossible.
If you want a method other than findcontrol try the following:
GridViewRow row = Gridview1.SelectedRow;
int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this
You can use jQuery serialize function along with get/post as follows:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theform').serialize())
jQuery Serialize Documentation: http://api.jquery.com/serialize/
Simple AJAX submit using jQuery:
// this is the id of the submit button
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.
(if you want to use your project created with other text engine type) copy /paste all layers to new project.
Another example with using Objective-C associated objects and computed properties for Swift 3 and Swift 4
import CoreLocation
extension CLLocation {
private struct AssociatedKeys {
static var originAddress = "originAddress"
static var destinationAddress = "destinationAddress"
}
var originAddress: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.originAddress) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.originAddress,
newValue as NSString?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
var destinationAddress: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.destinationAddress) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.destinationAddress,
newValue as NSString?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
}
Old question with many good answers, but here is another simple option that relies on two popular libraries to get it done. Some answers mention Papa Parse but roll their own solution for the download part. Combining Papa Parse and FileSaver.js, you can try the following:
const dataString = Papa.unparse(data, config);
const blob = new Blob([dataString], { type: 'text/csv;charset=utf-8' });
FileSaver.saveAs(blob, 'myfile.csv');
The config
options for unparse
are described here.
This worked for me fine:
File 1:
<html>
<head></head>
<body>
<a href="#" onclick="window.open('file:///D:/Examples/file2.html'); return false">CLICK ME</a>
</body>
<footer></footer>
</html>
File 2:
<html>
...
</html>
This method works regardless of whether or not the 2 files are in the same directory, BUT both files must be local.
For obvious security reasons, if File 1 is located on a remote server you absolutely cannot open a file on some client's host computer and trying to do so will open a blank target.
Being a void element, an <input>
element is considered empty by the HTML definition of "empty", since the content model of all void elements is always empty. So they will always match the :empty
pseudo-class, whether or not they have a value. This is also why their value is represented by an attribute in the start tag, rather than text content within start and end tags.
Also, from the Selectors spec:
The
:empty
pseudo-class represents an element that has no children at all. In terms of the document tree, only element nodes and content nodes (such as DOM text nodes, CDATA nodes, and entity references) whose data has a non-zero length must be considered as affecting emptiness;
Consequently, input:not(:empty)
will never match anything in a proper HTML document. (It would still work in a hypothetical XML document that defines an <input>
element that can accept text or child elements.)
I don't think you can style empty <input>
fields dynamically using just CSS (i.e. rules that apply whenever a field is empty, and don't once text is entered). You can select initially empty fields if they have an empty value
attribute (input[value=""]
) or lack the attribute altogether (input:not([value])
), but that's about it.
A jar
file is a zip file with some additional files containing metadata. (Despite the .jar extension, it is in zip format, and any utilities that deal with .zip files are also able to deal with .jar files.)
http://docs.oracle.com/javase/8/docs/technotes/guides/jar/index.html
Jar files can contain any kind of files, but they usually contain class files and supporting configuration files (properties), graphics and other data files needed by the application.
Class files contain compiled Java code, which is executable by the Java Virtual Machine.
String
A simple regex. See: How to check if a string contains only digits in Java. Use javax.constraints.Pattern.
$('.DataTables_sort_wrapper').trigger("click");
In my development I found two distinct advantages for using an SPA. That is not to say that the following can not be achieved in a traditional web app just that I see incremental benefit without introducing additional disadvantages.
Potential for less server request as rendering new content isn’t always or even ever an http server request for a new html page. But I say potential because new content could easily require an Ajax call to pull in data but that data could be incrementally lighter than the itself plus markup providing a net benefit.
The ability to maintain “State”. In its simplest terms, set a variable on entry to the app and it will be available to other components throughout the user’s experience without passing it around or setting it to a local storage pattern. Intelligently managing this ability however is key to keep the top level scope uncluttered.
Other than requiring JS (which is not a crazy thing to require of web apps) other noted disadvantages are in my opinion either not specific to SPA or can be mitigated through good habits and development patterns.
You can use deparse
and substitute
to get the name of a function argument:
myfunc <- function(v1) {
deparse(substitute(v1))
}
myfunc(foo)
[1] "foo"
Explanation
This is pretty vague but I'll do what I can to help.
First, while it may seem daunting at first, I suggest you learn how to do things from the command line (called terminal on OSX). This is a great way to make sure you're putting things where you really want to.
You should definitely google 'unix commands' to learn more, but here are a few important commands to help in this situation:
ls
- list all files and directories (folders) in current directory
cd <input directory here without these brackets>
- change directory, or change the folder you're looking in
mkdir <input directory name without brackets>
- Makes a new directory (be careful, you will have to cd into the directory after you make it)
rm -r <input directory name without brackets>
- Removes a directory and everything inside it
git clone <link to repo without brackets>
- Clones the repository into the directory you are currently browsing.
Answer
So, on my computer, I would run the following commands to create a directory (folder) called projects within my documents folder and clone a repo there.
cd documents
(Not case sensitive on mac)mkdir projects
cd projects
git clone https://github.com/seanbecker15/wherecanifindit.git
cd wherecanifindit
(if I want to go into the directory)p.s. wherecanifindit is just the name of my git repository, not a command!
TRUNCATE can be rolled back if wrapped in a transaction.
Please see the two references below and test yourself:-
The TRUNCATE vs. DELETE is one of the infamous questions during SQL interviews. Just make sure you explain it properly to the Interviewer or it might cost you the job. The problem is that not many are aware so most likely they will consider the answer as wrong if you tell them that YES Truncate can be rolled back.
NULL
is not a keyword. It's an identifier defined in some standard headers. You can include
#include <cstddef>
To have it in scope, including some other basics, like std::size_t
.
While @Jonas Giuro is right when saying that:
You cannot PAUSE the setInterval function, you can either STOP it (clearInterval), or let it run
On the other hand this behavior can be simulated with approach @VitaliyG suggested:
You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value.
var output = $('h1');_x000D_
var isPaused = false;_x000D_
var time = new Date();_x000D_
var offset = 0;_x000D_
var t = window.setInterval(function() {_x000D_
if(!isPaused) {_x000D_
var milisec = offset + (new Date()).getTime() - time.getTime();_x000D_
output.text(parseInt(milisec / 1000) + "s " + (milisec % 1000));_x000D_
}_x000D_
}, 10);_x000D_
_x000D_
//with jquery_x000D_
$('.toggle').on('click', function(e) {_x000D_
e.preventDefault();_x000D_
isPaused = !isPaused;_x000D_
if (isPaused) {_x000D_
offset += (new Date()).getTime() - time.getTime();_x000D_
} else {_x000D_
time = new Date();_x000D_
}_x000D_
_x000D_
});
_x000D_
h1 {_x000D_
font-family: Helvetica, Verdana, sans-serif;_x000D_
font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>Seconds: 0</h1>_x000D_
<button class="toggle">Toggle</button>
_x000D_
There are numerous methods of accomplishing this, which I'll detail with a few examples below.
img.grayscale {
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
filter: gray; /* IE6-9 */
-webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
}
img.grayscale:hover {
filter: none;
-webkit-filter: grayscale(0%);
}
img.grayscale {_x000D_
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");_x000D_
/* Firefox 3.5+, IE10 */_x000D_
filter: gray;_x000D_
/* IE6-9 */_x000D_
-webkit-filter: grayscale(100%);_x000D_
/* Chrome 19+ & Safari 6+ */_x000D_
-webkit-transition: all .6s ease;_x000D_
/* Fade to color for Chrome and Safari */_x000D_
-webkit-backface-visibility: hidden;_x000D_
/* Fix for transition flickering */_x000D_
}_x000D_
_x000D_
img.grayscale:hover {_x000D_
filter: none;_x000D_
-webkit-filter: grayscale(0%);_x000D_
}_x000D_
_x000D_
svg {_x000D_
background: url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);_x000D_
}_x000D_
_x000D_
svg image {_x000D_
transition: all .6s ease;_x000D_
}_x000D_
_x000D_
svg image:hover {_x000D_
opacity: 0;_x000D_
}
_x000D_
<p>Firefox, Chrome, Safari, IE6-9</p>_x000D_
<img class="grayscale" src="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" width="400">_x000D_
<p>IE10 with inline SVG</p>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 400 377" width="400" height="377">_x000D_
<defs>_x000D_
<filter id="filtersPicture">_x000D_
<feComposite result="inputTo_38" in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />_x000D_
<feColorMatrix id="filter_38" type="saturate" values="0" data-filterid="38" />_x000D_
</filter>_x000D_
</defs>_x000D_
<image filter="url("#filtersPicture")" x="0" y="0" width="400" height="377" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" />_x000D_
</svg>
_x000D_
You can find an article related to this technique here.
This approach requires two copies of an image: one in grayscale and the other in full color. Using the CSS :hover
psuedoselector, you can update the background of your element to toggle between the two:
#yourimage {
background: url(../grayscale-image.png);
}
#yourImage:hover {
background: url(../color-image.png};
}
#google {_x000D_
background: url('http://www.google.com/logos/keystroke10-hp.png');_x000D_
height: 95px;_x000D_
width: 275px;_x000D_
display: block;_x000D_
/* Optional for a gradual animation effect */_x000D_
transition: 0.5s;_x000D_
}_x000D_
_x000D_
#google:hover {_x000D_
background: url('https://graphics217b.files.wordpress.com/2011/02/logo1w.png');_x000D_
}
_x000D_
<a id='google' href='http://www.google.com'></a>
_x000D_
This could also be accomplished by using a Javascript-based hover effect such as jQuery's hover()
function in the same manner.
The desaturate library is a common library that allows you to easily switch between a grayscale version and full-colored version of a given element or image.
The accepted answer is incorrect.
createNativeQuery
will always return a Query
:
public Query createNativeQuery(String sqlString, Class resultClass);
Calling getResultList
on a Query
returns List
:
List getResultList()
When assigning (or casting) to List<MyEntity>
, an unchecked assignment warning is produced.
Whereas, createQuery
will return a TypedQuery
:
public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);
Calling getResultList
on a TypedQuery
returns List<X>
.
List<X> getResultList();
This is properly typed and will not give a warning.
With createNativeQuery
, using ObjectMapper
seems to be the only way to get rid of the warning. Personally, I choose to suppress the warning, as I see this as a deficiency in the library and not something I should have to worry about.
If it's not the Home edition of XP, you can use \\servername\c$
Mark Brackett's comment:
Note that you need to be an Administrator on the local machine, as the share permissions are locked down
Are you looking for total number of items that will be displayed in the table or total of items currently visible? Either way.. I believe that the 'viewDidLoad' method executes after all the datasource methods are called. However, this will only work on the first load of the data(if you are using a single alloc ViewController).
static
functions are functions that are only visible to other functions in the same file (more precisely the same translation unit).
EDIT: For those who thought, that the author of the questions meant a 'class method': As the question is tagged C
he means a plain old C function. For (C++/Java/...) class methods, static
means that this method can be called on the class itself, no instance of that class necessary.
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String
in as the string-to-match argument to the string.replace
method, it doesn't do a string replace. It converts the string to a RegExp
and does a regex substitution. As Gumbo explains, a regex substitution requires the g
?lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
In more modern browsers (including IE 10+) you can now use calc()
:
.moveto {
top: 0px;
left: calc(100% - 50px);
}
Use center
:
<center><form></form></center>
This is just one method, though it's not advised.
Ancient Edit: Please do not do this. I am just saying it is a thing that exists.
For more information about .scrollHeight
property refer to the docs:
The Element.scrollHeight read-only attribute is a measurement of the height of an element's content, including content not visible on the screen due to overflow. The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar. It includes the element padding but not its margin.
/*
If your delimiters are slash-based, escape it:
\/*
*
means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.
The PHP CLI as its called ( php for the Command Line Interface ) is called php.exe
It lives in c:\wamp\bin\php\php5.x.y\php.exe
( where x and y are the version numbers of php that you have installed )
If you want to create php scrips to run from the command line then great its easy and very useful.
Create yourself a batch file like this, lets call it phppath.cmd
:
PATH=%PATH%;c:\wamp\bin\php\phpx.y.z
php -v
Change x.y.z
to a valid folder name for a version of PHP that you have installed within WAMPServer
Save this into one of your folders that is already on your PATH, so you can run it from anywhere.
Now from a command window, cd into your source folder and run >phppath.
Then run
php your_script.php
It should work like a dream.
Here is an example that configures PHP Composer and PEAR if required and they exist
@echo off
REM **************************************************************
REM * PLACE This file in a folder that is already on your PATH
REM * Or just put it in your C:\Windows folder as that is on the
REM * Search path by default
REM * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
REM * EDIT THE NEXT 3 Parameters to fit your installed WAMPServer
REM **************************************************************
set baseWamp=D:\wamp
set defaultPHPver=7.4.3
set composerInstalled=%baseWamp%\composer
set phpFolder=\bin\php\php
if %1.==. (
set phpver=%baseWamp%%phpFolder%%defaultPHPver%
) else (
set phpver=%baseWamp%%phpFolder%%1
)
PATH=%PATH%;%phpver%
php -v
echo ---------------------------------------------------------------
REM IF PEAR IS INSTALLED IN THIS VERSION OF PHP
IF exist %phpver%\pear (
set PHP_PEAR_SYSCONF_DIR=%baseWamp%%phpFolder%%phpver%
set PHP_PEAR_INSTALL_DIR=%baseWamp%%phpFolder%%phpver%\pear
set PHP_PEAR_DOC_DIR=%baseWamp%%phpFolder%%phpver%\docs
set PHP_PEAR_BIN_DIR=%baseWamp%%phpFolder%%phpver%
set PHP_PEAR_DATA_DIR=%baseWamp%%phpFolder%%phpver%\data
set PHP_PEAR_PHP_BIN=%baseWamp%%phpFolder%%phpver%\php.exe
set PHP_PEAR_TEST_DIR=%baseWamp%%phpFolder%%phpver%\tests
echo PEAR INCLUDED IN THIS CONFIG
echo ---------------------------------------------------------------
) else (
echo PEAR DOES NOT EXIST IN THIS VERSION OF php
echo ---------------------------------------------------------------
)
REM IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM **************************************************************
REM * IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM *
REM * This assumes that composer is installed in /wamp/composer
REM *
REM **************************************************************
IF EXIST %composerInstalled% (
ECHO COMPOSER INCLUDED IN THIS CONFIG
echo ---------------------------------------------------------------
set COMPOSER_HOME=%baseWamp%\composer
set COMPOSER_CACHE_DIR=%baseWamp%\composer
PATH=%PATH%;%baseWamp%\composer
rem echo TO UPDATE COMPOSER do > composer self-update
echo ---------------------------------------------------------------
) else (
echo ---------------------------------------------------------------
echo COMPOSER IS NOT INSTALLED
echo ---------------------------------------------------------------
)
set baseWamp=
set defaultPHPver=
set composerInstalled=
set phpFolder=
Call this command file like this to use the default version of PHP
> phppath
Or to get a specific version of PHP like this
> phppath 5.6.30
When you need built-in indexed access, sorting (and after this binary searching), and "ToArray()" method, you should use List.
n=int(input('please enter the no. in decimal format: '))
x=n
k=[]
while (n>0):
a=int(float(n%2))
k.append(a)
n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
string=string+str(j)
print('The binary no. for %d is %s'%(x, string))
Here are some exchange APIs with PHP example.
Provides 1,000 requests per month free. You must register and grab the App ID. The base currency USD for free account. Check the supported currencies and documentation.
// open exchange URL // valid app_id * REQUIRED *
$exchange_url = 'https://openexchangerates.org/api/latest.json';
$params = array(
'app_id' => 'YOUR_APP_ID'
);
// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);
if (!empty($response->rates)) {
// convert 150 USD to JPY ( Japanese Yen )
echo $response->rates->JPY * 150;
}
150 USD = 18039.09015 JPY
Provides 1,000 requests per month free. You must register and grab the Access KEY. Custom base currency is not supported in free account. Check the documentation.
$exchange_url = 'http://apilayer.net/api/live';
$params = array(
'access_key' => 'YOUR_ACCESS_KEY',
'source' => 'USD',
'currencies' => 'JPY',
'format' => 1 // 1 = JSON
);
// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);
if (!empty($response->quotes)) {
// convert 150 USD to JPY ( Japanese Yen )
echo '150 USD = ' . $response->quotes->USDJPY * 150 . ' JPY';
}
150 USD = 18036.75045 JPY
Some additions to a given set of answers:
First of all if you going to use Redis hash efficiently you must know a keys count max number and values max size - otherwise if they break out hash-max-ziplist-value or hash-max-ziplist-entries Redis will convert it to practically usual key/value pairs under a hood. ( see hash-max-ziplist-value, hash-max-ziplist-entries ) And breaking under a hood from a hash options IS REALLY BAD, because each usual key/value pair inside Redis use +90 bytes per pair.
It means that if you start with option two and accidentally break out of max-hash-ziplist-value you will get +90 bytes per EACH ATTRIBUTE you have inside user model! ( actually not the +90 but +70 see console output below )
# you need me-redis and awesome-print gems to run exact code
redis = Redis.include(MeRedis).configure( hash_max_ziplist_value: 64, hash_max_ziplist_entries: 512 ).new
=> #<Redis client v4.0.1 for redis://127.0.0.1:6379/0>
> redis.flushdb
=> "OK"
> ap redis.info(:memory)
{
"used_memory" => "529512",
**"used_memory_human" => "517.10K"**,
....
}
=> nil
# me_set( 't:i' ... ) same as hset( 't:i/512', i % 512 ... )
# txt is some english fictionary book around 56K length,
# so we just take some random 63-symbols string from it
> redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), 63] ) } }; :done
=> :done
> ap redis.info(:memory)
{
"used_memory" => "1251944",
**"used_memory_human" => "1.19M"**, # ~ 72b per key/value
.....
}
> redis.flushdb
=> "OK"
# setting **only one value** +1 byte per hash of 512 values equal to set them all +1 byte
> redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), i % 512 == 0 ? 65 : 63] ) } }; :done
> ap redis.info(:memory)
{
"used_memory" => "1876064",
"used_memory_human" => "1.79M", # ~ 134 bytes per pair
....
}
redis.pipelined{ 10000.times{ |i| redis.set( "t:#{i}", txt[rand(50000), 65] ) } };
ap redis.info(:memory)
{
"used_memory" => "2262312",
"used_memory_human" => "2.16M", #~155 byte per pair i.e. +90 bytes
....
}
For TheHippo answer, comments on Option one are misleading:
hgetall/hmset/hmget to the rescue if you need all fields or multiple get/set operation.
For BMiner answer.
Third option is actually really fun, for dataset with max(id) < has-max-ziplist-value this solution has O(N) complexity, because, surprise, Reddis store small hashes as array-like container of length/key/value objects!
But many times hashes contain just a few fields. When hashes are small we can instead just encode them in an O(N) data structure, like a linear array with length-prefixed key value pairs. Since we do this only when N is small, the amortized time for HGET and HSET commands is still O(1): the hash will be converted into a real hash table as soon as the number of elements it contains will grow too much
But you should not worry, you'll break hash-max-ziplist-entries very fast and there you go you are now actually at solution number 1.
Second option will most likely go to the fourth solution under a hood because as question states:
Keep in mind that if I use a hash, the value length isn't predictable. They're not all short such as the bio example above.
And as you already said: the fourth solution is the most expensive +70 byte per each attribute for sure.
My suggestion how to optimize such dataset:
You've got two options:
If you cannot guarantee max size of some user attributes than you go for first solution and if memory matter is crucial than compress user json before store in redis.
If you can force max size of all attributes. Than you can set hash-max-ziplist-entries/value and use hashes either as one hash per user representation OR as hash memory optimization from this topic of a Redis guide: https://redis.io/topics/memory-optimization and store user as json string. Either way you may also compress long user attributes.
You can use this code for number validation:
if (!preg_match("/^[0-9]+$/i", $phone)) {
$errorMSG = 'Invalid Number!';
$error = 1;
}
Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:
(DT_I8)FLOOR((DT_R8)systemDateTime)
But you'd have to test to doublecheck.
You have a JSON object that contains an Array. You need to access the array results
. Change your code to:
this.data = res.json().results
Add CDN Files of toastr.css and toastr.js
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
function toasterOptions() {
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": true,
"positionClass": "toast-top-center",
"preventDuplicates": true,
"onclick": null,
"showDuration": "100",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "show",
"hideMethod": "hide"
};
};
toasterOptions();
toastr.error("Error Message from toastr");
Simple Definition:
npm - Javascript package manager
npx - Execute npm package binaries
I had the same problem. My work around is to use adb shell and su. Next, copy the file to /sdcard/Download
Then, I can use adb pull to get the file.
.Cells(.Rows.Count,"A").End(xlUp).row
I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:
.Cells(Rows.Count,"A").End(xlUp).row
Before the Cells, you can write your worksheet name, for example:
Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row
The worksheet name is not necessary when you operate on the same worksheet.
I think that understanding why you can't change the referer
header might help people reading this question.
From this page: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
From that link:
A forbidden header name is the name of any HTTP header that cannot be modified programmatically...
Modifying such headers is forbidden because the user agent retains full control over them.
Forbidden header names ... are one of the following names:
...
Referer
...
Math.round also returns an integer value, so you don't need to typecast.
int b = Math.round(float a);
To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:
SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)
In my case the missing type was referencing an import for java class in a dependent jar. For some reason my project file was missing the javabuilder and therefore couldnt resolve the path to the import.
Why it was missing in the first place I don't know, but adding these lines in fixed the error.
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
k-a-f's answer works for selecting one column, if selecting multiple column, we can.
DECLARE a BIGINT DEFAULT 1;
DECLARE b BIGINT DEFAULT "name";
SELECT id, name from table into a,b;
Then we just need to check a,b for values.
if (!*ptr) { /* empty string */}
similarly
if (*ptr) { /* not empty */ }
startInfo.Arguments = "/c \"netsh http add sslcert ipport=127.0.0.1:8085 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-4455-6677-8899-AABBCCDDEEFF} clientcertnegotiation=enable\"";
and...
startInfo.Arguments = "/c \"makecert -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer\"";
The /c
tells cmd to quit once the command has completed. Everything after /c
is the command you want to run (within cmd
), including all of the arguments.
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2
will return
password : [pwd1, pwd2]
(length = 2)
username : [james, smith]
(length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
You can do a $string = nl2br($string) so that your line break is changed to
<br />.
This way it does not matter if the system uses \r\n or \n or \r
Then you can feed it into an array:
$array = explode("<br />", $string);
As Kris mentions, you can use the $resource
service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http
service. In this case you can call its get
method.
If you have the following JSON
[{ "text":"learn angular", "done":true },
{ "text":"build an angular app", "done":false},
{ "text":"something", "done":false },
{ "text":"another todo", "done":true }]
You can load it like this
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
});
});
The get
method returns a promise object which
first argument is a success callback and the second an error
callback.
When you add $http
as a parameter of a function Angular does it magic
and injects the $http
resource into your controller.
I've put some examples here
I meet the same problem and I solved with a solution like the following code:
var drfs = new Array();
var external = $.Deferred();
drfs.push(external.promise());
$('itemSelector').each( function() {
//initialize the context for each cycle
var t = this; // optional
var internal = $.Deferred();
// after the previous deferred operation has been resolved
drfs.pop().then( function() {
// do stuff of the cycle, optionally using t as this
var result; //boolean set by the stuff
if ( result ) {
internal.resolve();
} else {
internal.reject();
}
}
drfs.push(internal.promise());
});
external.resolve("done");
$.when(drfs).then( function() {
// after all each are resolved
});
The solution solves the following problem: to synchronize the asynchronous operations started in the .each() iteration, using Deferred object.
Infinity, NaN and subnormals
These are important caveats that no other answer has mentioned so far.
First read this introduction to IEEE 754 and subnormal numbers: What is a subnormal floating point number?
Then, for single precision floats (32-bit):
IEEE 754 says that if the exponent is all ones (0xFF == 255
), then it represents either NaN or Infinity.
This is why the largest non-infinite number has exponent 0xFE == 254
and not 0xFF
.
Then with the bias, it becomes:
254 - 127 == 127
FLT_MIN
is the smallest normal number. But there are smaller subnormal ones! Those take up the -127
exponent slot.
All asserts of the following program pass on Ubuntu 18.04 amd64:
#include <assert.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
float float_from_bytes(
uint32_t sign,
uint32_t exponent,
uint32_t fraction
) {
uint32_t bytes;
bytes = 0;
bytes |= sign;
bytes <<= 8;
bytes |= exponent;
bytes <<= 23;
bytes |= fraction;
return *(float*)&bytes;
}
int main(void) {
/* All 1 exponent and non-0 fraction means NaN.
* There are of course many possible representations,
* and some have special semantics such as signalling vs not.
*/
assert(isnan(float_from_bytes(0, 0xFF, 1)));
assert(isnan(NAN));
printf("nan = %e\n", NAN);
/* All 1 exponent and 0 fraction means infinity. */
assert(INFINITY == float_from_bytes(0, 0xFF, 0));
assert(isinf(INFINITY));
printf("infinity = %e\n", INFINITY);
/* ANSI C defines FLT_MAX as the largest non-infinite number. */
assert(FLT_MAX == 0x1.FFFFFEp127f);
/* Not 0xFF because that is infinite. */
assert(FLT_MAX == float_from_bytes(0, 0xFE, 0x7FFFFF));
assert(!isinf(FLT_MAX));
assert(FLT_MAX < INFINITY);
printf("largest non infinite = %e\n", FLT_MAX);
/* ANSI C defines FLT_MIN as the smallest non-subnormal number. */
assert(FLT_MIN == 0x1.0p-126f);
assert(FLT_MIN == float_from_bytes(0, 1, 0));
assert(isnormal(FLT_MIN));
printf("smallest normal = %e\n", FLT_MIN);
/* The smallest non-zero subnormal number. */
float smallest_subnormal = float_from_bytes(0, 0, 1);
assert(smallest_subnormal == 0x0.000002p-126f);
assert(0.0f < smallest_subnormal);
assert(!isnormal(smallest_subnormal));
printf("smallest subnormal = %e\n", smallest_subnormal);
return EXIT_SUCCESS;
}
Compile and run with:
gcc -ggdb3 -O0 -std=c11 -Wall -Wextra -Wpedantic -Werror -o subnormal.out subnormal.c
./subnormal.out
Output:
nan = nan
infinity = inf
largest non infinite = 3.402823e+38
smallest normal = 1.175494e-38
smallest subnormal = 1.401298e-45
Oracles Java Tutorial for File Choosers: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
Note getSelectedFile()
returns the selected folder, despite the name.
getCurrentDirectory()
returns the directory of the selected folder.
import javax.swing.*;
public class Example
{
public static void main(String[] args)
{
JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showSaveDialog(null);
System.out.println(f.getCurrentDirectory());
System.out.println(f.getSelectedFile());
}
}
None of the above worked.
But this did the trick:
override fun onCreate() {
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
toolbar.logo = null
(removed icon from toolbar)
Just in case someone is still looking for the answer,
let the browser take care of that. Try this:
display: table
on the container element.display: table-cell
on the child elements.The browser will evenly divide it whether you have 3 or 10 columns.
EDIT
the container element should also have: table-layout: fixed
otherwise the browser will determine the width of each element (most of the time not that bad).
You can use list comprehension:
content = open("path/to/file.txt").readlines()
lookup = 'the dog barked'
lines = [line_num for line_num, line_content in enumerate(content) if lookup in line_content]
print(lines)
Follow this steps:
-Build
-Generate Signed Apk
-Create new
Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)
in map.jsx
or map.js
file, if you exporting as default like:
export default MapComponent;
then you can import it like
import MapComponent from './map'
but if you do not export it as default like this one here
export const MapComponent = () => { ...whatever }
you need to import in inside curly braces like
import { MapComponent } from './map'
like below:
import './css/app.css'
if you are using sass all you need to do is just use sass loader with webpack!
Tested in .NET 5
public static class LikeExtension {
private static string ColumnDataBase<TEntity, TKey>(IModel model, Expression<Func<TEntity, TKey>> predicate) where TEntity : class {
ITable table = model
.GetRelationalModel()
.Tables
.First(f => f
.EntityTypeMappings
.First()
.EntityType == model
.FindEntityType(predicate
.Parameters
.First()
.Type
));
string column = (predicate.Body as MemberExpression).Member.Name;
string columnDataBase = table.Columns.First(f => f.PropertyMappings.Count(f2 => f2.Property.Name == column) > 0).Name;
return columnDataBase;
}
public static IQueryable<TEntity> Like<TEntity, TKey>(this DbContext context, Expression<Func<TEntity, TKey>> predicate, string text) where TEntity : class {
string columnDataBase = ColumnDataBase(context.Model, predicate);
return context.Set<TEntity>().FromSqlRaw(context.Set<TEntity>().ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text);
}
public static async Task<IEnumerable<TEntity>> LikeAsync<TEntity, TKey>(this DbContext context, Expression<Func<TEntity, TKey>> predicate, string text, CancellationToken cancellationToken) where TEntity : class {
string columnDataBase = ColumnDataBase(context.Model, predicate);
return await context.Set<TEntity>().FromSqlRaw(context.Set<TEntity>().ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text).ToListAsync(cancellationToken);
}
public static async Task<IEnumerable<TEntity>> LikeAsync<TEntity, TKey>(this IQueryable<TEntity> query, Expression<Func<TEntity, TKey>> predicate, string text, CancellationToken cancellationToken) where TEntity : class {
DbSet<TEntity> entities = query as DbSet<TEntity>;
string columnDataBase = ColumnDataBase(entities.EntityType.Model, predicate);
return await entities.FromSqlRaw(query.ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text).ToListAsync(cancellationToken);
}
public static IQueryable<TEntity> Like<TEntity, TKey>(this IQueryable<TEntity> query, Expression<Func<TEntity, TKey>> predicate, string text) where TEntity : class {
DbSet<TEntity> entities = query as DbSet<TEntity>;
string columnDataBase = ColumnDataBase(entities.EntityType.Model, predicate);
return entities.FromSqlRaw(query.ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text);
}
}
public async Task<IEnumerable<TEntity>> LikeAsync<TKey>(Expression<Func<TEntity, TKey>> predicate, string text, CancellationToken cancellationToken) {
return await context.LikeAsync(predicate, text, cancellationToken);
}
public IQueryable<TEntity> Like<TKey>(Expression<Func<TEntity, TKey>> predicate, string text) {
return context.Like(predicate, text);
}
IQueryable<CountryEntity> result = countryRepository
.Like(k => k.Name, "%Bra[sz]il%") /*Use Sync*/
.Where(w => w.DateRegister < DateTime.Now) /*Example*/
.Take(10); /*Example*/
Or
IEnumerable<CountryEntity> result = await countryRepository
.LikeAsync(k => k.Name, "%Bra[sz]il%", cancellationToken); /*Use Async*/
Or
IQueryable<CountryEntity> result = context.Countries
.Like(k => k.Name, "%Bra[sz]il%")
.Where(w => w.Name != null); /*Example*/
Or
List<CountryEntity> result2 = await context.Countries
.Like(k => k.Name, "%Bra[sz]il%")
.Where(w => w.Name != null) /*Example*/
.ToListAsync(); /*Use Async*/
Or
IEnumerable<CountryEntity> result3 = await context.Countries
.Where(w => w.Name != null)
.LikeAsync(k => k.Name, "%Bra[sz]il%", cancellationToken); /*Use Async*/
Late to the party. I was looking into this myself and just found about this axes option called ColorOrder you can specify the colour order for the session or just for the figure and then just plot an array and let MATLAB automatically cycle through the colours specified.
see Changing the Default ColorOrder
example
set(0,'DefaultAxesColorOrder',jet(5))
A=rand(10,5);
plot(A);
Another great implementation is balupton's jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.
Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!
My problem was slightly different. I did everything right. But I was inheriting the wrong class for the activity hosting the fragment.
So to be clear, if you are overriding onCreateOptionsMenu(Menu menu, MenuInflater inflater)
in the fragment, make sure your activity class which hosts this fragment inherits android.support.v7.app.ActionBarActivity
(in case you would want to support below API level 11).
I was inheriting the android.support.v4.app.FragmentActivity
to support API level below 11.
A variation on Duncan's answer (I don't have sufficient reputation to comment), which uses calendar.monthrange to dramatically simplify the computation of the last day of the month:
import calendar
def monthdelta(date, delta):
m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
if not m: m = 12
d = min(date.day, calendar.monthrange(y, m)[1])
return date.replace(day=d,month=m, year=y)
Info on monthrange from Get Last Day of the Month in Python
Heres how to change all databases/tables/columns. Run these queries and they will output all of the subsequent queries necessary to convert your entire schema to utf8. Hope this helps!
-- Change DATABASE Default Collation
SELECT DISTINCT concat('ALTER DATABASE `', TABLE_SCHEMA, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change TABLE Collation / Char Set
SELECT concat('ALTER TABLE `', TABLE_SCHEMA, '`.`', table_name, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change COLUMN Collation / Char Set
SELECT concat('ALTER TABLE `', t1.TABLE_SCHEMA, '`.`', t1.table_name, '` MODIFY `', t1.column_name, '` ', t1.data_type , '(' , t1.CHARACTER_MAXIMUM_LENGTH , ')' , ' CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.columns t1
where t1.TABLE_SCHEMA like 'database_name' and t1.COLLATION_NAME = 'old_charset_name';
For Retrofit 2.0.0-beta1
or beta2
, the code goes as follows:
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.yourapp.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
nodeName
is the attribute you are looking for. For example:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
Note that nodeName
returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div>
element you could do it as follows:
elt.nodeName == "DIV"
While this would not give you the expected results:
elt.nodeName == "<div>"
Regexes can also limit the number of characters.
r = re.compile("^[a-z]{1,15}$")
gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.
Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.
In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.
This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.
OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory
Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx
The following code worked for me.
$('input[name="chkGender[]"]:checked').length;
Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:
version: '2'
services:
mysql:
container_name: mysql
image: mysql:latest
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
ports:
- "3306:3306"
networks:
vpcbr:
ipv4_address: 10.5.0.5
apigw-tomcat:
container_name: apigw-tomcat
build: tomcat/.
ports:
- "8080:8080"
- "8009:8009"
networks:
vpcbr:
ipv4_address: 10.5.0.6
depends_on:
- mysql
networks:
vpcbr:
driver: bridge
ipam:
config:
- subnet: 10.5.0.0/16
gateway: 10.5.0.1
Adding the following line of CSS works for Chrome, but not Internet Explorer or Firefox.
text-shadow: #fff 0px 1px 1px;
Interfaces do not contain any implementation.
My answer on this question might help you:
int finalHeight, finalWidth;
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
final TextView tv = (TextView)findViewById(R.id.size_label);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
iv.getViewTreeObserver().removeOnPreDrawListener(this);
finalHeight = iv.getMeasuredHeight();
finalWidth = iv.getMeasuredWidth();
tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
return true;
}
});
You can then add your image scaling work from within the onPreDraw() method.
With Git there is no “correct” workflow. Use whatever floats your boat. However, if you constantly get conflicts when merging branches maybe you should coordinate your efforts better with your fellow developer(s)? Sounds like the two of you keep editing the same files. Also, watch out for whitespace and subversion keywords (i.e., “$Id$” and others).
All I did was added the below lines in config.xml
<icon src="www/img/appIcon.png" />
And it worked totally fine
This is a message for me in the future:
Just use: (unsigned)!((int)0)
It creates the largest possible number in any machine by assigning all bits to 1s (ones) and then casts it to unsigned
Even better
#define INF (unsigned)!((int)0)
And then just use INF in your code
The OP didn't actually need to pivot without agregation but for those of you coming here to know how see:
The answer to that question involves a situation where pivot without aggregation is needed so an example of doing it is part of the solution.
"In python do you generally use PEP 8 -- Style Guide for Python Code as your coding standards/guidelines? Are there any other formalized standards that you prefer?"
As mentioned by you follow PEP 8 for the main text, and PEP 257 for docstring conventions
Along with Python Style Guides, I suggest that you refer the following:
It points to your top level output directory (which by default is target
):
EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:
If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.
project.build.sourceDirectory project.build.scriptSourceDirectory project.build.testSourceDirectory project.build.outputDirectory project.build.testOutputDirectory project.build.directory
sourceDirectory
,scriptSourceDirectory
, andtestSourceDirectory
provide access to the source directories for the project.outputDirectory
andtestOutputDirectory
provide access to the directories where Maven is going to put bytecode or other build output.directory
refers to the directory which contains all of these output directories.
I made a simple (stupid or not) bash script, that extracts the longs from the adb shell, converts them to timestamps and shows it in red.
echo "Please set a search filter"
read search
adb shell dumpsys alarm | grep $search | (while read i; do echo $i; _DT=$(echo $i | grep -Eo 'when\s+([0-9]{10})' | tr -d '[[:alpha:][:space:]]'); if [ $_DT ]; then echo -e "\e[31m$(date -d @$_DT)\e[0m"; fi; done;)
try it ;)
This returns max heap size in bytes:
Runtime.getRuntime().maxMemory()
I was using ActivityManager.getMemoryClass() but on CyanogenMod 7 (I didn't test it elsewhere) it returns wrong value if the user sets heap size manually.
I took Jezzipin's answer and made it so that if you are scrolled when you refresh the page, the correct size applies. Also removed some stuff that isn't necessarily needed.
function sizer() {
if($(document).scrollTop() > 0) {
$('#header_nav').stop().animate({
height:'40px'
},600);
} else {
$('#header_nav').stop().animate({
height:'100px'
},600);
}
}
$(window).scroll(function(){
sizer();
});
sizer();
The CSS you have applies color #c1c1c1 to all <a>
elements.
And it also applies color #c1c1c1 to the first <li>
element.
Perhaps the code you posted is missing something because I don't see any other colors being defined.
Try this code.
var startTime = "05:01:20";
var endTime = "09:00:00";
var regExp = /(\d{1,2})\:(\d{1,2})\:(\d{1,2})/;
if(parseInt(endTime .replace(regExp, "$1$2$3")) > parseInt(startTime .replace(regExp, "$1$2$3"))){
alert("End time is greater");
}
Try with this code. I hope it's useful for you.
function sleep(seconds)
{
var e = new Date().getTime() + (seconds * 1000);
while (new Date().getTime() <= e) {}
}
This snippet works in IE7 at least
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
You can use top_n
df %>% group_by(A, B) %>% top_n(n=1)
This will rank by the last column (value
) and return the top n=1
rows.
Currently, you can't change the this default without causing an error (See https://github.com/hadley/dplyr/issues/426)
Thank you all for your help.
This is what I have used in the end:
SELECT *,
CASE WHEN [url] NOT LIKE '%[^-A-Za-z0-9/.+$]%'
THEN 'Valid'
ELSE 'No valid'
END [Validate]
FROM
*table*
ORDER BY [Validate]
$('select').change(function() {
console.log($(this).val())
});?
.val()
will get the value.
You can use TreeMap
which will store values in sorted form.
Map <String, String> map = new TreeMap <String, String>();
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
mysqladmin -u$USER -p$PASSWORD create $DB_NAME
Replace above variables and you are good to go with this oneliner. $USER is the username, $PASSWORD is the password and $DB_NAME is the name of the database.
>>> from datetime import datetime
>>> dt = datetime.now().strftime("%Y-%m-%d %X")
>>> print(dt)
'2021-02-05 04:10:24'
Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb
func compare(a, b T) bool {
if &a == &b {
return true
}
if a.X != b.X || a.Y != b.Y {
return false
}
if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
return false
}
for i, v := range a.Z {
if b.Z[i] != v {
return false
}
}
for k, v := range a.M {
if b.M[k] != v {
return false
}
}
return true
}
The problem with VBA is that there are both dynamic and static arrays...
Dynamic Array Example
Dim myDynamicArray() as Variant
Static Array Example
Dim myStaticArray(10) as Variant
Dim myOtherStaticArray(0 To 10) as Variant
Using error handling to check if the array is empty works for a Dynamic Array, but a static array is by definition not empty, there are entries in the array, even if all those entries are empty.
So for clarity's sake, I named my function "IsZeroLengthArray".
Public Function IsZeroLengthArray(ByRef subject() As Variant) As Boolean
'Tell VBA to proceed if there is an error to the next line.
On Error Resume Next
Dim UpperBound As Integer
Dim ErrorNumber As Long
Dim ErrorDescription As String
Dim ErrorSource As String
'If the array is empty this will throw an error because a zero-length
'array has no UpperBound (or LowerBound).
'This only works for dynamic arrays. If this was a static array there
'would be both an upper and lower bound.
UpperBound = UBound(subject)
'Store the Error Number and then clear the Error object
'because we want VBA to treat unintended errors normally
ErrorNumber = Err.Number
ErrorDescription = Err.Description
ErrorSource = Err.Source
Err.Clear
On Error GoTo 0
'Check the Error Object to see if we have a "subscript out of range" error.
'If we do (the number is 9) then we can assume that the array is zero-length.
If ErrorNumber = 9 Then
IsZeroLengthArray = True
'If the Error number is something else then 9 we want to raise
'that error again...
ElseIf ErrorNumber <> 0 Then
Err.Raise ErrorNumber, ErrorSource, ErrorDescription
'If the Error number is 0 then we have no error and can assume that the
'array is not of zero-length
ElseIf ErrorNumber = 0 Then
IsZeroLengthArray = False
End If
End Function
I hope that this helps others as it helped me.
if you want to get the value attribute (buttonValue) then I'd use:
<script type="text/javascript">
$(document).ready(function() {
$('.my_button').click(function() {
alert($(this).attr('value'));
});
});
</script>
To add to Box9's answer:
Backbone.js is dependent on underscore.js, which itself implements John Resig's original microtemplates.
If you decide to use Backbone.js with Rails, be sure to check out the Jammit gem. It provides a very clean way to manage asset packaging for templates. http://documentcloud.github.com/jammit/#jst
By default Jammit also uses JResig's microtemplates, but it also allows you to replace the templating engine.
There is a library for this purpose: https://github.com/bestiejs/platform.js#readme
Then you can use it this way
// example 1
platform.os; // 'Windows Server 2008 R2 / 7 x64'
// example 2 on an iPad
platform.os; // 'iOS 5.0'
// you can also access on the browser and some other properties
platform.name; // 'Safari'
platform.version; // '5.1'
platform.product; // 'iPad'
platform.manufacturer; // 'Apple'
platform.layout; // 'WebKit'
// or use the description to put all together
platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)'
You can always wrap Double.parseDouble() in a try catch block.
try
{
Double.parseDouble(number);
}
catch(NumberFormatException e)
{
//not a double
}
Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.
You put your template in the wrong place. From the Flask docs:
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates
How about:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("input.xml"));
NodeList nodeList = document.getElementsByTagName("Item");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
}
}
}
WITH TEMP (DIA, SIGUIENTE_DIA ) AS
(SELECT
1,
CAST(@FECHAINI AS DATE)
FROM
DUAL
UNION ALL
SELECT
DIA,
DATEADD(DAY, DIA, SIGUIENTE_DIA)
FROM
TEMP
WHERE
DIA < DATEDIFF(DAY, @FECHAINI, @FECHAFIN)
AND DATEADD(DAY, 1, SIGUIENTE_DIA) <= CAST(@FECHAFIN AS DATE)
)
SELECT
SIGUIENTE_DIA AS CALENDARIO
FROM
TEMP
ORDER BY
SIGUIENTE_DIA
The detail is on the table DUAL but if your exchange this table for a dummy table this works.