Set the parent div as position:relative
and the inner element to position:absolute; bottom:0
This answer might be stupid, but I spent quite some time to figure it out.
What happened to me was I didn't set display: flex
to the container. And of course, justify-content
won't work without a container with that property.
Use a margin to space around an element.
.box {
margin: top right bottom left;
}
.box {
margin: 10px 5px 10px 5px;
}
This adds space outside of the element. So background colours, borders etc will not be included.
If you want to add spacing within an element use padding instead. It can be called in the same way as above.
Here is yet another answer. I was answering a similar question and saw link referenced to this question. I didnt see any answer similar to mine. So, I thought of writing it here.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
setupViews()
}
var constraints: [NSLayoutConstraint] = []
func setupViews() {
let container1 = createButtonContainer(withButtonTitle: "Button 1")
let container2 = createButtonContainer(withButtonTitle: "Button 2")
let container3 = createButtonContainer(withButtonTitle: "Button 3")
let container4 = createButtonContainer(withButtonTitle: "Button 4")
view.addSubview(container1)
view.addSubview(container2)
view.addSubview(container3)
view.addSubview(container4)
[
// left right alignment
container1.leftAnchor.constraintEqualToAnchor(view.leftAnchor, constant: 20),
container1.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: -20),
container2.leftAnchor.constraintEqualToAnchor(container1.leftAnchor),
container2.rightAnchor.constraintEqualToAnchor(container1.rightAnchor),
container3.leftAnchor.constraintEqualToAnchor(container1.leftAnchor),
container3.rightAnchor.constraintEqualToAnchor(container1.rightAnchor),
container4.leftAnchor.constraintEqualToAnchor(container1.leftAnchor),
container4.rightAnchor.constraintEqualToAnchor(container1.rightAnchor),
// place containers one after another vertically
container1.topAnchor.constraintEqualToAnchor(view.topAnchor),
container2.topAnchor.constraintEqualToAnchor(container1.bottomAnchor),
container3.topAnchor.constraintEqualToAnchor(container2.bottomAnchor),
container4.topAnchor.constraintEqualToAnchor(container3.bottomAnchor),
container4.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor),
// container height constraints
container2.heightAnchor.constraintEqualToAnchor(container1.heightAnchor),
container3.heightAnchor.constraintEqualToAnchor(container1.heightAnchor),
container4.heightAnchor.constraintEqualToAnchor(container1.heightAnchor)
]
.forEach { $0.active = true }
}
func createButtonContainer(withButtonTitle title: String) -> UIView {
let view = UIView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
let button = UIButton(type: .System)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(title, forState: .Normal)
view.addSubview(button)
[button.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor),
button.leftAnchor.constraintEqualToAnchor(view.leftAnchor),
button.rightAnchor.constraintEqualToAnchor(view.rightAnchor)].forEach { $0.active = true }
return view
}
}
And again, this can be done quite easily with iOS9 UIStackViews as well.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.greenColor()
setupViews()
}
var constraints: [NSLayoutConstraint] = []
func setupViews() {
let container1 = createButtonContainer(withButtonTitle: "Button 1")
let container2 = createButtonContainer(withButtonTitle: "Button 2")
let container3 = createButtonContainer(withButtonTitle: "Button 3")
let container4 = createButtonContainer(withButtonTitle: "Button 4")
let stackView = UIStackView(arrangedSubviews: [container1, container2, container3, container4])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .Vertical
stackView.distribution = .FillEqually
view.addSubview(stackView)
[stackView.topAnchor.constraintEqualToAnchor(view.topAnchor),
stackView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor),
stackView.leftAnchor.constraintEqualToAnchor(view.leftAnchor, constant: 20),
stackView.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: -20)].forEach { $0.active = true }
}
func createButtonContainer(withButtonTitle title: String) -> UIView {
let button = UIButton(type: .Custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.redColor()
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button.setTitle(title, forState: .Normal)
let buttonContainer = UIStackView(arrangedSubviews: [button])
buttonContainer.distribution = .EqualCentering
buttonContainer.alignment = .Center
buttonContainer.translatesAutoresizingMaskIntoConstraints = false
return buttonContainer
}
}
Notice that it is exact same approach as above. It adds four container views which are filled equally and a view is added to each stack view which is aligned in center. But, this version of UIStackView reduces some code and looks nice.
I feel your pain. I've tried every answer above, including the setIncludeFontPadding
to false, which did nothing for me.
My solution? layout_marginBottom="-3dp"
on the TextView
gives you a solution for the bottom,
BAM!
Although, -3dp on layout_marginTop
fails....ugh.
I've looked around and the
display: table-cell;
vertical-align: middle;
seems to be the most popular solution
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
Then call it like so:
>>> str2bool("yes")
True
>>> str2bool("no")
False
>>> str2bool("stuff")
False
>>> str2bool("1")
True
>>> str2bool("0")
False
Handling true and false explicitly:
You could also make your function explicitly check against a True list of words and a False list of words. Then if it is in neither list, you could throw an exception.
i have seen your running code .There is one line correction in your code.
Write:
$("#wrapper").rotate(angle);
instead of:
$("#image").rotate(angle);
and you will get your desired output,hope this is what you want.
value_counts()
is now a DataFrame method since pandas 1.1.0
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.value_counts.html
in C# I found they use \r\n in a string.
LocalDateTime.parse(
"2016-01-23 12:34".replace( " " , "T" )
)
.atZone( ZoneId.of( "Asia/Karachi" ) )
.plusMinutes( 10 )
Use the excellent java.time classes for date-time work. These classes supplant the troublesome old date-time classes such as java.util.Date
and java.util.Calendar
.
The java.time classes use standard ISO 8601 formats by default for parsing/generating strings of date-time values. To make your input string comply, replace the SPACE in the middle with a T
.
String input = "2016-01-23 12:34" ;
String inputModified = input.replace( " " , "T" );
LocalDateTime
Parse your input string as a LocalDateTime
as it lacks any info about time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( inputModified );
Add ten minutes.
LocalDateTime ldtLater = ldt.plusMinutes( 10 );
ldt.toString(): 2016-01-23T12:34
ldtLater.toString(): 2016-01-23T12:44
That LocalDateTime
has no time zone, so it does not represent a point on the timeline. Apply a time zone to translate to an actual moment. Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
, or Asia/Karachi
. Never use the 3-4 letter abbreviation such as EST
or IST
or PKT
as they are not true time zones, not standardized, and not even unique(!).
ZonedDateTime
If you know the intended time zone for this value, apply a ZoneId
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "Asia/Karachi" );
ZonedDateTime zdt = ldt.atZone( z );
zdt.toString(): 2016-01-23T12:44+05:00[Asia/Karachi]
Think about whether to add those ten minutes before or after adding a time zone. You may get a very different result because of anomalies such as Daylight Saving Time (DST) that shift the wall-clock time.
Whether you should add the 10 minutes before or after adding the zone depends on the meaning of your business scenario and rules.
Tip: When you intend a specific moment on the timeline, always keep the time zone information. Do not lose that info, as done with your input data. Is the value 12:34
meant to be noon in Pakistan or noon in France or noon in Québec? If you meant noon in Pakistan, say so by including at least the offset-from-UTC (+05:00
), and better still, the name of the time zone (Asia/Karachi
).
Instant
If you want the same moment as seen through the lens of UTC, extract an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = zdt.toInstant();
Avoid the troublesome old date-time classes whenever possible. But if you must, you can convert. Call new methods added to the old classes.
java.util.Date utilDate = java.util.Date.from( instant );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
It is not a good idea to return iterators. Iterators become invalid when modifications to the vector (inversion\deletion ) happens. Also, the iterator is a local object created on stack and hence returning the address of the same is not at all safe. I'd suggest you to work with myObject rather than vector iterators.
EDIT: If the object is lightweight then its better you return the object itself. Otheriwise return pointers to myObject stored in the vector.
I had a similar issue not long time ago and this was how I solved it
.rotated-half-circle {_x000D_
/* Create the circle */_x000D_
width: 40px;_x000D_
height: 40px;_x000D_
border: 10px solid black;_x000D_
border-radius: 50%;_x000D_
/* Halve the circle */_x000D_
border-bottom-color: transparent;_x000D_
border-left-color: transparent;_x000D_
/* Rotate the circle */_x000D_
transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="rotated-half-circle"></div>
_x000D_
Here are my favorites:
Dependency:
<dependency>
<groupId>org.apache.any23</groupId>
<artifactId>apache-any23-encoding</artifactId>
<version>1.1</version>
</dependency>
Sample:
public static Charset guessCharset(InputStream is) throws IOException {
return Charset.forName(new TikaEncodingDetector().guessEncoding(is));
}
Dependency:
<dependency>
<groupId>org.codehaus.guessencoding</groupId>
<artifactId>guessencoding</artifactId>
<version>1.4</version>
<type>jar</type>
</dependency>
Sample:
public static Charset guessCharset2(File file) throws IOException {
return CharsetToolkit.guessEncoding(file, 4096, StandardCharsets.UTF_8);
}
Here i have found some useful link, with live working example.
I have tried its working fine.
How to prevent Right Click option using jquery
$(document).bind("contextmenu", function (e) {
e.preventDefault();
alert("Right Click is Disabled");
});
import sys
from Tkinter import *
def quit():
sys.exit()
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
Should do what you are asking.
Not sure I completely understand the question but:
$(":button.brown").click(function() {
$(":button.brown.selected").removeClass("selected");
$(this).addClass("selected");
});
seems to be along the lines of what you want.
I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:
$("...").css("background", "brown");
But when you want to reverse that change, what do you set it to?
Try the Date
function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$
. Now()
also includes the current time (which you might not need). It all depends on what you need. :)
Try using while
loop, Array.prototype.push()
var myArray = [], X = 3;
while (myArray.length < X) {
myArray.push("")
}
Alternatively, using Array.prototype.fill()
var myArray = Array(3).fill("");
I agree with the accepted answer above but it is only good for known string values. For dynamic string values here is my suggestion.
// A list may come from an API JSON like
{
"names": [
"Person 1",
"Person 2",
"Person 3",
...
"Person N"
]
}
var listOfNames = mutableListOf<String>()
val stringOfNames = listOfNames.joinToString(", ")
// ", " <- a separator for the strings, could be any string that you want
// Posible result
// Person 1, Person 2, Person 3, ..., Person N
This is useful for concatenating list of strings with separator.
The most famous library to create some GUI in C language is certainly GTK.
With this library you can easily create some buttons (for your example). When a user clicks on the button, a signal is emitted and you can write a handler to do some actions.
Hmm... it works for me and with far less than 999MB of stack:
> java -Xss4m Test
0
(Windows JDK 7, build 17.0-b05 client VM, and Linux JDK 6 - same version information as you posted)
This can be achieved in a very simple way 1. Write this in the view.
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Width="50" Height="30">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsHide}" Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
The following is the Boolean property which holds the true/ false value. The following is the code snippet. In my example this property is in UserNote class.
public bool _isHide = false;
public bool IsHide
{
get { return _isHide; }
set
{
_isHide = value;
OnPropertyChanged("IsHide");
}
}
This is the way the IsHide property gets the value.
userNote.IsHide = userNote.IsNoteDeleted;
The User Country API has exactly what you need. Here is a sample code using file_get_contents() as you originally do:
$result = json_decode(file_get_contents('http://usercountry.com/v1.0/json/'.$cip), true);
$result['country']['name']; // this contains what you need
I made this very simple function that works wonders:
function safeOrZero(route) {
try {
Function(`return (${route})`)();
} catch (error) {
return 0;
}
return Function(`return (${route})`)();
}
The route is whatever chain of values that can blow up. I use it for jQuery/cheerio and objects and such.
Examples 1: a simple object such as this const testObj = {items: [{ val: 'haya' }, { val: null }, { val: 'hum!' }];};
.
But it could be a very large object that we haven't even made. So I pass it through:
let value1 = testobj.items[2].val; // "hum!"
let value2 = testobj.items[3].val; // Uncaught TypeError: Cannot read property 'val' of undefined
let svalue1 = safeOrZero(`testobj.items[2].val`) // "hum!"
let svalue2 = safeOrZero(`testobj.items[3].val`) // 0
Of course if you prefer you can use null
or 'No value'
... Whatever suit your needs.
Usually a DOM query or a jQuery selector may throw an error if it's not found. But using something like:
const bookLink = safeOrZero($('span.guidebook > a')[0].href);
if(bookLink){
[...]
}
I use this to check for first launch:
- (NSInteger) checkForFirstLaunch
{
NSInteger result = 0; //no first launch
// Get current version ("Bundle Version") from the default Info.plist file
NSString *currentVersion = (NSString*)[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
NSArray *prevStartupVersions = [[NSUserDefaults standardUserDefaults] arrayForKey:@"prevStartupVersions"];
if (prevStartupVersions == nil)
{
// Starting up for first time with NO pre-existing installs (e.g., fresh
// install of some version)
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:currentVersion] forKey:@"prevStartupVersions"];
result = 1; //first launch of the app
} else {
if (![prevStartupVersions containsObject:currentVersion])
{
// Starting up for first time with this version of the app. This
// means a different version of the app was alread installed once
// and started.
NSMutableArray *updatedPrevStartVersions = [NSMutableArray arrayWithArray:prevStartupVersions];
[updatedPrevStartVersions addObject:currentVersion];
[[NSUserDefaults standardUserDefaults] setObject:updatedPrevStartVersions forKey:@"prevStartupVersions"];
result = 2; //first launch of this version of the app
}
}
// Save changes to disk
[[NSUserDefaults standardUserDefaults] synchronize];
return result;
}
(if the user deletes the app and re-installs it, it counts like a first launch)
In the AppDelegate I check for first launch and create a navigation-controller with the login screens (login and register), which I put on top of the current main window:
[self.window makeKeyAndVisible];
if (firstLaunch == 1) {
UINavigationController *_login = [[UINavigationController alloc] initWithRootViewController:loginController];
[self.window.rootViewController presentViewController:_login animated:NO completion:nil];
}
As this is on top of the regular view controller it's independent from the rest of your app and you can just dismiss the view controller, if you don't need it anymore. And you can also present the view this way, if the user presses a button manually.
BTW: I save the login-data from my users like this:
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"com.youridentifier" accessGroup:nil];
[keychainItem setObject:password forKey:(__bridge id)(kSecValueData)];
[keychainItem setObject:email forKey:(__bridge id)(kSecAttrAccount)];
For the logout: I switched away from CoreData (too slow) and use NSArrays and NSDictionaries to manage my data now. Logout just means to empty those arrays and dictionaries. Plus I make sure to set my data in viewWillAppear.
That's it.
Here is a different approach that trades space for faster search time. This may be fastest so.
import math
def primes(n):
if n < 2:
return []
numbers = [0]*(n+1)
primes = [2]
# Mark all odd numbers as maybe prime, leave evens marked composite.
for i in xrange(3, n+1, 2):
numbers[i] = 1
sqn = int(math.sqrt(n))
# Starting with 3, look at each odd number.
for i in xrange(3, len(numbers), 2):
# Skip if composite.
if numbers[i] == 0:
continue
# Number is prime. Would have been marked as composite if there were
# any smaller prime factors already examined.
primes.append(i)
if i > sqn:
# All remaining odd numbers not marked composite must be prime.
primes.extend([i for i in xrange(i+2, len(numbers), 2)
if numbers[i]])
break
# Mark all multiples of the prime as composite. Check odd multiples.
for r in xrange(i*i, len(numbers), i*2):
numbers[r] = 0
return primes
n = 1000000
p = primes(n)
print "Found", len(p), "primes <=", n
In order to address @kcpr's comment on the (currently accepted) answer by @Honza Osobne
Unfortunately it doesn't work then the argument got it's default value defined.
one can first check if the argument was provided by comparing it with the Namespace
object and providing the default=argparse.SUPPRESS
option (see @hpaulj's and @Erasmus Cedernaes answers and this python3 doc) and if it hasn't been provided, then set it to a default value.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--infile', default=argparse.SUPPRESS)
args = parser.parse_args()
if 'infile' in args:
# the argument is in the namespace, it's been provided by the user
# set it to what has been provided
theinfile = args.infile
print('argument \'--infile\' was given, set to {}'.format(theinfile))
else:
# the argument isn't in the namespace
# set it to a default value
theinfile = 'your_default.txt'
print('argument \'--infile\' was not given, set to default {}'.format(theinfile))
Usage
$ python3 testargparse_so.py
argument '--infile' was not given, set to default your_default.txt
$ python3 testargparse_so.py --infile user_file.txt
argument '--infile' was given, set to user_file.txt
You can control the behavior in a headerfile or C-file:
#pragma warning(error:4003) //not enough actual parameters for macro
yet tested with Visual studio 2015. I have a common headerfile 'compl_adaption.h' for such things, included in all files, to set this behavior for all my projects compiled on visual studio.
Try this:
select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;
PHP will do it for you within limits
<?php
$str = "3.148";
$num = $str;
printf("%f\n", $num);
?>
I have an application that I am developing that is laid out similar with Tabs in the Action Bar that launches fragments, some of these Fragments have multiple embedded Fragments within them.
I was getting the same error when I tried to run the application. It seems like if you instantiate the Fragments within the xml layout after a tab was unselected and then reselected I would get the inflator error.
I solved this replacing all the fragments in xml with Linearlayouts and then useing a Fragment manager/ fragment transaction to instantiate the fragments everything seems to working correctly at least on a test level right now.
I hope this helps you out.
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.
Simplest of all Solutions:
dict = {'first': 1,
'second': 2,
'third': 3}
Now,
dict['last'] || 'Excluded'
will return 'Excluded', which is the default value.
Leaving database modeling issues aside. I think you can try
SELECT * FROM STUDENTS WHERE ISNUMERIC(STUDENTID) = 0
But ISNUMERIC
returns 1 for any value that seems numeric including things like -1.0e5
If you want to exclude digit-only studentids, try something like
SELECT * FROM STUDENTS WHERE STUDENTID LIKE '%[^0-9]%'
Code counts the unique/distinct combination of Tag & Entry ID when [Entry Id]>0
select count(distinct(concat(tag,entryId)))
from customers
where id>0
In the output it will display the count of unique values Hope this helps
I had the same error with Symfony on wamp and PHP 7.0.0.
None of the JS and CSS dependencies was loaded on the "dev" environnement, with error Failed to load resource: net::ERR_CONNECTION_RESET
It's effectively a certificate problem in php.ini
.
You need to set the property curl.cainfo
to a valid certificate in the line :
curl.cainfo = C:\your\wamp\path\bin\cacert\cacert.pem
First, you cannot have multiple elements with the same id. I know you said you can't control how the form is created, but...try to somehow remove all the ids from the radios, or make them unique.
To get the value of the selected radio button, select it by name with the :checked
filter.
var selectedVal = "";
var selected = $("input[type='radio'][name='s_2_1_6_0']:checked");
if (selected.length > 0) {
selectedVal = selected.val();
}
EDIT
So you have no control over the names. In that case I'd say put these radio buttons all inside a div, named, say, radioDiv
, then slightly modify your selector:
var selectedVal = "";
var selected = $("#radioDiv input[type='radio']:checked");
if (selected.length > 0) {
selectedVal = selected.val();
}
Swift 2.0
extension Dictionary {
mutating func unionInPlace(dictionary: Dictionary) {
dictionary.forEach { self.updateValue($1, forKey: $0) }
}
func union(var dictionary: Dictionary) -> Dictionary {
dictionary.unionInPlace(self)
return dictionary
}
}
sudo nano /etc/apache2/httpd.conf
ServerName
in nano editor <Ctrl + W>
ServerName localhost
sudo /usr/sbin/apachectl restart
Listing Keys Using the AWS SDK for Java
http://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingJava.html
import java.io.IOException;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
public class ListKeys {
private static String bucketName = "***bucket name***";
public static void main(String[] args) throws IOException {
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
try {
System.out.println("Listing objects");
final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName);
ListObjectsV2Result result;
do {
result = s3client.listObjectsV2(req);
for (S3ObjectSummary objectSummary :
result.getObjectSummaries()) {
System.out.println(" - " + objectSummary.getKey() + " " +
"(size = " + objectSummary.getSize() +
")");
}
System.out.println("Next Continuation Token : " + result.getNextContinuationToken());
req.setContinuationToken(result.getNextContinuationToken());
} while(result.isTruncated() == true );
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, " +
"which means your request made it " +
"to Amazon S3, but was rejected with an error response " +
"for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, " +
"which means the client encountered " +
"an internal error while trying to communicate" +
" with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
}
This is a nice 5-part tutorial that covers a lot of useful material: http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch/
(Anyone else noticing a trend forming here??? hehehee )
And this will definitely be of use to all developers:
http://blip.tv/mobiletuts/weinre-demonstration-5922038
=)
Todd
Edit I just finished a nice four part tutorial building an app to write, save, edit, & delete notes using jQuery mobile (only), it was very practical & useful, but it was also only for jQM. So, I looked to see what else they had on DZone.
I'm now going to start sorting through these search results. At a glance, it looks really promising. I remembered this post; so I thought I'd steer people to it. ?
For Python 2.7:
As it says here,
You don't need to download
Tkinter
- it's an integral part of all Python distributions (except binary distributions for platforms that don't support Tcl/Tk).
In my case, on Windows, what helped was reinstalling the Python distribution. A long time ago, I had unchecked the "Tcl/Tk" installation feature. After reinstalling, all works fine and I can import _tkinter
and import Tkinter
.
tl;dr: It's nowadays implemented into Laravel, see "edit 3" below.
Sadly, as of today there are some caveats with the ->orderBy(DB::raw('RAND()'))
proposed solution:
RANDOM()
Even worse, this solution isn't applicable anymore since this change:
$direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';
edit: Now you can use the orderByRaw() method: ->orderByRaw('RAND()')
. However this is still not DB-agnostic.
FWIW, CodeIgniter implements a special RANDOM
sorting direction, which is replaced with the correct grammar when building query. Also it seems to be fairly easy to implement. Looks like we have a candidate for improving Laravel :)
update: here is the issue about this on GitHub, and my pending pull request.
edit 2: Let's cut the chase. Since Laravel 5.1.18 you can add macros to the query builder:
use Illuminate\Database\Query\Builder;
Builder::macro('orderByRandom', function () {
$randomFunctions = [
'mysql' => 'RAND()',
'pgsql' => 'RANDOM()',
'sqlite' => 'RANDOM()',
'sqlsrv' => 'NEWID()',
];
$driver = $this->getConnection()->getDriverName();
return $this->orderByRaw($randomFunctions[$driver]);
});
Usage:
User::where('active', 1)->orderByRandom()->limit(10)->get();
DB::table('users')->where('active', 1)->orderByRandom()->limit(10)->get();
edit 3: Finally! Since Laravel 5.2.33 (changelog, PR #13642) you can use the native method inRandomOrder()
:
User::where('active', 1)->inRandomOrder()->limit(10)->get();
DB::table('users')->where('active', 1)->inRandomOrder()->limit(10)->get();
I went through all answers. None worked for me. All I had to do was:
self.myTableView.rowHeight = UITableViewAutomaticDimension
self.myTableView.estimatedRowHeight = 44.0
Additionally the issue wasn't happening at the top of tableView. It was happening at the top of each section of the tableView.
FWIW this issue was only happening for iOS9. Our app worked fine for iOS10 and iOS 11.
I highly recommend you to see this awesome question and its top answers:
Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
I came across this problem because my cols exceeded the row grid length (> 12)
A solution using 100% Bootstrap 4:
Since the rows in Bootstrap are already display: flex
You just need to add flex-fill
to the Col, and h-100
to the container and any children.
Pen here: https://codepen.io/joshkopecek/pen/Exjdgjo
<div class="container-fluid h-100">
<div class="row justify-content-center h-100">
<div class="col-4 hidden-md-down flex-fill" id="yellow">
XXXX
</div>
<div id="blue" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
Form Goes Here
</div>
<div id="green" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
Another form
</div>
</div>
</div>
From Dockerfile reference:
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.The
ENV
instruction sets the environment variable<key>
to the value<value>
.
The environment variables set usingENV
will persist when a container is run from the resulting image.
So if you need build-time customization, ARG
is your best choice.
If you need run-time customization (to run the same image with different settings), ENV
is well-suited.
If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable
Given the number of combinations involved, using ENV
to set those features at runtime is best here.
But you can combine both by:
ARG
ARG
as an ENV
That is, with a Dockerfile including:
ARG var
ENV var=${var}
You can then either build an image with a specific var
value at build-time (docker build --build-arg var=xxx
), or run a container with a specific runtime value (docker run -e var=yyy
)
You can create a Global Class
like this:
public class GlobalClass extends Application{
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public String getEmail() {
return email;
}
public void setEmail(String aEmail) {
email = aEmail;
}
}
Then define it in the manifest:
<application
android:name="com.example.globalvariable.GlobalClass" ....
Now you can set values to global variable like this:
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
globalVariable.setName("Android Example context variable");
You can get those values like this:
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
final String name = globalVariable.getName();
Please find complete example from this blog Global Variables
To answer your question:
If we can have inner private class then why can't we have outer private class...?
You can, the distinction is that the inner class is at the "class" access level, whereas the "outer" class is at the "package" access level. From the Oracle Tutorials:
If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)
Thus, package-private (declaring no modifier) is the effect you would expect from declaring an "outer" class private, the syntax is just different.
This is an old question, but here's my two cents. PeterSO's answer is slightly more concise, but slightly less efficient. You already know how big it's going to be so you don't even need to use append:
keys := make([]int, len(mymap))
i := 0
for k := range mymap {
keys[i] = k
i++
}
In most situations it probably won't make much of a difference, but it's not much more work, and in my tests (using a map with 1,000,000 random int64
keys and then generating the array of keys ten times with each method), it was about 20% faster to assign members of the array directly than to use append.
Although setting the capacity eliminates reallocations, append still has to do extra work to check if you've reached capacity on each append.
Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):
var ListenerTracker=new function(){
var is_active=false;
// listener tracking datas
var _elements_ =[];
var _listeners_ =[];
this.init=function(){
if(!is_active){//avoid duplicate call
intercep_events_listeners();
}
is_active=true;
};
// register individual element an returns its corresponding listeners
var register_element=function(element){
if(_elements_.indexOf(element)==-1){
// NB : split by useCapture to make listener easier to find when removing
var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
_elements_.push(element);
_listeners_.push(elt_listeners);
}
return _listeners_[_elements_.indexOf(element)];
};
var intercep_events_listeners = function(){
// backup overrided methods
var _super_={
"addEventListener" : HTMLElement.prototype.addEventListener,
"removeEventListener" : HTMLElement.prototype.removeEventListener
};
Element.prototype["addEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["addEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])listeners[useCapture][type]=[];
listeners[useCapture][type].push(listener);
};
Element.prototype["removeEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["removeEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])return;
var lid = listeners[useCapture][type].indexOf(listener);
if(lid>-1)listeners[useCapture][type].splice(lid,1);
};
Element.prototype["getEventListeners"]=function(type){
var listeners=register_element(this);
// convert to listener datas list
var result=[];
for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
if(typeof(type)=="string"){// filtered by type
if(list[type]){
for(var id in list[type]){
result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
}
}
}else{// all
for(var _type in list){
for(var id in list[_type]){
result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
}
}
}
}
return result;
};
};
}();
ListenerTracker.init();
I've spent the last few months messing around with Gemfiles and Gemfile.locks a lot whilst building an automated dependency update tool1. The below is far from definitive, but it's a good starting point for understanding the Gemfile.lock format. You might also want to check out the source code for Bundler's lockfile parser.
You'll find the following headings in a lockfile generated by Bundler 1.x:
GEM (optional but very common)
These are dependencies sourced from a Rubygems server. That may be the main Rubygems index, at Rubygems.org, or it may be a custom index, such as those available from Gemfury and others. Within this section you'll see:
remote:
one or more lines specifying the location of the Rubygems index(es)specs:
a list of dependencies, with their version number, and the constraints on any subdependenciesGIT (optional)
These are dependencies sourced from a given git remote. You'll see a different one of these sections for each git remote, and within each section you'll see:
remote:
the git remote. E.g., [email protected]:rails/rails
revision:
the commit reference the Gemfile.lock is locked totag:
(optional) the tag specified in the Gemfilespecs:
the git dependency found at this remote, with its version number, and the constraints on any subdependenciesPATH (optional)
These are dependencies sourced from a given path
, provided in the Gemfile. You'll see a different one of these sections for each path dependency, and within each section you'll see:
remote:
the path. E.g., plugins/vendored-dependency
specs:
the git dependency found at this remote, with its version number, and the constraints on any subdependenciesPLATFORMS
The Ruby platform the Gemfile.lock was generated against. If any dependencies in the Gemfile specify a platform then they will only be included in the Gemfile.lock when the lockfile is generated on that platform (e.g., through an install).
DEPENDENCIES
A list of the dependencies which are specified in the Gemfile
, along with the version constraint specified there.
Dependencies specified with a source other than the main Rubygems index (e.g., git dependencies, path-based, dependencies) have a !
which means they are "pinned" to that source2 (although one must sometimes look in the Gemfile to determine in).
RUBY VERSION (optional)
The Ruby version specified in the Gemfile, when this Gemfile.lock was created. If a Ruby version is specified in a .ruby_version
file instead this section will not be present (as Bundler will consider the Gemfile / Gemfile.lock agnostic to the installer's Ruby version).
BUNDLED WITH (Bundler >= v1.10.x)
The version of Bundler used to create the Gemfile.lock. Used to remind installers to update their version of Bundler, if it is older than the version that created the file.
PLUGIN SOURCE (optional and very rare)
In theory, a Gemfile can specify Bundler plugins, as well as gems3, which would then be listed here. In practice, I'm not aware of any available plugins, as of July 2017. This part of Bundler is still under active development!
If your SQL Server table has a column of type INT IDENTITY
(or BIGINT IDENTITY
), then you can get the latest inserted value using:
INSERT INTO dbo.YourTable(columns....)
VALUES(..........)
SELECT SCOPE_IDENTITY()
This works as long as you haven't inserted another row - it just returns the last IDENTITY
value handed out in this scope here.
There are at least two more options - @@IDENTITY
and IDENT_CURRENT
- read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.
See the example on the filter page. Use an object, and set the color in the color property:
Search by color: <input type="text" ng-model="search.color">
<div ng-repeat="product in products | filter:search">
WSDL
(Web Service Description Language
) from a Web Service URL.Is possible from SOAP Web Services:
http://www.w3schools.com/xml/tempconvert.asmx
to get the WSDL we have only to add ?WSDL
, for example:
This is a solution suggested by the MySQl manual:
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:
Create a table to hold the sequence counter and initialize it:
mysql> CREATE TABLE sequence (id INT NOT NULL); mysql> INSERT INTO sequence VALUES (0);
Use the table to generate sequence numbers like this:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1); mysql> SELECT LAST_INSERT_ID();
The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 23.8.7.37, “mysql_insert_id()”.
You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.
If it were about committed changes, you should have a look at git-rebase, but as pointed out in comment by VonC, as you're talking about local changes, git-stash would certainly be the good way to do this.
I'm not certain, based on your question if you want numbered rows that will remember their numbers even if the underlying data changes (and gives a different ordering), but if you just want numbered rows - that reset on a change in customer ID, then try using the Partition by clause of row_number()
row_number() over(partition by CustomerID order by CustomerID)
jQuery's .show() and .hide() functions are probably your best bet.
The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.
Example
This one works!
SELECT t.device,
SUM(case when transits.direction = 1 then 1 else 0 end) ,
SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t
where t.device in ('A','B') group by t.device
This one not (omitted t.device from the select)
SELECT
SUM(case when transits.direction = 1 then 1 else 0 end) ,
SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t
where t.device in ('A','B') group by t.device
This will produce your error complaining that I'm grouping for something that is not included in the select
Please, provide all the query to get more support.
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. So there is no need to pause timer and you will get best possible accuracy in this way.
Support for single character marker labels was added to Google Maps in version 3.21 (Aug 2015). See the new marker label API.
You can now create your label marker like this:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.latitude, result.longitude),
icon: markerIcon,
label: {
text: 'A'
}
});
If you would like to see the 1 character restriction removed, please vote for this issue.
Update October 2016:
This issue was fixed and as of version 3.26.10, Google Maps natively supports multiple character labels in combination with custom icons using MarkerLabels.
not as pythonic as the other answers, but mathematics:
return len(c) == 0
As some comments wondered about the impact len(set)
could have on complexity. It is O(1) as shown in the source code given it relies on a variable that tracks the usage of the set.
static Py_ssize_t
set_len(PyObject *so)
{
return ((PySetObject *)so)->used;
}
you can specify the max length for the multiline textbox in pageLoad Javascript Event
function pageLoad(){
$("[id$='txtInput']").attr("maxlength","10");
}
I have set the max length property of txtInput multiline textbox to 10 characters in pageLoad() Javascript function
I can't imagine everyone uses all 20 different keypresses to navigate text, 10 or so keys to start adding text, and 18 ways to visually select an inner block. Or do you!?
I do.
In theory, once I have that and start becoming as proficient in VIM as I am in Textmate, then I can start learning the thousands of other VIM commands that will make me more efficient.
That's the right way to do it. Start with basic commands and then pick up ones that improve your productivity. I like following this blog for tips on how to improve my productivity with vim.
Just had similar question and decided to try out some of the suggestions in this thread.
I've benchmarked best and worst case scenarios of 3 types of lookup:
here's the function code:
func belongsToMap(lookup string) bool {
list := map[string]bool{
"900898296857": true,
"900898302052": true,
"900898296492": true,
"900898296850": true,
"900898296703": true,
"900898296633": true,
"900898296613": true,
"900898296615": true,
"900898296620": true,
"900898296636": true,
}
if _, ok := list[lookup]; ok {
return true
} else {
return false
}
}
func belongsToList(lookup string) bool {
list := []string{
"900898296857",
"900898302052",
"900898296492",
"900898296850",
"900898296703",
"900898296633",
"900898296613",
"900898296615",
"900898296620",
"900898296636",
}
for _, val := range list {
if val == lookup {
return true
}
}
return false
}
func belongsToSwitch(lookup string) bool {
switch lookup {
case
"900898296857",
"900898302052",
"900898296492",
"900898296850",
"900898296703",
"900898296633",
"900898296613",
"900898296615",
"900898296620",
"900898296636":
return true
}
return false
}
best case scenarios pick the first item in lists, worst case ones use nonexistant value.
here are the results:
BenchmarkBelongsToMapWorstCase-4 2000000 787 ns/op
BenchmarkBelongsToSwitchWorstCase-4 2000000000 0.35 ns/op
BenchmarkBelongsToListWorstCase-4 100000000 14.7 ns/op
BenchmarkBelongsToMapBestCase-4 2000000 683 ns/op
BenchmarkBelongsToSwitchBestCase-4 100000000 10.6 ns/op
BenchmarkBelongsToListBestCase-4 100000000 10.4 ns/op
Switch wins all the way, worst case is surpassingly quicker than best case. Maps are the worst and list is closer to switch.
So the moral is: If you have a static, reasonably small list, switch statement is the way to go.
From the man page:
Sending mail
To send a message to one or more people, mailx can be invoked with arguments which are the names of people to whom the mail will be sent. The user is then expected to type in his message, followed by an ‘control-D’ at the beginning of a line.
In other words, mailx reads the content to send from standard input and can be redirected to like normal. E.g.:
ls -l $HOME | mailx -s "The content of my home directory" [email protected]
I got the Similar issue while importing the project.
The issue is you select "Use an execution environment JRE" and which is lower then the libraries used in the projects being imported.
There are two ways to resolve this issue:
1.While first time importing the project:
in JRE tab select "USE project specific JRE" instead of "Use an execution environment JRE".
2.Delete the Project from your work space and import again. This time:
select "Check out as a project in the workspace" instead of "Check out as a project configured using the new Project Wizard"
Static methods should be called on the Class, Instance methods should be called on the Instances of the Class. But what does that mean in reality? Here is a useful example:
A car class might have an instance method called Accelerate(). You can only Accelerate a car, if the car actually exists (has been constructed) and therefore this would be an instance method.
A car class might also have a count method called GetCarCount(). This would return the total number of cars created (or constructed). If no cars have been constructed, this method would return 0, but it should still be able to be called, and therefore it would have to be a static method.
I know this question is pretty old but just want to share my findings.
My laptop is able to handle program which spawns 25,000
threads and all those threads write some data in MySql database at regular interval of 2 seconds.
I ran this program with 10,000 threads
for 30 minutes continuously
then also my system was stable and I was able to do other normal operations like browsing, opening, closing other programs, etc.
With 25,000 threads
system slows down
but it remains responsive.
With 50,000 threads
system stopped responding
instantly and I had to restart my system manually.
My system details are as follows :
Processor : Intel core 2 duo 2.13 GHz
RAM : 4GB
OS : Windows 7 Home Premium
JDK Version : 1.6
Before running I set jvm argument -Xmx2048m
.
Hope it helps.
the accepted solution by Patrick Evans doesn't take scrolling into account. i've slightly changed his jsfiddle to demonstrate this:
css: add some random height to make sure we got some space to scroll
body{height:3000px;}
js: set some scroll position
jQuery(window).scrollTop(100);
as a result the two reported values differ now: http://jsfiddle.net/sNLMe/66/
UPDATE Feb. 14 2015
there is a pull request for jqLite waiting, including its own offset method (taking care of current scroll position). have a look at the source in case you want to implement it yourself: https://github.com/angular/angular.js/pull/3799/files
resultList = results.Where(x=>x.Id != 2).ToList();
There's a little Linq helper I like that's easy to implement and can make queries with "where not" conditions a little easier to read:
public static IEnumerable<T> ExceptWhere<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
return source.Where(x=>!predicate(x));
}
//usage in above situation
resultList = results.ExceptWhere(x=>x.Id == 2).ToList();
I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .
While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output
I too was looking for a good way to do this, I found the best way was to set a transition on the "transform" property and then change the transform and then remove the transition.
I put it all together in a jQuery plugin
https://gist.github.com/dustinpoissant/8a4837c476e3939a5b3d1a2585e8d1b0
You would use the code like this:
$("#myElement").animateTransform("rotate(180deg)", 750, function(){
console.log("animation completed after 750ms");
});
First of all you should create property with employee details in the Employee
class:
public class Employee
{
public Employee()
{
EmployeeDetails = new EmployeeDetails();
EmployeeDetails.EmpID = 123;
EmployeeDetails.EmpName = "ABC";
}
public EmployeeDetails EmployeeDetails { get; set; }
}
If you don't do that, you will create instance of object in Employee
constructor and you lose reference to it.
In the XAML you should create instance of Employee
class, and after that you can assign it to DataContext
.
Your XAML should look like this:
<Window x:Class="SampleApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:SampleApplication"
>
<Window.Resources>
<local:Employee x:Key="Employee" />
</Window.Resources>
<Grid DataContext="{StaticResource Employee}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
<Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
<TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
<TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
</Grid>
</Window>
Now, after you created property with employee details you should binding by using this property:
Text="{Binding EmployeeDetails.EmpID}"
You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:
$ /path/to/the/script.py > output.txt
This will overwrite the file. You can use >>
to append to it.
If you want errors to be logged in the file as well, use &>>
or &>
.
This worked for me on Debian stretch
sudo apt-get update
sudo apt install php-mbstring
service apache2 restart
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
In native LINQ you may use combination of Contains/StartsWith/EndsWith
or RegExp.
In LINQ2SQL use method SqlMethods.Like()
from i in db.myTable
where SqlMethods.Like(i.field, "tra%ata")
select i
add Assembly: System.Data.Linq (in System.Data.Linq.dll) to use this feature.
#include <stdint.h>
uintptr_t
standard type defined in the included standard header file.The solution from @ford04 didn't worked to me and specially if you need to use the isMounted in multiple places (multiple useEffect for instance), it's recommended to useRef, as bellow:
"dependencies":
{
"react": "17.0.1",
}
"devDependencies": {
"typescript": "4.1.5",
}
export const SubscriptionsView: React.FC = () => {
const [data, setData] = useState<Subscription[]>();
const isMounted = React.useRef(true);
React.useEffect(() => {
if (isMounted.current) {
// fetch data
// setData (fetch result)
return () => {
isMounted.current = false;
};
}
}
});
Assuming your date column is an actual MySQL date column:
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY score DESC;
One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:
test_json = { "a": 1, "b": 2}
Once you do this, adding a json element only involves the following line:
test_json["c"] = 3
This will result in:
{'a': 1, 'b': 2, 'c': 3}
Afterwards, you can add that json back into an array or a list of that is desired.
link_to "+ Service", controller_action_path(:account_id => acct.id)
If it is still not working check the path:
$ rake routes
Open a connection to your server first (SQL IDE) from the home screen. Then use the context menu in the schema tree to run a query that simply selects rows from the selected table. The LIMIT attached to that is to avoid reading too many rows by accident. This limit can be switched off (or adjusted) in the preferences dialog.
This quick way to select rows is however not very flexible. Normally you would run a query (File / New Query Tab) in the editor with additional conditions, like a sort order:
@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.
For that we have provide one setter method for myobj and set the myobj value with mocked object.
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
In our Test class, we have to write below code
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
@test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in @before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
To give you a different perspective on this, using throw is particularly useful if you're providing an API to a client and you want to provide verbose stack trace information for your internal library. By using throw here, I'd get the stack trace in this case of the System.IO.File library for File.Delete. If I use throw ex, then that information will not be passed to my handler.
static void Main(string[] args) {
Method1();
}
static void Method1() {
try {
Method2();
} catch (Exception ex) {
Console.WriteLine("Exception in Method1");
}
}
static void Method2() {
try {
Method3();
} catch (Exception ex) {
Console.WriteLine("Exception in Method2");
Console.WriteLine(ex.TargetSite);
Console.WriteLine(ex.StackTrace);
Console.WriteLine(ex.GetType().ToString());
}
}
static void Method3() {
Method4();
}
static void Method4() {
try {
System.IO.File.Delete("");
} catch (Exception ex) {
// Displays entire stack trace into the .NET
// or custom library to Method2() where exception handled
// If you want to be able to get the most verbose stack trace
// into the internals of the library you're calling
throw;
// throw ex;
// Display the stack trace from Method4() to Method2() where exception handled
}
}
AFAIK all you can do is omit the returns to make things more compact in C++:
switch(Answer)
{
case 1: case 2: case 3: case 4:
cout << "You need more cars.";
break;
...
}
(You could remove the other returns as well, of course.)
If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.
<input id="addButton" type="button" value="Add" />
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#addButton').click(function()
{
showDialog('#addPerson');
});
});
</script>
If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:
<asp:Button ID="buttonAdd" runat="server" Text="Add" />
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#<%= buttonAdd.ClientID %>').click(function(e)
{
showDialog('#addPerson');
if(/*Some Condition Is Not Met*/)
return false;
});
});
</script>
You can have a constructor in the abstract class that accepts the init parameters. The Java spec only specifies that the anonymous class, which is the offspring of the (optionally) abstract class or implementation of an interface, can not have a constructor by her own right.
The following is absolutely legal and possible:
static abstract class Q{
int z;
Q(int z){ this.z=z;}
void h(){
Q me = new Q(1) {
};
}
}
If you have the possibility to write the abstract class yourself, put such a constructor there and use fluent API where there is no better solution. You can this way override the constructor of your original class creating an named sibling class with a constructor with parameters and use that to instantiate your anonymous class.
What we do, is to create two tables for each multilingual object.
E.g. the first table contains only language-neutral data (primary key, etc.) and the second table contains one record per language, containing the localized data plus the ISO code of the language.
In some cases we add a DefaultLanguage field, so that we can fall-back to that language if no localized data is available for a specified language.
Example:
Table "Product":
----------------
ID : int
<any other language-neutral fields>
Table "ProductTranslations"
---------------------------
ID : int (foreign key referencing the Product)
Language : varchar (e.g. "en-US", "de-CH")
IsDefault : bit
ProductDescription : nvarchar
<any other localized data>
With this approach, you can handle as many languages as needed (without having to add additional fields for each new language).
Update (2014-12-14): please have a look at this answer, for some additional information about the implementation used to load multilingual data into an application.
I might be wrong on this but I think you need to implement your own com.android.volley.toolbox.HttpStack
for this because the default ones (HurlStack
if version > Gingerbread or HttpClientStack
) don't deal with multipart/form-data
.
Edit:
And indeed I was wrong. I was able to do it using MultipartEntity
in Request like this:
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final String mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file, String stringPart)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
try
{
entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
@Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
return Response.success("Uploaded", getCacheEntry());
}
@Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
}
It's pretty raw but I tried it with an image and a simple string and it works. The response is a placeholder, doesn't make much sense to return a Response String in this case. I had problems using apache httpmime to use MultipartEntity so I used this https://code.google.com/p/httpclientandroidlib/ don't know if there's a better way. Hope it helps.
Edit
You can use httpmime without using httpclientandroidlib, the only dependency is httpcore.
Kotlin? Here we go:
android {
// ... (compileSdkVersion, buildToolsVersion, etc)
defaultConfig {
// ... (applicationId, miSdkVersion, etc)
kapt {
arguments {
arg("room.schemaLocation", "$projectDir/schemas")
}
}
}
buildTypes {
// ... (buildTypes, compileOptions, etc)
}
}
//...
Don't forget about plugin:
apply plugin: 'kotlin-kapt'
For more information about kotlin annotation processor please visit: Kotlin docs
This is the sort of thing that sed
is really good at: $ sed 's/[ \t]*$//'
. Be aware the you will probably need to literally type a TAB character instead of \t
for this to work.
You can just adjust your constraints:
where T : class
Then returning null is allowed.
Assuming a Css class of "image" :
input.image {
background: url(/i/bg.png) no-repeat top left;
width: /* img-width */;
height: /* img-height */
}
If you don't know what the image width and height are, you can set this dynamically with javascript.
Despite using of React here - elements layout is completely html/css feature.
The root cause of the issue is in how height
property in css works. When you are using relative values for height (in %) - this means that height will be set in relation to its parent.
So if you have a structure like html > body > div#root > div.app
- to make div.app
100% height all its ancestors should have 100% height. You may play with next example:
html {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
body {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
div#root {_x000D_
height: 100%; /* remove this line to see div.app is no more 100% height */_x000D_
background-color: indigo;_x000D_
padding: 0 30px;_x000D_
}_x000D_
_x000D_
div.app {_x000D_
height: 100%;_x000D_
background-color: cornsilk;_x000D_
}
_x000D_
<div id="root">_x000D_
<div class="app"> I will be 100% height if my parents are </div>_x000D_
</div>
_x000D_
Few arguments:
!important
- despite some time this feature is useful in ~95% of cases, it indicates a poor structure of html/css. Also, this is not a solution to the current problem.position: absolute
. Property positon
is designed to change how the element will be rendered in relation to (own position - relative, viewport - fixed, nearest parent whos position is not static - absolute). Ans despite position: absolute; top: 0; right: 0; bottom: 0; left: 0;
will result in the same look - it also pushes you to change parents position
to something not static
- so you need to maintain 2 elements. That also causes parent div be collapsed in a line (0-height), and inner - full screen. That makes confusion in element inspector.You can set timeouts for all connections made from the jvm by changing the following System-properties:
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
Every connection will time out after 10 seconds.
Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.
FIND_IN_SET is your friend in this case
select * from shirts where FIND_IN_SET(1,colors)
Just to add another one:
datestring = datetime.datetime.strftime(datetime.datetime( \
random.randint(2000, 2015), \
random.randint(1, 12), \
random.randint(1, 28), \
random.randrange(23), \
random.randrange(59), \
random.randrange(59), \
random.randrange(1000000)), '%Y-%m-%d %H:%M:%S')
The day handling needs some considerations. With 28 you are on the secure site.
This is the approach you don't need to use padding
, just set the height
and width
for the a
and let the flex
handle with margin: 0 auto
.
.social-links a{_x000D_
text-align:center;_x000D_
float: left;_x000D_
width: 36px;_x000D_
height: 36px;_x000D_
border: 2px solid #909090;_x000D_
border-radius: 100%;_x000D_
margin-right: 7px; /*space between*/_x000D_
display: flex;_x000D_
align-items: flex-start;_x000D_
transition: all 0.4s;_x000D_
-webkit-transition: all 0.4s;_x000D_
} _x000D_
.social-links a i{_x000D_
font-size: 20px;_x000D_
align-self:center;_x000D_
color: #909090;_x000D_
transition: all 0.4s;_x000D_
-webkit-transition: all 0.4s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
.social-links a i::before{_x000D_
display:inline-block;_x000D_
text-decoration:none;_x000D_
}_x000D_
.social-links a:hover{_x000D_
background: rgba(0,0,0,0.2);_x000D_
}_x000D_
.social-links a:hover i{_x000D_
color:#fff;_x000D_
}
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="social-links">_x000D_
<a href="#"><i class="fa fa-facebook fa-lg"></i></a>_x000D_
<a href="#"><i class="fa fa-twitter fa-lg"></i></a>_x000D_
<a href="#"><i class="fa fa-google-plus fa-lg"></i></a>_x000D_
<a href="#"><i class="fa fa-pinterest fa-lg"></i></a>_x000D_
</div>
_x000D_
The simplest of them all:
<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, "");
Result:
"Hello, this is Mike"
Personally, I would fix this in the .htaccess file. You should have access to that.
Define your CSS URL as such:
url(/image_dir/image.png);
In your .htacess file, put:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/$1
or
RewriteRule ^image_dir/(.*) images/$1
depending on the site.
Just for people who want to do the same thing in 2018
You can assign a CSS custom property to your element (through CSS or JS) and change it:
Assigment through CSS:
element {
--element-width: 300px;
width: var(--element-width, 100%);
}
Assignment through JS
ELEMENT.style.setProperty('--element-width', NEW_VALUE);
Get property value through JS
ELEMENT.style.getPropertyValue('--element-width');
Here useful links:
body{_x000D_
background: #333 url(/images/classy_fabric.png);_x000D_
width: 430px;_x000D_
margin: 0 auto;_x000D_
padding: 30px;_x000D_
}_x000D_
.preview{_x000D_
background: #ccc;_x000D_
width: 415px;_x000D_
height: 430px;_x000D_
border: solid 10px #fff;_x000D_
}_x000D_
_x000D_
input[type='radio'] {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
width: 25px;_x000D_
height: 25px;_x000D_
margin: 5px 0 5px 5px;_x000D_
background-size: 225px 70px;_x000D_
position: relative;_x000D_
float: left;_x000D_
display: inline;_x000D_
top: 0;_x000D_
border-radius: 3px;_x000D_
z-index: 99999;_x000D_
cursor: pointer;_x000D_
box-shadow: 1px 1px 1px #000;_x000D_
}_x000D_
_x000D_
input[type='radio']:hover{_x000D_
-webkit-filter: opacity(.4);_x000D_
filter: opacity(.4); _x000D_
}_x000D_
_x000D_
.red{_x000D_
background: red;_x000D_
}_x000D_
_x000D_
.red:checked{_x000D_
background: linear-gradient(brown, red)_x000D_
}_x000D_
_x000D_
.green{_x000D_
background: green;_x000D_
}_x000D_
_x000D_
.green:checked{_x000D_
background: linear-gradient(green, lime);_x000D_
}_x000D_
_x000D_
.yellow{_x000D_
background: yellow;_x000D_
}_x000D_
_x000D_
.yellow:checked{_x000D_
background: linear-gradient(orange, yellow);_x000D_
}_x000D_
_x000D_
.purple{_x000D_
background: purple;_x000D_
}_x000D_
_x000D_
.pink{_x000D_
background: pink;_x000D_
}_x000D_
_x000D_
.purple:checked{_x000D_
background: linear-gradient(purple, violet);_x000D_
}_x000D_
_x000D_
.red:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 red);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 red);_x000D_
}_x000D_
_x000D_
.green:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 green);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 green);_x000D_
}_x000D_
_x000D_
.yellow:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 yellow);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 yellow);_x000D_
}_x000D_
_x000D_
.purple:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 purple);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 purple);_x000D_
}_x000D_
_x000D_
.pink:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 pink);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 pink);_x000D_
}_x000D_
_x000D_
_x000D_
img{_x000D_
width: 394px;_x000D_
height: 375px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.label{_x000D_
width: 150px;_x000D_
height: 75px;_x000D_
position: absolute;_x000D_
top: 170px;_x000D_
margin-left: 130px;_x000D_
}_x000D_
_x000D_
::selection{_x000D_
background: #000;_x000D_
}
_x000D_
<div class="preview">_x000D_
<input class='red' name='color' type='radio' />_x000D_
<input class='green' name='color' type='radio' />_x000D_
<input class='pink' name='color' type='radio' />_x000D_
<input checked class='yellow' name='color' type='radio' />_x000D_
<input class='purple' name='color' type='radio' /> _x000D_
<img src="https://i.stack.imgur.com/bd7VJ.png"/>_x000D_
</div>
_x000D_
If your problem is so special that you really need to have more readers open simultaneously, and your requirements allow not older than SQL Server 2005 DB backend, then the magic word is MARS (Multiple Active Result Sets). http://msdn.microsoft.com/en-us/library/ms345109%28v=SQL.90%29.aspx. Bob Vale's linked topic's solution shows how to enable it: specify MultipleActiveResultSets=true
in your connection string. I just tell this as an interesting possibility, but you should rather transform your solution.
Screen
If process is running in a screen session you can use screen's log command to log the output of that window to a file:
Switch to the script's window, C-a H to log.
Now you can :
$ tail -f screenlog.2 | grep whatever
From screen's man page:
log [on|off]
Start/stop writing output of the current window to a file "screenlog.n" in the window's default directory, where n is the number of the current window. This filename can be changed with the 'logfile' command. If no parameter is given, the state of logging is toggled. The session log is appended to the previous contents of the file if it already exists. The current contents and the contents of the scrollback history are not included in the session log. Default is 'off'.
I'm sure tmux has something similar as well.
Open the command prompt and enter the following commands:
net stop MySQL
net start MySQL
the MySQL service name maybe changes based on the version you installed. In my situation, MySQL version is MySQL Server 5.7. So I use the following command
net stop MySQL57
net start MySQL57
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
css names must be consistent.
Names of jqueryUI css are not "jquery.ui.XXX" in Contents/themes/base folder .
so it should be :
wrong:
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
correct :
bundles.Add(new StyleBundle("~/Bundles/themes/base/css").Include(
"~/Content/themes/base/core.css",
"~/Content/themes/base/resizable.css",
"~/Content/themes/base/selectable.css",
"~/Content/themes/base/accordion.css",
"~/Content/themes/base/autocomplete.css",
"~/Content/themes/base/button.css",
"~/Content/themes/base/dialog.css",
"~/Content/themes/base/slider.css",
"~/Content/themes/base/tabs.css",
"~/Content/themes/base/datepicker.css",
"~/Content/themes/base/progressbar.css",
"~/Content/themes/base/theme.css"));
I tried in MVC5 and worked successfully.
If you're wondering whether to type HEAD^
or HEAD~
in your command, just use either:
They're both names for the same commit - the first parent of the current commit.
Likewise with master~
and master^
- both names for the first parent of master.
In the same way as 2 + 2
and 2 x 2
are both 4
- they're different ways of getting there, but the answer is the same.
This answers the question: What's the difference between HEAD^ and HEAD~ in Git?
If you just did a merge (so your current commit has more than one parent), or you're still interested in how the caret and tilde work, see the other answers (which I won't duplicate here) for an in-depth explanation, as well as how to use them repeatedly (e.g.HEAD~~~
), or with numbers (e.g.HEAD^2
). Otherwise, I hope this answer saves you some time.
Updated 2017-12-16
I was not sure about the tests in OP. I decided to experiment a little and ended up busting some of the myths.
Synchronous
<script src...>
will block downloading of the resources below it until it is downloaded and executed
This is no longer true. Have a look at the waterfall generated by Chrome 63:
<head>
<script src="//alias-0.redacted.com/payload.php?type=js&delay=333&rand=1"></script>
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&rand=2"></script>
<script src="//alias-2.redacted.com/payload.php?type=js&delay=333&rand=3"></script>
</head>
<link rel=stylesheet>
will not block download and execution of scripts below it
This is incorrect. The stylesheet will not block download but it will block execution of the script (little explanation here). Have a look at performance chart generated by Chrome 63:
<link href="//alias-0.redacted.com/payload.php?type=css&delay=666" rel="stylesheet">
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&block=1000"></script>
Keeping the above in mind, the results in OP can be explained as follows:
CSS First:
CSS Download 500ms:<------------------------------------------------>
JS Download 400ms:<-------------------------------------->
JS Execution 1000ms: <-------------------------------------------------------------------------------------------------->
DOM Ready @1500ms: ?
JS First:
JS Download 400ms:<-------------------------------------->
CSS Download 500ms:<------------------------------------------------>
JS Execution 1000ms: <-------------------------------------------------------------------------------------------------->
DOM Ready @1400ms: ?
May be by:-
for(Row row : sheet) {
for(Cell cell : row) {
System.out.print(cell.getStringCellValue());
}
}
For specific type of cell you can try:
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
cellValue = Double.toString(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
Check out UI Bootstrap's pagination directive. I ended up using it rather than what is posted here as it has enough features for my current use and has a thorough test spec to accompany it.
<!-- table here -->
<pagination
ng-model="currentPage"
total-items="todos.length"
max-size="maxSize"
boundary-links="true">
</pagination>
<!-- items/page select here if you like -->
todos.controller("TodoController", function($scope) {
$scope.filteredTodos = []
,$scope.currentPage = 1
,$scope.numPerPage = 10
,$scope.maxSize = 5;
$scope.makeTodos = function() {
$scope.todos = [];
for (i=1;i<=1000;i++) {
$scope.todos.push({ text:"todo "+i, done:false});
}
};
$scope.makeTodos();
$scope.$watch("currentPage + numPerPage", function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredTodos = $scope.todos.slice(begin, end);
});
});
I have made a working plunker for reference.
<!-- table here -->
<div data-pagination="" data-num-pages="numPages()"
data-current-page="currentPage" data-max-size="maxSize"
data-boundary-links="true"></div>
<!-- items/page select here if you like -->
todos.controller("TodoController", function($scope) {
$scope.filteredTodos = []
,$scope.currentPage = 1
,$scope.numPerPage = 10
,$scope.maxSize = 5;
$scope.makeTodos = function() {
$scope.todos = [];
for (i=1;i<=1000;i++) {
$scope.todos.push({ text:"todo "+i, done:false});
}
};
$scope.makeTodos();
$scope.numPages = function () {
return Math.ceil($scope.todos.length / $scope.numPerPage);
};
$scope.$watch("currentPage + numPerPage", function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredTodos = $scope.todos.slice(begin, end);
});
});
I have made a working plunker for reference.
Todo this in a single system call you can use the fs-extra
npm module.
After this the file will have been created as well as the directory it is to be placed in.
const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFile(file, err => {
console.log(err) // => null
});
Another way is to use ensureFileSync which will do the same thing but synchronous.
const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFileSync(file)
There used to be a pattern with metaprogramming:
template<unsigned T>
struct Fact {
enum Enum {
VALUE = Fact<T-1>*T;
};
};
template<>
struct Fact<1u> {
enum Enum {
VALUE = 1;
};
};
// Fact<10>::VALUE is known be a compile-time constant
I believe constexpr
was introduced to let you write such constructs without the need for templates and weird constructs with specialization, SFINAE and stuff - but exactly like you'd write a run-time function, but with the guarantee that the result will be determined in compile-time.
However, note that:
int fact(unsigned n) {
if (n==1) return 1;
return fact(n-1)*n;
}
int main() {
return fact(10);
}
Compile this with g++ -O3
and you'll see that fact(10)
is indeed evaulated at compile-time!
An VLA-aware compiler (so a C compiler in C99 mode or C++ compiler with C99 extensions) may even allow you to do:
int main() {
int tab[fact(10)];
int tab2[std::max(20,30)];
}
But that it's non-standard C++ at the moment - constexpr
looks like a way to combat this (even without VLA, in the above case). And there's still the problem of the need to have "formal" constant expressions as template arguments.
There are a few possible ways to do this:
PYTHONPATH
to a colon-separated list of directories to search for imported modules.sys.path.append('/path/to/search')
to add the names of directories you want Python to search for imported modules. sys.path
is just the list of directories Python searches every time it gets asked to import a module, and you can alter it as needed (although I wouldn't recommend removing any of the standard directories!). Any directories you put in the environment variable PYTHONPATH
will be inserted into sys.path
when Python starts up.site.addsitedir
to add a directory to sys.path
. The difference between this and just plain appending is that when you use addsitedir
, it also looks for .pth
files within that directory and uses them to possibly add additional directories to sys.path
based on the contents of the files. See the documentation for more detail.Which one of these you want to use depends on your situation. Remember that when you distribute your project to other users, they typically install it in such a manner that the Python code files will be automatically detected by Python's importer (i.e. packages are usually installed in the site-packages
directory), so if you mess with sys.path
in your code, that may be unnecessary and might even have adverse effects when that code runs on another computer. For development, I would venture a guess that setting PYTHONPATH
is usually the best way to go.
However, when you're using something that just runs on your own computer (or when you have nonstandard setups, e.g. sometimes in web app frameworks), it's not entirely uncommon to do something like
import sys
from os.path import dirname
sys.path.append(dirname(__file__))
Yes you can! Just tested this and it works great, this is awesome! It still doesn't work with html, but it does with svg.
In my index.html I have:
<div id="test" style="content: url(test.svg); width: 200px; height: 200px;"></div>
And my test.svg looks like this:
<svg xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
<polyline points="20,20 40,25 60,40 80,120 120,140 200,180" style="fill:none;stroke:black;stroke-width:3"/>
</svg>
As mentioned before you can use --extra-vars (-e) , but instead of specifying the pwd on the commandline so it doesn't end up in the history files you can save it to an environment variable. This way it also goes away when you close the session.
read -s PASS
ansible windows -i hosts -m win_ping -e "ansible_password=$PASS"
There is another possible scenario that might get some people as well (if you have python and python3 on your system):
pip3 install boto3
Note the use of pip3
indicates the use of Python 3's pip installation vs just pip
which indicates the use of Python 2's.
Call control.invalidate and the paint event will be raised.
If your main element has some child elements or text, you could make use of it.
Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).
Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.
This element will start acting like his owner is your main element.
HTML
<div class="circle">
<span>Some text</span>
</div>
CSS
.circle {
position: relative; /* or absolute/fixed */
}
.circle:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle:after {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle span {
/* not relative/absolute/fixed */
}
.circle span:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
Open you working copy folder in console (terminal) and choose commands below. To see last changes: If you have commited last changes use:
svn diff -rPREV
If you left changes in working copy (that's bad practice) than use:
svn diff
To see log of commits: If you're working in branch:
svn log --stop-on-copy
If you're working with trunk:
svn log | head
or just
svn log
Use PHP's $_POST
or $_GET
superglobals to retrieve the value of the input tag via the name of the HTML tag.
For Example, change the method in your form and then echo out the value by the name of the input:
Using $_GET
method:
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_GET['subject']; ?>
Using $_POST
method:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_POST['subject']; ?>
Use --format option
git tag -l --format='%(tag) %(subject)'
If you are using PHP, try using <?php flush(); ?>
after </head>
and before </body>
or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.
You can use the Background Panel class. It does the custom painting as explained above but gives you options to display the image scaled, tiled or normal size. It also explains how you can use a JLabel with an image as the content pane for the frame.
<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
Below query will provide exactly the same result as given in the desired response:
db.books.aggregate([
{
$group: {
_id: { addresses: "$addr", books: "$book" },
num: { $sum :1 }
}
},
{
$group: {
_id: "$_id.addresses",
bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
}
},
{
$project: {
_id: 1,
bookCounts:1,
"totalBookAtAddress": {
"$sum": "$bookCounts.count"
}
}
}
])
The response will be looking like below:
/* 1 */
{
"_id" : "address4",
"bookCounts" : [
{
"bookName" : "book3",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 2 */
{
"_id" : "address90",
"bookCounts" : [
{
"bookName" : "book33",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 3 */
{
"_id" : "address15",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 4 */
{
"_id" : "address3",
"bookCounts" : [
{
"bookName" : "book9",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 5 */
{
"_id" : "address5",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 6 */
{
"_id" : "address1",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 3
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 4
},
/* 7 */
{
"_id" : "address2",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 2
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 3
},
/* 8 */
{
"_id" : "address77",
"bookCounts" : [
{
"bookName" : "book11",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 9 */
{
"_id" : "address9",
"bookCounts" : [
{
"bookName" : "book99",
"count" : 1
}
],
"totalBookAtAddress" : 1
}
In line with billjamesdev answer, here is another approach to validate an URL without using a RegEx:
From Apache Commons Validator lib, look at class UrlValidator. Some example code:
Construct a UrlValidator with valid schemes of "http", and "https".
String[] schemes = {"http","https"}.
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("ftp://foo.bar.com/")) {
System.out.println("url is valid");
} else {
System.out.println("url is invalid");
}
prints "url is invalid"
If instead the default constructor is used.
UrlValidator urlValidator = new UrlValidator();
if (urlValidator.isValid("ftp://foo.bar.com/")) {
System.out.println("url is valid");
} else {
System.out.println("url is invalid");
}
prints out "url is valid"
Here's an extension to Tony's extension... :-)
For Entity Framework 4.x, if you want to get the name and value of the key field so that you know which entity instance (DB record) has the problem, you can add the following. This provides access to the more powerful ObjectContext class members from your DbContext object.
// Get the key field name & value.
// This assumes your DbContext object is "_context", and that it is a single part key.
var e = ((IObjectContextAdapter)_context).ObjectContext.ObjectStateManager.GetObjectStateEntry(validationErrors.Entry.Entity);
string key = e.EntityKey.EntityKeyValues[0].Key;
string val = e.EntityKey.EntityKeyValues[0].Value;
just a convenient way of getting last n=5 containers (no matter running or not):
$ docker container ls -a -n5
Additional information to abouve answers for those still having problems.
FindBoost.cmake
may not content last
version fo Boost. Add it if needed.Boost_COMPILER
and Boost_ARCHITECTURE
suffix vars if needed.I tried the below and it worked like a charm :)
rec_list = ['[email protected]', '[email protected]']
rec = ', '.join(rec_list)
msg['To'] = rec
send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())
I encountered the write:errno=104
attempting to test connecting to an SSL-enabled RabbitMQ broker port with openssl s_client.
The issue turned out to be simply that the user RabbitMQ was running as did not have read permissions on the certificate file. There was little-to-no useful logging in RabbitMQ.
I think this way helps you...
var name=[];
var age=[];
name.push('sulfikar');
age.push('24');
var ent={};
for(var i=0;i<name.length;i++)
{
ent.name=name[i];
ent.age=age[i];
}
JSON.Stringify(ent);
If your html link is like this:
<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>
Then you can access the href in jquery as given below (there is no need to use "a" in href for this)
$(".linkClass").on("click",accesshref);
function accesshref()
{
var url = $(".linkClass").attr("href");
//OR
var url = $(this).attr("href");
}
The latest release of Requests will build CookieJars for you from simple dictionaries.
import requests
cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
r = requests.post('http://wikipedia.org', cookies=cookies)
Enjoy :)
Easy approach:
CREATE TABLE T
(
C [nvarchar](100) NOT NULL UNIQUE,
);
SET XACT_ABORT ON -- Turns on rollback if T-SQL statement raises a run-time error.
SELECT * FROM T; -- Check before.
BEGIN TRAN
INSERT INTO T VALUES ('A');
INSERT INTO T VALUES ('B');
INSERT INTO T VALUES ('B');
INSERT INTO T VALUES ('C');
COMMIT TRAN
SELECT * FROM T; -- Check after.
DELETE T;
Delete old virtual environment and create a fresh virtual environment.
I found these lists on Scott Hanselman's blog:
Here are what I think are the most important questions from these posts divided into categories. I edited and re-arranged them. Fortunately for most of these questions there is already a good answer on Stack Overflow. Just follow the links (I will update them all ASAP).
a.Equals(b)
and a == b
?Assembly.LoadFrom
or Assembly.LoadFile
be appropriate?Finalize()
and Dispose()
? (external article)Debug.Write
and Trace.Write
? When should each be used?catch (Exception e) {throw e;}
and catch (Exception e) {throw;}
?typeof(foo)
and myFoo.GetType()
? q=
except where q=5
(as in http://localhost/page.aspx?q=5
)?String param="2019-07-18 19:29:37";
param="%27"+param.trim().replace(" ", "%20")+"%27";
I observed in case of Datetime (Timestamp)
URLEncoder.encode(param,"UTF-8")
does not work.
You can remove database directly as:
$ mysqladmin -h [host] -u [user] -p drop [database_name]
[Enter Password]
Do you really want to drop the 'hairfree' database [y/N]: y
git log --numstat just gives you only the numbers
The best way is to use different database groups. If you want to keep using the master database as usual ($this->db) just turn off persistent connexion configuration option to your secondary database(s). Only master database should work with persistent connexion :
Master database
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
Secondary database (notice pconnect is set to false)
$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = FALSE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;
Then you can use secondary databases as database objects while using master database as usual :
// use master dataabse
$users = $this->db->get('users');
// connect to secondary database
$otherdb = $this->load->database('otherdb', TRUE);
$stuff = $otherdb->get('struff');
$otherdb->insert_batch('users', $users->result_array());
// keep using master database as usual, for example insert stuff from other database
$this->db->insert_batch('stuff', $stuff->result_array());
The config file is just an XML file, you can open it by:
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
and later retrieving values by:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
If my understanding is correct then you want to match any line which has Clinton and Reagan, in any order, but not Bush. As suggested by Stuck, here is a version with lookahead assertions:
#!/usr/bin/perl
use strict;
use warnings;
my $regex = qr/
(?=.*clinton)
(?!.*bush)
.*reagan
/ix;
while (<DATA>) {
chomp;
next unless (/$regex/);
print $_, "\n";
}
__DATA__
shouldn't match - reagan came first, then clinton, finally bush
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
shouldn't match - last two: clinton and bush
shouldn't match - reverse: bush and clinton
shouldn't match - and then came obama, along comes mary
shouldn't match - to clinton with perl
Results
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
as desired it matches any line which has Reagan and Clinton in any order.
You may want to try reading how lookahead assertions work with examples at http://www252.pair.com/comdog/mastering_perl/Chapters/02.advanced_regular_expressions.html
they are very tasty :)
When I started learning Spring Security, then I overrided the method userDetailsService() as in below code snippet:
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Override
@Bean
public UserDetailsService userDetailsService() {
List<UserDetails> users= new ArrayList<UserDetails>();
users.add(User.withDefaultPasswordEncoder().username("admin").password("nimda").roles("USER","ADMIN").build());
users.add(User.withDefaultPasswordEncoder().username("Spring").password("Security").roles("USER").build());
return new InMemoryUserDetailsManager(users);
}
}
So we can log in to the application using the above-mentioned creds. (e.g. admin/nimda)
Note: This we should not use in production.
var futureMinDate = Date()
val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
try {
futureMinDate = sdf.parse("2019-08-22")
} catch (e: ParseException) {
e.printStackTrace()
}
// Here futureMinDate.time Returns the number of milliseconds since January 1, 1970, 00:00:00 GM
// So we need to subtract the millis from current millis to get actual millis
object : CountDownTimer(futureMinDate.time - System.currentTimeMillis(), 1000) {
override fun onTick(millisUntilFinished: Long) {
val sec = (millisUntilFinished / 1000) % 60
val min = (millisUntilFinished / (1000 * 60)) % 60
val hr = (millisUntilFinished / (1000 * 60 * 60)) % 24
val day = ((millisUntilFinished / (1000 * 60 * 60)) / 24).toInt()
val formattedTimeStr = if (day > 1) "$day days $hr : $min : $sec"
else "$day day $hr : $min : $sec"
tvFlashDealCountDownTime.text = formattedTimeStr
}
override fun onFinish() {
tvFlashDealCountDownTime.text = "Done!"
}
}.start()
Pass a future date and convert it to millisecond.
It will work like a charm.
One option is to install the cli globally.
Since Babel 7 was released the namespace has changed from babel-cli
to @babel/cli
, hence:
npm install --global @babel/cli
You'll likely still encounter errors for @babel/core
so:
npm install --global @babel/core
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
For an iBeacon with ProximityUUID E2C56DB5-DFFB-48D2-B060-D0F5A71096E0
, major 0
, minor 0
, and calibrated Tx Power of -59
RSSI, the transmitted BLE advertisement packet looks like this:
d6 be 89 8e 40 24 05 a2 17 6e 3d 71 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 52 ab 8d 38 a5
This packet can be broken down as follows:
d6 be 89 8e # Access address for advertising data (this is always the same fixed value)
40 # Advertising Channel PDU Header byte 0. Contains: (type = 0), (tx add = 1), (rx add = 0)
24 # Advertising Channel PDU Header byte 1. Contains: (length = total bytes of the advertising payload + 6 bytes for the BLE mac address.)
05 a2 17 6e 3d 71 # Bluetooth Mac address (note this is a spoofed address)
02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 # Bluetooth advertisement
52 ab 8d 38 a5 # checksum
The key part of that packet is the Bluetooth Advertisement, which can be broken down like this:
02 # Number of bytes that follow in first AD structure
01 # Flags AD type
1A # Flags value 0x1A = 000011010
bit 0 (OFF) LE Limited Discoverable Mode
bit 1 (ON) LE General Discoverable Mode
bit 2 (OFF) BR/EDR Not Supported
bit 3 (ON) Simultaneous LE and BR/EDR to Same Device Capable (controller)
bit 4 (ON) Simultaneous LE and BR/EDR to Same Device Capable (Host)
1A # Number of bytes that follow in second (and last) AD structure
FF # Manufacturer specific data AD type
4C 00 # Company identifier code (0x004C == Apple)
02 # Byte 0 of iBeacon advertisement indicator
15 # Byte 1 of iBeacon advertisement indicator
e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 # iBeacon proximity uuid
00 00 # major
00 00 # minor
c5 # The 2's complement of the calibrated Tx Power
Any Bluetooth LE device that can be configured to send a specific advertisement can generate the above packet. I have configured a Linux computer using Bluez to send this advertisement, and iOS7 devices running Apple's AirLocate test code pick it up as an iBeacon with the fields specified above. See: Use BlueZ Stack As A Peripheral (Advertiser)
This blog has full details about the reverse engineering process.
The updated latest version of "The Java language Specification" can be found via the following links. Java 7
Window -> Preferences -> Java -> Code Style -> Code Templates -> Comments -> Types Chnage the tage infront ${user} to your name.
Before
/**
* @author ${user}
*
* ${tags}
*/
After
/**
* @author Waqas Ahmed
*
* ${tags}
*/
According to the TextView docs, the programmatic version of android:password is setTransformationMethod(), not setInputType(). So something like:
mEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
should do the trick.
In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3]
>>> sum(l)
6
>>> sum = 0 # oops! shadowed a builtin!
>>> sum(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> import sys
>>> sum = sys.modules['__builtin__'].sum # -- fixing sum
>>> sum(l)
6
This also comes in handy if you happened to assign a value to any other builtin, like dict
or list
Generally you should also override hashCode()
each time you override equals()
, even if just for the performance boost. HashCode()
decides which 'bucket' your object gets sorted into when doing a comparison, so any two objects which equal()
evaluates to true should return the same hashCode
value()
. I cannot remember the default behavior of hashCode()
(if it returns 0 then your code should work but slowly, but if it returns the address then your code will fail). I do remember a bunch of times when my code failed because I forgot to override hashCode()
though. :)
For me, I had an issue until I removed the padding. It looks like there is a bug on certain devices that doesn't alter the size of the view to accommodate the padding, and instead compresses the contents.
Remove padding
, use layout_margin
instead.
background:url(bgimage.jpg) no-repeat; background-size: cover;
This did the trick
I wasn't able to do that with any swal(sweatAlert) default callback function, so I forced with jquery, got the Ok button class inspecting the element in chrome an made something like this:
<script>
sweetAlert({
title:'Warning!',
text: 'Invalid user or password!',
type:'warning'
},function(isConfirm){
alert('ok');
});
$('.swal2-confirm').click(function(){
window.location.href = 'index.php';
});
</script>
The 'Ok' alert in function(isConfirm) was just a test to see if it would get into this function, if so I should be able to redirect from there, but I wasn't...
So I used jQuery to determine if the button "OK" of swal was clicked by getting it class: ".swal2-confirm' then I could redirect with success...
Hope this helps you all !
PS: I am using php echo to run the script, I din't have to leave php to run it, just use single quotes and you're done !
Add following to your maven dependency
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
Here is the solution
import boto3
s3=boto3.resource('s3')
BUCKET_NAME = 'Your S3 Bucket Name'
allFiles = s3.Bucket(BUCKET_NAME).objects.all()
for file in allFiles:
print(file.key)
In case of upgrading your python on mac os 10.7 and pkg_resources doesn't work, the simplest way to fix this is just reinstall setuptools as Ned mentioned above.
sudo pip install setuptools --upgrade
or sudo easy_install install setuptools --upgrade
I wanted to provide a solution based on the answer of @kopelitsa. The main differences being:
HandlerExceptionResolver
.First, you need to make sure, that you have a class that handles exceptions occurring in a regular RestController/Controller (a class annotated with @RestControllerAdvice
or @ControllerAdvice
and method(s) annotated with @ExceptionHandler
). This handles your exceptions occurring in a controller. Here is an example using the RestControllerAdvice:
@RestControllerAdvice
public class ExceptionTranslator {
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorDTO processRuntimeException(RuntimeException e) {
return createErrorDTO(HttpStatus.INTERNAL_SERVER_ERROR, "An internal server error occurred.", e);
}
private ErrorDTO createErrorDTO(HttpStatus status, String message, Exception e) {
(...)
}
}
To reuse this behavior in the Spring Security filter chain, you need to define a Filter and hook it into your security configuration. The filter needs to redirect the exception to the above defined exception handling. Here is an example:
@Component
public class FilterChainExceptionHandler extends OncePerRequestFilter {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
log.error("Spring Security Filter Chain Exception:", e);
resolver.resolveException(request, response, null, e);
}
}
}
The created filter then needs to be added to the SecurityConfiguration. You need to hook it into the chain very early, because all preceding filter's exceptions won't be caught. In my case, it was reasonable to add it before the LogoutFilter
. See the default filter chain and its order in the official docs. Here is an example:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private FilterChainExceptionHandler filterChainExceptionHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(filterChainExceptionHandler, LogoutFilter.class)
(...)
}
}
For my case, below worked on Mac:
I could not access container IPs directly on Mac. I need to use localhost
with port forwarding, e.g. if the port is 8000, then http://localhost:8000
See https://docs.docker.com/docker-for-mac/networking/#known-limitations-use-cases-and-workarounds
The original answer was from: https://github.com/docker/for-mac/issues/2670#issuecomment-371249949
As mentioned in many sites, there are various reasons for this. For me it was due to the length of Source and Destination (Path length). I tried xcopy in the command prompt and I was unable to type the complete source and path (after some characters it wont allow you to type). I then reduced the path length and was able to run. Hope this helps.
Either might be fine, but I don't think there is a definite answer.
None
is better than comparing with ""
, since ""
might be a valid value,""
is probably better, because its actually a string, and you can call string methods on it. If you went with None
, these would lead to exceptions.""
can help with that.If you have a loop, say:
def myfunc (self, mystr = ""):
for other in self.strs:
mystr = self.otherfunc (mystr, other)
then a potential future optimizer would know that str
is always a string. If you used None
, then it might not be a string until the first iteration, which would require loop unrolling to get the same effects. While this isn't a hypothetical (it comes up a lot in my PHP compiler) you should certainly never write your code to take this into account. I just thought it might be interesting :)
This function is to convert duration in minutes to readable hours and minutes format. i.e 2h30m. It eliminates the hours if the duration is less than one hour, and shows only the hours if the duration in hours with no extra minutes.
CREATE FUNCTION [dbo].[MinutesToDuration]
(
@minutes int
)
RETURNS nvarchar(30)
AS
BEGIN
declare @hours nvarchar(20)
SET @hours =
CASE WHEN @minutes >= 60 THEN
(SELECT CAST((@minutes / 60) AS VARCHAR(2)) + 'h' +
CASE WHEN (@minutes % 60) > 0 THEN
CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
ELSE
''
END)
ELSE
CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
END
return @hours
END
To use this function :
SELECT dbo.MinutesToDuration(23)
Results: 23m
SELECT dbo.MinutesToDuration(120)
Results: 2h
SELECT dbo.MinutesToDuration(147)
Results: 2h27m
Hope this helps!
You can find some resources related to developing web services client using Apache axis2 here.
http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html
Below posts gives good explanations about developing web services using Apache axis2.
http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/
The main reason you use the default queue over the main queue is to run tasks in the background.
For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
Example of using a Timer
:
using System;
using System.Timers;
static void Main(string[] args)
{
Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
t.AutoReset = true;
t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
t.Start();
}
// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
Console.WriteLine("...");
}
http://phpcodechecker.com/ performs syntax check and a custom check for common errors.
I'm a novice, but it helped me.
Android Support V7 GridLayout library makes excess space distribution easy by accommodating the principle of weight. To make a column stretch, make sure the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity. Remember to add dependency for this library. Add com.android.support:gridlayout-v7:25.0.1 in build.gradle.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="2">
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="First"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="Second"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="Third"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
app:layout_columnWeight="1"
app:layout_rowWeight="1"
android:text="fourth"/>
</android.support.v7.widget.GridLayout>
We faced the same problem:
ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log
In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.
I had to put the statement under the [mysqld] block to make it work. Otherwise the change was not reflected. I have a REL distribution.
Password Protected Zip File
if you want to compress files with password you can take a look at this library that can zip files with password easily:
Zip:
ZipArchive zipArchive = new ZipArchive();
zipArchive.zip(targetPath,destinationPath,password);
Unzip:
ZipArchive zipArchive = new ZipArchive();
zipArchive.unzip(targetPath,destinationPath,password);
Rar:
RarArchive rarArchive = new RarArchive();
rarArchive.extractArchive(file archive, file destination);
The documentation of this library is good enough, I just added a few examples from there. It's totally free and wrote specially for android.
You can create a user using MySQL
like this:
CREATE USER 'username'@'servername' IDENTIFIED BY 'password';
and if you want to do that for a specific database, simply you can write in the MySQL
:
GRANT ALL PRIVILEGES ON database_name.*
TO 'username'@'servername'
IDENTIFIED BY 'password';
Note that it's all one sentence, also note that you need to change:
database_name // your database name
username // any name you want to use as username
servername // the name of your server, for example: localhost
password // any text you want to use as user password
This code help clone methods
class Foo{
private $run=10;
public $foo=array(2,array(2,8));
public function hoo(){return 5;}
public function __clone(){
$this->boo=function(){$this->hoo();};
}
}
$obj=new Foo;
$news= clone $obj;
var_dump($news->hoo());
To avoid x !instance of Long
prob
Add
<property name="openjpa.Compatibility" value="StrictIdentityValues=false"/>
in your persistence.xml
You can hover to .ipython
folder (i.e. you can type $ ipython locate
in your terminal/bash OR CMD.exe Prompt
from your Anaconda Navigator to see where is your ipython is located)
Then, in .ipython
, you will see profile_default
directory which is the default one. This directory will have static/custom/custom.css
file located.
You can now apply change to this custom.css
file. There are a lot of styles in the custom.css
file that you can use or search for. For example, you can see this link (which is my own customize custom.css
file)
Basically, this custom.css
file apply changes to your browser. You can use inspect elements in your ipython notebook to see which elements you want to change. Then, you can changes to the custom.css
file. For example, you can add these chunk to change font in .CodeMirror pre
to type Monaco
.CodeMirror pre {font-family: Monaco; font-size: 9pt;}
Note that now for Jupyter notebook version >= 4.1, the custom css file is moved to ~/.jupyter/custom/custom.css
instead.
How does your .NET Webservice look like?
I had the same effect using ksoap 2.3 from code.google.com. I followed the tutorial on The Code Project (which is great BTW.)
And everytime I used
Integer result = (Integer)envelope.getResponse();
to get the result of a my webservice (regardless of the type, I tried Object, String, int) I ran into the org.ksoap2.serialization.SoapPrimitive
exception.
I found a solution (workaround). The first thing I had to do was to remove the "SoapRpcMethod() attribute from my webservice methods.
[SoapRpcMethod(), WebMethod]
public Object GetInteger1(int i)
{
// android device will throw exception
return 0;
}
[WebMethod]
public Object GetInteger2(int i)
{
// android device will get the value
return 0;
}
Then I changed my Android code to:
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
However, I get a SoapPrimitive object, which has a "value" filed that is private. Luckily the value is passed through the toString()
method, so I use Integer.parseInt(result.toString())
to get my value, which is enough for me, because I don't have any complex types that I need to get from my Web service.
Here is the full source:
private static final String SOAP_ACTION = "http://tempuri.org/GetInteger2";
private static final String METHOD_NAME = "GetInteger2";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:4711/Service1.asmx";
public int GetInteger2() throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("i");
pi.setValue(123);
request.addProperty(pi);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
return Integer.parseInt(result.toString());
}
Sometimes this will be enough:
int colorInt = getResources().getColor(R.color.ColorVerificaLunes);
ColorStateList csl = ColorStateList.valueOf(colorInt);
You can use vh on the min-height property.
min-height: 100vh;
You can do as follows, depending on how you are using the margins...
min-height: calc(100vh - 10px) //Considering you're using some 10px margin top on an outside element
To do this for a specific target, you can do the following:
target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)
You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.
Expanding on the answers provided here.
You can just do set idx = 1
to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1
would not be valid.
This means that you should prefer the syntax: set variable idx = 1
or set var idx = 1
.
Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.
(gdb) p idx = 1
$1 = 1
You can read more about gdb here.
For those of you on AWS (Amazon Web Services), remember to add a rule for your SSL port (in my case 443) to your security groups. I was getting this error because I forgot to open the port.
3 hours of tearing my hair out later...
classes are like blueprints to create objects. Let's make a metaphor with building a house. You have the blueprint of the house so you can build a house. You can build as many houses as your resources allow.
In this metaphor, the blueprint is the class and the house is the instantiation of the class, creating an object.
The houses have common attributes like having a roof, living room, etc. This is where you init method goes. It constructs the object (house) with the attributes you want.
Lets suppose you have:
`class house:`
`roof = True`
`def __init__(self, color):`
`self.wallcolor = color`
>> create little goldlock's house:
>> goldlock = house() #() invoke's class house, not function
>> goldlock.roof
>> True
all house's have roofs, now let's define goldlock's wall color to white:
>> goldlock.wallcolor = 'white'
>>goldlock.wallcolor
>> 'white'
you can also set environment variables in the script itself, rather than passing region_name parameter
os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'
case sensitivity may matter.
If you cannot utilize the ActiveDirectory
Module or the Get-ADGroupMember
cmdlet, you can do it with the LDAP "in chain"-matching rule:
$GroupDN = "CN=MyGroup,OU=Groups,DC=mydomain,DC=tld"
$LDAPFilter = "(&(objectClass=user)(objectCategory=Person)(memberOf:1.2.840.113556.1.4.1941:=$GroupDN))"
# Ideally using an instance of adsisearcher here:
Get-ADObject -LDAPFilter $LDAPFilter
See MSDN for additional LDAP matching rules implemented in Active Directory
My issue was I had this code in my css
html,
body {
height: 100%;
width: 100%;
overflow: auto;
}
Once I removed it, the scroll event on window fired again
This is the slickest solution I've found that works on OSX and Linux, and it works nicely with git too!
find . -name "*.js" -exec bash -c 'mv "$1" "${1%.js}".tsx' - '{}' \;
and with git:
find . -name "*.js" -exec bash -c 'git mv "$1" "${1%.js}".tsx' - '{}' \;
I used:
Get-Content c:\FileToAppend_*.log | Out-File -FilePath C:\DestinationFile.log
-Encoding ASCII -Append
This appended fine. I added the ASCII encoding to remove the nul characters Notepad++ was showing without the explicit encoding.
As it was already mentioned: READONLY
does not work for <input type='checkbox'>
and <select>...</select>
.
If you have a Form
with disabled checkboxes / selects AND need them to be submitted, you can use jQuery:
$('form').submit(function(e) {
$(':disabled').each(function(e) {
$(this).removeAttr('disabled');
})
});
This code removes the disabled
attribute from all elements on submit.
Python >= 2.6 has Abstract Base Classes.
Abstract Base Classes (abbreviated ABCs) complement duck-typing by providing a way to define interfaces when other techniques like hasattr() would be clumsy. Python comes with many builtin ABCs for data structures (in the collections module), numbers (in the numbers module), and streams (in the io module). You can create your own ABC with the abc module.
There is also the Zope Interface module, which is used by projects outside of zope, like twisted. I'm not really familiar with it, but there's a wiki page here that might help.
In general, you don't need the concept of abstract classes, or interfaces in python (edited - see S.Lott's answer for details).
While I think the regex-based solution is probably the way I'd go, I'd be tempted to encapsulate this in a type.
public class AlphaNumericString
{
public AlphaNumericString(string s)
{
Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(s))
{
value = s;
}
else
{
throw new ArgumentException("Only alphanumeric characters may be used");
}
}
private string value;
static public implicit operator string(AlphaNumericString s)
{
return s.value;
}
}
Now, when you need a validated string, you can have the method signature require an AlphaNumericString, and know that if you get one, it is valid (apart from nulls). If someone attempts to pass in a non-validated string, it will generate a compiler error.
You can get fancier and implement all of the equality operators, or an explicit cast to AlphaNumericString from plain ol' string, if you care.
I found a possible solution here: http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15
Edit:
If you automate Microsoft Excel with Microsoft Visual Basic .NET, Microsoft Visual C# .NET, or Microsoft Visual C++, you may receive the following errors when calling certain methods because the machine has the locale set to something other than US English (locale ID or LCID 1033):
Exception from HRESULT: 0x800A03EC
and/or
Old format or invalid type library
SOLUTION 1:
To get around this error you can set CurrentCulture to en-US when executing code related to Excel and reset back to your originale by using these 2 functions.
//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
void SetNewCurrentCulture()
{
oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
//reset Current Culture back to the originale
void ResetCurrentCulture()
{
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}
SOLUTION 2:
Another solution that could work, create a 1033 directory under Microsoft Office\Office11 (or your corresponding office-version), copy excel.exe to the 1033 directory, and rename it to xllex.dll.
Although you might solve the problem using one off these solutions, when you call the Excel object model in locales other than US English, the Excel object model can act differently and your code can fail in ways you may not have thought of. For example, you might have code that sets the value of a range to a date:
yourRange.Value2 = "10/10/09"
Depending on the locale this code can act differently resulting in Excel putting into the range any of the following values:
October 10, 2009 September 10, 2009 October 9, 2010
The sane way to do this is to use zip()
and a List Comprehension / Generator Expression:
filtered = (
(email, other)
for email, other in zip(emails, other_list)
if email == '[email protected]')
new_emails, new_other_list = zip(*filtered)
Also, if your'e not using array.array()
or numpy.array()
, then most likely you are using []
or list()
, which give you Lists, not Arrays. Not the same thing.