Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.
Perhaps declare it above your first while
?
Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.
<?php
$searchthis = "mystring";
$matches = array();
$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $buffer;
}
fclose($handle);
}
//show results:
print_r($matches);
?>
Note the way strpos
is used with !==
operator.
You have to escape [
and ]
.
Try this:
$('.button').click(function(){
var fieldID = $(this).prev().attr("id");
fieldID = fieldID.replace(/([\[\]]+)/g, "\\$1");
$('#' + fieldID).val("hello world");
});
I saved NSDictionary normally and able to get it correctly.
dictForaddress = placemark.addressDictionary! as NSDictionary
let userDefaults = UserDefaults.standard
userDefaults.set(dictForaddress, forKey:Constants.kAddressOfUser)
// For getting data from NSDictionary.
let userDefaults = UserDefaults.standard
let dictAddress = userDefaults.object(forKey: Constants.kAddressOfUser) as! NSDictionary
I just wanted to add, that you can also use de-structuring to refactor the code and make it look neater.
inputChangeHandler: function ({ target: { id, value }) {
this.setState({ [id]: value });
},
This is a little hacky I guess, but it results in the correct validation attributes etc being applied
@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))
You could take your entire server-side model and turn it into a Javascript object by doing the following:
var model = @Html.Raw(Json.Encode(Model));
In your case if you just want the FloorPlanSettings object, simply pass the Encode
method that property:
var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));
If you want to use $PSScriptRoot you can do
Join-Path -Path $PSScriptRoot -ChildPath ..\.. -Resolve
$http({
url: '/api/user',
method: "POST",
data: angular.toJson(yourData)
}).success(function (data, status, headers, config) {
$scope.users = data.users;
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
});
You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException
.
WordList words = new WordList();
These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.
To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.
Prophylactic measures to prevent you getting the error again
The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR
package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.
Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.
Common syntactic mistakes that generate these errors
Mismatched parentheses, braces or brackets
If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.
{}}
## Error: unexpected '}' in "{}}"
{{}} # OK
Missing *
when doing multiplication
This is a common mistake by mathematicians.
5x
Error: unexpected symbol in "5x"
5*x # OK
Not wrapping if, for, or return values in parentheses
This is a common mistake by MATLAB users. In R, if
, for
, return
, etc., are functions, so you need to wrap their contents in parentheses.
if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK
Not using multiple lines for code
Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.
x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK
else
starting on a new line
In an if
-else
statement, the keyword else
must appear on the same line as the end of the if
block.
if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"
if(TRUE) 1 else 2 # OK
if(TRUE)
{
1
} else # also OK
{
2
}
=
instead of ==
=
is used for assignment and giving values to function arguments. ==
tests two values for equality.
if(x = 0) {}
## Error: unexpected '=' in "if(x ="
if(x == 0) {} # OK
Missing commas between arguments
When calling a function, each argument must be separated by a comma.
c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK
Not quoting file paths
File paths are just strings. They need to be wrapped in double or single quotes.
path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK
Quotes inside strings
This is a common problem when trying to pass quoted values to the shell via system
, or creating quoted xPath
or sql
queries.
Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.
"x"y"
## Error: unexpected symbol in ""x"y"
"x\"y" # OK
'x"y' # OK
Using curly quotes
So-called "smart" quotes are not so smart for R programming.
path.expand(“~”)
## Error: unexpected input in "path.expand(“"
path.expand("~") # OK
Using non-standard variable names without backquotes
?make.names
describes what constitutes a valid variable name. If you create a non-valid variable name (using assign
, perhaps), then you need to access it with backquotes,
assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK
This also applies to column names in data frames created with check.names = FALSE
.
dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y` # also OK
It also applies when passing operators and other special values to functions. For example, looking up help on %in%
.
?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK
Sourcing non-R code
The source
function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table
.
source(textConnection("x y"))
## Error in source(textConnection("x y")) :
## textConnection("x y"):1:3: unexpected symbol
## 1: x y
## ^
Corrupted RStudio desktop file
RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop
file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.
Using expression without paste in mathematical plot annotations
When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath
page. Otherwise the contents should be contained inside a call to paste.
plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK
Press CMD + SHIFT + P
(MAC) and search for Toggle Editor Group
var newTH = document.createElement('th');
newTH.setAttribute("onclick", "removeColumn(#)");
newTH.setAttribute("id", "#");
function removeColumn(#){
// remove column #
}
Here is what you are looking for:
String sDate = DateTime.Now.ToString();
DateTime datevalue = (Convert.ToDateTime(sDate.ToString()));
String dy = datevalue.Day.ToString();
String mn = datevalue.Month.ToString();
String yy = datevalue.Year.ToString();
OR
Alternatively, you can use split function to split string date into day, month and year here.
Hope, it will helps you... Cheers. !!
I would recommend using Oracle's "dbms_crypto.randombytes" function.
select REGEXP_REPLACE(dbms_crypto.randombytes(16), '(.{8})(.{4})(.{4})(.{4})(.{12})', '\1-\2-\3-\4-\5') from dual;
You should not use the function "sys_guid" because only one character changes.
ALTER TABLE locations ADD (uid_col RAW(16));
UPDATE locations SET uid_col = SYS_GUID();
SELECT location_id, uid_col FROM locations
ORDER BY location_id, uid_col;
LOCATION_ID UID_COL
----------- ----------------------------------------------------------------
1000 09F686761827CF8AE040578CB20B7491
1100 09F686761828CF8AE040578CB20B7491
1200 09F686761829CF8AE040578CB20B7491
1300 09F68676182ACF8AE040578CB20B7491
1400 09F68676182BCF8AE040578CB20B7491
1500 09F68676182CCF8AE040578CB20B7491
https://docs.oracle.com/database/121/SQLRF/functions202.htm#SQLRF06120
In case you have a repository with few local checkedout branches /refs/heads/* and few remote branch branches remotes/origin/* AND if you want to convert this into a BARE repository with all branches in /refs/heads/*
you can do the following to save the history.
__del__()
gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.__init__()
raises an exception then the object is assumed to be incomplete and __del__()
won't be invoked.Here is a complete example showing how to use the **
operator to pass values from a dictionary as keyword arguments.
>>> def f(x=2):
... print(x)
...
>>> new_x = {'x': 4}
>>> f() # default value x=2
2
>>> f(x=3) # explicit value x=3
3
>>> f(**new_x) # dictionary value x=4
4
((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;
I had the same issue, all I did was add a setTimeout
of about 10 seconds before trying to connect to the Mongo server and it solved the issue right up. I dont know why I had to add a delay but it worked...
Define a converter:
public class RowIndexConverter : IValueConverter
{
public object Convert( object value, Type targetType,
object parameter, CultureInfo culture )
{
var row = (IDictionary<string, object>) value;
var key = (string) parameter;
return row.Keys.Contains( key ) ? row[ key ] : null;
}
public object ConvertBack( object value, Type targetType,
object parameter, CultureInfo culture )
{
throw new NotImplementedException( );
}
}
Bind to a custom definition of a Dictionary. There's lot of overrides that I've omitted, but the indexer is the important one, because it emits the property changed event when the value is changed. This is required for source to target binding.
public class BindableRow : INotifyPropertyChanged, IDictionary<string, object>
{
private Dictionary<string, object> _data = new Dictionary<string, object>( );
public object Dummy // Provides a dummy property for the column to bind to
{
get
{
return this;
}
set
{
var o = value;
}
}
public object this[ string index ]
{
get
{
return _data[ index ];
}
set
{
_data[ index ] = value;
InvokePropertyChanged( new PropertyChangedEventArgs( "Dummy" ) ); // Trigger update
}
}
}
In your .xaml file use this converter. First reference it:
<UserControl.Resources>
<ViewModelHelpers:RowIndexConverter x:Key="RowIndexConverter"/>
</UserControl.Resources>
Then, for instance, if your dictionary has an entry where the key is "Name", then to bind to it: use
<TextBlock Text="{Binding Dummy, Converter={StaticResource RowIndexConverter}, ConverterParameter=Name}">
In Android Studio just click on right sidebar panel "Gradle" to show gardel panel then: -YOURAPPNAME --Task ---Android ----(double click) signingReport (to start Gradle Daemon)
then you will see result:
Config: debug
Store: C:\Users\username\.android\debug.keystore
Alias: AndroidDebugKey
MD5: C8:46:01:EA:36:02:D1:21:1B:23:19:91:D4:32:CB:AC
SHA1: 38:AB:4C:01:01:D7:62:E0:61:D1:9F:52:04:0C:E5:07:4E:E4:9B:39
SHA-256: 1B:8C:DC:35:48:10:01:2C:1F:BD:01:64:F1:01:06:01:60:01:A6:8B:10:15:2E:BF:7B:C4:FD:38:4C:C1:74:01
Valid until: Saturday, February 12, 2050
copy SHA1:
38:AB:4C:01:01:D7:62:E0:68:D1:9F:52:04:0C:E5:07:4E:E4:9B:39
go to this PAGE
Paste SHA1 and generate your Facebook key hash code.
Tensorflow also implemented functions for resizing/padding images tf.image.pad tf.pad.
padded_image = tf.image.pad_to_bounding_box(image, top_padding, left_padding, target_height, target_width)
padded_image = tf.pad(image, paddings, "CONSTANT")
These functions work just like other input-pipeline features of tensorflow and will work much better for machine learning applications.
Basic authentication using HTTP POST method:
$http({
method: 'POST',
url: '/API/authenticate',
data: 'username=' + username + '&password=' + password + '&email=' + email,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Login-Ajax-call": 'true'
}
}).then(function(response) {
if (response.data == 'ok') {
// success
} else {
// failed
}
});
...and GET method call with header:
$http({
method: 'GET',
url: '/books',
headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json',
"X-Login-Ajax-call": 'true'
}
}).then(function(response) {
if (response.data == 'ok') {
// success
} else {
// failed
}
});
Aha. This turned out to be a simple problem of there being spaces in the path to the script.
Changing the Invoke-Expression line to:
Invoke-Expression "& `"$scriptPath`" $argumentList"
...was enough to get it to kick off. Thanks to Neolisk for your help and feedback!
Make file executable:
chmod +x file
Find location of perl:
which perl
This should return something like
/bin/perl sometimes /usr/local/bin
Then in the first line of your script add:
#!"path"/perl with path from above e.g.
#!/bin/perl
Then you can execute the file
./file
There may be some issues with the PATH, so you may want to change that as well ...
SYSDATE
, systimestamp
return datetime of server where database is installed. SYSDATE
- returns only date, i.e., "yyyy-mm-dd". systimestamp
returns date with time and zone, i.e., "yyyy-mm-dd hh:mm:ss:ms timezone"now()
returns datetime at the time statement execution, i.e., "yyyy-mm-dd hh:mm:ss"CURRENT_DATE
- "yyyy-mm-dd", CURRENT_TIME
- "hh:mm:ss", CURRENT_TIMESTAMP
- "yyyy-mm-dd hh:mm:ss timezone". These are related to a record insertion time.This is a problem with your web server sending out an HTTP header that does not match the one you define. For instructions on how to make the server send the correct headers, see this page.
Otherwise, you can also use PHP to modify the headers, but this has to be done before outputting any text using this code:
header('Content-Type: text/html; charset=utf-8');
More information on how to send out headers using PHP can be found in the documentation for the header function.
You probably want the next transformation for you pixels:
pixels = map(list, image.getdata())
You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:
int a = 0;
scanf("%d",&a);
return YOUR_MAIN_CODE;
and this way the window would not close until you enter data for the a
variable.
I just got my GUC232A cable with a molded-in PL2302 converter chip.
In addition to adding myself and br to group dialout
, I found this helpful tip in the README.Debian file in /usr/share/doc/bottlerocket
:
This package uses debconf to configure the /dev/firecracker symlink, should you need to change the symlink in the future run this command:
dpkg-reconfigure -pmedium bottlerocket
That will then prompt you for your new serial port and modify the symlink. This is required for proper use of bottlerocket.
I did that and voila! bottlerocket is able to communicate with my X-10 devices.
Normally when querying a database with SQL and then fill a data-table with its results, it will never be a null Data table. You have the column headers filled with column information even if you returned 0 records.When one tried to process a data table with 0 records but with column information it will throw exception.To check the datatable before processing one could check like this.
if (DetailTable != null && DetailTable.Rows.Count>0)
Check chart.Boxplot from package PerformanceAnalytics
. It lets you define the symbol to use for the mean of the distribution.
By default, the chart.Boxplot(data)
command adds the mean as a red circle and the median as a black line.
Here is the output with sample data; MWE:
#install.packages(PerformanceAnalytics)
library(PerformanceAnalytics)
chart.Boxplot(cars$speed)
You can see all the version of a module with npm view
.
eg: To list all versions of bootstrap including beta.
npm view bootstrap versions
But if the version list is very big it will truncate. An --json
option will print all version including beta versions as well.
npm view bootstrap versions --json
If you want to list only the stable versions not the beta then use singular version
npm view bootstrap@* versions
Or
npm view bootstrap@* versions --json
And, if you want to see only latest version then here you go.
npm view bootstrap version
The above method works good.
Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.
To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).
To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name])
.
Debug.Print
outputs to the "Immediate" window.
Also, you can simply type ?
and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:
This can be very handy to quickly output the property of an object...
? myWidget.name
...to set the property of an object...
myWidget.name = "thingy"
...or to even execute a function or line of code, while in debugging mode:
Sheet1.MyFunction()
yes, it is possible we can pass structure and return structure as well. You were right but you actually did not pass the data type which should be like this struct MyObj b = a.
Actually I also came to know when I was trying to find out a better solution to return more than one values for function without using pointer or global variable.
Now below is the example for the same, which calculate the deviation of a student marks about average.
#include<stdio.h>
struct marks{
int maths;
int physics;
int chem;
};
struct marks deviation(struct marks student1 , struct marks student2 );
int main(){
struct marks student;
student.maths= 87;
student.chem = 67;
student.physics=96;
struct marks avg;
avg.maths= 55;
avg.chem = 45;
avg.physics=34;
//struct marks dev;
struct marks dev= deviation(student, avg );
printf("%d %d %d" ,dev.maths,dev.chem,dev.physics);
return 0;
}
struct marks deviation(struct marks student , struct marks student2 ){
struct marks dev;
dev.maths = student.maths-student2.maths;
dev.chem = student.chem-student2.chem;
dev.physics = student.physics-student2.physics;
return dev;
}
For the first question I think answer would be:
<your DataFrame>.rename(columns={'count':'Total_Numbers'})
or
<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']
As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:
Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]
The name
of the Series becomes the index
of the row in the DataFrame:
In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
In [100]: s = df.xs(3)
In [101]: s.name = 10
In [102]: df.append(s)
Out[102]:
A B C D
0 -2.083321 -0.153749 0.174436 1.081056
1 -1.026692 1.495850 -0.025245 -0.171046
2 0.072272 1.218376 1.433281 0.747815
3 -0.940552 0.853073 -0.134842 -0.277135
4 0.478302 -0.599752 -0.080577 0.468618
5 2.609004 -1.679299 -1.593016 1.172298
6 -0.201605 0.406925 1.983177 0.012030
7 1.158530 -2.240124 0.851323 -0.240378
10 -0.940552 0.853073 -0.134842 -0.277135
The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).
The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.
So, imagine a view that has a size of 100x100 (width x height) positioned at 25,25 (x,y) of its superview. The following code prints out this view's bounds and frame:
// This method is in the view controller of the superview
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"bounds.origin.x: %f", label.bounds.origin.x);
NSLog(@"bounds.origin.y: %f", label.bounds.origin.y);
NSLog(@"bounds.size.width: %f", label.bounds.size.width);
NSLog(@"bounds.size.height: %f", label.bounds.size.height);
NSLog(@"frame.origin.x: %f", label.frame.origin.x);
NSLog(@"frame.origin.y: %f", label.frame.origin.y);
NSLog(@"frame.size.width: %f", label.frame.size.width);
NSLog(@"frame.size.height: %f", label.frame.size.height);
}
And the output of this code is:
bounds.origin.x: 0
bounds.origin.y: 0
bounds.size.width: 100
bounds.size.height: 100
frame.origin.x: 25
frame.origin.y: 25
frame.size.width: 100
frame.size.height: 100
So, we can see that in both cases, the width and the height of the view is the same regardless of whether we are looking at the bounds or frame. What is different is the x,y positioning of the view. In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view (which earlier we said was at 25,25).
There is also a great presentation that covers UIViews. See slides 1-20 which not only explain the difference between frames and bounds but also show visual examples.
Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3
alert( Cookies.get("example") );
Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.
There is a numpy built-in function to help with that.
import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])
Go to the folder in which eclipse is installed then open readme folder followed by the readme txt file. Here you will find all the info you need.
Try this when you want to "fix" your body's scroll:
jQuery('body').css('height', '100vh').css('overflow-y', 'hidden');
and this when you want to turn it normal again:
jQuery('body').css('height', '').css('overflow-y', '');
To return only one row use LIMIT 1
:
SELECT *
FROM tbl_foo
WHERE name = 'sarmen'
LIMIT 1
It doesn't make sense to say 'first row' or 'last row' unless you have an ORDER BY
clause. Assuming you add an ORDER BY
clause then you can use LIMIT in the following ways:
LIMIT 1
.LIMIT 1, 1
.LIMIT 1
.after that change in git-ignore file run this command , This command will remove all file cache not the files or changes
git rm -r --cached .
after execution of this command commit the files
for removing single file or folder from cache use this command
git rm --cached filepath/foldername
string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);
Note: the hash is important!
There are many ways can do that!
jQuery
remove all class
$("element").removeClass();
OR
$("#item").removeAttr('class');
OR
$("#item").attr('class', '');
OR
$('#item')[0].className = '';
remove multi class
$("element").removeClass("class1 ... classn");
OR
$("element").removeClass("class1").removeClass("...").removeClass("classn");
// remove all items all class _x000D_
const items = document.querySelectorAll('item');_x000D_
for (let i = 0; i < items.length; i++) {_x000D_
items[i].className = '';_x000D_
}
_x000D_
// only remove all class of first item_x000D_
const item1 = document.querySelector('item');_x000D_
item1.className = '';
_x000D_
EMPNO DEPTNO DEPT_COUNT
7839 10 4
5555 10 4
7934 10 4
7782 10 4 --- 4 records in table for dept 10
7902 20 4
7566 20 4
7876 20 4
7369 20 4 --- 4 records in table for dept 20
7900 30 6
7844 30 6
7654 30 6
7521 30 6
7499 30 6
7698 30 6 --- 6 records in table for dept 30
Here we are getting count for respective deptno. As for deptno 10 we have 4 records in table emp similar results for deptno 20 and 30 also.
There are several ways to try to prevent line breaks, and the phrase “a newer construct” might refer to more than one way—that’s actually the most reasonable interpretation. They probably mostly think of the CSS declaration white-space:nowrap
and possibly the no-break space character. The different ways are not equivalent, far from that, both in theory and especially in practice, though in some given case, different ways might produce the same result.
There is probably nothing real to be gained by switching from the HTML attribute to the somewhat clumsier CSS way, and you would surely lose when style sheets are disabled. But even the nowrap
attribute does no work in all situations. In general, what works most widely is the nobr
markup, which has never made its way to any specifications but is alive and kicking: <td><nobr>...</nobr></td>
.
Give full access of .composer to user.
sudo chown -R 'user-name' /home/'user-name'/.composer
or
sudo chmod 777 -R /home/'user-name'/.composer
user-name
is your system user-name.
to get user-name type "whoami" in terminal:
It's a simple Mistake while adding a new file you just have to make sure that \
is added to the file before and the new file remain as it is
eg.
Check Out what to do if i want to add a new file named customer.cc
Or for multiple ignores on the next line, string the rules using commas
// eslint-disable-next-line class-methods-use-this, no-unused-vars
If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
will give you a ScheduledExecutorService
with similar functionality to Timer
(i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer
class). Using a ScheduledExecutorService
also gives you advantages such as:
newScheduledThreadPoolExecutor()
or the ScheduledThreadPoolExecutor
class)About the only reasons for sticking to Timer
I can think of are:
Due to the disadvantages described below, I would recommend following the accepted answer:
Use
npm install --save-dev [package_name]
then execute scripts with:$ npm run lint $ npm run build $ npm test
My original but not recommended answer follows.
Instead of using a global install, you could add the package to your devDependencies
(--save-dev
) and then run the binary from anywhere inside your project:
"$(npm bin)/<executable_name>" <arguments>...
In your case:
"$(npm bin)"/node.io --help
This engineer provided an npm-exec
alias as a shortcut. This engineer uses a shellscript called env.sh
. But I prefer to use $(npm bin)
directly, to avoid any extra file or setup.
Although it makes each call a little larger, it should just work, preventing:
sudo
Disadvantages:
$(npm bin)
won't work on Windows.npm bin
folder. (Install npm-run or npm-which to find them.)It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json
, as Jason demonstrates above.
breast$class <- as.numeric(as.character(breast$class))
If you have many columns to convert to numeric
indx <- sapply(breast, is.factor)
breast[indx] <- lapply(breast[indx], function(x) as.numeric(as.character(x)))
Another option is to use stringsAsFactors=FALSE
while reading the file using read.table
or read.csv
Just in case, other options to create/change columns
breast[,'class'] <- as.numeric(as.character(breast[,'class']))
or
breast <- transform(breast, class=as.numeric(as.character(breast)))
Run package declaration and body separately.
I believe you need to make sure that all the container div tags above the 100% height div also has 100% height set on them including the body tag and html.
Try this....
HTML inline
onKeydown="Javascript: if (event.keyCode==13) fnsearch();"
or
onkeypress="Javascript: if (event.keyCode==13) fnsearch();"
JavaScript
<script>
function fnsearch()
{
alert('you press enter');
}
</script>
With React's support for string interpolation, you could do the following:
class Pill extends React.Component {
render() {
return (
<button className={`pill ${this.props.styleName}`}>{this.props.children}</button>
);
}
}
//$(document).ready(function(){_x000D_
// $("a").click(function(event){_x000D_
// event.preventDefault();_x000D_
// $("div").html("This is prevent link...");_x000D_
// });_x000D_
//}); _x000D_
_x000D_
$(document).ready(function(){_x000D_
$("a").click(function(event){_x000D_
event.preventDefault();_x000D_
$.ajax({_x000D_
beforeSend: function(){_x000D_
$('#text').html("<img src='ajax-loader.gif' /> Loading...");_x000D_
},_x000D_
success : function(){_x000D_
setInterval(function(){ $('#text').load("cd_catalog.txt"); },1000);_x000D_
}_x000D_
});_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<a href="http://www.wantyourhelp.com">[click to redirect][1]</a>_x000D_
<div id="text"></div>
_x000D_
I did the following :
I would not build or clean build it. Hope that helps you out.
This isn't as good an answer as using the special built-in __subclasses__()
class method which @unutbu mentions, so I present it merely as an exercise. The subclasses()
function defined returns a dictionary which maps all the subclass names to the subclasses themselves.
def traced_subclass(baseclass):
class _SubclassTracer(type):
def __new__(cls, classname, bases, classdict):
obj = type(classname, bases, classdict)
if baseclass in bases: # sanity check
attrname = '_%s__derived' % baseclass.__name__
derived = getattr(baseclass, attrname, {})
derived.update( {classname:obj} )
setattr(baseclass, attrname, derived)
return obj
return _SubclassTracer
def subclasses(baseclass):
attrname = '_%s__derived' % baseclass.__name__
return getattr(baseclass, attrname, None)
class BaseClass(object):
pass
class SubclassA(BaseClass):
__metaclass__ = traced_subclass(BaseClass)
class SubclassB(BaseClass):
__metaclass__ = traced_subclass(BaseClass)
print subclasses(BaseClass)
Output:
{'SubclassB': <class '__main__.SubclassB'>,
'SubclassA': <class '__main__.SubclassA'>}
If you are working in PHP version 5.* then you have to install
sudo apt-get install php5-gd
And if you are working in PHP version 7.* then you have to install
sudo apt-get install php7.0-gd
Hope it will work...
And if you are working in PHP version 7.2 then you have to install
sudo apt-get install php7.2-gd... it worked for me
Above all answers are right but there is another method also which is very handy.
Pre-condition: Your project is Maven project Or converts it to Maven project.
RightclickOnProject > Configuration > Convert in to Maven Project
1. Select any jar for which you want to download sources or javadocs.
2. RightClick > Maven > Download javadoc or Download javasources
The tensorflow version can be checked either on terminal or console or in any IDE editer as well (like Spyder or Jupyter notebook, etc)
Simple command to check version:
(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)
>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'
I think you are asking two things which are not necessarily the same
I want to extract every 6th element of the original
You can do this by indexing a sequence:
foo <- 1:120
foo[1:20*6]
I would like to create a vector in which each element is the i+6th element of another vector.
An easy way to do this is to supplement a logical factor with FALSEs until i+6
:
foo <- 1:120
i <- 1
foo[1:(i+6)==(i+6)]
[1] 7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 112 119
i <- 10
foo[1:(i+6)==(i+6)]
[1] 16 32 48 64 80 96 112
just change state config to disable and choose what you want, background Image for disabled state
Btw, now ruby already supports just strip without "!".
Compare:
p "abc".strip! == " abc ".strip! # false, because "abc".strip! will return nil
p "abc".strip == " abc ".strip # true
Also it's impossible to strip
without duplicates. See sources in string.c:
static VALUE
rb_str_strip(VALUE str)
{
str = rb_str_dup(str);
rb_str_strip_bang(str);
return str;
}
ruby 1.9.3p0 (2011-10-30) [i386-mingw32]
Update 1: As I see now -- it was created in 1999 year (see rev #372 in SVN):
Update2:
strip!
will not create duplicates — both in 1.9.x, 2.x and trunk versions.
break ends execution of the current for, foreach, while, do-while or switch structure.
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
So depending on your need, you can reset the position currently being executed in your code to a different level of the current nesting.
Also, see here for an artical detailing Break vs Continue with a number of examples
-- create test table "Accounts"
create table Accounts (
c_ID int primary key
,first_name varchar(100)
,last_name varchar(100)
,city varchar(100)
);
insert into Accounts values (101, 'Sebastian', 'Volk', 'Frankfurt' );
insert into Accounts values (102, 'Beate', 'Mueller', 'Hamburg' );
insert into Accounts values (103, 'John', 'Walker', 'Washington' );
insert into Accounts values (104, 'Britney', 'Sears', 'Holywood' );
insert into Accounts values (105, 'Sarah', 'Schmidt', 'Mainz' );
insert into Accounts values (106, 'George', 'Lewis', 'New Jersey' );
insert into Accounts values (107, 'Jian-xin', 'Wang', 'Peking' );
insert into Accounts values (108, 'Katrina', 'Khan', 'Bolywood' );
-- declare table variable
declare @tb_FirstName table(name varchar(100));
insert into @tb_FirstName values ('John'), ('Sarah'), ('George');
SELECT *
FROM Accounts
WHERE first_name in (select name from @tb_FirstName);
SELECT *
FROM Accounts
WHERE first_name not in (select name from @tb_FirstName);
go
drop table Accounts;
go
You can use Strings replace method with a regular expression.
"Hello World ".replace(/ /g, "");
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp
/ / - Regular expression matching spaces
g - Global flag; find all matches rather than stopping after the first match
const str = "H e l l o World! ".replace(/ /g, "");_x000D_
document.getElementById("greeting").innerText = str;
_x000D_
<p id="greeting"><p>
_x000D_
You can also try to restart your code editor. That works well too.
I would like to point out that TypeScript does not provide a direct mechanism for dynamically testing whether an object implements a particular interface.
Instead, TypeScript code can use the JavaScript technique of checking whether an appropriate set of members are present on the object. For example:
var obj : any = new Foo();
if (obj.someInterfaceMethod) {
...
}
from cStringIO import StringIO # Python3 use: from io import StringIO
import sys
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
# blah blah lots of code ...
sys.stdout = old_stdout
# examine mystdout.getvalue()
There is a difference between .
and text()
, but this difference might not surface because of your input document.
If your input document looked like (the simplest document one can imagine given your XPath expressions)
Example 1
<html>
<a>Ask Question</a>
</html>
Then //a[text()="Ask Question"]
and //a[.="Ask Question"]
indeed return exactly the same result. But consider a different input document that looks like
Example 2
<html>
<a>Ask Question<other/>
</a>
</html>
where the a
element also has a child element other
that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"]
still returns the a
element, while //a[.="Ask Question"]
does not return anything!
This is because the meaning of the two predicates (everything between [
and ]
) is different. [text()="Ask Question"]
actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"]
means: return true if the string value of an element is identical to "Ask Question".
In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other
element is between "Ask Question" and a newline character that also counts as text content.
To make an even clearer example, consider as an input document:
Example 3
<a>Ask Question<other/>more text</a>
Here, the a
element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a
. You can test this by running //a/text()
on this document, which will return (individual results separated by ----
):
Ask Question
-----------------------
more text
So, in such a scenario, text()
returns a set of individual nodes, while .
in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text']
which will successfully return the a
element.
Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()
) is given a sequence of nodes, it will only process the first node and silently ignore the rest.
I think you can let the Android OS take care of this for you. Set the scale type on the ImageView to fitXY
and the image it displays will be sized to fit the current size of the view.
<ImageView
android:layout_width="90px"
android:layout_height="60px"
android:scaleType="fitXY" />
It's simple. On the sender side, use Intent.putExtra
:
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
On the receiver side, use Intent.getIntExtra
:
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
You can use either jQuery Autocomplete or ASP.NET AJAX Toolkit Autocomplete
Just in-case you don't wanna use a TreeSet
you could try this.
set = set.stream().sorted().collect(Collectors.toCollection(LinkedHashSet::new));
SELECCT TO_BASE64(blobfield)
FROM the Table
worked for me.
The CAST(blobfield AS CHAR(10000) CHARACTER SET utf8) and CAST(blobfield AS CHAR(10000) CHARACTER SET utf16) did not show me the text value I wanted to get.
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
There isn't specifically an attribute to control that. Marquee isn't a highly reliable tag anyways. You may want to consider using jQuery and the .animate() function. If you are interested in pursuing that avenue and need code for it, just let me know.
Yes, it prints GARBAGE unless you are lucky.
VERY IMPORTANT.
The type of the printf/sprintf/fprintf argument MUST match the associated format type char.
If the types don't match and it compiles, the results are very undefined.
Many newer compilers know about printf and issue warnings if the types do not match. If you get these warnings, FIX them.
If you want to convert types for arguments for variable functions, you must supply the cast (ie, explicit conversion) because the compiler can't figure out that a conversion needs to be performed (as it can with a function prototype with typed arguments).
printf("%d\n", (int) ch)
In this example, printf is being TOLD that there is an "int" on the stack. The cast makes sure that whatever thing sizeof returns (some sort of long integer, usually), printf will get an int.
printf("%d", (int) sizeof('\n'))
I encountered this error too, it occurs because %HTTPPORT% isn’t part of the system variables yet.
The solution to this is NOT by manually typing in the url to your browser, which works but you have to keep doing it every single time.
Simply goto “this pc” or “my computer” right click on it and select properties, then select “advanced system settings” When the new window comes up select “Environment Variables...”
Now under system variables click new to create a new system variable. Type HTTPPORT into the variable name text box, Then type 8080 into the variable value text box. Click OK, close the windows and logout!
Thats an important step, make sure you log out. When you log back in, click the get started icon again and it will open without errors.
??
for those of us that love all things pandas, apply, and of course lambda functions:
df['Col3'] = df[['Col1', 'Col2']].apply(lambda x: ''.join(x), axis=1)
In my cases, I solved the problem when using the labs()
instead of abs()
.
Runtime.getCurrentRumtime().halt(0);
function nextFormInput() {
var focused = $(':focus');
var inputs = $(focused).closest('form').find(':input');
inputs.eq(inputs.index(focused) + 1).focus();
}
Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.
And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.
Very, very late to answer this one, but I've just discovered that using a background-image that is encoded as a base64 URI in the CSS, rather than held as a separate image, continues to animate in IE8.
First read the the section in the View Controller Programming Guide for iOS about 'Adopting a Full-Screen Layout for Navigation Views' and the section about the same for Custom Views. If you are trying to do something like the Photos.app then you are probably using a scroll view. Note the comment that Navigation bars automatically add a scroll content inset to your scroll view to account for the height of the navigation bar (and status bar) so you have to reset the contentInset property of your scroll view back to zero (UIEdgeInsetsZero) right after setting up the initial state of the navigationBar and before the view appears.
Then if you have a single tap that toggles the navigationBar and/or status bar to show or hide, you need to do two things in you toggling method. The first seems to be to save the scroll view's contentOffset property before changing the NavigationBar hidden property and restore your saved value to contentOffset right afterward. And second to again zero out the contentInset property to UIEdgeInsetsZero after changing the navigationBarHidden property. Also, if you are toggling the status bar, you need to change its state before you change the navigationBar's state.
First make sure you have the runat="server"
attribute in your textarea
tag like this
<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>
Then you can access the content via:
string body = TextArea1.value;
From Chromium's style guide:
Don't use else after return:
# Bad
if (foo)
return 1
else
return 2
# Good
if (foo)
return 1
return 2
return 1 if foo else 2
Very old question, but just had to build this for an app today and found the settings shown in other answers do not result in a clean image (possibly as new options were added in later .Net versions).
Assuming you want the text in the centre of the bitmap, you can do this:
// Load the original image
Bitmap bmp = new Bitmap("filename.bmp");
// Create a rectangle for the entire bitmap
RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);
// Create graphic object that will draw onto the bitmap
Graphics g = Graphics.FromImage(bmp);
// ------------------------------------------
// Ensure the best possible quality rendering
// ------------------------------------------
// The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing).
// One exception is that path gradient brushes do not obey the smoothing mode.
// Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
g.SmoothingMode = SmoothingMode.AntiAlias;
// The interpolation mode determines how intermediate values between two endpoints are calculated.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
// This one is important
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// Create string formatting options (used for alignment)
StringFormat format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
// Draw the text onto the image
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf, format);
// Flush all graphics changes to the bitmap
g.Flush();
// Now save or use the bitmap
image.Image = bmp;
ODATA is a special kind of REST where we can query data uniformly from URL.
I store date in the DB in UTC format but then I show them to the final user in their local timezone
// retrieve
$d = (new \DateTime($val . ' UTC'))->format('U');
return date("Y-m-d H:i:s", $d);
The only built-in way of handling checked exceptions that can be thrown by a map
operation is to encapsulate them within a CompletableFuture
. (An Optional
is a simpler alternative if you don't need to preserve the exception.) These classes are intended to allow you to represent contingent operations in a functional way.
A couple of non-trivial helper methods are required, but you can arrive at code that's relatively concise, while still making it apparent that your stream's result is contingent on the map
operation having completed successfully. Here's what it looks like:
CompletableFuture<List<Class<?>>> classes =
Stream.of("java.lang.String", "java.lang.Integer", "java.lang.Double")
.map(MonadUtils.applyOrDie(Class::forName))
.map(cfc -> cfc.thenApply(Class::getSuperclass))
.collect(MonadUtils.cfCollector(ArrayList::new,
List::add,
(List<Class<?>> l1, List<Class<?>> l2) -> { l1.addAll(l2); return l1; },
x -> x));
classes.thenAccept(System.out::println)
.exceptionally(t -> { System.out.println("unable to get class: " + t); return null; });
This produces the following output:
[class java.lang.Object, class java.lang.Number, class java.lang.Number]
The applyOrDie
method takes a Function
that throws an exception, and converts it into a Function
that returns an already-completed CompletableFuture
-- either completed normally with the original function's result, or completed exceptionally with the thrown exception.
The second map
operation illustrates that you've now got a Stream<CompletableFuture<T>>
instead of just a Stream<T>
. CompletableFuture
takes care of only executing this operation if the upstream operation succeeded. The API makes this explict, but relatively painless.
Until you get to the collect
phase, that is. This is where we require a pretty significant helper method. We want to "lift" a normal collection operation (in this case, toList()
) "inside" the CompletableFuture
-- cfCollector()
lets us do that using a supplier
, accumulator
, combiner
, and finisher
that don't need to know anything at all about CompletableFuture
.
The helper methods can be found on GitHub in my MonadUtils
class, which is very much still a work in progress.
C:\>help if
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
In Python 3.4 you will be able to do:
[*innerlist for innerlist in outer_list]
Use @Named
to differentiate between different objects of the same type bound in the same scope.
@Named("maxWaitTime")
public long maxWaitTimeMs;
@Named("minWaitTime")
public long minWaitTimeMs;
Without the @Named
qualifier, the injector would not know which long to bind to which variable.
If you want to create annotations that act like @Named
, use the @Qualifier
annotation when creating them.
If you look at @Named
, it is itself annotated with @Qualifier
.
Using system("pause");
is Ungood Practice™ because
It's completely unnecessary.
To keep the program's console window open at the end when you run it from Visual Studio, use Ctrl+F5 to run it without debugging, or else place a breakpoint at the last right brace }
of main
. So, no problem in Visual Studio. And of course no problem at all when you run it from the command line.
It's problematic & annoying
when you run the program from the command line. For interactive execution you have to press a key at the end to no purpose whatsoever. And for use in automation of some task that pause
is very much undesired!
It's not portable.
Unix-land has no standard pause
command.
The pause
command is an internal cmd.exe
command and can't be overridden, as is erroneously claimed in at least one other answer. I.e. it's not a security risk, and the claim that AV programs diagnose it as such is as dubious as the claim of overriding the command (after all, a C++ program invoking system
is in position to do itself all that the command interpreter can do, and more). Also, while this way of pausing is extremely inefficient by the usual standards of C++ programming, that doesn't matter at all at the end of a novice's program.
So, the claims in the horde of answers before this are not correct, and the main reason you shouldn't use system("pause")
or any other wait command at the end of your main
, is the first point above: it's completely unnecessary, it serves absolutely no purpose, it's just very silly.
A simple case that generates this error message:
In [8]: [1,2,3,4,5][np.array([1])]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-55def8e1923d> in <module>()
----> 1 [1,2,3,4,5][np.array([1])]
TypeError: only integer scalar arrays can be converted to a scalar index
Some variations that work:
In [9]: [1,2,3,4,5][np.array(1)] # this is a 0d array index
Out[9]: 2
In [10]: [1,2,3,4,5][np.array([1]).item()]
Out[10]: 2
In [11]: np.array([1,2,3,4,5])[np.array([1])]
Out[11]: array([2])
Basic python list indexing is more restrictive than numpy's:
In [12]: [1,2,3,4,5][[1]]
....
TypeError: list indices must be integers or slices, not list
Looking again at
indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)
indices
is a 1d array of integers - but it certainly isn't scalar. It's an array of 50000 integers. List's cannot be indexed with multiple indices at once, regardless of whether they are in a list or array.
Using a fadeTo()
that is fading to an opacity of 500 in 2 seconds in "I Can Has Kittenz"'s code isn't readable to me. I think it's better using other options like a delay()
$(".alert").delay(4000).slideUp(200, function() {
$(this).alert('close');
});
In my case I was getting the grey background and it turned out to be inclusion of a zoom value in the map options. Yup, makes no sense.
Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.
Look here for permanently changing the heap size.
I have exactly the same issue as above, and took me the whole day to discover that it doesn't like my newline approach. Instead I reused the same code with semi-colon approach instead. For example my initial code using the newline (which threw the same error as yours):
Y=1
while test "$Y" -le "20"
do
echo "Number $Y"
Y=$[Y+1]
done
And using code with semicolon approach with worked wonder:
Y=1 ; while test "$Y" -le "20"; do echo "Number $Y"; Y=$[Y+1] ; done
I notice the same problem occurs for other commands as well using the newline approach, so I think I am gonna stick to using semicolon for my future code.
BookTitle
have a Composite key. so if the key of BookTitle
is referenced as a foreign key
you have to bring the complete composite key.
So to resolve the problem you need to add the complete composite key in the BookCopy
. So add ISBN
column as well. and they at the end.
foreign key (ISBN, Title) references BookTitle (ISBN, Title)
The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page.
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
Make it a background image and larger than 100% to get the desired effect: http://jsfiddle.net/derekstory/hVM9v/
HTML
<div id="image"></div>
CSS
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#image {
width: 100%;
height: 500px;
background: #000 url('http://static.ddmcdn.com/gif/dog-9.jpg') center no-repeat;
background-size: auto 200%;
}
Following is an up to date ES6 example using a ref.
Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount()
because we can only determine the height of an element after it is rendered in the DOM.
import React, {Component} from 'react'
import {render} from 'react-dom'
class DivSize extends Component {
constructor(props) {
super(props)
this.state = {
height: 0
}
}
componentDidMount() {
const height = this.divElement.clientHeight;
this.setState({ height });
}
render() {
return (
<div
className="test"
ref={ (divElement) => { this.divElement = divElement } }
>
Size: <b>{this.state.height}px</b> but it should be 18px after the render
</div>
)
}
}
render(<DivSize />, document.querySelector('#container'))
You can find the running example here: https://codepen.io/bassgang/pen/povzjKw
Hi first of all i would like you to use 'Synaptic Package Manager'. You just need to goto the ubuntu software center and search for synaptic package manager.. The beauty of this is that all the packages you need are easily available here. Second it will automatically configures all your paths. Now install this then search for opencv packages over there if you found the package with the green box then its installed but else the package is not in the right place so you need to reinstall it but from package manager this time. If installed then you can do this only, you just need to fill the OpenCV_DIR variable with the path of opencv (containing the OpenCVConfig.cmake file)
export OpenCV_DIR=<path_of_opencv>
Get this error at the time of adding Node in my Angular project -
TSError: ? Unable to compile TypeScript: (path)/base.api.ts:19:13 - error TS2564: Property 'apiRoot Path' has no initializer and is not definitely assigned in the constructor.
private apiRootPath: string;
Solution -
Added "strictPropertyInitialization": false
in 'compilerOptions' of tsconfig.json.
my package.json -
"dependencies": {
...
"@angular/common": "~10.1.3",
"@types/express": "^4.17.9",
"express": "^4.17.1",
...
}
Your syntax is incorrect, you should pass the value as the second parameter:
jQuery(this).prev("li").attr("id","newId");
<%# (string)Eval("gender") =="M" ? "Male" :"Female"%>
Eric Leschinski and Bartosz Milewski have given the answer already. Here, I will try to present it in a more beginner friendly manner.
Once a thread has been started within a scope (which itself is running on a thread), one must explicitly ensure one of the following happens before the thread goes out of scope:
Note, by the time the thread is joined with or detached, it may have well finished executing. Still either of the two operations must be performed explicitly.
You can add these single quotes with template literals:
var text = "http://example.com"_x000D_
var quoteText = `'${text}'`_x000D_
_x000D_
console.log(quoteText)
_x000D_
Docs are here. Browsers that support template literals listed here.
They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).
The main equations are:
frame.origin = center - bounds.size / 2
(which is the same as)
center = frame.origin + bounds.size / 2
(and there’s also)
frame.size = bounds.size
That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.
This stuff is all explained in more detail with a useful mini-library here:
THE ANSWER BELOW IS THE GOOD ONE
You aren't using the data method correctly. The correct code to update data is:
$('#foo').data('num', num);
So your example would be:
var num = $('#foo').data("num") + 1;
console.log(num)
$('#foo').data('num', num);
console.log(num)
I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:
df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)
One of the easiest solution is
$objectData = (object) $arrayData
It's a language abstraction - some languages have both, some one, some neither.
In the case of C++, the code is not run in either the stack or the heap. You can test what happens if you run out of heap memory by repeatingly calling new
to allocate memory in a loop without calling delete
to free it it. But make a system backup before doing this.
After messing about with some stuff in cron which wasn't instantly compatible I found that the following approach was nice for debugging:
crontab -e
* * * * * /path/to/prog var1 var2 &>>/tmp/cron_debug_log.log
This will run the task once a minute and you can simply look in the /tmp/cron_debug_log.log
file to figure out what is going on.
It is not exactly the "fire job" you might be looking for, but this helped me a lot when debugging a script that didn't work in cron at first.
do a :
git branch
if git show you something like :
* (no branch)
master
Dbranch
You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with
git checkout master
Now you should be able to delete the Dbranch.
As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )
The querystring (get) parameters included in your url probably will not do anything.
Try this:
string url = "http://myserver/method";
string content = "param1=1¶m2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);
HTH,
bovako
I think that SYSLOG levels NOTICE and ALERT/EMERGENCY are largely superfluous for application-level logging - while CRITICAL/ALERT/EMERGENCY may be useful alert levels for an operator that may trigger different actions and notifications, to an application admin it's all the same as FATAL. And I just cannot sufficiently distinguish between being given a notice or some information. If the information is not noteworthy, it's not really information :)
I like Jay Cincotta's interpretation best - tracing your code's execution is something very useful in tech support, and putting trace statements into the code liberally should be encouraged - especially in combination with a dynamic filtering mechanism for logging the trace messages from specific application components. However DEBUG level to me indicates that we're still in the process of figuring out what's going on - I see DEBUG level output as a development-only option, not as something that should ever show up in a production log.
There is however a logging level that I like to see in my error logs when wearing the hat of a sysadmin as much as that of tech support, or even developer: OPER, for OPERATIONAL messages. This I use for logging a timestamp, the type of operation invoked, the arguments supplied, possibly a (unique) task identifier, and task completion. It's used when e.g. a standalone task is fired off, something that is a true invocation from within the larger long-running app. It's the sort of thing I want always logged, no matter whether anything goes wrong or not, so I consider the level of OPER to be higher than FATAL, so you can only turn it off by going to totally silent mode. And it's much more than mere INFO log data - a log level often abused for spamming logs with minor operational messages of no historical value whatsoever.
As the case dictates this information may be directed to a separate invocation log, or may be obtained by filtering it out of a large log recording more information. But it's always needed, as historical info, to know what was being done - without descending to the level of AUDIT, another totally separate log level that has nothing to do with malfunctions or system operation, doesn't really fit within the above levels (as it needs its own control switch, not a severity classification) and which definitely needs its own separate log file.
One major feature of rsync
over scp
(beside the delta algorithm and encryption if used w/ ssh) is that it automatically verifies if the transferred file has been transferred correctly. Scp will not do that, which occasionally might result in corruption when transferring larger files. So in general rsync is a copy with guarantee.
Centos manpages mention this the end of the --checksum
option description:
Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option’s before-the-transfer “Does this file need to be updated?” check.
I found the solution myself later, so I placed it as an answer:
The error persisted every now and then when adding new function to my JS file. I ultimately stripped down my concatenated JS file and found out that there were two versions of jQuery being loaded, of which one was very, very old.
A far more common answer is that you have some error that is getting appended to whatever your compressing. The solution is to set display_errors = Off
in your php.ini file (Check in your terminal if it's On by running php --info
and look for "display_errors")
That should do it. And, how do you discover what errors you're actually? Check your PHP error logs whenever you hit that route/page.
Good luclk!
I have a set of 15 subroutines I add to every Coded Excel Workbook I create and this is one of them. The following routine clears the area and creates a border.
Sample Call:
Call BoxIt(Range("A1:z25"))
Subroutine:
Sub BoxIt(aRng As Range)
On Error Resume Next
With aRng
'Clear existing
.Borders.LineStyle = xlNone
'Apply new borders
.BorderAround xlContinuous, xlThick, 0
With .Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = 0
.Weight = xlMedium
End With
With .Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = 0
.Weight = xlMedium
End With
End With
End Sub
I have used a method to test if any specific key is pressed by storing the currently pressed key codes in an array:
var keysPressed = [],
shiftCode = 16;
$(document).on("keyup keydown", function(e) {
switch(e.type) {
case "keydown" :
keysPressed.push(e.keyCode);
break;
case "keyup" :
var idx = keysPressed.indexOf(e.keyCode);
if (idx >= 0)
keysPressed.splice(idx, 1);
break;
}
});
$("a.shifty").on("click", function(e) {
e.preventDefault();
console.log("Shift Pressed: " + (isKeyPressed(shiftCode) ? "true" : "false"));
});
function isKeyPressed(code) {
return keysPressed.indexOf(code) >= 0;
}
Use the inbuilt function in PHP, implode(array, separator)
:
<?php
$ar = array("parth","raja","nikhar");
echo implode($ar,"/");
?>
Result: parth/raja/nikhar
I'm guessing that you don't need to re-increment the existing data so, why can't you just run a simple ALTER TABLE command to change the PK's attributes?
Something like:
ALTER TABLE `content` CHANGE `id` `id` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT
I've tested this code on my own MySQL database and it works but I have not tried it with any meaningful number of records. Once you've altered the row then you need to reset the increment to a number guaranteed not to interfere with any other records.
ALTER TABLE `content` auto_increment = MAX(`id`) + 1
Again, untested but I believe it will work.
I think if the HTML and other UI stuff needs the data returned then there is not going to be a way to async it.
I believe the only way to do this in PHP would be to log a request in a database and have a cron check every minute, or use something like Gearman queue processing, or maybe exec() a command line process
In the meantime you php page would have to generate some html or js that makes it reload every few seconds to check on progress, not ideal.
To sidestep the issue, how many different requests are you expecting? Could you download them all automatically every hour or so and save to a database?
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it
<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>
Online Demo! - https://codepen.io/frank-dspeed/pen/mdywbre
import json
list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
Write to json File:
with open('/home/ubuntu/test.json', 'w') as fout:
json.dump(list , fout)
Read Json file:
with open(r"/home/ubuntu/test.json", "r") as read_file:
data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
Try It :
DECLARE @String NVARCHAR(100)
SET @String = '12354851'
SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))
You could try my (*heavily borrowed from various sites) recursive method to go through all JSON objects and JSON arrays until you find JSON elements. This example actually searches for a particular key and returns all values for all instances of that key. 'searchKey' is the key you are looking for.
ArrayList<String> myList = new ArrayList<String>();
myList = findMyKeyValue(yourJsonPayload,null,"A"); //if you only wanted to search for A's values
private ArrayList<String> findMyKeyValue(JsonElement element, String key, String searchKey) {
//OBJECT
if(element.isJsonObject()) {
JsonObject jsonObject = element.getAsJsonObject();
//loop through all elements in object
for (Map.Entry<String,JsonElement> entry : jsonObject.entrySet()) {
JsonElement array = entry.getValue();
findMyKeyValue(array, entry.getKey(), searchKey);
}
//ARRAY
} else if(element.isJsonArray()) {
//when an array is found keep 'key' as that is the array's name i.e. pass it down
JsonArray jsonArray = element.getAsJsonArray();
//loop through all elements in array
for (JsonElement childElement : jsonArray) {
findMyKeyValue(childElement, key, searchKey);
}
//NEITHER
} else {
//System.out.println("SKey: " + searchKey + " Key: " + key );
if (key.equals(searchKey)){
listOfValues.add(element.getAsString());
}
}
return listOfValues;
}
Use the Arrays.toString() function. It keeps your code short and readable. It uses a string builder internally, thus, it's also efficient. To get rid of the extra characters, you might chose to eliminate them using the String.replace() function, which, admittedly, reduces readability again.
String str = Arrays.toString(arr).replaceAll(", |\\[|\\]", "");
This is similar to the answer of Tris Nefzger, but without the lengthy substring construction to get rid of the square brackets.
Explanation of the Regex: "|" means any of ", " and "[" and "]". The "\\" tells the Java String that we are not meaning some special character (like a new line "\n" or a tab "\t") but a real backslash "\". So instead of "\\[", the Regex interpreter reads "\[", which tells it that we mean a literal square bracket and do not want to use it as part of the Regex language (for instance, "[^3]*" denotes any number of characters, but none of them should be "3").
Try running fuser command
[root@guest2 ~]# fuser -mv /home
USER PID ACCESS COMMAND
/home: root 2919 f.... automount
[root@guest2 ~]# kill -9 2919
autofs
service is known to cause this issue.
You can use command
#service autofs stop
And try again.
On Windows/Linux press Alt+F3.
Jenkins 1.627, OS X 10.10.5
/Users/Shared/Jenkins/Home/jobs/{project_name}/config.xml
These words existed way before Computer Science came around.
Attribute is a quality or object that we attribute to someone or something. For example, the scepter is an attribute of power and statehood.
Property is a quality that exists without any attribution. For example, clay has adhesive qualities; i.e, a property of clay is its adhesive quality. Another example: one of the properties of metals is electrical conductivity. Properties demonstrate themselves through physical phenomena without the need to attribute them to someone or something. By the same token, saying that someone has masculine attributes is self-evident. In effect, you could say that a property is owned by someone or something.
To be fair though, in Computer Science these two words, at least for the most part, can be used interchangeably - but then again programmers usually don't hold degrees in English Literature and do not write or care much about grammar books :).
typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)
Try this :
<style type="text/css">
.myTableStyle
{
position:absolute;
top:50%;
left:50%;
/*Alternatively you could use: */
/*
position: fixed;
bottom: 50%;
right: 50%;
*/
}
</style>
You can try :
>>> string = "test test test test"
>>> for index,value in enumerate(string):
if string[index:index+(len("test"))] == "test":
print index
0
5
10
15
$('#toptitle').html('New world');
or
$('#toptitle').text('New world');
With the latest .NET Framework, it is possible to return a value from a separate thread using a Task, where the Result property blocks the calling thread until the task finishes:
Task<MyClass> task = Task<MyClass>.Factory.StartNew(() =>
{
string s = "my message";
double d = 3.14159;
return new MyClass { Name = s, Number = d };
});
MyClass test = task.Result;
For details, please see http://msdn.microsoft.com/en-us/library/dd537613(v=vs.110).aspx
This is an UIImage extension compatible with Swift 3 and Swift 4 which scales image to given size with an aspect ratio
extension UIImage {
func scaledImage(withSize size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
return UIGraphicsGetImageFromCurrentImageContext()!
}
func scaleImageToFitSize(size: CGSize) -> UIImage {
let aspect = self.size.width / self.size.height
if size.width / aspect <= size.height {
return scaledImage(withSize: CGSize(width: size.width, height: size.width / aspect))
} else {
return scaledImage(withSize: CGSize(width: size.height * aspect, height: size.height))
}
}
}
Example usage
let image = UIImage(named: "apple")
let scaledImage = image.scaleImageToFitSize(size: CGSize(width: 45.0, height: 45.0))
The generic answer provided by "Joel Coehoorn" is good.
But, this is another way without using those GetConverter...
or try/catch
blocks... (i'm not sure but this may have better performance in some cases):
public static class StrToNumberExtensions
{
public static short ToShort(this string s, short defaultValue = 0) => short.TryParse(s, out var v) ? v : defaultValue;
public static int ToInt(this string s, int defaultValue = 0) => int.TryParse(s, out var v) ? v : defaultValue;
public static long ToLong(this string s, long defaultValue = 0) => long.TryParse(s, out var v) ? v : defaultValue;
public static decimal ToDecimal(this string s, decimal defaultValue = 0) => decimal.TryParse(s, out var v) ? v : defaultValue;
public static float ToFloat(this string s, float defaultValue = 0) => float.TryParse(s, out var v) ? v : defaultValue;
public static double ToDouble(this string s, double defaultValue = 0) => double.TryParse(s, out var v) ? v : defaultValue;
public static short? ToshortNullable(this string s, short? defaultValue = null) => short.TryParse(s, out var v) ? v : defaultValue;
public static int? ToIntNullable(this string s, int? defaultValue = null) => int.TryParse(s, out var v) ? v : defaultValue;
public static long? ToLongNullable(this string s, long? defaultValue = null) => long.TryParse(s, out var v) ? v : defaultValue;
public static decimal? ToDecimalNullable(this string s, decimal? defaultValue = null) => decimal.TryParse(s, out var v) ? v : defaultValue;
public static float? ToFloatNullable(this string s, float? defaultValue = null) => float.TryParse(s, out var v) ? v : defaultValue;
public static double? ToDoubleNullable(this string s, double? defaultValue = null) => double.TryParse(s, out var v) ? v : defaultValue;
}
Usage is as following:
var x1 = "123".ToInt(); //123
var x2 = "abc".ToInt(); //0
var x3 = "abc".ToIntNullable(); // (int?)null
int x4 = ((string)null).ToInt(-1); // -1
int x5 = "abc".ToInt(-1); // -1
var y = "19.50".ToDecimal(); //19.50
var z1 = "invalid number string".ToDoubleNullable(); // (double?)null
var z2 = "invalid number string".ToDoubleNullable(0); // (double?)0
<div class="col-md-4 offset-md-4">
put your form here
</div>
Because UICollectionView
is so flexible, there are multiple ways you could change the number of columns, depending on the kind of layout you use.
The UICollectionViewFlowLayout
(which is probably what you're working with) doesn't specify a number of columns directly (because it depends on the view size/orientation). The easiest way to change it would be to set the itemSize
property and/or minimumInteritemSpacing
/minimumLineSpacing
.
var counter = 0;
function getSlug(tokens) {
var slug = '';
if (!!tokens.length) {
slug = tokens.shift();
slug = slug.toLowerCase();
slug += getSlug(tokens);
counter += 1;
console.log('THE SLUG ELEMENT IS: %s, counter is: %s', slug, counter);
}
return slug;
}
var mySlug = getSlug(['This', 'Is', 'My', 'Slug']);
console.log('THE SLUG IS: %s', mySlug);
Notice that the counter
counts "backwards" in regards to what slug
's value is. This is because of the position at which we are logging these values, as the function recurs before logging -- so, we essentially keep nesting deeper and deeper into the call-stack before logging takes place.
Once the recursion meets the final call-stack item, it trampolines "out" of the function calls, whereas, the first increment of counter
occurs inside of the last nested call.
I know this is not a "fix" on the Questioner's code, but given the title I thought I'd generically exemplify Recursion for a better understanding of recursion, outright.
Although Marcus Ekwall is absolutely right about the synchronicity of append, I have also found that in odd situations sometimes the DOM isn't completely rendered by the browser when the next line of code runs.
In this scenario then shadowdiver solutions is along the correct lines - with using .ready - however it is a lot tidier to chain the call to your original append.
$('#root')
.append(html)
.ready(function () {
// enter code here
});
What about :
List myList = new ArrayList();
String[] myStringArray = new String[] {"Java", "is", "Cool"};
Collections.addAll(myList, myStringArray);
Whether the file is sorted or not, you can use below regex to remove duplicates in anywhere occurred in your file.
Find what: ^([^\r]*[^\n])(.*?)\r?\n\1$
Replace with: \1\2
Search Mode:
do "Replace All" as many time as possible until you see "0 occurrences were replaced"
Make sure R.layout.themechanger
has no background color because by default the dialog has a default background color.
You also need to add dialog.getWindow().setBackgroundDrawable(newColorDrawable(Color.TRANSPARENT));
And finally
<style name="TransparentDialog">
<item name="android:windowIsFloating">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowTitleStyle">@null</item>
</style>
Cody has it right, but I want to provide an example of what an inline function is.
Let's say you have this code:
private void OutputItem(string x)
{
Console.WriteLine(x);
//maybe encapsulate additional logic to decide
// whether to also write the message to Trace or a log file
}
public IList<string> BuildListAndOutput(IEnumerable<string> x)
{ // let's pretend IEnumerable<T>.ToList() doesn't exist for the moment
IList<string> result = new List<string>();
foreach(string y in x)
{
result.Add(y);
OutputItem(y);
}
return result;
}
The compilerJust-In-Time optimizer could choose to alter the code to avoid repeatedly placing a call to OutputItem() on the stack, so that it would be as if you had written the code like this instead:
public IList<string> BuildListAndOutput(IEnumerable<string> x)
{
IList<string> result = new List<string>();
foreach(string y in x)
{
result.Add(y);
// full OutputItem() implementation is placed here
Console.WriteLine(y);
}
return result;
}
In this case, we would say the OutputItem() function was inlined. Note that it might do this even if the OutputItem() is called from other places as well.
Edited to show a scenario more-likely to be inlined.
RasterizeHTML is a very good project, but if you need to access the canvas it wont work on chrome. due to the use of <foreignObject>
.
If you need to access the canvas then you can use html2canvas
I am trying to find another project as html2canvas is very slow in performance
I suspect GCC (mingw) has custom code to disable the checks for the wide printf
functions on Windows. This is because Microsoft's own implementation (MSVCRT) is badly wrong and has %s
and %ls
backwards for the wide printf
functions; since GCC can't be sure whether you will be linking with MS's broken implementation or some corrected one, the least-obtrusive thing it can do is just shut off the warning.
You will need to,
ON DELETE CASCADE
setting enabled.Something like:
ALTER TABLE dbo.T2
DROP CONSTRAINT FK_T1_T2 -- or whatever it's called
ALTER TABLE dbo.T2
ADD CONSTRAINT FK_T1_T2_Cascade
FOREIGN KEY (EmployeeID) REFERENCES dbo.T1(EmployeeID) ON DELETE CASCADE
I had this error message when trying "hello world" like things with Qt. The problems went away by correctly running the qt moc (meta object compiler) and compiling+including these moc-generated files correctly.
To prevent browser auto fill with the user's saved site login credentials, place a text and password input field at the top of the form with non empty values and style "position: absolute; top: -999px; left:-999px" set to hide the fields.
<form>
<input type="text" name="username_X" value="-" tabindex="-1" aria-hidden="true" style="position: absolute; top: -999px; left:-999px" />
<input type="password" name="password_X" value="-" tabindex="-1" aria-hidden="true" style="position: absolute; top: -999px; left:-999px" />
<!-- Place the form elements below here. -->
</form>
It is important that a text field precede the password field. Otherwise the auto fill may not be prevented in some cases.
It is important that the value of both the text and password fields not be empty, to prevent default values from being overwritten in some cases.
It is important that these two fields are before the "real" password type field(s) in the form.
For newer browsers that are html 5.3 compliant the autocomplete attribute value "new-password" should work.
<form>
<input type="text" name="username" value="" />
<input type="password" name="password" value="" autocomplete="new-password" />
</form>
A combination of the two methods can be used to support both older and newer browsers.
<form>
<div style="display:none">
<input type="text" readonly tabindex="-1" />
<input type="password" readonly tabindex="-1" />
</div>
<!-- Place the form elements below here. -->
<input type="text" name="username" value="" />
<input type="password" name="password" value="" autocomplete="new-password" />
</form>
As an add-on, if you need to see if a file exists before you try to open an input stream, you can use the DocumentsContract.
(Kotlin code)
var iStream = null
if(DocumentsContract.isDocumentUri(context,myUri)) {
val pfd: ParcelFileDescriptor? = context.contentResolver.openFileDescriptor(
myUri, "r") ?: return null
iStream = ParcelFileDescriptor.AutoCloseInputStream(pfd)
}
I made a small adaptation in Nicko's solution so that it is not necessary to use the Apache Commons BeanUtils library and replace it with the solution already available in spring, for those using it as I can be simpler:
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {
private String firstFieldName;
private String secondFieldName;
@Override
public void initialize(final FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
@Override
public boolean isValid(final Object object, final ConstraintValidatorContext context) {
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
final Object firstObj = beanWrapper.getPropertyValue(firstFieldName);
final Object secondObj = beanWrapper.getPropertyValue(secondFieldName);
boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
if (!isValid) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addPropertyNode(firstFieldName)
.addConstraintViolation();
}
return isValid;
}
}
Another answer: in some contexts, it makes sense to define your enumeration in a non-code format, like a CSV, YAML, or XML file, and then generate both the C++ enumeration code and the to-string code from the definition. This approach may or may not be practical in your application, but it's something to keep in mind.
try translate
>>> import string
>>> print '\t\r\n hello \r\n world \t\r\n'
hello
world
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr)
' hello world '
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'
Try this:
if (AgeItem.AgeIndex != null)
{
SqlParameter[] parameters = new SqlParameter[1];
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
planIndexParameter.Value = AgeItem.AgeIndex;
parameters[0] = planIndexParameter;
}
In other words, if the parameter is null just don't send it to your stored proc (assuming, of course, that the stored proc accepts null parameters which is implicit in your question).
I think this is not the best way, but in my cases other methods did not work.
stylesheet = document.styleSheets[0]
stylesheet.insertRule(".have-border { border: 1px solid black;}", 0);
Example from https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript
There is my version of an email validator. This code is done with object-oriented programming and realized as a class with static methods. You will find two versions of the validators: strict(EmailValidator.validate
) and kind(EmailValidator.validateKind
).
The first throws an error if an email is invalid and returns email otherwise. The second returns Boolean value that says if an email is valid. I prefer the strict version in most of the cases.
export class EmailValidator {
/**
* @param {string} email
* @return {string}
* @throws {Error}
*/
static validate(email) {
email = this.prepareEmail(email);
const isValid = this.validateKind(email);
if (isValid)
return email;
throw new Error(`Got invalid email: ${email}.`);
}
/**
* @param {string} email
* @return {boolean}
*/
static validateKind(email) {
email = this.prepareEmail(email);
const regex = this.getRegex();
return regex.test(email);
}
/**
* @return {RegExp}
* @private
*/
static getRegex() {
return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
}
/**
* @param {string} email
* @return {string}
* @private
*/
static prepareEmail(email) {
return String(email).toLowerCase();
}
}
To validate an email you can follow these ways:
// First way.
try {
EmailValidator.validate('[email protected]');
} catch (e) {
console.error(e.message);
}
// Second way.
const email = '[email protected]';
const isValid = EmailValidator.validateKind(email);
if (isValid)
console.log(`Email is valid: ${email}.`);
else
console.log(`Email is invalid: ${email}.`);
For Me adding few below line in WebApi.config works as after updating the new nuget package did not works out
var setting = config.Formatters.JsonFormatter.SerializerSettings;
setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
setting.Formatting = Formatting.Indented;
Don't forget to add namespace:
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
functional
function encodeData(data) {
return Object.keys(data).map(function(key) {
return [key, data[key]].map(encodeURIComponent).join("=");
}).join("&");
}
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
window.location = myUrl;
Anyway, this is not jQuery: it's plain javascript
body{
background-image: url(../url/imageName.jpg);
background-attachment: fixed;
background-size: auto 100%;
background-position: center;
}
The Arrays.equals(array1, array2)
:
check if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.
The array1.equals(array2)
:
compare the object to another object and return true only if the reference of the two object are equal as in the Object.equals()
The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.
Step 1:
Step 2:
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:
vars:
myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
How was the database exported?
If it was exported using exp
and a full schema was exported, then
Create the user:
create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
Grant the rights:
grant connect, create session, imp_full_database to <username>;
Start the import with imp
:
imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
If it was exported using expdp
, then start the import with impdp
:
impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp
file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\
).
Either move the export file to the above path or create a directory object to pointing to the path where the dmp
file is present and pass the object name to the impdp
command above.
None of these answers really work. As others noted the Cors package will only use the Access-Control-Allow-Origin header if the request had an Origin header. But you can't generally just add an Origin header to the request because browsers may try to regulate that too.
If you want a quick and dirty way to allow cross site requests to a web api, it's really a lot easier to just write a custom filter attribute:
public class AllowCors : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext == null)
{
throw new ArgumentNullException("actionExecutedContext");
}
else
{
actionExecutedContext.Response.Headers.Remove("Access-Control-Allow-Origin");
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
base.OnActionExecuted(actionExecutedContext);
}
}
Then just use it on your Controller action:
[AllowCors]
public IHttpActionResult Get()
{
return Ok("value");
}
I won't vouch for the security of this in general, but it's probably a lot safer than setting the headers in the web.config since this way you can apply them only as specifically as you need them.
And of course it is simple to modify the above to allow only certain origins, methods etc.
That's not a typical Wordpress rewrite block. This is:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
See http://codex.wordpress.org/Using_Permalinks#Where.27s_my_.htaccess_file.3F
Where's my .htaccess file? WordPress's index.php and .htaccess files should be together in the directory indicated by the Site address (URL) setting on your General Options page. Since the name of the file begins with a dot, the file may not be visible through an FTP client unless you change the preferences of the FTP tool to show all files, including the hidden files. Some hosts (e.g. Godaddy) may not show or allow you to edit .htaccess if you install WordPress through the Godaddy Hosting Connection installation.
Creating and editing (.htaccess) If you do not already have a .htaccess file, create one. If you have shell or ssh access to the server, a simple touch .htaccess command will create the file. If you are using FTP to transfer files, create a file on your local computer, call it 1.htaccess, upload it to the root of your WordPress folder, and then rename it to .htaccess.
You can edit the .htaccess file by FTP, shell, or (possibly) your host's control panel.
The easiest and fastest thing to do it reset your permalinks in Dashboard>>Settings>>Permalinks and make sure .htaccess is writable so WordPress can write the rules itself.
And: are you aware you are calling index.cgi
as your default document rather than index.php
? That's wrong. Remove index.cgi
. Or try removing the whole line, too, because defining a default doc on your server may not be needed.
Always use the printf
family of functions for this. Even if you want to get the value as a float, you're best off using snprintf
to get the rounded value as a string and then parsing it back with atof
:
#include <math.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
double dround(double val, int dp) {
int charsNeeded = 1 + snprintf(NULL, 0, "%.*f", dp, val);
char *buffer = malloc(charsNeeded);
snprintf(buffer, charsNeeded, "%.*f", dp, val);
double result = atof(buffer);
free(buffer);
return result;
}
I say this because the approach shown by the currently top-voted answer and several others here - multiplying by 100, rounding to the nearest integer, and then dividing by 100 again - is flawed in two ways:
To illustrate the first kind of error - the rounding direction sometimes being wrong - try running this program:
int main(void) {
// This number is EXACTLY representable as a double
double x = 0.01499999999999999944488848768742172978818416595458984375;
printf("x: %.50f\n", x);
double res1 = dround(x, 2);
double res2 = round(100 * x) / 100;
printf("Rounded with snprintf: %.50f\n", res1);
printf("Rounded with round, then divided: %.50f\n", res2);
}
You'll see this output:
x: 0.01499999999999999944488848768742172978818416595459
Rounded with snprintf: 0.01000000000000000020816681711721685132943093776703
Rounded with round, then divided: 0.02000000000000000041633363423443370265886187553406
Note that the value we started with was less than 0.015, and so the mathematically correct answer when rounding it to 2 decimal places is 0.01. Of course, 0.01 is not exactly representable as a double, but we expect our result to be the double nearest to 0.01. Using snprintf
gives us that result, but using round(100 * x) / 100
gives us 0.02, which is wrong. Why? Because 100 * x
gives us exactly 1.5 as the result. Multiplying by 100 thus changes the correct direction to round in.
To illustrate the second kind of error - the result sometimes being wrong due to * 100
and / 100
not truly being inverses of each other - we can do a similar exercise with a very big number:
int main(void) {
double x = 8631192423766613.0;
printf("x: %.1f\n", x);
double res1 = dround(x, 2);
double res2 = round(100 * x) / 100;
printf("Rounded with snprintf: %.1f\n", res1);
printf("Rounded with round, then divided: %.1f\n", res2);
}
Our number now doesn't even have a fractional part; it's an integer value, just stored with type double
. So the result after rounding it should be the same number we started with, right?
If you run the program above, you'll see:
x: 8631192423766613.0
Rounded with snprintf: 8631192423766613.0
Rounded with round, then divided: 8631192423766612.0
Oops. Our snprintf
method returns the right result again, but the multiply-then-round-then-divide approach fails. That's because the mathematically correct value of 8631192423766613.0 * 100
, 863119242376661300.0
, is not exactly representable as a double; the closest value is 863119242376661248.0
. When you divide that back by 100, you get 8631192423766612.0
- a different number to the one you started with.
Hopefully that's a sufficient demonstration that using roundf
for rounding to a number of decimal places is broken, and that you should use snprintf
instead. If that feels like a horrible hack to you, perhaps you'll be reassured by the knowledge that it's basically what CPython does.
According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:
cv2.cv.CV_CAP_PROP_POS_FRAMES
to
cv2.CAP_PROP_POS_FRAMES
and same applies to cv2.CAP_PROP_POS_FRAME_COUNT
.
Hope it helps.
If you have less than 4 rows, you can use the head
function ( head(data, 4)
or head(data, n=4)
) and it works like a charm. But, assume we have the following dataset with 15 rows
>data <- data <- read.csv("./data.csv", sep = ";", header=TRUE)
>data
LungCap Age Height Smoke Gender Caesarean
1 6.475 6 62.1 no male no
2 10.125 18 74.7 yes female no
3 9.550 16 69.7 no female yes
4 11.125 14 71.0 no male no
5 4.800 5 56.9 no male no
6 6.225 11 58.7 no female no
7 4.950 8 63.3 no male yes
8 7.325 11 70.4 no male no
9 8.875 15 70.5 no male no
10 6.800 11 59.2 no male no
11 6.900 12 59.3 no male no
12 6.100 13 59.4 no male no
13 6.110 14 59.5 no male no
14 6.120 15 59.6 no male no
15 6.130 16 59.7 no male no
Let's say, you want to select the first 10 rows. The easiest way to do it would be data[1:10, ]
.
> data[1:10,]
LungCap Age Height Smoke Gender Caesarean
1 6.475 6 62.1 no male no
2 10.125 18 74.7 yes female no
3 9.550 16 69.7 no female yes
4 11.125 14 71.0 no male no
5 4.800 5 56.9 no male no
6 6.225 11 58.7 no female no
7 4.950 8 63.3 no male yes
8 7.325 11 70.4 no male no
9 8.875 15 70.5 no male no
10 6.800 11 59.2 no male no
However, let's say you try to retrieve the first 19 rows and see the what happens - you will have missing values
> data[1:19,]
LungCap Age Height Smoke Gender Caesarean
1 6.475 6 62.1 no male no
2 10.125 18 74.7 yes female no
3 9.550 16 69.7 no female yes
4 11.125 14 71.0 no male no
5 4.800 5 56.9 no male no
6 6.225 11 58.7 no female no
7 4.950 8 63.3 no male yes
8 7.325 11 70.4 no male no
9 8.875 15 70.5 no male no
10 6.800 11 59.2 no male no
11 6.900 12 59.3 no male no
12 6.100 13 59.4 no male no
13 6.110 14 59.5 no male no
14 6.120 15 59.6 no male no
15 6.130 16 59.7 no male no
NA NA NA NA <NA> <NA> <NA>
NA.1 NA NA NA <NA> <NA> <NA>
NA.2 NA NA NA <NA> <NA> <NA>
NA.3 NA NA NA <NA> <NA> <NA>
and with the head() function,
> head(data, 19) # or head(data, n=19)
LungCap Age Height Smoke Gender Caesarean
1 6.475 6 62.1 no male no
2 10.125 18 74.7 yes female no
3 9.550 16 69.7 no female yes
4 11.125 14 71.0 no male no
5 4.800 5 56.9 no male no
6 6.225 11 58.7 no female no
7 4.950 8 63.3 no male yes
8 7.325 11 70.4 no male no
9 8.875 15 70.5 no male no
10 6.800 11 59.2 no male no
11 6.900 12 59.3 no male no
12 6.100 13 59.4 no male no
13 6.110 14 59.5 no male no
14 6.120 15 59.6 no male no
15 6.130 16 59.7 no male no
Hope this help!
Try what's below. It will help you...
Fiddle : http://jsfiddle.net/RYh7U/146/
Script :
if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
alert("Availed");
else
alert("Not Availed");
function dateCheck(from,to,check) {
var fDate,lDate,cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if((cDate <= lDate && cDate >= fDate)) {
return true;
}
return false;
}
On macOS, one option is to install FUSE for macOS and use sshfs
to mount a remote directory:
mkdir local_dir
sshfs remote_user@remote_host:remote_dir/ local_dir
Some caveats apply with mounting network volumes, so YMMV.
In 2021 - use ES6 Template Literals for this task. If you need IE11 Support - use a transpiler.
let a = `something something`;
Template Literals are fast, powerful and produce cleaner code.
If you need IE11 support and you don't have transpiler, stay strong and use \xa0
- it is a NO-BREAK SPACE char.
Reference from UTF-8 encoding table and Unicode characters, you can write as below:
var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + 'something';
There is a minimal amount of "default" buffer when you startup a 'screen' session within your 'putty session'. I use screens a lot in my work, so I can tell you that you will not have a combination of 'screen' buffer & 'putty' buffer within your 'screen' session.
Setting the default number of scrollback lines by adding defscrollback 10000
to your ~/.screenrc
file is the correct solution.
By the way, I use "defscrollback 200000" in my ./screenrc
file.
Look at the package DBMS_Redefinition. It will rebuild the table with the new ordering. It can be done with the table online.
As Phil Brown noted, think carefully before doing this. However there is overhead in scanning the row for columns and moving data on update. Column ordering rules I use (in no particular order):
These rules conflict and have not all been tested for performance on the latest release. Most have been tested in practice, but I didn't document the results. Placement options target one of three conflicting goals: easy to understand column placement; fast data retrieval; and minimal data movement on updates.
Definitely the second method is preferred because you don't have the overhead of another function invocation:
window.location.href = "webpage.htm";
What exactly do you want to know? ActiveRecord has methods that serialize records into JSON. For instance, open up your rails console and enter ModelName.all.to_json
and you will see JSON output. render :json
essentially calls to_json
and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback
option to specify the name of the callback you would like to call via JSONP.
For instance, lets say we have a User
model that looks like this: {name: 'Max', email:' [email protected]'}
We also have a controller that looks like this:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user
end
end
Now, if we do an AJAX call using jQuery like this:
$.ajax({
type: "GET",
url: "/users/5",
dataType: "json",
success: function(data){
alert(data.name) // Will alert Max
}
});
As you can see, we managed to get the User with id 5 from our rails app and use it in our JavaScript code because it was returned as a JSON object. The callback option just calls a JavaScript function of the named passed with the JSON object as the first and only argument.
To give an example of the callback
option, take a look at the following:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user, callback: "testFunction"
end
end
Now we can crate a JSONP request as follows:
function testFunction(data) {
alert(data.name); // Will alert Max
};
var script = document.createElement("script");
script.src = "/users/5";
document.getElementsByTagName("head")[0].appendChild(script);
The motivation for using such a callback is typically to circumvent the browser protections that limit cross origin resource sharing (CORS). JSONP isn't used that much anymore, however, because other techniques exist for circumventing CORS that are safer and easier.
You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.
Request and response HTTP headers can also be used to pass information between service calls.
For creating an array of random numbers NumPy provides array creation using:
Real numbers
Integers
For creating array using random Real numbers: there are 2 options
random.rand
import numpy as np
arr = np.random.rand(row_size, column_size)
random.randn
import numpy as np
arr = np.random.randn(row_size, column_size)
For creating array using random Integers:
import numpy as np
numpy.random.randint(low, high=None, size=None, dtype='l')
where
eg:
The given example will produce an array of random integers between 0 and 4, its size will be 5*5 and have 25 integers
arr2 = np.random.randint(0,5,size = (5,5))
arr2 = np.random.randint(0,5,size = (5,5)), change the multiplication symbol* to a comma ,#
[[2 1 1 0 1][3 2 1 4 3][2 3 0 3 3][1 3 1 0 0][4 1 2 0 1]]
eg2:
The given example will produce an array of random integers between 0 and 1, its size will be 1*10 and will have 10 integers
arr3= np.random.randint(2, size = 10)
[0 0 0 0 1 1 0 0 1 1]
Similar to Jeff's idea (untested):
find . -name * -print0 | grep -v "exclude" | xargs -0 -I {} cp -a {} destination/