You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)
If you pass $element
into a controller, like you would $scope
, you can use its find()
function. Note that, in the jQueryLite included in Angular, find()
will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find()
can be used, including finding by attribute.
So, for this HTML:
<div ng-controller='MyCtrl'>
<div>
<div name='foo' class='myElementClass'>this one</div>
</div>
</div>
This AngularJS code should work:
angular.module('MyClient').controller('MyCtrl', [
'$scope',
'$element',
'$log',
function ($scope, $element, $log) {
// Find the element by its class attribute, within your controller's scope
var myElements = $element.find('.myElementClass');
// myElements is now an array of jQuery DOM elements
if (myElements.length == 0) {
// Not found. Are you sure you've included the full jQuery?
} else {
// There should only be one, and it will be element 0
$log.debug(myElements[0].name); // "foo"
}
}
]);
There are two possible solutions for these kind of situations:
Add a unique suffix to the image src
to force browser downloading it again, like this:
var img = new Image();
img.src = "img.jpg?_="+(new Date().getTime());
img.onload = function () {
alert("image is loaded");
}
In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again
The pygame documentation for mouse events is here. You can either use the pygame.mouse.get_pressed
method in collaboration with the pygame.mouse.get_pos
(if needed). But please use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.
EDIT:
To perform pixel perfect collisions use pygame.sprite.collide_rect()
found on their docs for sprites.
There are so many ways:
You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Collection.update({
_id: parentDocumentId
}, {
$pull: {
subDocument: {
_id: SubDocumentId
}
}
});
This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.
Read more about pull here.
You need to enclose your try-catch
inside a while
loop like this: -
int count = 0;
int maxTries = 3;
while(true) {
try {
// Some Code
// break out of loop, or return, on success
} catch (SomeException e) {
// handle exception
if (++count == maxTries) throw e;
}
}
I have taken count
and maxTries
to avoid running into an infinite loop, in case the exception keeps on occurring in your try block
.
Always use mongoose.Types.ObjectId('your id')
for conditions in your query it will validate the id field before running your query as a result your app will not crash.
The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.
Try using headers to do authentication:
import urllib2, base64
request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662
I am not able to add a comment to M. Kiewisch since I do not have enough reputation points (only have 41 but need more than 50 to comment).
Anyway, just want to point out that M. Kiewisch solution does not work as is and may need more tweaking. Consider for example
>>> df = pd.DataFrame({'a': [1, 2, 3, 5], 'b': [4, np.NaN, 6, 4]})
>>> df
a b
0 1 4.0
1 2 NaN
2 3 6.0
3 5 4.0
>>> df.groupby(['b']).sum()
a
b
4.0 6
6.0 3
>>> df.astype(str).groupby(['b']).sum()
a
b
4.0 15
6.0 3
nan 2
which shows that for group b=4.0, the corresponding value is 15 instead of 6. Here it is just concatenating 1 and 5 as strings instead of adding it as numbers.
On RHEL6.6 only this works (note the use of export
):
/etc/sysconfig/docker
export http_proxy="http://myproxy.example.com:8080"
export https_proxy="http://myproxy.example.com:8080"
NOTE: Both can use the http
protocol.)
I has this error because the git repo was (accidentally) initialised twice on the same location : first as a non-bare repo and shortly after as a bare repo. Because the .git folder remains, git assumes the repository is non-bare. Removing the .git folder and working directory data solved the issue.
Yes, with set_index you can make Locality
your row index.
data.set_index('Locality', inplace=True)
If inplace=True
is not provided, set_index
returns the modified dataframe as a result.
Example:
> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> df
Locality 2005 2006
0 ABBOTSFORD 427000 448000
1 ABERFELDIE 534000 600000
> df.set_index('Locality', inplace=True)
> df
2005 2006
Locality
ABBOTSFORD 427000 448000
ABERFELDIE 534000 600000
> df.loc['ABBOTSFORD']
2005 427000
2006 448000
Name: ABBOTSFORD, dtype: int64
> df.loc['ABBOTSFORD'][2005]
427000
> df.loc['ABBOTSFORD'].values
array([427000, 448000])
> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]
jQuery recently started using source maps.
For example, let's look at the minified jQuery 2.0.3 file's first few lines.
/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/
Excerpt from Introduction to JavaScript Source Maps:
Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.
Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.
emphasis mine
It's incredibly useful, and will only download if the user opens dev tools.
Remove the source mapping line, or do nothing. It isn't really a problem.
Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.
Here is my one liner for this.
file_count=$( shopt -s nullglob ; set -- $directory_to_search_inside/* ; echo $#)
It depends. On MySQL an index is created if you don't create it on your own:
MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created.
Source: https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html
The same for MySQL 5.6 eh.
This is exactly what TO_DATE()
is for: to convert timestamp to date.
Just use TO_DATE(sysdate)
instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS')
.
UPDATE:
Per your update, your cdate
column is not real DATE
or TIMESTAMP
type, but VARCHAR2
. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.
You should convert your cdate
VARCHAR2
field into real TIMESTAMP
. Assuming there are no other users for this field except for your code, you can convert cdate
to timestamp as follows:
BEGIN TRANSACTION;
-- add new temp field tdate:
ALTER TABLE mytable ADD tdate TIMESTAMP;
-- save cdate to tdate while converting it:
UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');
-- you may want to check contents of tdate before next step!!!
-- drop old field
ALTER TABLE mytable DROP COLUMN cdate;
-- rename tdate to cdate:
ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
COMMIT;
Scanner scanner = new Scanner(System.in);
String part = scanner.nextLine();
String line = scanner.nextLine();
String temp = "\\b" + part +"|"+ part + "\\b";
Pattern pattern = Pattern.compile(temp.toLowerCase());
Matcher matcher = pattern.matcher(line.toLowerCase());
System.out.println(matcher.find() ? "YES":"NO");
If you need to determine if any of the words of this text start or end with the sequence. you can use this regex \bsubstring|substring\b anythingsubstring substringanything anythingsubstringanything
This code generates the App Store link on iOS
NSString *appName = [NSString stringWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]];
NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"itms-apps://itunes.com/app/%@",[appName stringByReplacingOccurrencesOfString:@" " withString:@""]]];
Replace itms-apps with http on Mac:
NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"http:/itunes.com/app/%@",[appName stringByReplacingOccurrencesOfString:@" " withString:@""]]];
Open URL on iOS:
[[UIApplication sharedApplication] openURL:appStoreURL];
Mac:
[[NSWorkspace sharedWorkspace] openURL:appStoreURL];
Have you tried to change in Tortoise Settings the status cache to 'Default'? I had this problem with the overlay icon on folders because I had this option in 'Shell'. The option is in Settings -> Icons overlay.
Maybe this could help you http://tortoisesvn.net/node/97
Despite the fact that this is a very old question and probably many of the beforementioned ideas solved many problems, I still want to share the solution with the community that fixed my problem.
I found that the problem was a function called "hasItem" which I was using to check whether or not a JSON-Array contains a specific item. In my case I checked for a value of type Long.
And this led to the problem.
Somehow, the Matchers have problems with values of type Long. (I do not use JUnit or Rest-Assured so much so idk. exactly why, but I guess that the returned JSON-data does just contain Integers.)
So what I did to actually fix the problem was the following. Instead of using:
long ID = ...;
...
.then().assertThat()
.body("myArray", hasItem(ID));
you just have to cast to Integer. So the working code looked like this:
long ID = ...;
...
.then().assertThat()
.body("myArray", hasItem((int) ID));
That's probably not the best solution, but I just wanted to mention that the exception can also be thrown because of wrong/unknown data types.
The best way I see is to use live() or delegate() to capture the event in a parent and not in each child element.
If your button is inside a #parent element, you can replace:
$('#myButton').bind('click', onButtonClicked);
by
$('#parent').delegate('#myButton', 'click', onButtonClicked);
even if #myButton doesn't exist yet when this code is executed.
Use join
:
>>> sentence = ['this', 'is', 'a', 'sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
>>> ' '.join(sentence)
'this is a sentence'
try {
ObjectMapper mapper = new ObjectMapper();
JsonFactory f = new JsonFactory();
List<User> lstUser = null;
JsonParser jp = f.createJsonParser(new File("C:\\maven\\user.json"));
TypeReference<List<User>> tRef = new TypeReference<List<User>>() {};
lstUser = mapper.readValue(jp, tRef);
for (User user : lstUser) {
System.out.println(user.toString());
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can try with this, it worked for me
WebView wb_previewSurvey=new WebView(this);
wb_previewSurvey.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//Required functionality here
return super.onJsAlert(view, url, message, result);
}
});
You name it... Lambda version... :)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;
You need several includes... I leave you that as an exercise...
Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.
In 2.3.2 the collapse
class wasn't getting replaced by the in
class. The in
class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse
class correctly is removed, and the <tr>
collapses.
Use @Chad's solution for the html, and try using these links for referencing Bootstrap:
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
I was having this issue too with SQL Server 2017.
I'm on the same network as the server via VPN and can ping it. After being frustrated that no authentication method would work - I set up an SSH server on the SQL server - and I was able to connect normally. This confirmed the correct port wasn't being hit for some reason. I even created a new user accounts, domain accounts, firewall checks on both ends, etc...
The solution for me was: 1. Set Connection to strictly use TCP/IP on SSMS 2. Use a custom string to point to the default port (ex: Data Source=192.168.168.166,1433;)
All the other comments above haven't worked so far. It looks like it was mandatory to include the port (even though its default).
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
Use the in
keyword to test if a attribute is defined in a object
if (assoc_var in assoc_pagine)
OR
if ("home" in assoc_pagine)
There are quite a few issues here.
Firstly, is var
supposed to a variable has the value "home", "work" or "about"? Or did you mean to inspect actual property called "var"?
If var
is supposed to be a variable that has a string value, please note that var
is a reserved word in JavaScript and you will need to use another name, such as assoc_var
.
var assoc_var = "home";
assoc_pagine[assoc_var] // equals 0 in your example
If you meant to inspect the property called "var", then you simple need to put it inside of quotes.
assoc_pagine["var"]
Then, undefined
is not the same as "undefined"
. You will need typeof
to get the string representation of the objects type.
This is a breakdown of all the steps.
var assoc_var = "home";
var value = assoc_pagine[assoc_var]; // 0
var typeofValue = typeof value; // "number"
So to fix your problem
if (typeof assoc_pagine[assoc_var] != "undefined")
update: As other answers have indicated, using a array is not the best sollution for this problem. Consider using a Object instead.
var assoc_pagine = new Object();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
After some time with Google I asked on the ask ubuntu chat room.
A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:
grep -P "(^|\s)abc(\s|$)"
gives the result I was looking for. -P is an experimental implementation of perl regexps.
grepping for abc
and then using filters like grep -v '@abc'
(this is far from perfect...) should also work, but my patch does something similar.
Basically set up your css like:
element {
border: 1px solid #fff;
transition: border .5s linear;
}
element.saved {
border: 1px solid transparent;
}
I had to stop the apache server first.
(f.e. sudo systemctl stop httpd.service
/ sudo systemctl disable httpd.service
).
That solved my problem besides editing the 'settings.py
' file
to ALLOWED_HOSTS = ['se.rv.er.ip', 'www.example.com']
It is very important to notice that, as of HTML5, <wbr>
and ­
are not supposed to do the same thing!
Soft hyphens
­
is a soft hyphen, i.e., U+00AD: SOFT HYPHEN. For example,
innehålls­förteckning
might be rendered as
innehållsförteckning
or as
innehålls-
förteckning
As of today, soft hyphens work in Firefox, Chrome, and Internet Explorer.
The wbr
element
The wbr
element is a word-break opportunity, which will not display a hyphen if a line break occurs. For example,
ABCDEFG<wbr/>abcdefg
might be rendered as
ABCDEFGabcdefg
or as
ABCDEFG
abcdefg
As of today, this element works in Firefox and Chrome.
You have to make one ajax call to get the required result, in this case you can use Google API to get the same
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false
Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
Another way to toggle:
- (IBAction)signOnClick:(id)sender
{
if ([_signOnButton.titleLabel.text isEqualToString:@"Sign off"])
{
[sender setTitle:@"Sign on" forState:UIControlStateNormal];
}
else
{
[sender setTitle:@"Sign off" forState:UIControlStateNormal];
}
}
I always love solutions that involve categories as they are bolt on and can be easily reused.
So I created a category on UIWindow. You can now call visibleViewController on UIWindow and this will get you the visible view controller by searching down the controller hierarchy. This works if you are using navigation and/or tab bar controller. If you have another type of controller to suggest please let me know and I can add it.
UIWindow+PazLabs.h (header file)
#import <UIKit/UIKit.h>
@interface UIWindow (PazLabs)
- (UIViewController *) visibleViewController;
@end
UIWindow+PazLabs.m (implementation file)
#import "UIWindow+PazLabs.h"
@implementation UIWindow (PazLabs)
- (UIViewController *)visibleViewController {
UIViewController *rootViewController = self.rootViewController;
return [UIWindow getVisibleViewControllerFrom:rootViewController];
}
+ (UIViewController *) getVisibleViewControllerFrom:(UIViewController *) vc {
if ([vc isKindOfClass:[UINavigationController class]]) {
return [UIWindow getVisibleViewControllerFrom:[((UINavigationController *) vc) visibleViewController]];
} else if ([vc isKindOfClass:[UITabBarController class]]) {
return [UIWindow getVisibleViewControllerFrom:[((UITabBarController *) vc) selectedViewController]];
} else {
if (vc.presentedViewController) {
return [UIWindow getVisibleViewControllerFrom:vc.presentedViewController];
} else {
return vc;
}
}
}
@end
Swift Version
public extension UIWindow {
public var visibleViewController: UIViewController? {
return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
}
public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
if let nc = vc as? UINavigationController {
return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
} else if let tc = vc as? UITabBarController {
return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
} else {
if let pvc = vc?.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(pvc)
} else {
return vc
}
}
}
}
i suggest in Javascript:
var item=1387843200000;
var date1=new Date(item);
and then date1 is a Date.
For me, I tried the above. Turns out my USB cable was bad. I changed the cable and then it worked.
you can use
display: normal;
It works as normal.... Its a small hacking in css ;)
You can use the CSS property background-size
and set it to cover
or contain
, depending your preference. Cover will cover the window entirely, while contain will make one side fit the window thus not covering the entire page (unless the aspect ratio of the screen is equal to the image).
Please note that this is a CSS3 property. In older browsers, this property is ignored. Alternatively, you can use javascript to change the CSS settings depending on the window size, but this isn't preferred.
body {
background-image: url(image.jpg); /* image */
background-position: center; /* center the image */
background-size: cover; /* cover the entire window */
}
I ended up doing this in 2 steps. Selected the records I want into a new table in the database then generated a SQL data only script in SSMS. I did find and replace on the generated script and removed the table.
You could use a regex to find out if the String contains a number. Take a look at the matches()
method.
You've got a couple regexes now which will do what you want, so that's adequately covered.
What hasn't been mentioned is why your attempt won't work: Inside a character class, $
(as well as ^
, .
, and /
) has no special meaning, so [/$]
matches either a literal /
or a literal $
rather than terminating the regex (/
) or matching end-of-line ($
).
If you're running a node on localhost, try to use brew service stop elasticsearch
I run elasticsearch on iOS localhost.
In Swift 4, if the image is returned as nil.
Click on image, on the right hand side (Utilities) -> Check Target Membership
Try this:
First change your controller
yourModuleName.controller("yourControllerName", function ($scope) {
var list = [
{ H1:'A', H2:'B', H3:'C', H4:'d' },
{ H1:'E', H2:'B', H3:'F', H4:'G' },
{ H1:'C', H2:'H', H3:'L', H4:'M' },
{ H1:'I', H2:'B', H3:'E', H4:'A' }
];
$scope.list = list;
$scope.headers = ["Header1", "Header2", "Header3", "Header4"];
$scope.sortColumn = 'Header1';
$scope.reverseSort = false;
$scope.sortData = function (columnIndex) {
$scope.reverseSort = ($scope.sortColumn == $scope.headers[columnIndex]) ? !$scope.reverseSort : false;
$scope.sortColumn = $scope.headers[columnIndex];
}
});
then change code in html side like this
<th ng-repeat= "header in headers">
<a ng-click="sortData($index)"> {{headers[$index]}} </a>
</th>
<tr ng-repeat "result in results | orderBy : sortColumn : reverseSort">
<td> {{results.h1}} </td>
<td> {{results.h2}} </td>
<td> {{results.h3}} </td>
<td> {{results.h4}} </td>
</tr>
I adapted the merge
function to get this functionality. On larger dataframes it uses less memory than the full merge solution. And I can play with the names of the key columns.
Another solution is to use the library prob
.
# Derived from src/library/base/R/merge.R
# Part of the R package, http://www.R-project.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of the GNU General Public License is available at
# http://www.r-project.org/Licenses/
XinY <-
function(x, y, by = intersect(names(x), names(y)), by.x = by, by.y = by,
notin = FALSE, incomparables = NULL,
...)
{
fix.by <- function(by, df)
{
## fix up 'by' to be a valid set of cols by number: 0 is row.names
if(is.null(by)) by <- numeric(0L)
by <- as.vector(by)
nc <- ncol(df)
if(is.character(by))
by <- match(by, c("row.names", names(df))) - 1L
else if(is.numeric(by)) {
if(any(by < 0L) || any(by > nc))
stop("'by' must match numbers of columns")
} else if(is.logical(by)) {
if(length(by) != nc) stop("'by' must match number of columns")
by <- seq_along(by)[by]
} else stop("'by' must specify column(s) as numbers, names or logical")
if(any(is.na(by))) stop("'by' must specify valid column(s)")
unique(by)
}
nx <- nrow(x <- as.data.frame(x)); ny <- nrow(y <- as.data.frame(y))
by.x <- fix.by(by.x, x)
by.y <- fix.by(by.y, y)
if((l.b <- length(by.x)) != length(by.y))
stop("'by.x' and 'by.y' specify different numbers of columns")
if(l.b == 0L) {
## was: stop("no columns to match on")
## returns x
x
}
else {
if(any(by.x == 0L)) {
x <- cbind(Row.names = I(row.names(x)), x)
by.x <- by.x + 1L
}
if(any(by.y == 0L)) {
y <- cbind(Row.names = I(row.names(y)), y)
by.y <- by.y + 1L
}
## create keys from 'by' columns:
if(l.b == 1L) { # (be faster)
bx <- x[, by.x]; if(is.factor(bx)) bx <- as.character(bx)
by <- y[, by.y]; if(is.factor(by)) by <- as.character(by)
} else {
## Do these together for consistency in as.character.
## Use same set of names.
bx <- x[, by.x, drop=FALSE]; by <- y[, by.y, drop=FALSE]
names(bx) <- names(by) <- paste("V", seq_len(ncol(bx)), sep="")
bz <- do.call("paste", c(rbind(bx, by), sep = "\r"))
bx <- bz[seq_len(nx)]
by <- bz[nx + seq_len(ny)]
}
comm <- match(bx, by, 0L)
if (notin) {
res <- x[comm == 0,]
} else {
res <- x[comm > 0,]
}
}
## avoid a copy
## row.names(res) <- NULL
attr(res, "row.names") <- .set_row_names(nrow(res))
res
}
XnotinY <-
function(x, y, by = intersect(names(x), names(y)), by.x = by, by.y = by,
notin = TRUE, incomparables = NULL,
...)
{
XinY(x,y,by,by.x,by.y,notin,incomparables)
}
You can use the xmp
element, see What was the <XMP> tag used for?. It has been in HTML since the beginning and is supported by all browsers. Specifications frown upon it, but HTML5 CR still describes it and requires browsers to support it (though it also tells authors not to use it, but it cannot really prevent you).
Everything inside xmp
is taken as such, no markup (tags or character references) is recognized there, except, for apparent reason, the end tag of the element itself, </xmp>
.
Otherwise xmp
is rendered like pre
.
When using “real XHTML”, i.e. XHTML served with an XML media type (which is rare), the special parsing rules do not apply, so xmp
is treated like pre
. But in “real XHTML”, you can use a CDATA section, which implies similar parsing rules. It has no special formatting, so you would probably want to wrap it inside a pre
element:
<pre><![CDATA[
This is a demo, tags like <p> will
appear literally.
]]></pre>
I don’t see how you could combine xmp
and CDATA section to achieve so-called polyglot markup
Example:
.parent-class .flex-control-thumbs li {
width: auto;
float: none;
}
Demo:
.sample-class {
height: 50px;
width: 50px;
background: red;
}
.inner-page .sample-class {
background: green;
}
_x000D_
<div>
<div class="sample-class"></div>
</div>
<div class="inner-page">
<div class="sample-class"></div>
</div>
_x000D_
From $http.get
docs, the second parameter is a configuration object:
get(url, [config]);
Shortcut method to perform
GET
request.
You may change your code to:
$http.get('accept.php', {
params: {
source: link,
category_id: category
}
});
Or:
$http({
url: 'accept.php',
method: 'GET',
params: {
source: link,
category_id: category
}
});
As a side note, since Angular 1.6: .success
should not be used anymore, use .then
instead:
$http.get('/url', config).then(successCallback, errorCallback);
The second method would almost certainly be the fastest way to test whether a null-terminated string is empty, since it involves one read and one comparison. There's certainly nothing wrong with this approach in this case, so you may as well use it.
The third method doesn't check whether a character array is empty; it ensures that a character array is empty.
At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:
<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>
In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.
To get the API key:
1.) Go to https://console.developers.google.com/ Create a new project.
2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.
3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.
4.) Copy the newly generated API key.
To get the folder ID:
1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.
2.) Copy the part after 'folders/', this is your folder ID.
Now put both the API key and folder id in the above code and embed.
Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.
I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.
PHP 5.4 and later have a built-in web server these days.
You simply run the command from the terminal:
cd path/to/your/app
php -S 127.0.0.1:8000
Then in your browser go to http://127.0.0.1:8000
and boom, your system should be up and running. (There must be an index.php or index.html file for this to work.)
You could also add a simple Router
<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
return false; // serve the requested resource as-is.
} else {
require_once('resolver.php');
}
?>
And then run the command
php -S 127.0.0.1:8000 router.php
References:
Simple ---
I have created a Sheet 2 with 4 cells and Sheet 1 with a single Cell with a Formula:
=SUM(Sheet2!B3:E3)
Note, trying as you stated, it does not make sense to assign a Single Cell a value from a range. Send it to a Formula that uses a range to do something with it.
It is a file ext that some folks used for a while to denote that it was PHP generated HTML. As servers like Apache don't care what you use as a file ext as long as it is mapped to something, you could go ahead and call all your PHP files .jimyBobSmith and it would happily run them. PHTML just happened to be a trend that caught on for a while.
You can use the command line cc.rnl ', '
of ConyEdit (a plugin) to replace new lines with the contents you want.
Below code will work ,but first install cors by:
npm install --save cors
Then:
module.exports = function(app) {
var express = require("express");
var cors = require('cors');
var router = express.Router();
app.use(cors());
app.post("/movies",cors(), function(req, res) {
res.send("test");
});
i had the same problem, i added the following lines in build.gradle
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
maven {
url 'http://dl.bintray.com/dev-fingerlinks/maven'
}
mavenCentral()
}
}
Had to solve this myself today. Solved it in C# as I needed it for a program, but I guess it can be esily rewritten. Consider this Public Domain.
public static string GetGitRoot (string file_path) {
file_path = System.IO.Path.GetDirectoryName (file_path);
while (file_path != null) {
if (Directory.Exists (System.IO.Path.Combine (file_path, ".git")))
return file_path;
file_path = Directory.GetParent (file_path).FullName;
}
return null;
}
Try this for Xamarin.Android (Cross Platform)
edittext.EditorAction += (object sender, TextView.EditorActionEventArgs e) {
if (e.ActionId.Equals (global::Android.Views.InputMethods.ImeAction.Done)) {
//TODO Something
}
};
UIImage extension in Swift. You don't need to do all that flipping at all, really. Objective-C original is here, but I've added the bit that respects the alpha of the original image (crudely, but it works to differentiate opaque images from transparent images).
// from https://github.com/mbcharbonneau/UIImage-Categories/blob/master/UIImage%2BAlpha.m
// Returns true if the image has an alpha layer
private func hasAlpha() -> Bool {
guard let cg = self.cgImage else { return false }
let alpha = cg.alphaInfo
let retVal = (alpha == .first || alpha == .last || alpha == .premultipliedFirst || alpha == .premultipliedLast)
return retVal
}
func normalizedImage() -> UIImage? {
if self.imageOrientation == .up {
return self
}
UIGraphicsBeginImageContextWithOptions(self.size, !self.hasAlpha(), self.scale)
var rect = CGRect.zero
rect.size = self.size
self.draw(in: rect)
let retVal = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return retVal
}
That's right. 'list index out of range' most likely means you are referring to n-th
element of the list, while the length of the list is smaller than n
.
$('#mySelect')
.empty()
.append('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected")
;
You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common type are:
Type application
application/java-archive
application/EDI-X12
application/EDIFACT
application/javascript
application/octet-stream
application/ogg
application/pdf
application/xhtml+xml
application/x-shockwave-flash
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
Type audio
audio/mpeg
audio/x-ms-wma
audio/vnd.rn-realaudio
audio/x-wav
Type image
image/gif
image/jpeg
image/png
image/tiff
image/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Type multipart
multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Type text
text/css
text/csv
text/html
text/javascript (obsolete)
text/plain
text/xml
Type video
video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
Type vnd :
application/vnd.android.package-archive
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml
One-to-one: Use a foreign key to the referenced table:
student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
# "link back" if you need
You must also put a unique constraint on the foreign key column (addess.student_id
) to prevent multiple rows in the child table (address
) from relating to the same row in the referenced table (student
).
One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:
teachers: teacher_id, first_name, last_name # the "one" side
classes: class_id, class_name, teacher_id # the "many" side
Many-to-many: Use a junction table (example):
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table
Example queries:
-- Getting all students for a class:
SELECT s.student_id, last_name
FROM student_classes sc
INNER JOIN students s ON s.student_id = sc.student_id
WHERE sc.class_id = X
-- Getting all classes for a student:
SELECT c.class_id, name
FROM student_classes sc
INNER JOIN classes c ON c.class_id = sc.class_id
WHERE sc.student_id = Y
I changed windows password today then Tortoise declined to connect me to SVN server. I got around it by opening a Dos box and doing an "svn co ...". It prompted for the new credential then happily did its work. After that, Tortoise works also.
As I know, there is no direct support, but you can use plain-ol' javascript for that:
// Cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Execute
. example.txt
That does exactly what you ask for, without setting an executable flag on the file or running an extra bash instance.
For a detailed explanation see e.g. https://unix.stackexchange.com/questions/43882/what-is-the-difference-between-sourcing-or-source-and-executing-a-file-i
If you're using Visual C#, all you need to do is add a class in Program.cs inheriting Form and change all the inherited class from Form to your class in every Form*.cs.
//Program.cs
public class Forms : Form
{
//Declare your global valuables here.
}
//Form1.cs
public partial class Form1 : Forms //Change from Form to Forms
{
//...
}
Of course, there might be a way to extending the class Form without modifying it. If that's the case, all you need to do is extending it! Since all the forms are inheriting it by default, so all the valuables declared in it will become global automatically! Good luck!!!
It might be a bit of an overkill, but I wrote an extension method, so you can do a LeftJoin
using the Join
syntax (at least in method call notation):
persons.LeftJoin(
phoneNumbers,
person => person.Id,
phoneNumber => phoneNumber.PersonId,
(person, phoneNumber) => new
{
Person = person,
PhoneNumber = phoneNumber?.Number
}
);
My code does nothing more than adding a GroupJoin
and a SelectMany
call to the current expression tree. Nevertheless, it looks pretty complicated because I have to build the expressions myself and modify the expression tree specified by the user in the resultSelector
parameter to keep the whole tree translatable by LINQ-to-Entities.
public static class LeftJoinExtension
{
public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
this IQueryable<TOuter> outer,
IQueryable<TInner> inner,
Expression<Func<TOuter, TKey>> outerKeySelector,
Expression<Func<TInner, TKey>> innerKeySelector,
Expression<Func<TOuter, TInner, TResult>> resultSelector)
{
MethodInfo groupJoin = typeof (Queryable).GetMethods()
.Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
.MakeGenericMethod(typeof (TOuter), typeof (TInner), typeof (TKey), typeof (LeftJoinIntermediate<TOuter, TInner>));
MethodInfo selectMany = typeof (Queryable).GetMethods()
.Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
.MakeGenericMethod(typeof (LeftJoinIntermediate<TOuter, TInner>), typeof (TInner), typeof (TResult));
var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> {OneOuter = oneOuter, ManyInners = manyInners});
MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);
var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
(t => t.ManyInners.DefaultIfEmpty());
ParameterExpression paramUser = resultSelector.Parameters.First();
ParameterExpression paramNew = Expression.Parameter(typeof (LeftJoinIntermediate<TOuter, TInner>), "t");
MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");
LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body), paramNew, resultSelector.Parameters.Skip(1).First());
MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);
return outer.Provider.CreateQuery<TResult>(exprSelectMany);
}
private class LeftJoinIntermediate<TOuter, TInner>
{
public TOuter OneOuter { get; set; }
public IEnumerable<TInner> ManyInners { get; set; }
}
private class Replacer : ExpressionVisitor
{
private readonly ParameterExpression _oldParam;
private readonly Expression _replacement;
public Replacer(ParameterExpression oldParam, Expression replacement)
{
_oldParam = oldParam;
_replacement = replacement;
}
public override Expression Visit(Expression exp)
{
if (exp == _oldParam)
{
return _replacement;
}
return base.Visit(exp);
}
}
}
As Peter Mortensen wrote:
In the Visual Studio 2005 menu:
Debug -> New Breakpoint -> New Data Breakpoint
Enter: &myVariable
Additional information:
Obviously, the system must know which address in memory to watch.
So
- set a normal breakpoint to the initialisation of myVariable
(or myClass.m_Variable
)
- run the system and wait till it stops at that breakpoint.
- Now the Menu entry is enabled, and you can watch the variable by entering &myVariable
,
or the instance by entering &myClass.m_Variable
. Now the addresses are well defined.
Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this.
I think op wants to know what the font that is used on a webpage is, and hoped that info might be findable in the 'inspect' pane.
Try adding the Whatfont Chrome extension.
You can delete IDEA configuration directory to reset everything to the defaults. If you want to reset the editor Colors&Fonts, then just switch the scheme to Default.
You need to change the default layout type of top level QWidget object from Break layout type to other layout types (Vertical Layout, Horizontal Layout, Grid Layout, Form Layout). For example:
To something like this:
jQuery used to ONLY have the callback functions for success
and error
and complete
.
Then, they decided to support promises with the jqXHR object and that's when they added .done()
, .fail()
, .always()
, etc... in the spirit of the promise API. These new methods serve much the same purpose as the callbacks but in a different form. You can use whichever API style works better for your coding style.
As people get more and more familiar with promises and as more and more async operations use that concept, I suspect that more and more people will move to the promise API over time, but in the meantime jQuery supports both.
The .success()
method has been deprecated in favor of the common promise object method names.
From the jQuery doc, you can see how various promise methods relate to the callback types:
jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.
In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {}); Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.
If you want to code in a way that is more compliant with the ES6 Promises standard, then of these four options you would only use .then()
.
Coming late to this party, but I recently implemented this with a dedicated section in a config file for a list:
[paths]
path1 = /some/path/
path2 = /another/path/
...
and using config.items( "paths" )
to get an iterable list of path items, like so:
path_items = config.items( "paths" )
for key, path in path_items:
#do something with path
Hope this helps other folk Googling this question ;)
Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:
$.ajax({
type: "POST",
url: "index.php",
dataType: "json",
data: JSON.stringify({ paramName: info }),
success: function(msg){
$('.answer').html(msg);
}
});
You just need to make sure you include the JSON2.js file in your page...
It boggles my mind why so may people write the increment expression in for-loop as i++.
In a for-loop, when the 3rd component is a simple increment statement, as in
for (i=0; i<x; i++)
or
for (i=0; i<x; ++i)
there is no difference in the resulting executions.
I noticed one answer that was similar, but in my case I used the IIS Configured Editor to find the section I wanted to "unlock".
Then I copied the path and used it in my automation to unlock it prior to changing the sections I wanted to edit.
. "$($env:windir)\system32\inetsrv\appcmd" unlock config -section:system.webServer/security/authentication/windowsAuthentication
. "$($env:windir)\system32\inetsrv\appcmd" unlock config -section:system.webServer/security/authentication/anonymousAuthentication
People have suggested piping the output of git ls-files
to git add
but this is going to fail in cases where there are filenames containing white space or glob characters such as *
.
The safe way would be to use:
git ls-files -o --exclude-standard -z | xargs -0 git add
where -z
tells git to use \0
line terminators and -0
tells xargs the same. The only disadvantage of this approach is that the -0
option is non-standard, so only some versions of xargs
support it.
The default behavior of Commit PL/SQL block:
You should explicitly commit or roll back every transaction. Whether you issue the commit or rollback in your PL/SQL program or from a client program depends on the application logic. If you do not commit or roll back a transaction explicitly, the client environment determines its final state.
For example, in the SQLPlus environment, if your PL/SQL block does not include a COMMIT or ROLLBACK statement, the final state of your transaction depends on what you do after running the block. If you execute a data definition, data control, or COMMIT statement or if you issue the EXIT, DISCONNECT, or QUIT command, Oracle commits the transaction. If you execute a ROLLBACK statement or abort the SQLPlus session, Oracle rolls back the transaction.
https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/sqloperations.htm#i7105
You should use Comparable instead of a Comparator if a default sort is what your looking for.
See here, this may be of some help - When should a class be Comparable and/or Comparator?
Try this -
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestSort {
public static void main(String args[]){
ToSort toSort1 = new ToSort(new Float(3), "3");
ToSort toSort2 = new ToSort(new Float(6), "6");
ToSort toSort3 = new ToSort(new Float(9), "9");
ToSort toSort4 = new ToSort(new Float(1), "1");
ToSort toSort5 = new ToSort(new Float(5), "5");
ToSort toSort6 = new ToSort(new Float(0), "0");
ToSort toSort7 = new ToSort(new Float(3), "3");
ToSort toSort8 = new ToSort(new Float(-3), "-3");
List<ToSort> sortList = new ArrayList<ToSort>();
sortList.add(toSort1);
sortList.add(toSort2);
sortList.add(toSort3);
sortList.add(toSort4);
sortList.add(toSort5);
sortList.add(toSort6);
sortList.add(toSort7);
sortList.add(toSort8);
Collections.sort(sortList);
for(ToSort toSort : sortList){
System.out.println(toSort.toString());
}
}
}
public class ToSort implements Comparable<ToSort> {
private Float val;
private String id;
public ToSort(Float val, String id){
this.val = val;
this.id = id;
}
@Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
@Override
public String toString(){
return this.id;
}
}
Preamble: Since Spring-Security 3.2 there is a nice annotation @AuthenticationPrincipal
described at the end of this answer. This is the best way to go when you use Spring-Security >= 3.2.
When you:
HandlerMethodArgumentResolver
or WebArgumentResolver
can solve this in an elegant way, or just want to an learn the background behind @AuthenticationPrincipal
and AuthenticationPrincipalArgumentResolver
(because it is based on a HandlerMethodArgumentResolver
)then keep on reading — else just use @AuthenticationPrincipal
and thank to Rob Winch (Author of @AuthenticationPrincipal
) and Lukas Schmelzeisen (for his answer).
(BTW: My answer is a bit older (January 2012), so it was Lukas Schmelzeisen that come up as the first one with the @AuthenticationPrincipal
annotation solution base on Spring Security 3.2.)
Then you can use in your controller
public ModelAndView someRequestHandler(Principal principal) {
User activeUser = (User) ((Authentication) principal).getPrincipal();
...
}
That is ok if you need it once. But if you need it several times its ugly because it pollutes your controller with infrastructure details, that normally should be hidden by the framework.
So what you may really want is to have a controller like this:
public ModelAndView someRequestHandler(@ActiveUser User activeUser) {
...
}
Therefore you only need to implement a WebArgumentResolver
. It has a method
Object resolveArgument(MethodParameter methodParameter,
NativeWebRequest webRequest)
throws Exception
That gets the web request (second parameter) and must return the User
if its feels responsible for the method argument (the first parameter).
Since Spring 3.1 there is a new concept called HandlerMethodArgumentResolver
. If you use Spring 3.1+ then you should use it. (It is described in the next section of this answer))
public class CurrentUserWebArgumentResolver implements WebArgumentResolver{
Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
if(methodParameter is for type User && methodParameter is annotated with @ActiveUser) {
Principal principal = webRequest.getUserPrincipal();
return (User) ((Authentication) principal).getPrincipal();
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
You need to define the Custom Annotation -- You can skip it if every instance of User should always be taken from the security context, but is never a command object.
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ActiveUser {}
In the configuration you only need to add this:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
id="applicationConversionService">
<property name="customArgumentResolver">
<bean class="CurrentUserWebArgumentResolver"/>
</property>
</bean>
@See: Learn to customize Spring MVC @Controller method arguments
It should be noted that if you're using Spring 3.1, they recommend HandlerMethodArgumentResolver over WebArgumentResolver. - see comment by Jay
HandlerMethodArgumentResolver
for Spring 3.1+public class CurrentUserHandlerMethodArgumentResolver
implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return
methodParameter.getParameterAnnotation(ActiveUser.class) != null
&& methodParameter.getParameterType().equals(User.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
if (this.supportsParameter(methodParameter)) {
Principal principal = webRequest.getUserPrincipal();
return (User) ((Authentication) principal).getPrincipal();
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
In the configuration, you need to add this
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="CurrentUserHandlerMethodArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
@See Leveraging the Spring MVC 3.1 HandlerMethodArgumentResolver interface
Spring Security 3.2 (do not confuse with Spring 3.2) has own build in solution: @AuthenticationPrincipal
(org.springframework.security.web.bind.annotation.AuthenticationPrincipal
) . This is nicely described in Lukas Schmelzeisen`s answer
It is just writing
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
...
}
To get this working you need to register the AuthenticationPrincipalArgumentResolver
(org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver
) : either by "activating" @EnableWebMvcSecurity
or by registering this bean within mvc:argument-resolvers
- the same way I described it with may Spring 3.1 solution above.
@See Spring Security 3.2 Reference, Chapter 11.2. @AuthenticationPrincipal
It works like the Spring 3.2 solution, but in Spring 4.0 the @AuthenticationPrincipal
and AuthenticationPrincipalArgumentResolver
was "moved" to an other package:
org.springframework.security.core.annotation.AuthenticationPrincipal
org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver
(But the old classes in its old packges still exists, so do not mix them!)
It is just writing
import org.springframework.security.core.annotation.AuthenticationPrincipal;
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
...
}
To get this working you need to register the (org.springframework.security.web.method.annotation.
) AuthenticationPrincipalArgumentResolver
: either by "activating" @EnableWebMvcSecurity
or by registering this bean within mvc:argument-resolvers
- the same way I described it with may Spring 3.1 solution above.
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
@See Spring Security 5.0 Reference, Chapter 39.3 @AuthenticationPrincipal
JQUERY INR v1.2
A simple jQuery plug-in for convert Rs. to standard Indian rupee symbol through out the web page. Simple to use and simple instillation
The Indian Rupee sign is the currency sign: ? for the Indian Rupee, the official currency of India. Designed by D. Udaya Kumar, it was presented to the public by the Government of India on 15 July 2010,[1] following its selection through an “open” competition among Indian residents. Before its adoption, the most commonly used symbols for the rupee were Rs, Re or, if the text was in an Indian language, an appropriate abbreviation in that language. The new sign relates solely to the Indian rupee; other countries that use a rupee, such as Sri Lanka, Pakistan and Nepal, still use the generic U+20A8 ? rupee sign character. The design resembles both the Devanagari letter "?" (ra) and the Latin capital letter "R", with a double horizontal line at the top.
Instillation:
Include jQuery min and jQuery Ui to your page first
eg: NB: use jQuery stable version only
include the “indianRupee_v1.2.js” and “indianRupee_ctrl.js” after the jQuery library eg:
Use Span tag to wrap Rs through out the web it will replace with the symbol eg: Rs 1280000/-
Source:
Pay Him Rs 1280000/-
Pay Him Rs 528500/-
Pay Him Rs 1250/-
Result:
http://romy.theqtl.com/rupeePlugin/
Plug-in Options:
$("body").indianRupee({ targets:"span",// use as default we can also use [p, div, h1 , li etc...] vector:"on"//[on/off] of [true/false] NB: {vector not support in Internet Explore } });
Ilmari Karonen has good advice, and I'd just like to generalize it a bit. In general, before you ask "how can I get a computer to do this?" ask "how would I do this?"
So, if someone gave you an empty Word document and asked you to create the triangles, how would you go about doing it? Whatever solution you come up with, it's usually not hard to translate it to Java (or any other programming language). It might not be the best solution, but (hopefully!) it'll work, and it may point you to a better solution.
So for instance, maybe you would say that you'd type out the base, then go up a line, then type the next highest line, etc. That suggests that you can do the same in Java -- create a list of Strings, base-to-top, and then reverse them. That might suggest that you can just create them in reverse order, and then not have to reverse them. And then that might suggest that you don't need the list anymore, since you'll just be creating and printing them out in the same order -- at which point you've come up with essentially Ilmari Karonen's advice.
Or, maybe you'd come up with another way of doing it -- maybe you'd come up with Ilmari Karonen's idea more directly. Regardless, it should help you solve this and many other problems.
* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080' ^^^^^
The https://
is wrong, it should be http://
. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.
CD E:\Documents and Settings\All Users\Application Data
E:\Documents and Settings\All Users\Application Data>REGSVR32 xyz.dll
Running two instances of adb (eg eclipse debugger and android studio) at same time causes conflicts as this too
This problem appears when you have a path or a property containing a space and that is not quoted.
All your properties and path have quote around them, it's strange. The error message indicates Education
as a switch, try to remove /p:ProductName="Total Education TEST"
to see if it works.
If you are trying to access the variable from another PHP file directly, you can include that file with include()
or include_once()
, giving you access to that variable. Note that this will include the entire first file in the second file.
Arrays in C++ are very different from those in Java in that they are completely unmanaged. The compiler or run-time have no idea whatsoever what size the array is.
The information is only known at compile-time if the size is defined in the declaration:
char array[256];
In this case, sizeof(array) gives you the proper size.
If you use a pointer as an array however, the "array" will just be a pointer, and sizeof will not give you any information about the actual size of the array.
STL offers a lot of templates that allow you to have arrays, some of them with size information, some of them with variable sizes, and most of them with good accessors and bounds checking.
I know there are a lot of answers already, but these are the steps that worked for me:
git fetch <remote_name> <branch_name>
git branch <branch_name> FETCH_HEAD
git checkout <branch_name>
These are based on the answer by @Abdulsattar Mohammed, the comment by @Christoph on that answer, and these other stack overflow questions and their answers:
If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html
If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/
Your question "what are they" is already answered above.
As far as debugging (your second question) though, and in developing libraries where you want to check for special input values, you may find the following functions useful in Windows C++:
_isnan(), _isfinite(), and _fpclass()
On Linux/Unix you should find isnan(), isfinite(), isnormal(), isinf(), fpclassify() useful (and you may need to link with libm by using the compiler flag -lm).
I know there is already an answer - and this is an old question - but I was wondering the same thing and after finding this answer I did a little experimentation on my own and had (IMO) a worthwhile addition to the discussion.
The non-visible characters can still be used in a folder name - a placeholder is inserted - but the sort on ASCII value still seems to hold.
I tested on Windows7, holding down the alt-key and typing in the ASCII code using the numeric keypad. I did not test very many, but was successful creating foldernames that started with ASCII 1, ASCII 2, and ASCII 3. Those correspond with SOH, STX and ETX. Respectively it displayed happy face, filled happy face, and filled heart.
I'm not sure if I can duplicate that here - but I will type them in on the next lines and submit.
?foldername
?foldername
?foldername
How about just doing some linq queries against your dictionary, and then binding your graph to the results of those?...
var under = colStates.Where(c => (decimal)c.Value / (decimal)totalCount < .05M);
var over = colStates.Where(c => (decimal)c.Value / (decimal)totalCount >= .05M);
var newColStates = over.Union(new Dictionary<string, int>() { { "Other", under.Sum(c => c.Value) } });
foreach (var item in newColStates)
{
Console.WriteLine("{0}:{1}", item.Key, item.Value);
}
Editor's Note: All functions in JavaScript are closures as explained in this post. However we are only interested in identifying a subset of these functions which are interesting from a theoretical point of view. Henceforth any reference to the word closure will refer to this subset of functions unless otherwise stated.
A simple explanation for closures:
Now let's use this to figure out who uses closures and who doesn't (for the sake of explanation I have named the functions):
Case 1: Your Friend's Program
for (var i = 0; i < 10; i++) {
(function f() {
var i2 = i;
setTimeout(function g() {
console.log(i2);
}, 1000);
})();
}
In the above program there are two functions: f
and g
. Let's see if they are closures:
For f
:
i2
is a local variable.i
is a free variable.setTimeout
is a free variable.g
is a local variable.console
is a free variable.i
is bound to the global scope.setTimeout
is bound to the global scope.console
is bound to the global scope.i
is not closed over by f
.setTimeout
is not closed over by f
.console
is not closed over by f
.Thus the function f
is not a closure.
For g
:
console
is a free variable.i2
is a free variable.console
is bound to the global scope.i2
is bound to the scope of f
.setTimeout
.
console
is not closed over by g
.i2
is closed over by g
.Thus the function g
is a closure for the free variable i2
(which is an upvalue for g
) when it's referenced from within setTimeout
.
Bad for you: Your friend is using a closure. The inner function is a closure.
Case 2: Your Program
for (var i = 0; i < 10; i++) {
setTimeout((function f(i2) {
return function g() {
console.log(i2);
};
})(i), 1000);
}
In the above program there are two functions: f
and g
. Let's see if they are closures:
For f
:
i2
is a local variable.g
is a local variable.console
is a free variable.console
is bound to the global scope.console
is not closed over by f
.Thus the function f
is not a closure.
For g
:
console
is a free variable.i2
is a free variable.console
is bound to the global scope.i2
is bound to the scope of f
.setTimeout
.
console
is not closed over by g
.i2
is closed over by g
.Thus the function g
is a closure for the free variable i2
(which is an upvalue for g
) when it's referenced from within setTimeout
.
Good for you: You are using a closure. The inner function is a closure.
So both you and your friend are using closures. Stop arguing. I hope I cleared the concept of closures and how to identify them for the both of you.
Edit: A simple explanation as to why are all functions closures (credits @Peter):
First let's consider the following program (it's the control):
lexicalScope();_x000D_
_x000D_
function lexicalScope() {_x000D_
var message = "This is the control. You should be able to see this message being alerted.";_x000D_
_x000D_
regularFunction();_x000D_
_x000D_
function regularFunction() {_x000D_
alert(eval("message"));_x000D_
}_x000D_
}
_x000D_
lexicalScope
and regularFunction
aren't closures from the above definition.message
to be alerted because regularFunction
is not a closure (i.e. it has access to all the variables in its parent scope - including message
).message
is indeed alerted.Next let's consider the following program (it's the alternative):
var closureFunction = lexicalScope();_x000D_
_x000D_
closureFunction();_x000D_
_x000D_
function lexicalScope() {_x000D_
var message = "This is the alternative. If you see this message being alerted then in means that every function in JavaScript is a closure.";_x000D_
_x000D_
return function closureFunction() {_x000D_
alert(eval("message"));_x000D_
};_x000D_
}
_x000D_
closureFunction
is a closure from the above definition.message
not to be alerted because closureFunction
is a closure (i.e. it only has access to all its non-local variables at the time the function is created (see this answer) - this does not include message
).message
is actually being alerted.What do we infer from this?
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
var results = from DataRow myRow in myDataTable.Rows
where (int)myRow["RowNo"] == 1
select myRow
it turns out that I got this error because my requested module is not bundled in the minification prosses
due to path misspelling
so make sure that your module exists in minified js file (do search for a word within it to be sure)
Use DATE_FORMAT
select DATE_FORMAT(date,'%d') from tablename =>Date only
example:
select DATE_FORMAT(`date_column`,'%d') from `database_name`.`table_name`;
First off:
public class ProfileCollection implements Iterable<Profile> {
Second:
return m_Profiles.get(m_ActiveProfile);
The method GetFileNameWithoutExtension
, as the name implies, does not return the extension on the file. In your case, it would only return "a". You want to append your ".Jpeg" to that result. However, at a different level, this seems strange, as image files have different metadata and cannot be converted so easily.
Well, data.str().c_str()
yields a char const*
but your function Printfunc()
wants to have char*
s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be
void Printfunc(int a, char const* loc, char const* stream)
The alternative might be to turn the char const*
into a char*
but fixing the declaration is preferable:
Printfunc(num, addr, const_cast<char*>(data.str().c_str()));
If you want to create a new A
you can use INTO
;
select * into A from dbo.myView
The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch'
ref using any Git client tool".
The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>
. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>
; it lies to the git client.
Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH>
refs.
When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].
After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>
. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository
.
set scan off; Above command also works.
I had this problem in two projects. Maven and command line worked as expected for both. The problems were Eclipse specific. Two different solutions: Project 1): Move the main method declaration to the top within the class, above all other declarations like fields and constructors. Crazy, but it worked. Project 2): The solution for Project 1) did not remedy the problem. However, removing lombok imports and explicitly writing a getter method solved the problem
Conclusion: Eclipse and/or the lombok plugin have/has a bug.
Use the View's post method like this
post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "width " + MyView.this.getMeasuredWidth());
}
});
There is another error with the forwars=d slash.
if we get this : def get_x(r): return path/'train'/r['fname']
is the same as def get_x(r): return path + 'train' + r['fname']
Well you missed quotation mark around your string selectcard
it should be "selectcard"
if (card.value == selectcard)
should be
if (card.value == "selectcard")
Here is complete code for that
function validate()
{
var ddl = document.getElementById("cardtype");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "selectcard")
{
alert("Please select a card type");
}
}
You should group by the field you want the SUM apply to, and not include in SELECT any field other than multiple rows values, like COUNT, SUM, AVE, etc, because if you include Bill field like in this case, only the first value in the set of rows will be displayed, being almost meaningless and confusing.
This will return the sum of bills per account number:
SELECT SUM(Bill) FROM Table1 GROUP BY AccountNumber
You could add more clauses like WHERE, ORDER BY etc as needed.
I eventually shut-down and restarted Microsoft SQL Server Management Studio; and that fixed it for me. But at other times, just starting a new query window was enough.
You should try the following:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);?
result
1234561613213213
If you are trying to simply return a string to a View, try this:
public string Test()
{
return "test";
}
This will return a view with the word test in it. You can insert some html in the string.
You can also try this:
public ActionResult Index()
{
return Content("<html><b>test</b></html>");
}
I made a procedure that execute a FOREACH
with CURSOR
for any table.
Example of use:
CREATE TABLE #A (I INT, J INT)
INSERT INTO #A VALUES (1, 2), (2, 3)
EXEC PRC_FOREACH
#A --Table we want to do the FOREACH
, 'SELECT @I, @J' --The execute command, each column becomes a variable in the same type, so DON'T USE SPACES IN NAMES
--The third variable is the database, it's optional because a table in TEMPB or the DB of the proc will be discovered in code
The result is 2 selects for each row.
The syntax of UPDATE
and break the FOREACH
are written in the hints.
This is the proc code:
CREATE PROC [dbo].[PRC_FOREACH] (@TBL VARCHAR(100) = NULL, @EXECUTE NVARCHAR(MAX)=NULL, @DB VARCHAR(100) = NULL) AS BEGIN
--LOOP BETWEEN EACH TABLE LINE
IF @TBL + @EXECUTE IS NULL BEGIN
PRINT '@TBL: A TABLE TO MAKE OUT EACH LINE'
PRINT '@EXECUTE: COMMAND TO BE PERFORMED ON EACH FOREACH TRANSACTION'
PRINT '@DB: BANK WHERE THIS TABLE IS (IF NOT INFORMED IT WILL BE DB_NAME () OR TEMPDB)' + CHAR(13)
PRINT 'ROW COLUMNS WILL VARIABLE WITH THE SAME NAME (COL_A = @COL_A)'
PRINT 'THEREFORE THE COLUMNS CANT CONTAIN SPACES!' + CHAR(13)
PRINT 'SYNTAX UPDATE:
UPDATE TABLE
SET COL = NEW_VALUE
WHERE CURRENT OF MY_CURSOR
CLOSE CURSOR (BEFORE ALL LINES):
IF 1 = 1 GOTO FIM_CURSOR'
RETURN
END
SET @DB = ISNULL(@DB, CASE WHEN LEFT(@TBL, 1) = '#' THEN 'TEMPDB' ELSE DB_NAME() END)
--Identifies the columns for the variables (DECLARE and INTO (Next cursor line))
DECLARE @Q NVARCHAR(MAX)
SET @Q = '
WITH X AS (
SELECT
A = '', @'' + NAME
, B = '' '' + type_name(system_type_id)
, C = CASE
WHEN type_name(system_type_id) IN (''VARCHAR'', ''CHAR'', ''NCHAR'', ''NVARCHAR'') THEN ''('' + REPLACE(CONVERT(VARCHAR(10), max_length), ''-1'', ''MAX'') + '')''
WHEN type_name(system_type_id) IN (''DECIMAL'', ''NUMERIC'') THEN ''('' + CONVERT(VARCHAR(10), precision) + '', '' + CONVERT(VARCHAR(10), scale) + '')''
ELSE ''''
END
FROM [' + @DB + '].SYS.COLUMNS C WITH(NOLOCK)
WHERE OBJECT_ID = OBJECT_ID(''[' + @DB + '].DBO.[' + @TBL + ']'')
)
SELECT
@DECLARE = STUFF((SELECT A + B + C FROM X FOR XML PATH('''')), 1, 1, '''')
, @INTO = ''--Read the next line
FETCH NEXT FROM MY_CURSOR INTO '' + STUFF((SELECT A + '''' FROM X FOR XML PATH('''')), 1, 1, '''')'
DECLARE @DECLARE NVARCHAR(MAX), @INTO NVARCHAR(MAX)
EXEC SP_EXECUTESQL @Q, N'@DECLARE NVARCHAR(MAX) OUTPUT, @INTO NVARCHAR(MAX) OUTPUT', @DECLARE OUTPUT, @INTO OUTPUT
--PREPARE TO QUERY
SELECT
@Q = '
DECLARE ' + @DECLARE + '
-- Cursor to scroll through object names
DECLARE MY_CURSOR CURSOR FOR
SELECT *
FROM [' + @DB + '].DBO.[' + @TBL + ']
-- Opening Cursor for Reading
OPEN MY_CURSOR
' + @INTO + '
-- Traversing Cursor Lines (While There)
WHILE @@FETCH_STATUS = 0
BEGIN
' + @EXECUTE + '
-- Reading the next line
' + @INTO + '
END
FIM_CURSOR:
-- Closing Cursor for Reading
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR'
EXEC SP_EXECUTESQL @Q --MAGIA
END
Dim a As Range, b As Range
Set a = Selection
For Each b In a.Rows
MsgBox b.Address
Next
The answer by Tony Andrews is a decent one. But the real answer is that this has been a convention used by relational database community and is NOT a necessity. Maybe it is a good convention, maybe not.
Comparing anything to NULL results in UNKNOWN (3rd truth value). So as has been suggested with nulls all traditional wisdom concerning equality goes out the window. Well that's how it seems at first glance.
But I don't think this is necessarily so and even SQL databases don't think that NULL destroys all possibility for comparison.
Run in your database the query SELECT * FROM VALUES(NULL) UNION SELECT * FROM VALUES(NULL)
What you see is just one tuple with one attribute that has the value NULL. So the union recognized here the two NULL values as equal.
When comparing a composite key that has 3 components to a tuple with 3 attributes (1, 3, NULL) = (1, 3, NULL) <=> 1 = 1 AND 3 = 3 AND NULL = NULL The result of this is UNKNOWN.
But we could define a new kind of comparison operator eg. ==. X == Y <=> X = Y OR (X IS NULL AND Y IS NULL)
Having this kind of equality operator would make composite keys with null components or non-composite key with null value unproblematic.
In Python 3.4 pathlib was introduced:
>>> from pathlib import Path
>>> p = Path('/etc/usr/lib')
>>> p
PosixPath('/etc/usr/lib')
>>> p.parent
PosixPath('/etc/usr')
It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.
For more information refer to the docs or this blog post, which covers the differences between os.path and pathlib.
You are using wrong JSON. In this case you should use JSON that looks like this:
["orange", "apple"]
If you have to accept JSON in that form :
{"fruits":["apple","orange"]}
You'll have to create wrapper object:
public class FruitWrapper{
List<String> fruits;
//getter
//setter
}
and then your controller method should look like this:
@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,
consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}
An alternative solution is using an external table: http://www.orafaq.com/node/848
Use this when you have to do this import very often and very fast.
Haven't tried it, but Elcomsoft released a product they claim is capable of decrypting backups, for forensics purposes. Maybe not as cool as engineering a solution yourself, but it might be faster.
TxtFarmerSize.Text = (int)reader[3];
ALTER TABLE tableName MODIFY tableNameID MEDIUMINT NOT NULL AUTO_INCREMENT;
Here tableName is name of your table,
tableName is your column name which is primary has to be modified
MEDIUMINT is a data type of your existing primary key
AUTO_INCREMENT you have to add just auto_increment after not null
It will make that primary key auto_increment......
Hope this is helpful:)
Replacing -ObjC
with $(inherited)
in Other Linker Flags
fixed my problem
You can execute commands in parallel with start
like this:
start "" ping myserver
start "" nslookup myserver
start "" morecommands
They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.
Hope this helps!
try this
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();
In JavaScript,...
null == undefined
...returns true
*. It's the difference between ==
and ===
. Also, the name undefined
can be defined (it's not a keyword like null
is) so you're better off checking some other way. The most reliable way is probably to compare the return value of the typeof
operator.
typeof o == "undefined"
Nevertheless, comparing to null should work in this case.
* Assuming undefined
is in fact undefined.
reference : https://stackoverflow.com/a/6438240/2624806
Following worked far better.
mObservableScrollView.post(new Runnable() {
public void run() {
mObservableScrollView.fullScroll([View_FOCUS][1]);
}
});
Creating and destroying the connections in each query maybe complicated, i had some headaches with a server migration when i decided to install MariaDB instead MySQL. For some reason in the file etc/my.cnf the parameter wait_timeout had a default value of 10 sec (it causes that the persistence can't be implemented). Then, the solution was set it in 28800, that's 8 hours. Well, i hope help somebody with this "güevonada"... excuse me for my bad english.
What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient
request.
At worst, it won't work.
Looking for the possibility to put a powershell script into a batch file, I found this thread. The idea of walid2mi did not worked 100% for my script. But via a temporary file, containing the script it worked out. Here is the skeleton of the batch file:
;@echo off
;setlocal ENABLEEXTENSIONS
;rem make from X.bat a X.ps1 by removing all lines starting with ';'
;Findstr -rbv "^[;]" %0 > %~dpn0.ps1
;powershell -ExecutionPolicy Unrestricted -File %~dpn0.ps1 %*
;del %~dpn0.ps1
;endlocal
;goto :EOF
;rem Here start your power shell script.
param(
,[switch]$help
)
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec
.
If you're still here, the following discussion should hopefully reveal why. When you run, say,
sh -c 'command'
you run a sh
instance, then start command
as a child of that sh
instance. When command
finishes, the sh
instance also finishes.
sh -c 'exec command'
runs a sh
instance, then replaces that sh
instance with the command
binary, and runs that instead.
Of course, both of these are useless in this limited context; you simply want
command
There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command
. This is pretty much the sole situation where exec command
is useful.
#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command
This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh
instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh
instance with the command
process, rather than have sh
run it as a child process and wait for it, then exit as soon as it finishes.
Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec
that command as an optimization.
If something forces you to run sh
but you really wanted to run something else, exec something else
is of course a workaround to replace the undesired sh
instance (like for example if you really wanted to run your own spiffy gosh
instead of sh
but yours isn't listed in /etc/shells
so you can't specify it as your login shell).
The second use of exec
to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec
is followed by a redirect instead of a command name.
The specific problem is that you're declaring a new variable instead of assigning to an existing one:
char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this
and trying to compare string values by comparing pointers:
if (array!="") // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string
although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.
The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::string
and it will manage all the memory allocation for you:
std::string appendCharToString(std::string const & s, char a) {
return s + a;
}
For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.
<html>
<head>
<script>
var div, container = document.getElementById("container")
for(var i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
https://codepen.io/pcwanderer/pen/MMEREr
Looking at the error in the console for the above code.
Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.
<html>
<head>
<style>
#container{
height: 200px;
width: 700px;
background-color: red;
margin: 10px;
}
div{
height: 100px;
width: 100px;
background-color: purple;
margin: 20px;
display: inline-block;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var div, container = document.getElementById("container")
for(let i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</body>
</html>
https://codepen.io/pcwanderer/pen/pXWBQL
I hope this helps. :)
You probably used the "Fix Issue" option in Xcode when plugging in a new device. Old question but I believe this is the actual answer to WHY this is happening. When you install an app on a device it is signed with a specific development provisioning profile. If, for instance, you plug in another device that is not registered on your developer account Xcode will ask you to "fix the issue". When you press that the device is added and another provisioning profile is created/modified. If you try to overwrite an existing app you'll receive that error. Deleting the app and reinstalling it works since the profile has been altered. I find this often happens when a Team is set and a member plugs in a new device then Xcode "Fixes" the problem.
For a more ruby-like approach with good backward compatibility:
range([begin], end = 0)
where begin
and end
are numbers
var range = function(begin, end) {
if (typeof end === "undefined") {
end = begin; begin = 0;
}
var result = [], modifier = end > begin ? 1 : -1;
for ( var i = 0; i <= Math.abs(end - begin); i++ ) {
result.push(begin + i * modifier);
}
return result;
}
Examples:
range(3); //=> [0, 1, 2, 3]
range(-2); //=> [0, -1, -2]
range(1, 2) //=> [1, 2]
range(1, -2); //=> [1, 0, -1, -2]
Sometimes the command that cron needs to run is in a directory where cron has no access, typically on systems where users' home directories' permissions are 700 and the command is in that directory.
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
You might be interested in the following:
I realize this is not a jQuery solution, but Sencha Touch framework is pretty good for building your target UI. Example (click the Carousel sidebar link): http://dev.sencha.com/deploy/touch/examples/kitchensink/
I had a similar problem after adding a new project (called "TestCleaner") to my solution: Build failed, no errors.
I increased output verbosity (see Richard J Foster's instructions) and searched the output for "failed". I quickly discovered which project was failing, and why: project "TestRunner" had failed with "error CS0246: The type or namespace name 'TestCleaner' could not be found" (even though no problems were highlighted in the code).
Checking TestRunner's references, sure enough the reference to TestCleaner was marked as unresolved, and the path was missing from the reference properties. Deleting and re-adding didn't fix it. Again, no explanation why.
I finally discovered the cause: "TestCleaner" was using a different target framework to the other projects. It was .Net 4.5.2; the others were 4.5.
Spark gives 5 types of Storage level
MEMORY_ONLY
MEMORY_ONLY_SER
MEMORY_AND_DISK
MEMORY_AND_DISK_SER
DISK_ONLY
cache()
will use MEMORY_ONLY
. If you want to use something else, use persist(StorageLevel.<*type*>)
.
By default persist()
will
store the data in the JVM heap as unserialized objects.
I might be late in the game, but how about:
public event Action<MyEvent> EventTriggered = delegate { };
private void Trigger(MyEvent e)
{
EventTriggered(e);
}
Setting the event to an anonymous delegate avoids for me to check to see if the event isn't null.
I find this comes in handy when using MVVM, like when using ICommand.CanExecute Method.
I have tried almost all the answers from below list, but did not work for me. But read the exception well and then tried rename my Dbset name TransactionsModel to Transactions and it work for me.
old Code:
public class MyContext : DbContext
{
//....
public DbSet<Models.TransactionsModel> TransactionsModel { get; set; }
}
New Code:
public class MyContext : DbContext
{
//....
public DbSet<Models.TransactionsModel> Transactions { get; set; }
}
If I understand you correctly, this should do the trick. You'll need add using System.IO
at the top of your file if you don't already have it.
public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
try
{
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(byteArray, 0, byteArray.Length);
return true;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in process: {0}", ex);
return false;
}
}
As none of the answers above are straight forward:
Backslash escape \ is what you need:
myscript \"test\"
Check some typo ','
<?php
//file_get_content(url);
$jsonD = '{
"bpath":"http://www.sampledomain.com/",
"clist":[{
"cid":"11",
"display_type":"grid",
"ctitle":"abc",
"acount":"71",
"alist":[{
"aid":"6865",
"adate":"2 Hours ago",
"atitle":"test",
"adesc":"test desc",
"aimg":"",
"aurl":"?nid=6865",
"weburl":"news.php?nid=6865",
"cmtcount":"0"
},
{
"aid":"6857",
"adate":"20 Hours ago",
"atitle":"test1",
"adesc":"test desc1",
"aimg":"",
"aurl":"?nid=6857",
"weburl":"news.php?nid=6857",
"cmtcount":"0"
}
]
},
{
"cid":"1",
"display_type":"grid",
"ctitle":"test1",
"acount":"2354",
"alist":[{
"aid":"6851",
"adate":"1 Days ago",
"atitle":"test123",
"adesc":"test123 desc",
"aimg":"",
"aurl":"?nid=6851",
"weburl":"news.php?nid=6851",
"cmtcount":"7"
},
{
"aid":"6847",
"adate":"2 Days ago",
"atitle":"test12345",
"adesc":"test12345 desc",
"aimg":"",
"aurl":"?nid=6847",
"weburl":"news.php?nid=6847",
"cmtcount":"7"
}
]
}
]
}
';
$parseJ = json_decode($jsonD,true);
print_r($parseJ);
?>
If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index
To match a substring inside parentheses excluding any inner parentheses you may use
\(([^()]*)\)
pattern. See the regex demo.
In JavaScript, use it like
var rx = /\(([^()]*)\)/g;
Pattern details
\(
- a (
char([^()]*)
- Capturing group 1: a negated character class matching any 0 or more chars other than (
and )
\)
- a )
char.To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value.
Most up-to-date JavaScript code demo (using matchAll
):
const strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
const rx = /\(([^()]*)\)/g;
strs.forEach(x => {
const matches = [...x.matchAll(rx)];
console.log( Array.from(matches, m => m[0]) ); // All full match values
console.log( Array.from(matches, m => m[1]) ); // All Group 1 values
});
_x000D_
Legacy JavaScript code demo (ES5 compliant):
var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
var rx = /\(([^()]*)\)/g;
for (var i=0;i<strs.length;i++) {
console.log(strs[i]);
// Grab Group 1 values:
var res=[], m;
while(m=rx.exec(strs[i])) {
res.push(m[1]);
}
console.log("Group 1: ", res);
// Grab whole values
console.log("Whole matches: ", strs[i].match(rx));
}
_x000D_
There are two potentially major problem with the leading answer to this question. First, as per the docs:
public BufferedImage getSubimage(int x, int y, int w, int h)
Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.
Essentially, what this means is that result from getSubimage acts as a pointer which points at a subsection of the original image.
Why is this important? Well, if you are planning to edit the subimage for any reason, the edits will also happen to the original image. For example, I ran into this problem when I was using the smaller image in a separate window to zoom in on the original image. (kind of like a magnifying glass). I made it possible to invert the colors to see certain details more easily, but the area that was "zoomed" also got inverted in the original image! So there was a small section of the original image that had inverted colors while the rest of it remained normal. In many cases, this won't matter, but if you want to edit the image, or if you just want a copy of the cropped section, you might want to consider a method.
Which brings us to the second problem. Fortunately, it is not as big a problem as the first. getSubImage shares the same data array as the original image. That means that the entire original image is still stored in memory. Assuming that by "crop" the image you actually want a smaller image, you will need to redraw it as a new image rather than just get the subimage.
Try this:
BufferedImage img = image.getSubimage(startX, startY, endX, endY); //fill in the corners of the desired crop location here
BufferedImage copyOfImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = copyOfImage.createGraphics();
g.drawImage(img, 0, 0, null);
return copyOfImage; //or use it however you want
This technique will give you the cropped image you are looking for by itself, without the link back to the original image. This will preserve the integrity of the original image as well as save you the memory overhead of storing the larger image. (If you do dump the original image later)
For Python3.x and starting Pillow==6.0.0
, Image
objects now provide a getexif()
method that returns a <class 'PIL.Image.Exif'>
instance or None
if the image has no EXIF data.
From Pillow 6.0.0 release notes:
getexif()
has been added, which returns anExif
instance. Values can be retrieved and set like a dictionary. When saving JPEG, PNG or WEBP, the instance can be passed as anexif
argument to include any changes in the output image.
As stated, you can iterate over the key-value pairs of the Exif
instance like a regular dictionary. The keys are 16-bit integers that can be mapped to their string names using the ExifTags.TAGS
module.
from PIL import Image, ExifTags
img = Image.open("sample.jpg")
img_exif = img.getexif()
print(type(img_exif))
# <class 'PIL.Image.Exif'>
if img_exif is None:
print('Sorry, image has no exif data.')
else:
for key, val in img_exif.items():
if key in ExifTags.TAGS:
print(f'{ExifTags.TAGS[key]}:{val}')
# ExifVersion:b'0230'
# ...
# FocalLength:(2300, 100)
# ColorSpace:1
# ...
# Model:'X-T2'
# Make:'FUJIFILM'
# LensSpecification:(18.0, 55.0, 2.8, 4.0)
# ...
# DateTime:'2019:12:01 21:30:07'
# ...
Tested with Python 3.8.8 and Pillow==8.1.0
.
django-fullurl
If you're trying to do this in a Django template, I've released a tiny PyPI package django-fullurl
to let you replace url
and static
template tags with fullurl
and fullstatic
, like this:
{% load fullurl %}
Absolute URL is: {% fullurl "foo:bar" %}
Another absolute URL is: {% fullstatic "kitten.jpg" %}
These badges should hopefully stay up-to-date automatically:
In a view, you can of course use request.build_absolute_uri
instead.
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
This is the one. The session will last for 1440 seconds (24 minutes).
session.gc_maxlifetime 1440 1440
I'm here because i have similar question but i find the short answers wrong and the one with the continuous "case when" is to much work and seeing anything repetitive in my code hurts my eyes. So here is the solution
SELECT --MIN(score), MAX(score),
[score range] = CAST(ROUND(score-5,-1)AS VARCHAR) + ' - ' + CAST((ROUND(score-5,-1)+10)AS VARCHAR),
[number of occurrences] = COUNT(*)
FROM order
GROUP BY CAST(ROUND(score-5,-1)AS VARCHAR) + ' - ' + CAST((ROUND(score-5,-1)+10)AS VARCHAR)
ORDER BY MIN(score)
Let's see the code of how we can use this
import react from 'react'
function Header()
{
return <p><b><h1>This is the Heading section</h1></b></p>;
}
**export default Header;**
Try like below
select
split.field(column_name,1,',','"') name1,
split.field(column_name,2,',','"') name2
from table_name
Here is how we fixed this.
Step 1: Open Keychain access, delete "Apple world wide Developer relations certification authority" (which expires on 14th Feb 2016) from both "Login" and "System" sections. If you can't find it, use “Show Expired Certificates” in the View menu.
Step 2: Download this and add it to Keychain access -> Certificates (which expires on 8th Feb 2023).
Step 3: Everything should be back to normal and working now.
Reference: Apple Worldwide Developer Relations Intermediate Certificate Expiration
As @kosev said in his answer you can use JobIntentService. But I use an alternative solution - I catch IllegalStateException and start the service as foreground. For example, this function starts my service:
@JvmStatic
protected fun startService(intentAction: String, serviceType: Class<*>, intentExtraSetup: (Intent) -> Unit) {
val context = App.context
val intent = Intent(context, serviceType)
intent.action = intentAction
intentExtraSetup(intent)
intent.putExtra(NEED_FOREGROUND_KEY, false)
try {
context.startService(intent)
}
catch (ex: IllegalStateException) {
intent.putExtra(NEED_FOREGROUND_KEY, true)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
}
else {
context.startService(intent)
}
}
}
and when I process Intent I do such thing:
override fun onHandleIntent(intent: Intent?) {
val needToMoveToForeground = intent?.getBooleanExtra(NEED_FOREGROUND_KEY, false) ?: false
if(needToMoveToForeground) {
val notification = notificationService.createSyncServiceNotification()
startForeground(notification.second, notification.first)
isInForeground = true
}
intent?.let {
getTask(it)?.process()
}
}
To split using a regex use /.../
lines = str.split(/\r\n|\r|\n/);
Works on Azure, doesn't require stored procs.
SELECT t.name, s.row_count from sys.tables t
JOIN sys.dm_db_partition_stats s
ON t.object_id = s.object_id
AND t.type_desc = 'USER_TABLE'
AND t.name not like '%dss%'
AND s.index_id IN (0,1)
The event is probably raised before the elements are fully loaded or the references are still unset, hence the exceptions. Try only setting properties if the reference is not null
and IsLoaded
is true
.
All the other answers are correct, but you also need to call your method correctly:
Calculate(5, 5, Operator.PLUS))
And since you use int
for left
and right
, the result will be int
as well (3/2 will result in 1
). you could cast to double
before calculating the result or modify your parameters to accept double
You could just use the FolderBrowserDialog
class from the System.Windows.Forms
namespace.
You can use the * selector to change the child styles back to the default
example
#parent {
white-space: pre-wrap;
}
#parent * {
white-space: initial;
}
Take a look at ContextSingletonBeanFactoryLocator. It provides static accessors to get hold of Spring's contexts, assuming they have been registered in certain ways.
It's not pretty, and more complex than perhaps you'd like, but it works.
DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{
//...
}
else if (result == DialogResult.No)
{
//...
}
else
{
//...
}
The man page for checkout: http://git-scm.com/docs/git-checkout
The man page for clone: http://git-scm.com/docs/git-clone
To sum it up, clone is for fetching repositories you don't have, checkout is for switching between branches in a repository you already have.
Note: for those who have a SVN/CVS background and new to Git, the equivalent of git clone
in SVN/CVS is checkout
. The same wording of different terms is often confusing.
you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link
One issue that can occur, and seemingly break this is when using auto minimization of css. The request path for the minified bundle can have a different path than the original css. This may happen automatically so it can cause confusion.
The mapped request path for the minified bundle should be "/originalcssfolder/minifiedbundlename" not just "minifiedbundlename".
In other words, name your bundles to have same path (with the /) as the original folder structure, this way any external resources like fonts, images will map to correct URIs by the browser. The alternative is to use absolute url( refs in your css but that isn't usually desirable.
which nginx
will give you the path of the nginx being used
EDIT (2017-Jan-18)
Thanks to Will Palmer's comment on this answer, I have added the following...
If you've installed nginx via a package manager such as HomeBrew...
which nginx
may not give you the EXACT path to the nginx being used. You can however find it using
realpath $(which nginx)
and as mentioned by @Daniel Li
you can get configuration of nginx via his method
alternatively you can use this:
nginx -V
Easier still: return a pointer to a string that's been malloc'd with strdup.
#include <ncurses.h>
char * getStr(int length)
{
char word[length];
for (int i = 0; i < length; i++)
{
word[i] = getch();
}
word[i] = '\0';
return strdup(&word[0]);
}
int main()
{
char wordd[10];
initscr();
*wordd = getStr(10);
printw("The string is:\n");
printw("%s\n",*wordd);
getch();
endwin();
return 0;
}
if you set in your .xml
android:focused="true", than he would not work because it is a set like it is not changeable.
so the solution: android:focusedByDefault="true"
than he will set it once and can be hide/show the keyboard
//you need to import
QuartzCore/QuartzCore.h
& then for ImageView in border
[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];
[imageView.layer setCornerRadius: 5.0];
SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;
This would return all rows with highest id
, in case id
column is not constrained to be unique.
If you want to use a dynamic filename filter you can implement FilenameFilter and pass in the constructor the dynamic name.
Of course this implies taht you must instantiate every time the class (overhead), but it works
Example:
public class DynamicFileNameFilter implements FilenameFilter {
private String comparingname;
public DynamicFileNameFilter(String comparingName){
this.comparingname = comparingName;
}
@Override
public boolean accept(File dir, String name) {
File file = new File(name);
if (name.equals(comparingname) && !file.isDirectory())
return false;
else
return true;
}
}
then you use where you need:
FilenameFilter fileNameFilter = new DynamicFileNameFilter("thedynamicNameorpatternYouAreSearchinfor");
File[] matchingFiles = dir.listFiles(fileNameFilter);
One solution would be to use the key of your items to remove them -- you can both the keys and the values, when looping using foreach.
For instance :
$arr = array(
'a' => 123,
'b' => 456,
'c' => 789,
);
foreach ($arr as $key => $item) {
if ($item == 456) {
unset($arr[$key]);
}
}
var_dump($arr);
Will give you this array, in the end :
array
'a' => int 123
'c' => int 789
Which means that, in your case, something like this should do the trick :
foreach($images as $key => $image)
{
if($image == 'http://i27.tinypic.com/29yk345.gif' ||
$image == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
$image == 'http://i42.tinypic.com/9pp2456x.gif')
{
unset($images[$key]);
}
}
code below allows user to input items until they press enter key to stop:
In [1]: items=[]
...: i=0
...: while 1:
...: i+=1
...: item=input('Enter item %d: '%i)
...: if item=='':
...: break
...: items.append(item)
...: print(items)
...:
Enter item 1: apple
Enter item 2: pear
Enter item 3: #press enter here
['apple', 'pear']
In [2]:
It is not possible with the default Link List web part, but there are resources describing how to extend Sharepoint server-side to add this functionality.
Share Point Links Open in New Window
Changing Link Lists in Sharepoint 2007
Simply delete that column using: del df['column_name']
You update core-js with the following command:
npm install --save core-js@^3
If you read the React Docs you will find that the command is derived from when you need to upgrade React itself.
To get the index by value, simply add .index[0] to the end of a query. This will return the index of the first row of the result...
So, applied to your dataframe:
In [1]: a[a['c2'] == 1].index[0] In [2]: a[a['c1'] > 7].index[0]
Out[1]: 0 Out[2]: 4
Where the query returns more than one row, the additional index results can be accessed by specifying the desired index, e.g. .index[n]
In [3]: a[a['c2'] >= 7].index[1] In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]
Out[3]: 4 Out[4]: 3
In order to have this result:
{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}
that holds the same data as:
{
"aoColumnDefs": [
{ "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
{ "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
{ "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
]
}
you could use this code:
JSONObject jo = new JSONObject();
Collection<JSONObject> items = new ArrayList<JSONObject>();
JSONObject item1 = new JSONObject();
item1.put("aDataSort", new JSONArray(0, 1));
item1.put("aTargets", new JSONArray(0));
items.add(item1);
JSONObject item2 = new JSONObject();
item2.put("aDataSort", new JSONArray(1, 0));
item2.put("aTargets", new JSONArray(1));
items.add(item2);
JSONObject item3 = new JSONObject();
item3.put("aDataSort", new JSONArray(2, 3, 4));
item3.put("aTargets", new JSONArray(2));
items.add(item3);
jo.put("aoColumnDefs", new JSONArray(items));
System.out.println(jo.toString());
var b = String(stringInterpolationSegment: a)
This works for me. You may have a try
This question has been out here a long time, but I wanted to contribute how I usually iterate through a JSON object. In the example below, I've shown a hard-coded string that contains the JSON, but the JSON string could just as easily have come from a web service or a file.
import json
def main():
# create a simple JSON array
jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'
# change the JSON string into a JSON object
jsonObject = json.loads(jsonString)
# print the keys and values
for key in jsonObject:
value = jsonObject[key]
print("The key and value are ({}) = ({})".format(key, value))
pass
if __name__ == '__main__':
main()
Just remove the :
in your Quantity
. Make sure that your attribute is the same with the parameter you include in the code, like this:
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
If Me.DataGridView1.Rows(i).Cells("Quantity").Value < 5 Then
Me.DataGridView1.Rows(i).Cells("Quantity").Style.ForeColor = Color.Red
End If
Next
End Sub
In case others have the same problem, I ran into this error after updating a project to 4.7. Oddly enough, I had to remove the System.ValueTuple reference for this error to go away.
The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.
Integer division of course returns the true result of division rounded towards zero. The result of 0.333...
is thus rounded down to 0 here. (Note that the processor doesn't actually do any rounding, but you can think of it that way still.)
Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you 0.333...
.
Building on Mark Byers's answer.
The 3rd project could be a WCF project, hosted as a Windows Service. If all programs listened to that service, one application could call the service. The service passes the message on to all listening clients and they can perform an action if suitable.
Good WCF videos here - http://msdn.microsoft.com/en-us/netframework/dd728059
Right click on the Project name > Configure > Convert to Maven Project > click finish. Here you will add some dependencies to download and add your expected jar file.
This will create an auto-generated pom.xml file. Open that file in xml format in your eclipse editor. After build tag (</build>
) add your dependencies which you can copy from maven website and add them there. Now you are good to go. These dependencies will automatically add your required jar files.
This question needed a more up-to-date answer, with sources. This is what actually works (though you don't have to take my word for it):
// Storing this jQuery object outside of the event callback
// prevents jQuery from having to search the DOM for it again
// every time an event is fired.
var $myButton = $("#buttonID")
// input :: for all modern browsers [1]
// selectionchange :: for IE9 [2]
// propertychange :: for <IE9 [3]
$('#textareaID').on('input selectionchange propertychange', function() {
// This is the correct way to enable/disabled a button in jQuery [4]
$myButton.prop('disabled', this.value.length === 0)
}
1: https://developer.mozilla.org/en-US/docs/Web/Events/input#Browser_compatibility
2: oninput in IE9 doesn't fire when we hit BACKSPACE / DEL / do CUT
3: https://msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx
4: http://api.jquery.com/prop/#prop-propertyName-function
BUT, for a more global solution that you can use throughout your project, I recommend using the textchange jQuery plugin to gain a new, cross-browser compatible textchange
event. It was developed by the same person who implemented the equivalent onChange
event for Facebook's ReactJS, which they use for nearly their entire website. And I think it's safe to say, if it's a robust enough solution for Facebook, it's probably robust enough for you. :-)
UPDATE: If you happen to need features like drag and drop support in Internet Explorer, you may instead want to check out pandell
's more recently updated fork of jquery-splendid-textchange
.
You need to set the text after the replace call:
$('.element span').each(function() {_x000D_
console.log($(this).text());_x000D_
var text = $(this).text().replace('N/A, ', '');_x000D_
$(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
<span>N/A, Category</span>_x000D_
</div>
_x000D_
Here's another cool way you can do it (hat tip @Felix King):
$(".element span").text(function(index, text) {
return text.replace("N/A, ", "");
});
I just spent the better part of an afternoon on this
There are two common ways of writing to a file, the first being a direct file access "write" statement. This adds the quotes.
The second is the "ActiveWorkbook.SaveAs" or "ActiveWorksheet.SaveAs" which both have the really bad side effect of changing the filename of the active workbook.
The solution here is a hybrid of a few solutions I found online. It basically does this: 1) Copy selected cells to a new worksheet 2) Iterate through each cell one at a time and "print" it to the open file 3) Delete the temporary worksheet.
The function works on the selected cells and takes in a string for a filename or prompts for a filename.
Function SaveFile(myFolder As String) As String
tempSheetName = "fileWrite_temp"
SaveFile = "False"
Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long
Set myRange = Selection
'myRange.Select
Selection.Copy
'Ask user for folder to save text file to.
If myFolder = "prompt" Then
myFolder = Application.GetSaveAsFilename(fileFilter:="XML Files (*.xml), *.xml, All Files (*), *")
End If
If myFolder = "False" Then
End
End If
Open myFolder For Output As #2
'This temporarily adds a sheet named "Test."
Sheets.Add.Name = tempSheetName
Sheets(tempSheetName).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
For i = 1 To LastRow
For j = 1 To LastCol
CellData = CellData + Trim(ActiveCell(i, j).Value) + " "
Next j
Print #2, CellData; " "
CellData = ""
Next i
Close #2
'Remove temporary sheet.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
'Indicate save action.
MsgBox "Text File Saved to: " & vbNewLine & myFolder
SaveFile = myFolder
End Function
This snippet works in IE7 at least
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
You might have misunderstood rstrip slightly, it strips not a string but any character in the string you specify.
Like this:
>>> text = "xxxxcbaabc"
>>> text.rstrip("abc")
'xxxx'
So instead, just use
text = text[:-3]
(after replacing whitespace with nothing)
Can't find this in actual MSDN documentation, but a moderator in the forums said
I am afraid that OLEDB does not preserve the sheet order as they were in Excel
Excel Sheet Names in Sheet Order
Seems like this would be a common enough requirement that there would be a decent workaround.