Comment to Skelly's really helpful workaround: in Bootstrap-sass 3.3.6, utilities.scss, line 19: .pull-left
has float:left !important
. Since that, I recommend to use !important in his CSS as well:
.dropdown-submenu.pull-left {
float:none !important;
}
The Fill function uses a DataReader internally. If your consideration is "Which one is more efficient?", then using a DataReader in a tight loop that populates a collection record-by-record, is likely to be the same load on the system as using DataAdapter.Fill.
(System.Data.dll, System.Data.Common.DbDataAdapter, FillInternal.)
alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");
or %0D%0A in a url
You need to link with the math library:
gcc -o sphere sphere.c -lm
The error you are seeing: error: ld returned 1 exit status
is from the linker ld
(part of gcc that combines the object files) because it is unable to find where the function pow
is defined.
Including math.h
brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a
. You need to link your program with this library so that the calls to functions like pow() are resolved.
The outfile should be in binary mode.
outFile = open('output.xml', 'wb')
You can set any pointer to NULL
, though NULL
is simply defined as 0 in C++:
myObject *foo = NULL;
Also note that NULL
is defined if you include standard headers, but is not built into the language itself. If NULL
is undefined, you can use 0 instead, or include this:
#ifndef NULL
#define NULL 0
#endif
As an aside, if you really want to set an object, not a pointer, to NULL
, you can read about the Null Object Pattern.
A cookie is simply a short text string that is sent back and forth between the client and the server. You could store name=bob; password=asdfas
in a cookie and send that back and forth to identify the client on the server side. You could think of this as carrying on an exchange with a bank teller who has no short term memory, and needs you to identify yourself for each and every transaction. Of course using a cookie to store this kind information is horrible insecure. Cookies are also limited in size.
Now, when the bank teller knows about his/her memory problem, He/She can write down your information on a piece of paper and assign you a short id number. Then, instead of giving your account number and driver's license for each transaction, you can just say "I'm client 12"
Translating that to Web Servers: The server will store the pertinent information in the session object, and create a session ID which it will send back to the client in a cookie. When the client sends back the cookie, the server can simply look up the session object using the ID. So, if you delete the cookie, the session will be lost.
One other alternative is for the server to use URL rewriting to exchange the session id.
Suppose you had a link - www.myserver.com/myApp.jsp
You could go through the page and rewrite every URL as www.myserver.com/myApp.jsp?sessionID=asdf
or even www.myserver.com/asdf/myApp.jsp
and exchange the identifier that way. This technique is handled by the web application container and is usually turned on by setting the configuration to use cookieless sessions.
Split the strings and then use chain.from_iterable to combine them into a single list
>>> import itertools
>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [ x for x in itertools.chain.from_iterable( x.split(';') for x in l ) ]
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
The Arduino serial monitor isn't a regular terminal so its not possible to clear the screen using standard terminal commands. I suggest using an actual terminal emulator, like Putty.
The command for clearing a terminal screen is ESC[2J
To accomplish in Arduino code:
Serial.write(27); // ESC command
Serial.print("[2J"); // clear screen command
Serial.write(27);
Serial.print("[H"); // cursor to home command
You can use either h()
or html_escape()
, but most people use h()
by convention. h()
is short for html_escape()
in rails.
In your controller:
@stuff = "<b>Hello World!</b>"
In your view:
<%=h @stuff %>
If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as <b>Hello World!</b>
.
It will appear an be displayed as <b>Hello World!</b>
I had the same issue, but i had figured out that basically what happens when spring is trying to render the response it will try to serialize it according to the media type you have specified and by using getter and setter methods in your class
before my class used to look like below
public class MyRestResponse{
private String message;
}
solution looks like below
public class MyRestResponse{
private String message;
public void setMessage(String msg){
this.message = msg;
}
public String getMessage(){
return this.message;
}
}
that's how it worked for me
If you are installing first time then please try login with username and password as root
Find elements:
var elements = document.getElementsByClassName('widget hover');
Since elements
is a live
array and reflects all dom changes you can remove all hover
classes with a simple while loop:
while(elements.length > 0){
elements[0].classList.remove('hover');
}
Yes, you can use several namespaces at a time, eg:
using namespace boost;
using namespace std;
shared_ptr<int> p(new int(1)); // shared_ptr belongs to boost
cout << "cout belongs to std::" << endl; // cout and endl are in std
[Feb. 2014 -- (Has it really been that long?): This particular example is now ambiguous, as Joey points out below. Boost and std:: now each have a shared_ptr.]
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
if you really want to use CSS, use following property which will make field non-editable.
pointer-events: none;
plot "data.dat" using 2: xtic(1) with histogram
Here data.dat contains data of the form
title 1 title2 3 "long title" 5
Change:
profileImage.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
To:
Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
I use this code to compare 2 methods .My OS is windows 8 , processor core i5 , RAM 4GB
import time
def t_time():
start=time.time()
time.sleep(0.1)
return (time.time()-start)
def t_clock():
start=time.clock()
time.sleep(0.1)
return (time.clock()-start)
counter_time=0
counter_clock=0
for i in range(1,100):
counter_time += t_time()
for i in range(1,100):
counter_clock += t_clock()
print "time() =",counter_time/100
print "clock() =",counter_clock/100
output:
time() = 0.0993799996376
clock() = 0.0993572257367
Trying to depict with venn diagrams for better understanding..
Left Semi join : A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join.
Note : There is another thing called left anti join : An anti join returns values from the left relation that has no match with the right. It is also referred to as a left anti join.
Inner join : It selects rows that have matching values in both relations.
Today, you could try editorconfig, there is also a vim plugin for it. With this, you are able not only change indentation size in vim, but in many other editors, keep consistent coding styles.
Below is a simple editorconfig, as you can see, the python files will have 4 spaces for indentation, and pug template files will only have 2.
# 4 space indentation for python files
[*.py]
indent_style = space
indent_size = 4
# 2 space indentation for pug templates
[*.pug]
indent_size = 2
The correct answer is
git checkout -m origin/master
It merges changes from the origin master branch with your local even uncommitted changes.
From JavaScript, since the Github API is CORS enabled:
fetch('https://api.github.com/repos/webdev23/source_control_sentry')
.then(v => v.json()).then((function(v){
console.log(v['size'] + "KB")
})
)
_x000D_
hi just to come back at the question. If you want to sort the List of this sequence "1" "10" "100" "200" "2" "20" "3" "30" "300" and get the sorted items in this form 1;2;3;10;20;30;100;200;300 you can use this:
public class OrderingAscending : IComparer<String>
{
public int Compare(String x, String y)
{
Int32.TryParse(x, out var xtmp);
Int32.TryParse(y, out var ytmp);
int comparedItem = xtmp.CompareTo(ytmp);
return comparedItem;
}
}
and you can use it in code behind in this form:
IComparer<String> comparerHandle = new OrderingAscending();
yourList.Sort(comparerHandle);
As the PHP.net manual suggests, take a read of this discussion.
One major difference is that echo
can take multiple parameters to output. E.g.:
echo 'foo', 'bar'; // Concatenates the 2 strings
print('foo', 'bar'); // Fatal error
If you're looking to evaluate the outcome of an output statement (as below) use print
. If not, use echo
.
$res = print('test');
var_dump($res); //bool(true)
The same, if you need "generic" regex from string :
const textTitle = "this is a test";_x000D_
const regEx = new RegExp(' ', "g");_x000D_
const result = textTitle.replace(regEx , '%20');_x000D_
console.log(result); // "this%20is%20a%20test" will be a result_x000D_
_x000D_
Here's a snippet I used - with plain SimpleDateFormat
. Hope somebody else may benefit from it:
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") {
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos) {
StringBuffer toFix = super.format(date, toAppendTo, pos);
return toFix.insert(toFix.length()-2, ':');
};
};
// Usage:
System.out.println(dateFormat.format(new Date()));
}
Output:
- Usual Output.........: 2013-06-14T10:54:07-0200
- This snippet's Output: 2013-06-14T10:54:07-02:00
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
// Usage:
System.out.println(dateFormat2.format(new Date()));
Output:
- This pattern's output: 2013-06-14T10:54:07-02:00
See the docs for that.
If you are using fpdf, in order to be able to use line breaks you will need to use a multi-line text cell as described here.
If you use this, then line breaks in your text should be interpreted and converted correctly.
Just a quick example:
$pdf->Multicell(0,2,"This is a multi-line text string\nNew line\nNew line");
Here, 2 is the height of the multi-line text box. I don't know what units that's measured in or if you can just set it to 0 and ignore it. Perhaps try it with a large number if at first it doesn't work.
To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.
Click the Clone or download button and choose your method. I placed these into a dev/py/libs
directory in my user home directory. It does not matter where they are saved, because they will not be installed there.
You will need to run the following inside the setup-tools directory.
python bootstrap.py
python setup.py install
Now you can navigate to the more-itertools direcotry and install it as normal.
cd ...
) into the directory containing setup.py
python setup.py install
Copied from MSDN:
At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. For example, the verbatim string
@"C:\files.txt"
will appear in the watch window as"C:\\files.txt"
.
I made a script expanding on Yup.'s script. I fixed some things. It will now bypass 403:Forbidden problems. It wont crash when an image fails to be retrieved. It tries to avoid corrupted previews. It gets the right absolute urls. It gives out more information. It can be run with an argument from the command line.
# getem.py
# python2 script to download all images in a given url
# use: python getem.py http://url.where.images.are
from bs4 import BeautifulSoup
import urllib2
import shutil
import requests
from urlparse import urljoin
import sys
import time
def make_soup(url):
req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"})
html = urllib2.urlopen(req)
return BeautifulSoup(html, 'html.parser')
def get_images(url):
soup = make_soup(url)
images = [img for img in soup.findAll('img')]
print (str(len(images)) + " images found.")
print 'Downloading images to current working directory.'
image_links = [each.get('src') for each in images]
for each in image_links:
try:
filename = each.strip().split('/')[-1].strip()
src = urljoin(url, each)
print 'Getting: ' + filename
response = requests.get(src, stream=True)
# delay to avoid corrupted previews
time.sleep(1)
with open(filename, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
except:
print ' An error occured. Continuing.'
print 'Done.'
if __name__ == '__main__':
url = sys.argv[1]
get_images(url)
I use the header(name, value) method and give the return to webResource var:
Client client = Client.create();
WebResource webResource = client.resource("uri");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("json", js); //set parametes for request
appKey = "Bearer " + appKey; // appKey is unique number
//Get response from RESTful Server get(ClientResponse.class);
ClientResponse response = webResource.queryParams(queryParams)
.header("Content-Type", "application/json;charset=UTF-8")
.header("Authorization", appKey)
.get(ClientResponse.class);
String jsonStr = response.getEntity(String.class);
So what will happen if two threads attack a volatile primitive variable at same time?
Usually each one can increment the value. However sometime, both will update the value at the same time and instead of incrementing by 2 total, both thread increment by 1 and only 1 is added.
Does this mean that whosoever takes lock on it, that will be setting its value first.
There is no lock. That is what synchronized
is for.
And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?
Yes,
What is the difference between Atomic and volatile keyword?
AtomicXxxx wraps a volatile so they are basically same, the difference is that it provides higher level operations such as CompareAndSwap which is used to implement increment.
AtomicXxxx also supports lazySet. This is like a volatile set, but doesn't stall the pipeline waiting for the write to complete. It can mean that if you read a value you just write you might see the old value, but you shouldn't be doing that anyway. The difference is that setting a volatile takes about 5 ns, bit lazySet takes about 0.5 ns.
Use KeyPressEventArgs,
Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
e.Handled = True
End Sub
Inside your function for the click action use
$( "#tabs" ).tabs({ active: # });
Where # is replaced by the tab index you want to select.
Edit: change from selected to active, selected is deprecated
There are 2 options to create quality word documents. Use COM to communicate with word (this requires a windows php server at least). Use openoffice and it's API to create and save documents in word format.
As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.
As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.
Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851
$scope has a different 'this' then the controller 'this'.Thus if you put a console.log(this) inside controller it gives you a object(controller) and this.addPane() adds addPane Method to the controller Object. But the $scope has different scope and all method in its scope need to be accesed by $scope.methodName().
this.methodName()
inside controller means to add methos inside controller object.$scope.functionName()
is in HTML and inside
$scope.functionName(){
this.name="Name";
//or
$scope.myname="myname"//are same}
Paste this code in your editor and open console to see...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>this $sope vs controller</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<script>
var app=angular.module("myApp",[]);
app.controller("ctrlExample",function($scope){
console.log("ctrl 'this'",this);
//this(object) of controller different then $scope
$scope.firstName="Andy";
$scope.lastName="Bot";
this.nickName="ABot";
this.controllerMethod=function(){
console.log("controllerMethod ",this);
}
$scope.show=function(){
console.log("$scope 'this",this);
//this of $scope
$scope.message="Welcome User";
}
});
</script>
</head>
<body ng-app="myApp" >
<div ng-controller="ctrlExample">
Comming From $SCOPE :{{firstName}}
<br><br>
Comming from $SCOPE:{{lastName}}
<br><br>
Should Come From Controller:{{nickName}}
<p>
Blank nickName is because nickName is attached to
'this' of controller.
</p>
<br><br>
<button ng-click="controllerMethod()">Controller Method</button>
<br><br>
<button ng-click="show()">Show</button>
<p>{{message}}</p>
</div>
</body>
</html>
inf
is infinity - a value that is greater than any other value. -inf
is therefore smaller than any other value.
nan
stands for Not A Number, and this is not equal to 0
.
Although positive and negative infinity can be said to be symmetric about 0
, the same can be said for any value n
, meaning that the result of adding the two yields nan
. This idea is discussed in this math.se question.
Because nan
is (literally) not a number, you can't do arithmetic with it, so the result of the second operation is also not a number (nan
)
using Aaron's answer, this can be the short & easiest solution:
function filterSelectList(selectListId, filterId)
{
var filter = $("#" + filterId).val().toUpperCase();
$("#" + selectListId + " option").each(function(i){
if ($(this).text.toUpperCase().includes(filter))
$(this).css("display", "block");
else
$(this).css("display", "none");
});
};
If we wanted to return the same matrix we would write:
return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]
What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:
[[1,2,3],
[4,5,6],
[7,8,9]]
Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:
[[1,4,7],
[2,5,8],
[3,6,9]]
Therefore just switch the order in which we iterate:
return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]
As far as I know the main reason for adding else to loops in any language is in cases when the iterator is not on in your control. Imagine the iterator is on a server and you just give it a signal to fetch the next 100 records of data. You want the loop to go on as long as the length of the data received is 100. If it is less, you need it to go one more times and then end it. There are many other situations where you have no control over the last iteration. Having the option to add an else in these cases makes everything much easier.
Like Johan pointed out many times its .bashrc that's needed:
ln -s .bash_profile .bashrc
const element = document.getElementById('box');
element.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' });
--Load tables to delete from
SELECT
DISTINCT
' Delete top 1000000 from <DBName>.<schema>.' + c.TABLE_NAME + ' WHERE <Filter Clause Here>' AS query,c.TABLE_NAME AS TableName, IsDeleted=0, '<InsertSomeDescriptorHere>' AS [Source]--,t.TABLE_TYPE, c.*
INTO dbo.AllTablesToDeleteFrom
FROM INFORMATION_SCHEMA.TABLES AS t
INNER JOIN information_schema.columns c ON c.TABLE_NAME = t.TABLE_NAME
WHERE c.COLUMN_NAME = '<column name>'
AND c.TABLE_SCHEMA = 'dbo'
AND c.TABLE_CATALOG = '<DB Name here>'
AND t.TABLE_TYPE='Base table'
--AND t.TABLE_NAME LIKE '<put filter here>'
DECLARE @TableSelect NVARCHAR(1000)= '';
DECLARE @Table NVARCHAR(1000)= '';
DECLARE @IsDeleted INT= 0;
DECLARE @NumRows INT = 1000000;
DECLARE @Source NVARCHAR(50)='';
WHILE ( @IsDeleted = 0 )
BEGIN
--This grabs one table at a time to be deleted from. @TableSelect has the sql to execute. it is important to order by IsDeleted ASC
--because it will pull tables to delete from by those that have a 0=IsDeleted first. Once the loop grabs a table with IsDeleted=1 then this will pop out of loop
SELECT TOP 1
@TableSelect = query,
@IsDeleted = IsDeleted,
@Table = TableName,
@Source=[a].[Source]
FROM dbo.AllTablesToDeleteFrom a
WHERE a.[Source]='SomeDescriptorHere'--use only if needed
ORDER BY a.IsDeleted ASC;--this is required because only those records returned with IsDeleted=0 will run through loop
--SELECT @Table; can add this in to monitor what table is being deleted from
WHILE ( @NumRows = 1000000 )--only delete a million rows at a time?
BEGIN
EXEC sp_executesql @TableSelect;
SET @NumRows = @@ROWCOUNT;
--IF @NumRows = 1000000 --can do something here if needed
--One wants this loop to continue as long as a million rows is deleted. Once < 1 million rows is deleted it pops out of loop
--and grabs next table to delete
-- BEGIN
--SELECT @NumRows;--can add this in to see current number of deleted records for table
INSERT INTO dbo.DeleteFromAllTables
( tableName,
query,
cnt,
[Source]
)
SELECT @Table,
@TableSelect,
@NumRows,
@Source;
-- END;
END;
SET @NumRows = 1000000;
UPDATE a
SET a.IsDeleted = 1
FROM dbo.AllTablesToDeleteFrom a
WHERE a.TableName = @Table;
--flag this as deleted so you can move on to the next table to delete from
END;
try this...
$("#yourdropdownid option:selected").val();
Taking advantage of @skip405's answer, I've made a Sass mixin for it:
@mixin inline-block-lr($container,$left,$right){
#{$container}{
text-align: justify;
&:after{
content: '';
display: inline-block;
width: 100%;
height: 0;
font-size:0;
line-height:0;
}
}
#{$left} {
display: inline-block;
vertical-align: middle;
}
#{$right} {
display: inline-block;
vertical-align: middle;
}
}
It accepts 3 parameters. The container, the left and the right element. For example, to fit the question, you could use it like this:
@include inline-block-lr('header', 'h1', 'nav');
Using time.time()/datetime.datetime.now() will break if the system time is changed (the user changes the time, it is corrected by a timesyncing services such as NTP or switching from/to dayligt saving time!).
time.monotonic() or time.perf_counter() seems to be the correct way to go, however they are only available from python 3.3. Another possibility is using threading.Timer. Whether or not this is more reliable than time.time() and friends depends on the internal implementation. Also note that creating a new thread is not completely free in terms of system resources, so this might be a bad choice in cases where a lot of timers has to be run in parallel.
you can also use "global"
Example:
declare like this :
app.use(function(req,res,next){
global.site_url = req.headers.host; // hostname = 'localhost:8080'
next();
});
Use like this: in any views or ejs file <% console.log(site_url); %>
in js files console.log(site_url);
In your case, when you just select a single property, the easiest way is probably to bypass any formatting altogether:
get-qadgroupmember 'Domain Admins' | foreach { $_.Name }
This will get you a simple string[]
without column headings or empty lines. The Format-*
cmdlets are mainly for human consumption and thus their output is not designed to be easily machine-readable or -parseable.
For multiple properties I'd probably go with the -f
format operator. Something along the lines of
alias | %{ "{0,-10}{1,-10}{2,-60}" -f $_.COmmandType,$_.Name,$_.Definition }
which isn't pretty but gives you easy and complete control over the output formatting. And no empty lines :-)
The proper JPA query format would be:
el.name IN :inclList
If you're using an older version of Hibernate as your provider you have to write:
el.name IN (:inclList)
but that is a bug (HHH-5126) (EDIT: which has been resolved by now).
[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]
If you can rely on having ECMAScript5 features available, you can use the Object.keys
function to get an array of the keys (property names) in an object. All modern browsers have Object.keys
(including IE9+).
Object.keys(jsonData).forEach(function(key) {
var value = jsonData[key];
// ...
});
The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim
or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim
).
Here's the rest of the answer from 2011:
Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:
if (typeof Object.keys !== "function") {
(function() {
var hasOwn = Object.prototype.hasOwnProperty;
Object.keys = Object_keys;
function Object_keys(obj) {
var keys = [], name;
for (name in obj) {
if (hasOwn.call(obj, name)) {
keys.push(name);
}
}
return keys;
}
})();
}
That uses a for..in
loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty
to check that the property is owned directly by the object rather than being inherited.
(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)
The new cv2
interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:
import cv2 # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)
This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:
blank_image[:,0:width//2] = (255,0,0) # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)
If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2
interface rather than the older cv
one. I made the change recently and have never looked back. You can read more about cv2
at the OpenCV Change Logs.
Yes, it is possible:
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
To chain to a particular superclass constructor instead of one in the same class, use super
instead of this
. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.
See also this related question, which is about C# but where the same principles apply.
<input type="text" name="name" id="event" onkeydown="return alphaOnly(event);" required />
function alphaOnly(event) {
var key = event.keyCode;`enter code here`
return ((key >= 65 && key <= 90) || key == 8);
};
What you have is a valid ADO.NET connection string - but it's NOT a valid Entity Framework connection string.
The EF connection string would look something like this:
<connectionStrings>
<add name="NorthwindEntities" connectionString=
"metadata=.\Northwind.csdl|.\Northwind.ssdl|.\Northwind.msl;
provider=System.Data.SqlClient;
provider connection string="Data Source=SERVER\SQL2000;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=False""
providerName="System.Data.EntityClient" />
</connectionStrings>
You're missing all the metadata=
and providerName=
elements in your EF connection string...... you basically only have what's contained in the provider connection string
part.
Using the EDMX designer should create a valid EF connection string for you, in your web.config or app.config.
Marc
UPDATE: OK, I understand what you're trying to do: you need a second "ADO.NET" connection string just for ASP.NET user / membership database. Your string is OK, but the providerName is wrong - it would have to be "System.Data.SqlClient" - this connection doesn't use ENtity Framework - don't specify the "EntityClient" for it then!
<add name="ASPNETMembership"
connectionString="Data Source=MONTGOMERY-DEV\SQLEXPRESS;Initial Catalog=ASPNETDB;Integrated Security=True;"
providerName="System.Data.SqlClient" />
If you specify providerName=System.Data.EntityClient
==> Entity Framework connection string (with the metadata= and everything).
If you need and specify providerName=System.Data.SqlClient
==> straight ADO.NET SQL Server connection string without all the EF additions
If you have imported an existing project, then just remove your source folders and then add them again to build path, and restart eclipse. Most of the times eclipse will keep showing the error till you restart.
For others having the same problem, try running
git add .
which will add all files of the current directory to track (including untracked) and then use
git commit -a
to commit all tracked files.
As suggested by @Pacerier, one liner that does the same thing is
git add -A
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
Strictly speaking, the answer is no. A developer cannot prevent a user from uploading files of any type or extension.
But still, the accept attribute of <input type = "file">
can help to provide a filter in the file select dialog box of the OS. For example,
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox 42+) -->
<input type="file" accept=".xls,.xlsx" />
_x000D_
should provide a way to filter out files other than .xls or .xlsx. Although the MDN page for input
element always said that it supports this, to my surprise, this didn't work for me in Firefox until version 42. This works in IE 10+, Edge, and Chrome.
So, for supporting Firefox older than 42 along with IE 10+, Edge, Chrome, and Opera, I guess it's better to use comma-separated list of MIME-types:
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" />
_x000D_
[Edge (EdgeHTML) behavior: The file type filter dropdown shows the file types mentioned here, but is not the default in the dropdown. The default filter is All files (*)
.]
You can also use asterisks in MIME-types. For example:
<input type="file" accept="image/*" /> <!-- all image types -->
<input type="file" accept="audio/*" /> <!-- all audio types -->
<input type="file" accept="video/*" /> <!-- all video types -->
_x000D_
W3C recommends authors to specify both MIME-types and corresponding extensions in the accept
attribute. So, the best approach is:
<!-- Right approach: Use both file extensions and corresponding MIME-types. -->
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" />
_x000D_
JSFiddle of the same: here.
Reference: List of MIME-types
IMPORTANT: Using the accept
attribute only provides a way of filtering in the files of types that are of interest. Browsers still allow users to choose files of any type. Additional (client-side) checks should be done (using JavaScript, one way would be this), and definitely file types MUST be verified on the server, using a combination of MIME-type using both the file extension and its binary signature (ASP.NET, PHP, Ruby, Java). You might also want to refer to these tables for file types and their magic numbers, to perform a more robust server-side verification.
Here are three good reads on file-uploads and security.
EDIT: Maybe file type verification using its binary signature can also be done on client side using JavaScript (rather than just by looking at the extension) using HTML5 File API, but still, the file must be verified on the server, because a malicious user will still be able to upload files by making a custom HTTP request.
with jQuery its even easier and works on Chrome as well
$('#your-button').on('click', function(){
$('<a href="https://www.some-page.com" target="blank"></a>')[0].click();
})
In mysql at least, you can use DATE(theDate)
.
Example below returns value of $name_of_var
var=name_of_var
echo $(eval echo "\$$var")
You can annotate a class or a method with SuppressWarnings
@java.lang.SuppressWarnings("squid:S00112")
squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.
Select * from table where upper(table.name) like upper('IgNoreCaSe');
Alternatively, substitute lower for upper.
Try to add the code in wp-config.php:
define('FS_METHOD', 'direct');
Depends what you mean by a pattern. If you're thinking Person/Company/Transaction/Product and such, then yes - there are a lot of generic database schemas already available.
If you're thinking Factory, Singleton... then no - you don't need any of these as they're too low level for DB programming.
If you're thinking database object naming, then it's under the category of conventions, not design per se.
BTW, S.Lott, one-to-many and many-to-many relationships aren't "patterns". They're the basic building blocks of the relational model.
Try storing the connection string along with the password in a variable and assign the variable in the connection string using expression.I also faced the same issue and I solved like dis.
If you want to use android R
class
textView.setBackgroundColor(ContextCompat.getColor(getActivity(), android.R.color.transparent));
and don't forget to add support library to Gradle file
compile 'com.android.support:support-v4:23.3.0'
Check the "tsconfig.json"
file for compilation options "include"
and "exclude"
. If it does not exist, just add them by informing your root directory.
// tsconfig.json
{
"compilerOptions": {
...
"include": [
"src",
],
"exclude": [
"node_modules",
]
}
I solved my silly problem just by removing the extension statement "*.spec.ts"
from the "exclude"
, because when including the "import"
in these files, there were always problems.
If somebody needs this solution in Swift 5:
private func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
image.draw(in:CGRect(x:0, y:0, width:newWidth, height:newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
Check whether you are using Login or not to add the certificates, if you are checking in System at top left hand side then we wont be able to see it.
So drag and drop the .cer into login then check you are able to get the private key or not.
If you want not to type class name twice during instantiation like in:
new SomeContainer<SomeType>(SomeType.class);
You can use factory method:
<E> SomeContainer<E> createContainer(Class<E> class);
Like in:
public class Container<E> {
public static <E> Container<E> create(Class<E> c) {
return new Container<E>(c);
}
Class<E> c;
public Container(Class<E> c) {
super();
this.c = c;
}
public E createInstance()
throws InstantiationException,
IllegalAccessException {
return c.newInstance();
}
}
Switch statements are far easier to read and maintain, hands down. And are usually faster and less error prone.
Explaining State Transitions in the official doc: https://developer.apple.com/library/ios/documentation/uikit/reference/UIViewController_Class/index.html
This image shows the valid state transitions between various view ‘will’ and ‘did’ callback methods
Valid State Transitions:
Taken from: https://developer.apple.com/library/ios/documentation/uikit/reference/UIViewController_Class/Art/UIViewController Class Reference_2x.png
Another command line tool is my new Xidel. It also supports XPath 2 and XQuery, contrary to the already mentioned xpath/xmlstarlet.
The title can be read like:
xidel xhtmlfile.xhtml -e /html/head/title > titleOfXHTMLPage.txt
And it also has a cool feature to export multiple variables to bash. For example
eval $(xidel xhtmlfile.xhtml -e 'title := //title, imgcount := count(//img)' --output-format bash )
sets $title
to the title and $imgcount
to the number of images in the file, which should be as flexible as parsing it directly in bash.
Browser scrollbars don't work at all on iPhone/iPad. At work we are using custom JavaScript scrollbars like jScrollPane to provide a consistent cross-browser UI: http://jscrollpane.kelvinluck.com/
It works very well for me - you can make some really beautiful custom scrollbars that fit the design of your site.
Update in 2017: Hey. This is a terrible answer. Don't use it. Back in the old days this type of jQuery use was common. And it probably worked back then. Just read it, realize it's terrible, then move on (or downvote or, whatever) to one of the other answers that are better for today's jQuery.
$("input[type=radio]").change(function(){
alert( $("input[type=radio][name="+ this.name + "]").val() );
});
The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.
For set the time life in php, you can use the function session_set_cookie_params, before the session_start:
session_set_cookie_params(3600,"/");
session_start();
For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.
But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.
You can have a Table "Sessions":
And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:
On login:
setcookie('sessid', $sessionid, 604800); // One week or seven days
setcookie('sesshash', $sessionhash, 604800); // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function
If the user return:
if (isset($_COOKIE['sessid'])) {
if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
$_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
} else {
// Dont validate the hash, possible session falsification
}
}
Obviously, save all session/cookies calls, before sending data.
Assuming a C-style array a
of size N
, with elements of a type implicitly convertible from 0
, the following sets all the elements to values constructed from 0
.
std::fill(a, a+N, 0);
Note that this is not the same as "emptying" or "clearing".
Edit: Following james Kanze's suggestion, in C++11 you could use the more idiomatic alternative
std::fill( std::begin( a ), std::end( a ), 0 );
In the absence of C++11, you could roll out your own solution along these lines:
template <typename T, std::size_t N> T* end_(T(&arr)[N]) { return arr + N; }
template <typename T, std::size_t N> T* begin_(T(&arr)[N]) { return arr; }
std::fill( begin_( a ), end_( a ), 0 );
alert(xml.data[0].city);
use xml.data["Data"][0].city instead
With Spark 2.0, following is how you can read CSV
val conf = new SparkConf().setMaster("local[2]").setAppName("my app")
val sc = new SparkContext(conf)
val sparkSession = SparkSession.builder
.config(conf = conf)
.appName("spark session example")
.getOrCreate()
val path = "/Users/xxx/Downloads/usermsg.csv"
val base_df = sparkSession.read.option("header","true").
csv(path)
server {
index index.html index.htm;
server_name test.example.com;
location / {
root /web/test.example.com/www;
}
location /static {
root /web/test.example.com;
}
}
If you're just needing the path of the MDB currently open in the Access UI, I'd suggest writing a function that parses CurrentDB.Name and then stores the result in a Static variable inside the function. Something like this:
Public Function CurrentPath() As String
Dim strCurrentDBName As String
Static strPath As String
Dim i As Integer
If Len(strPath) = 0 Then
strCurrentDBName = CurrentDb.Name
For i = Len(strCurrentDBName) To 1 Step -1
If Mid(strCurrentDBName, i, 1) = "\" Then
strPath = Left(strCurrentDBName, i)
Exit For
End If
Next
End If
CurrentPath = strPath
End Function
This has the advantage that it only loops through the name one time.
Of course, it only works with the file that's open in the user interface.
Another way to write this would be to use the functions provided at the link inside the function above, thus:
Public Function CurrentPath() As String
Static strPath As String
If Len(strPath) = 0 Then
strPath = FolderFromPath(CurrentDB.Name)
End If
CurrentPath = strPath
End Function
This makes retrieving the current path very efficient while utilizing code that can be used for finding the path for any filename/path.
I've gotten around this with
mystr = ' '.join(
["Why, hello there",
"wonderful stackoverflow people!"])
in the past. It's not perfect, but it works nicely for very long strings that need to not have line breaks in them.
This ORA error is occurred because of violation of unique constraint.
ORA-00001: unique constraint (constraint_name) violated
This is caused because of trying to execute an INSERT
or UPDATE
statement that has created a duplicate value in a field restricted by a unique index.
You can resolve this either by
$@
is nearly the same as $*
, both meaning "all command line arguments". They are often used to simply pass all arguments to another program (thus forming a wrapper around that other program).
The difference between the two syntaxes shows up when you have an argument with spaces in it (e.g.) and put $@
in double quotes:
wrappedProgram "$@"
# ^^^ this is correct and will hand over all arguments in the way
# we received them, i. e. as several arguments, each of them
# containing all the spaces and other uglinesses they have.
wrappedProgram "$*"
# ^^^ this will hand over exactly one argument, containing all
# original arguments, separated by single spaces.
wrappedProgram $*
# ^^^ this will join all arguments by single spaces as well and
# will then split the string as the shell does on the command
# line, thus it will split an argument containing spaces into
# several arguments.
Example: Calling
wrapper "one two three" four five "six seven"
will result in:
"$@": wrappedProgram "one two three" four five "six seven"
"$*": wrappedProgram "one two three four five six seven"
^^^^ These spaces are part of the first
argument and are not changed.
$*: wrappedProgram one two three four five six seven
try this,
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_sample, menu);
super.onCreateOptionsMenu(menu,inflater);
}
Finally, in onCreateView
method, add this line to make the options appear in your Toolbar
setHasOptionsMenu(true);
Setting links on the page woud require a combination of @Ravi and @ncksllvn's answers:
// Find link in $(".product-item") and set "target" attribute to "_blank".
$(this).find("a").attr("target", "_blank");
For opening the page in another window, see this question: jQuery click _blank And see this reference for window.open
options for customization.
Update:
You would need something along:
$(document).ready(function() {
$(".product-item").click(function() {
var productLink = $(this).find("a");
productLink.attr("target", "_blank");
window.open(productLink.attr("href"));
return false;
});
});
Note the usage of .attr()
:
$element.attr("attribute_name") // Get value of attribute.
$element.attr("attribute_name", attribute_value) // Set value of attribute.
Be very very careful renaming objects in sql. You can cause dependencies to fail if you are not fully away with what you are doing. Having said that this works easily(too much so) for renaming things provided you have access proper on the environment:
exec sp_rename 'Nameofobject', 'ReNameofobject'
Does not work, need --pos
to evaluate double:
String version = System.getProperty("java.version");
System.out.println("version:" + version);
int pos = 0, count = 0;
for (; pos < version.length() && count < 2; pos++) {
if (version.charAt(pos) == '.') {
count++;
}
}
--pos; //EVALUATE double
double dversion = Double.parseDouble(version.substring(0, pos));
System.out.println("dversion:" + dversion);
return dversion;
}
Select element (or group of elements) having class "abc", not having class "xyz":
$('.abc:not(".xyz")')
When selecting regular CSS you can use .abc:not(.xyz)
.
I had this error when I tried to use retrolambda inside my unit tests. I didn't find a solution how to make retrolambda work with unit tests. So, I use old fashioned anonymous classes instead of lambdas with my unit tests, and it works for me.
With Java 7, you can use Files.createDirectories()
.
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
Try executing it as sudo
.
sudo laravel new blog
Your file may not have the appropriate permissions. Let us know if it worked!
As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.
For example in firefox preferences:
Notice the last option.
You can always change a date on your computer, make a commit, then change the date back and push.
I'm not sure about you, but I spent about 30 minutes troubleshooting the same issue here, until I realized that the line for app/build.gradle is:
apply plugin: 'com.google.gms.google-services'
and not:
apply plugin: 'com.google.gms:google-services'
Eg: I had copied that line from a tutorial, but when specifying the apply plugin namespace, no colon (:
) is required. It's, in fact, a dot. (.
).
Hey... it's easy to miss.
Yes, it is asking for the application/executable that is capable of creating Javadoc. There is a javadoc
executable inside the jdk's bin folder.
You need to add the -i flag to the first command, to include the HTTP header in the output. This is required to print headers.
curl -X HEAD -i http://www.google.com
More here: https://serverfault.com/questions/140149/difference-between-curl-i-and-curl-x-head
I prefer to use the Structure view. To open it, use the menu: View/Tools Window/Structure. The hotkey on Windows is Alt+7
Instead of declaring a function in your scope, as suggested by Alex, you can convert it to a simple filter :
angular.module('myApp')
.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
Then you can use it like this :
<div ng-bind-html="preview_data.preview.embed.html | to_trusted"></div>
And here is a working example : http://jsfiddle.net/leeroy/6j4Lg/1/
This has happened to me . Jquery version : 3.3.
If you are looping through a list of objects, and want to add each object as a child of some parent dom element, then .html and .append will behave very different. .html
will end up adding only the last object to the parent element, whereas .append
will add all the list objects as children of the parent element.
Use:
Another option you can always consider is Apache Commons. It provides a lot of options.
import org.apache.commons.lang3.builder.CompareToBuilder;
Ex:
public int compare(Person a, Person b){
return new CompareToBuilder()
.append(a.getName(), b.getName())
.append(a.getAddress(), b.getAddress())
.toComparison();
}
If you are on Ubuntu,
sudo su postgres
pg_dump -d <database_name> -t <table_name> > file.sql
Make sure that you are executing the command where the postgres
user have write permissions (Example: /tmp
)
Edit
If you want to dump the .sql in another computer, you may need to consider skipping the owner information getting saved into the .sql file.
You can use pg_dump --no-owner -d <database_name> -t <table_name> > file.sql
Here you go:
user@host:~$ sed 's/^[\t ]*//g' < file-in.txt
Or:
user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
With files we know the size in advance, so just read it all at once!
String result;
File file = ...;
long length = file.length();
if (length < 1 || length > Integer.MAX_VALUE) {
result = "";
Log.w(TAG, "File is empty or huge: " + file);
} else {
try (FileReader in = new FileReader(file)) {
char[] content = new char[(int)length];
int numRead = in.read(content);
if (numRead != length) {
Log.e(TAG, "Incomplete read of " + file + ". Read chars " + numRead + " of " + length);
}
result = new String(content, 0, numRead);
}
catch (Exception ex) {
Log.e(TAG, "Failure reading " + this.file, ex);
result = "";
}
}
Hasan Badshah's answer worked for me, but the method is slated to be deprecated and may be problematic for others going forward. Following the MDN web docs on alternative methods, I landed here: PerformanceNavigationTiming.type
if (performance.getEntriesByType("navigation")[0].type === 'back_forward') {
// back or forward button functionality
}
This doesn't directly solve for back button over the forward button, but was good enough for what I needed. In the docs they detail the available event data that may be helpful with solving your specific needs:
function print_nav_timing_data() {
// Use getEntriesByType() to just get the "navigation" events
var perfEntries = performance.getEntriesByType("navigation");
for (var i=0; i < perfEntries.length; i++) {
console.log("= Navigation entry[" + i + "]");
var p = perfEntries[i];
// dom Properties
console.log("DOM content loaded = " + (p.domContentLoadedEventEnd -
p.domContentLoadedEventStart));
console.log("DOM complete = " + p.domComplete);
console.log("DOM interactive = " + p.interactive);
// document load and unload time
console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
console.log("document unload = " + (p.unloadEventEnd -
p.unloadEventStart));
// other properties
console.log("type = " + p.type);
console.log("redirectCount = " + p.redirectCount);
}
}
According to the Docs at the time of this post it is still in a working draft state and is not supported in IE or Safari, but that may change by the time it is finished. Check the Docs for updates.
if you got one of these error while compiling and running:
* NoClassDefFoundError
* Error: Could not find or load main class hello
* Exception in thread "main" java.lang.NoClassDefFoundError:javaTest/test/hello
(wrong name: test/hello)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
-------------------------- SOLUTIION -----------------------
the problem is mostly in packages organization. You should arrange your classes in folders properly regarding to the package classifications in your source code.
On Compiling process use this command:
javac -d . [FileName.java]
To Run the class please use this command:
java [Package].[ClassName]
Try this:
USE YourDB;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE YourDB
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 50 MB.
DBCC SHRINKFILE (YourDB_log, 50);
GO
-- Reset the database recovery model.
ALTER DATABASE YourDB
SET RECOVERY FULL;
GO
I hope it helps.
Since all responses to this make use of the now long-deprecated abstract WebMvcConfigurer Adapter instead of the WebMvcInterface (as already noted by @sebdooe), here is a working minimal example for a SpringBoot (2.1.4) application with an Interceptor:
Minimal.java:
@SpringBootApplication
public class Minimal
{
public static void main(String[] args)
{
SpringApplication.run(Minimal.class, args);
}
}
MinimalController.java:
@RestController
@RequestMapping("/")
public class Controller
{
@GetMapping("/")
@ResponseBody
public ResponseEntity<String> getMinimal()
{
System.out.println("MINIMAL: GETMINIMAL()");
return new ResponseEntity<String>("returnstring", HttpStatus.OK);
}
}
Config.java:
@Configuration
public class Config implements WebMvcConfigurer
{
//@Autowired
//MinimalInterceptor minimalInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry)
{
registry.addInterceptor(new MinimalInterceptor());
}
}
MinimalInterceptor.java:
public class MinimalInterceptor extends HandlerInterceptorAdapter
{
@Override
public boolean preHandle(HttpServletRequest requestServlet, HttpServletResponse responseServlet, Object handler) throws Exception
{
System.out.println("MINIMAL: INTERCEPTOR PREHANDLE CALLED");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
{
System.out.println("MINIMAL: INTERCEPTOR POSTHANDLE CALLED");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception
{
System.out.println("MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED");
}
}
works as advertised
The output will give you something like:
> Task :Minimal.main()
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.4.RELEASE)
2019-04-29 11:53:47.560 INFO 4593 --- [ main] io.minimal.Minimal : Starting Minimal on y with PID 4593 (/x/y/z/spring-minimal/build/classes/java/main started by x in /x/y/z/spring-minimal)
2019-04-29 11:53:47.563 INFO 4593 --- [ main] io.minimal.Minimal : No active profile set, falling back to default profiles: default
2019-04-29 11:53:48.745 INFO 4593 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-04-29 11:53:48.780 INFO 4593 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-04-29 11:53:48.781 INFO 4593 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-04-29 11:53:48.892 INFO 4593 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-04-29 11:53:48.893 INFO 4593 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1269 ms
2019-04-29 11:53:49.130 INFO 4593 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-29 11:53:49.375 INFO 4593 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-29 11:53:49.380 INFO 4593 --- [ main] io.minimal.Minimal : Started Minimal in 2.525 seconds (JVM running for 2.9)
2019-04-29 11:54:01.267 INFO 4593 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-04-29 11:54:01.267 INFO 4593 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-04-29 11:54:01.286 INFO 4593 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 19 ms
MINIMAL: INTERCEPTOR PREHANDLE CALLED
MINIMAL: GETMINIMAL()
MINIMAL: INTERCEPTOR POSTHANDLE CALLED
MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED
The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.
The simple answer is that there is no such function.
The closest thing you have is:
var millisecondsToWait = 500;
setTimeout(function() {
// Whatever you want to do after the wait
}, millisecondsToWait);
Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.
Here are a couple of other SO questions that deal with threads in JavaScript:
And this question may also be helpful:
Use .length
to count number of characters, and $.trim()
function to remove spaces, and replace(/ /g,'')
to replace multiple spaces with just one. Here is an example:
var str = " Hel lo ";
console.log(str.length);
console.log($.trim(str).length);
console.log(str.replace(/ /g,'').length);
Output:
20
7
5
Source: How to count number of characters in a string with JQuery
To help other bug-hunters. I had this error because the function didn't exist.
I had a spelling error.
This is a one-liner but uses four atomic commands:
head -1000 file.txt > newfile.txt; tail +1000 file.txt > file.txt.tmp; cp file.txt.tmp file.txt; rm file.txt.tmp
For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:
.field-error {_x000D_
color: #f44336;_x000D_
padding: 2px 5px;_x000D_
position: absolute;_x000D_
font-size: small;_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
-moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
-webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
-o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
from { background-color: lightgreen; } /** from color **/_x000D_
to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
In Your Controller
$scope.clearSearch = function() {
$scope.searchAll = '';
}
Simply add an attribute to your popover! See my JSFiddle if you're in a hurry.
We want to add an ID or a class to a particular popover so that we may customize it the way we want via CSS.
Please note that we don't want to customize all popovers! This is terrible idea.
Here is a simple example - display the popover like this:
// We add the id 'my-popover'_x000D_
$("#my-button").popover({_x000D_
html : true,_x000D_
placement: 'bottom'_x000D_
}).data('bs.popover').tip().attr('id', 'my-popover');
_x000D_
#my-popover {_x000D_
left: -169px!important;_x000D_
}_x000D_
#my-popover .arrow {_x000D_
left: 90%_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button id="my-button" data-toggle="popover">My Button</button>
_x000D_
Simply throw Exception if input is invalid
Scanner sc=new Scanner(System.in);
try
{
System.out.println("Please input an integer");
//nextInt will throw InputMismatchException
//if the next token does not match the Integer
//regular expression, or is out of range
int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
//Print "This is not an integer"
//when user put other than integer
System.out.println("This is not an integer");
}
Guava has a method to do this for you: double[] Doubles.toArray(Collection<Double>)
This isn't necessarily going to be any faster than just looping through the Collection
and adding each Double
object to the array, but it's a lot less for you to write.
No-one of safe solution work for me so to be safer than Neeraj and easier than Matthew just add:
System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
In your controller's method. That work for me.
public IHttpActionResult Get()
{
System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
return Ok("value");
}
There are some gotchas. Assignment in Javascript is from right to left so when you write:
var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
it effectively translates to:
var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));
which effectively translates to:
var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));
Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.
Note: My above example assumes you are running your code in the browser, hence window
. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global
which is the global context for that environment).
Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.
var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.
Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.
The ultimate solution would be setting overflow: hidden;
on document.documentElement
like so:
/* element is an HTML element You want catch the touch */
element.addEventListener('touchstart', function(e) {
document.documentElement.style.overflow = 'hidden';
});
document.addEventListener('touchend', function(e) {
document.documentElement.style.overflow = 'auto';
});
By setting overflow: hidden
on start of touch it makes everything exceeding window hidden thus removing availability to scroll anything (no content to scroll).
After touchend
the lock can be freed by setting overflow
to auto
(the default value).
It is better to append this to <html>
because <body>
may be used to do some styling, plus it can make children behave unexpectedly.
EDIT:
About touch-action: none;
- Safari doesn't support it according to MDN.
Just a note for anyone who stumbles upon this:
If you are trying to SSH with a key that has been shared with you, for example:
ssh -i /path/to/keyfile.pem user@some-host
Where keyfile.pem
is the private/public key shared with you and you're using it to connect, make sure you save it into ~/.ssh/
and chmod 777
.
Trying to use the file when it was saved elsewhere on my machine was giving the OP's error. Not sure if it is directly related.
This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.
var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;
Glide V4:
Glide.with(context)
.load(url)
.circleCrop()
.into(imageView);
Glide V3:
You can use RoundedBitmapDrawable
for circular images with Glide. No custom ImageView is required.
Glide.with(context).load(url).asBitmap().centerCrop().into(new BitmapImageViewTarget(imageView) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
imageView.setImageDrawable(circularBitmapDrawable);
}
});
Another cross-browser approach based on above solution
function doScrollTo(to, duration) {
var element = document.documentElement;
var start = element.scrollTop,
change = to - start,
increment = 20,
i = 0;
var animateScroll = function(elapsedTime) {
elapsedTime += increment;
var position = easeInOut(elapsedTime, start, change, duration);
if (i === 1 && window.scrollY === start) {
element = document.body;
start = element.scrollTop;
}
element.scrollTop = position;
if (!i) i++;
if (elapsedTime < duration) {
setTimeout(function() {
animateScroll(elapsedTime);
}, increment);
}
};
animateScroll(0);
}
The trick is to control the actual scroll change, and if it is zero, change the scroll element.
You can use this (the French locale has ,
for decimal separator)
NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
nf.parse(p);
Or you can use java.text.DecimalFormat
and set the appropriate symbols:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
df.parse(p);
There is no way to gracefully kill a thread.
You can try to interrupt the thread, one commons strategy is to use a poison pill to message the thread to stop itself
public class CancelSupport {
public static class CommandExecutor implements Runnable {
private BlockingQueue<String> queue;
public static final String POISON_PILL = “stopnow”;
public CommandExecutor(BlockingQueue<String> queue) {
this.queue=queue;
}
@Override
public void run() {
boolean stop=false;
while(!stop) {
try {
String command=queue.take();
if(POISON_PILL.equals(command)) {
stop=true;
} else {
// do command
System.out.println(command);
}
} catch (InterruptedException e) {
stop=true;
}
}
System.out.println(“Stopping execution”);
}
}
}
BlockingQueue<String> queue=new LinkedBlockingQueue<String>();
Thread t=new Thread(new CommandExecutor(queue));
queue.put(“hello”);
queue.put(“world”);
t.start();
Thread.sleep(1000);
queue.put(“stopnow”);
Usually this happens if something is wrong with the byte array.
File.WriteAllBytes("filename.PDF", Byte[]);
This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
Asynchronous implementation of this is also available.
public static System.Threading.Tasks.Task WriteAllBytesAsync
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);
I'm using SQL Server 2008 R2, my DB was already set for single user and there was a connection that restricted any action on the database. Thus the recommended SQLMenace's solution responded with error. Here is one that worked in my case.
If your goal is to use a profiler, use one of the suggested ones.
However, if you're in a hurry and you can manually interrupt your program under the debugger while it's being subjectively slow, there's a simple way to find performance problems.
Just halt it several times, and each time look at the call stack. If there is some code that is wasting some percentage of the time, 20% or 50% or whatever, that is the probability that you will catch it in the act on each sample. So, that is roughly the percentage of samples on which you will see it. There is no educated guesswork required. If you do have a guess as to what the problem is, this will prove or disprove it.
You may have multiple performance problems of different sizes. If you clean out any one of them, the remaining ones will take a larger percentage, and be easier to spot, on subsequent passes. This magnification effect, when compounded over multiple problems, can lead to truly massive speedup factors.
Caveat: Programmers tend to be skeptical of this technique unless they've used it themselves. They will say that profilers give you this information, but that is only true if they sample the entire call stack, and then let you examine a random set of samples. (The summaries are where the insight is lost.) Call graphs don't give you the same information, because
They will also say it only works on toy programs, when actually it works on any program, and it seems to work better on bigger programs, because they tend to have more problems to find. They will say it sometimes finds things that aren't problems, but that is only true if you see something once. If you see a problem on more than one sample, it is real.
P.S. This can also be done on multi-thread programs if there is a way to collect call-stack samples of the thread pool at a point in time, as there is in Java.
P.P.S As a rough generality, the more layers of abstraction you have in your software, the more likely you are to find that that is the cause of performance problems (and the opportunity to get speedup).
Added: It might not be obvious, but the stack sampling technique works equally well in the presence of recursion. The reason is that the time that would be saved by removal of an instruction is approximated by the fraction of samples containing it, regardless of the number of times it may occur within a sample.
Another objection I often hear is: "It will stop someplace random, and it will miss the real problem". This comes from having a prior concept of what the real problem is. A key property of performance problems is that they defy expectations. Sampling tells you something is a problem, and your first reaction is disbelief. That is natural, but you can be sure if it finds a problem it is real, and vice-versa.
Added: Let me make a Bayesian explanation of how it works. Suppose there is some instruction I
(call or otherwise) which is on the call stack some fraction f
of the time (and thus costs that much). For simplicity, suppose we don't know what f
is, but assume it is either 0.1, 0.2, 0.3, ... 0.9, 1.0, and the prior probability of each of these possibilities is 0.1, so all of these costs are equally likely a-priori.
Then suppose we take just 2 stack samples, and we see instruction I
on both samples, designated observation o=2/2
. This gives us new estimates of the frequency f
of I
, according to this:
Prior
P(f=x) x P(o=2/2|f=x) P(o=2/2&&f=x) P(o=2/2&&f >= x) P(f >= x | o=2/2)
0.1 1 1 0.1 0.1 0.25974026
0.1 0.9 0.81 0.081 0.181 0.47012987
0.1 0.8 0.64 0.064 0.245 0.636363636
0.1 0.7 0.49 0.049 0.294 0.763636364
0.1 0.6 0.36 0.036 0.33 0.857142857
0.1 0.5 0.25 0.025 0.355 0.922077922
0.1 0.4 0.16 0.016 0.371 0.963636364
0.1 0.3 0.09 0.009 0.38 0.987012987
0.1 0.2 0.04 0.004 0.384 0.997402597
0.1 0.1 0.01 0.001 0.385 1
P(o=2/2) 0.385
The last column says that, for example, the probability that f
>= 0.5 is 92%, up from the prior assumption of 60%.
Suppose the prior assumptions are different. Suppose we assume P(f=0.1)
is .991 (nearly certain), and all the other possibilities are almost impossible (0.001). In other words, our prior certainty is that I
is cheap. Then we get:
Prior
P(f=x) x P(o=2/2|f=x) P(o=2/2&& f=x) P(o=2/2&&f >= x) P(f >= x | o=2/2)
0.001 1 1 0.001 0.001 0.072727273
0.001 0.9 0.81 0.00081 0.00181 0.131636364
0.001 0.8 0.64 0.00064 0.00245 0.178181818
0.001 0.7 0.49 0.00049 0.00294 0.213818182
0.001 0.6 0.36 0.00036 0.0033 0.24
0.001 0.5 0.25 0.00025 0.00355 0.258181818
0.001 0.4 0.16 0.00016 0.00371 0.269818182
0.001 0.3 0.09 0.00009 0.0038 0.276363636
0.001 0.2 0.04 0.00004 0.00384 0.279272727
0.991 0.1 0.01 0.00991 0.01375 1
P(o=2/2) 0.01375
Now it says P(f >= 0.5)
is 26%, up from the prior assumption of 0.6%. So Bayes allows us to update our estimate of the probable cost of I
. If the amount of data is small, it doesn't tell us accurately what the cost is, only that it is big enough to be worth fixing.
Yet another way to look at it is called the Rule Of Succession.
If you flip a coin 2 times, and it comes up heads both times, what does that tell you about the probable weighting of the coin?
The respected way to answer is to say that it's a Beta distribution, with average value (number of hits + 1) / (number of tries + 2) = (2+1)/(2+2) = 75%
.
(The key is that we see I
more than once. If we only see it once, that doesn't tell us much except that f
> 0.)
So, even a very small number of samples can tell us a lot about the cost of instructions that it sees. (And it will see them with a frequency, on average, proportional to their cost. If n
samples are taken, and f
is the cost, then I
will appear on nf+/-sqrt(nf(1-f))
samples. Example, n=10
, f=0.3
, that is 3+/-1.4
samples.)
Added: To give an intuitive feel for the difference between measuring and random stack sampling:
There are profilers now that sample the stack, even on wall-clock time, but what comes out is measurements (or hot path, or hot spot, from which a "bottleneck" can easily hide). What they don't show you (and they easily could) is the actual samples themselves. And if your goal is to find the bottleneck, the number of them you need to see is, on average, 2 divided by the fraction of time it takes.
So if it takes 30% of time, 2/.3 = 6.7 samples, on average, will show it, and the chance that 20 samples will show it is 99.2%.
Here is an off-the-cuff illustration of the difference between examining measurements and examining stack samples. The bottleneck could be one big blob like this, or numerous small ones, it makes no difference.
Measurement is horizontal; it tells you what fraction of time specific routines take. Sampling is vertical. If there is any way to avoid what the whole program is doing at that moment, and if you see it on a second sample, you've found the bottleneck. That's what makes the difference - seeing the whole reason for the time being spent, not just how much.
@Html.LabelFor(model => model.SomekingStatus, "foo bar")
We can use relative path instead of absolute path:
$assetPath: '~src/assets/images/';
$logo-img: '#{$assetPath}logo.png';
@mixin logo {
background-image: url(#{$logo-img});
}
.logo {
max-width: 65px;
@include logo;
}
GET
and POST
are two different types of HTTP requests.
According to Wikipedia:
GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.
and
POST submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.
So essentially GET
is used to retrieve remote data, and POST
is used to insert/update remote data.
GET
and POST
as well as the other HTTP methods, if you are interested.
In addition to explaining the intended uses of each method, the spec also provides at least one practical reason for why GET
should only be used to retrieve data:
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead
GET
for AJAX requests is that some browsers - IE in particular - will cache the results of a GET
request. So if you, for example, poll using the same GET
request you will always get back the same results, even if the data you are querying is being updated server-side. One way to alleviate this problem is to make the URL unique for each request by appending a timestamp.
find and replace:
utf8mb4_unicode_520_ci
with
utf8_general_ci
in whole sql file
You should be able to force your local revision to the remote repo by using
git push -f <remote> <branch>
(e.g. git push -f origin master
). Leaving off <remote>
and <branch>
will force push all local branches that have set --set-upstream
.
Just be warned, if other people are sharing this repository their revision history will conflict with the new one. And if they have any local commits after the point of change they will become invalid.
Update: Thought I would add a side-note. If you are creating changes that others will review, then it's not uncommon to create a branch with those changes and rebase periodically to keep them up-to-date with the main development branch. Just let other developers know this will happen periodically so they'll know what to expect.
Update 2: Because of the increasing number of viewers I'd like to add some additional information on what to do when your upstream
does experience a force push.
Say I've cloned your repo and have added a few commits like so:
D----E topic / A----B----C development
But later the development
branch is hit with a rebase
, which will cause me to receive an error like so when I run git pull
:
Unpacking objects: 100% (3/3), done. From <repo-location> * branch development -> FETCH_HEAD Auto-merging <files> CONFLICT (content): Merge conflict in <locations> Automatic merge failed; fix conflicts and then commit the result.
Here I could fix the conflicts and commit
, but that would leave me with a really ugly commit history:
C----D----E----F topic / / A----B--------------C' development
It might look enticing to use git pull --force
but be careful because that'll leave you with stranded commits:
D----E topic A----B----C' development
So probably the best option is to do a git pull --rebase
. This will require me to resolve any conflicts like before, but for each step instead of committing I'll use git rebase --continue
. In the end the commit history will look much better:
D'---E' topic / A----B----C' development
Update 3: You can also use the --force-with-lease
option as a "safer" force
push, as mentioned by Cupcake in his
answer:
Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:
git push <remote> <branch> --force-with-lease
You can learn more details about how to use
--force-with-lease
by reading any of the following:
Turns out I don't have enough reputation to put this as a comment, which would be a more appropriate place for this:
Re. AllBlackt's answer, if you prefer Ansible's multiline format you need to adjust the quoting for state
(I spent a few minutes working this out, so hopefully this speeds someone else up),
- stat:
path: "/etc/nologin"
register: p
- name: create fake 'nologin' shell
file:
path: "/etc/nologin"
owner: root
group: sys
mode: 0555
state: '{{ "file" if p.stat.exists else "touch" }}'
You can set the default like this:
b = models.CharField(max_length=7,default="foobar")
and then you can hide the field with your model's Admin class like this:
class SomeModelAdmin(admin.ModelAdmin):
exclude = ("b")
Although JS implementations might keep track of such a value internally, there's no standard way to get it.
In the past, Mozilla's Javascript variant exposed the non-standard __count__
, but it has been removed with version 1.8.5.
For cross-browser scripting you're stuck with explicitly iterating over the properties and checking hasOwnProperty()
:
function countProperties(obj) {
var count = 0;
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
++count;
}
return count;
}
In case of ECMAScript 5 capable implementations, this can also be written as (Kudos to Avi Flax)
function countProperties(obj) {
return Object.keys(obj).length;
}
Keep in mind that you'll also miss properties which aren't enumerable (eg an array's length
).
If you're using a framework like jQuery, Prototype, Mootools, $whatever-the-newest-hype, check if they come with their own collections API, which might be a better solution to your problem than using native JS objects.
You are creating a dictionary first, then passing that dictionary to an OrderedDict
. For Python versions < 3.6 (*), by the time you do that, the ordering is no longer going to be correct. dict
is inherently not ordered.
Pass in a sequence of tuples instead:
ship = [("NAME", "Albatross"),
("HP", 50),
("BLASTERS", 13),
("THRUSTERS", 18),
("PRICE", 250)]
ship = collections.OrderedDict(ship)
What you see when you print the OrderedDict
is it's representation, and it is entirely correct. OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
just shows you, in a reproducable representation, what the contents are of the OrderedDict
.
(*): In the CPython 3.6 implementation, the dict
type was updated to use a more memory efficient internal structure that has the happy side effect of preserving insertion order, and by extension the code shown in the question works without issues. As of Python 3.7, the Python language specification has been updated to require that all Python implementations must follow this behaviour. See this other answer of mine for details and also why you'd still may want to use an OrderedDict()
for certain cases.
package lecture3;
import java.util.Scanner;
public class divisibleBy2and5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter an integer number:");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
if (x % 2==0){
System.out.println("The integer number you entered is divisible by 2");
}
else{
System.out.println("The integer number you entered is not divisible by 2");
if(x % 5==0){
System.out.println("The integer number you entered is divisible by 5");
}
else{
System.out.println("The interger number you entered is not divisible by 5");
}
}
}
}
What you have should work, unless ${STATUS}
is empty. It would probably be better to do:
if ! [ "${STATUS}" -eq 200 ] 2> /dev/null && [ "${STRING}" != "${VALUE}" ]; then
or
if [ "${STATUS}" != 200 ] && [ "${STRING}" != "${VALUE}" ]; then
It's hard to say, since you haven't shown us exactly what is going wrong with your script.
Personal opinion: never use [[
. It suppresses important error messages and is not portable to different shells.
You can also add the "value" attribute and set that so something like so:
<textarea value="your value"> </textarea>
If you want to know if a property exists in an instance of a class that you have defined, simply combine property_exists()
with isset()
.
public function hasProperty($property)
{
return property_exists($this, $property) && isset($this->$property);
}
If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces
still configured for eth0.
Diagnose:
ethtool -i eth0
Cannot get driver information: no such device
Find your interfaces:
ls /sys/class/net
eth1 eth2 lo
Fix it:
Edit /etc/networking/interfaces
and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)
:%s/eth0/eth2/g
The Stack When you call a function the arguments to that function plus some other overhead is put on the stack. Some info (such as where to go on return) is also stored there. When you declare a variable inside your function, that variable is also allocated on the stack.
Deallocating the stack is pretty simple because you always deallocate in the reverse order in which you allocate. Stack stuff is added as you enter functions, the corresponding data is removed as you exit them. This means that you tend to stay within a small region of the stack unless you call lots of functions that call lots of other functions (or create a recursive solution).
The Heap The heap is a generic name for where you put the data that you create on the fly. If you don't know how many spaceships your program is going to create, you are likely to use the new (or malloc or equivalent) operator to create each spaceship. This allocation is going to stick around for a while, so it is likely we will free things in a different order than we created them.
Thus, the heap is far more complex, because there end up being regions of memory that are unused interleaved with chunks that are - memory gets fragmented. Finding free memory of the size you need is a difficult problem. This is why the heap should be avoided (though it is still often used).
Implementation Implementation of both the stack and heap is usually down to the runtime / OS. Often games and other applications that are performance critical create their own memory solutions that grab a large chunk of memory from the heap and then dish it out internally to avoid relying on the OS for memory.
This is only practical if your memory usage is quite different from the norm - i.e for games where you load a level in one huge operation and can chuck the whole lot away in another huge operation.
Physical location in memory This is less relevant than you think because of a technology called Virtual Memory which makes your program think that you have access to a certain address where the physical data is somewhere else (even on the hard disc!). The addresses you get for the stack are in increasing order as your call tree gets deeper. The addresses for the heap are un-predictable (i.e implimentation specific) and frankly not important.
I just wrote a parser that I called Yay! (Yaml ain't Yamlesque!) which parses Yamlesque, a small subset of YAML. So, if you're looking for a 100% compliant YAML parser for Bash then this isn't it. However, to quote the OP, if you want a structured configuration file which is as easy as possible for a non-technical user to edit that is YAML-like, this may be of interest.
It's inspred by the earlier answer but writes associative arrays (yes, it requires Bash 4.x) instead of basic variables. It does so in a way that allows the data to be parsed without prior knowledge of the keys so that data-driven code can be written.
As well as the key/value array elements, each array has a keys
array containing a list of key names, a children
array containing names of child arrays and a parent
key that refers to its parent.
This is an example of Yamlesque:
root_key1: this is value one
root_key2: "this is value two"
drink:
state: liquid
coffee:
best_served: hot
colour: brown
orange_juice:
best_served: cold
colour: orange
food:
state: solid
apple_pie:
best_served: warm
root_key_3: this is value three
Here is an example showing how to use it:
#!/bin/bash
# An example showing how to use Yay
. /usr/lib/yay
# helper to get array value at key
value() { eval echo \${$1[$2]}; }
# print a data collection
print_collection() {
for k in $(value $1 keys)
do
echo "$2$k = $(value $1 $k)"
done
for c in $(value $1 children)
do
echo -e "$2$c\n$2{"
print_collection $c " $2"
echo "$2}"
done
}
yay example
print_collection example
which outputs:
root_key1 = this is value one
root_key2 = this is value two
root_key_3 = this is value three
example_drink
{
state = liquid
example_coffee
{
best_served = hot
colour = brown
}
example_orange_juice
{
best_served = cold
colour = orange
}
}
example_food
{
state = solid
example_apple_pie
{
best_served = warm
}
}
And here is the parser:
yay_parse() {
# find input file
for f in "$1" "$1.yay" "$1.yml"
do
[[ -f "$f" ]] && input="$f" && break
done
[[ -z "$input" ]] && exit 1
# use given dataset prefix or imply from file name
[[ -n "$2" ]] && local prefix="$2" || {
local prefix=$(basename "$input"); prefix=${prefix%.*}
}
echo "declare -g -A $prefix;"
local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
sed -n -e "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$input" |
awk -F$fs '{
indent = length($1)/2;
key = $2;
value = $3;
# No prefix or parent for the top level (indent zero)
root_prefix = "'$prefix'_";
if (indent ==0 ) {
prefix = ""; parent_key = "'$prefix'";
} else {
prefix = root_prefix; parent_key = keys[indent-1];
}
keys[indent] = key;
# remove keys left behind if prior row was indented more than this row
for (i in keys) {if (i > indent) {delete keys[i]}}
if (length(value) > 0) {
# value
printf("%s%s[%s]=\"%s\";\n", prefix, parent_key , key, value);
printf("%s%s[keys]+=\" %s\";\n", prefix, parent_key , key);
} else {
# collection
printf("%s%s[children]+=\" %s%s\";\n", prefix, parent_key , root_prefix, key);
printf("declare -g -A %s%s;\n", root_prefix, key);
printf("%s%s[parent]=\"%s%s\";\n", root_prefix, key, prefix, parent_key);
}
}'
}
# helper to load yay data file
yay() { eval $(yay_parse "$@"); }
There is some documentation in the linked source file and below is a short explanation of what the code does.
The yay_parse
function first locates the input
file or exits with an exit status of 1. Next, it determines the dataset prefix
, either explicitly specified or derived from the file name.
It writes valid bash
commands to its standard output that, if executed, define arrays representing the contents of the input data file. The first of these defines the top-level array:
echo "declare -g -A $prefix;"
Note that array declarations are associative (-A
) which is a feature of Bash version 4. Declarations are also global (-g
) so they can be executed in a function but be available to the global scope like the yay
helper:
yay() { eval $(yay_parse "$@"); }
The input data is initially processed with sed
. It drops lines that don't match the Yamlesque format specification before delimiting the valid Yamlesque fields with an ASCII File Separator character and removing any double-quotes surrounding the value field.
local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
sed -n -e "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$input" |
The two expressions are similar; they differ only because the first one picks out quoted values where as the second one picks out unquoted ones.
The File Separator (28/hex 12/octal 034) is used because, as a non-printable character, it is unlikely to be in the input data.
The result is piped into awk
which processes its input one line at a time. It uses the FS character to assign each field to a variable:
indent = length($1)/2;
key = $2;
value = $3;
All lines have an indent (possibly zero) and a key but they don't all have a value. It computes an indent level for the line dividing the length of the first field, which contains the leading whitespace, by two. The top level items without any indent are at indent level zero.
Next, it works out what prefix
to use for the current item. This is what gets added to a key name to make an array name. There's a root_prefix
for the top-level array which is defined as the data set name and an underscore:
root_prefix = "'$prefix'_";
if (indent ==0 ) {
prefix = ""; parent_key = "'$prefix'";
} else {
prefix = root_prefix; parent_key = keys[indent-1];
}
The parent_key
is the key at the indent level above the current line's indent level and represents the collection that the current line is part of. The collection's key/value pairs will be stored in an array with its name defined as the concatenation of the prefix
and parent_key
.
For the top level (indent level zero) the data set prefix is used as the parent key so it has no prefix (it's set to ""
). All other arrays are prefixed with the root prefix.
Next, the current key is inserted into an (awk-internal) array containing the keys. This array persists throughout the whole awk session and therefore contains keys inserted by prior lines. The key is inserted into the array using its indent as the array index.
keys[indent] = key;
Because this array contains keys from previous lines, any keys with an indent level grater than the current line's indent level are removed:
for (i in keys) {if (i > indent) {delete keys[i]}}
This leaves the keys array containing the key-chain from the root at indent level 0 to the current line. It removes stale keys that remain when the prior line was indented deeper than the current line.
The final section outputs the bash
commands: an input line without a value starts a new indent level (a collection in YAML parlance) and an input line with a value adds a key to the current collection.
The collection's name is the concatenation of the current line's prefix
and parent_key
.
When a key has a value, a key with that value is assigned to the current collection like this:
printf("%s%s[%s]=\"%s\";\n", prefix, parent_key , key, value);
printf("%s%s[keys]+=\" %s\";\n", prefix, parent_key , key);
The first statement outputs the command to assign the value to an associative array element named after the key and the second one outputs the command to add the key to the collection's space-delimited keys
list:
<current_collection>[<key>]="<value>";
<current_collection>[keys]+=" <key>";
When a key doesn't have a value, a new collection is started like this:
printf("%s%s[children]+=\" %s%s\";\n", prefix, parent_key , root_prefix, key);
printf("declare -g -A %s%s;\n", root_prefix, key);
The first statement outputs the command to add the new collection to the current's collection's space-delimited children
list and the second one outputs the command to declare a new associative array for the new collection:
<current_collection>[children]+=" <new_collection>"
declare -g -A <new_collection>;
All of the output from yay_parse
can be parsed as bash commands by the bash eval
or source
built-in commands.
This is a very c# type of code:
var bks: Book[] = new Book[2];
In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:
var bks: Book[] = [];
bks.push(new Book());
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;
Now to explain what new Book[2];
would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:
Book[2] = function (){alert("hey");}
var foo = new Book[2]
and you should see hey. Try it
This also works if you are looping over an object.
unset($object->$key);
No need to use brackets.
<button>
's are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!
$('form button').on("click",function(e){
e.preventDefault();
});
This is a general issue, and doesn't appear in a single case. But, the common problem in all the cases is that you forget to import
a specific component (doesn't matter if it's either from a library that you installed or a custom made component that you created):
import {SomeClass} from 'some-library'
When you use it later, without importing it, the compiler thinks it's a function. Therefore, it breaks. This is a common example:
imports
...code...
and then somewhere inside your code
<Image {..some props} />
If you forgot to import the component <Image />
then the compiler will not complain like it does for other imports, but will break when it reaches your code.
# or even faster copy paste answer if you have sudo on the host
sudo su - postgres -c "psql template1 -c 'CREATE EXTENSION IF NOT EXISTS \"dblink\";'"
Try this
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />
if you want 0 or 1 "description" elements, Or
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />
if you want 0 to infinity number of "description" elements.
public byte[] loadBinaryFile (String name) {
try {
DataInputStream dis = new DataInputStream(new FileInputStream(name));
byte[] theBytes = new byte[dis.available()];
dis.read(theBytes, 0, dis.available());
dis.close();
return theBytes;
} catch (IOException ex) {
}
return null;
} // ()
See here: Cross Browser favicon
Thats the way to go:
<link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->
For me it was because of vmware (services-it has about 2 or 3 different services),stop it and every thing works fine
For mac osx users
brew tap homebrew/cask
brew cask install chromedriver
This is what I did on OS X:
git mv File file.tmp
git mv file.tmp file
Two steps because otherwise I got a “file exists” error. Perhaps it can be done in one step by adding --cached
or such.
The following method DO NOT use external tools and AUTOMATICALLY include all needed DLL (no manual action required, everything done at compilation)
I read a lot of answer here saying to use ILMerge, ILRepack or Jeffrey Ritcher method but none of that worked with WPF applications nor was easy to use.
When you have a lot of DLL it can be hard to manually include the one you need in your exe. The best method i found was explained by Wegged here on StackOverflow
Copy pasted his answer here for clarity (all credit to Wegged)
.csproj
file:<Target Name="AfterResolveReferences">
<ItemGroup>
<EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
<LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
</EmbeddedResource>
</ItemGroup>
</Target>
Program.cs
look like this:[STAThreadAttribute]
public static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
App.Main();
}
OnResolveAssembly
method:private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = new AssemblyName(args.Name);
var path = assemblyName.Name + ".dll";
if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false) path = String.Format(@"{0}\{1}", assemblyName.CultureInfo, path);
using (Stream stream = executingAssembly.GetManifestResourceStream(path))
{
if (stream == null) return null;
var assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
return Assembly.Load(assemblyRawBytes);
}
}
if you are having dependency on some other project in work space and these projects are not build properly, such error might come. try building such dependent projects first, it may help
I'm using Debian 7 64-bit.
I didn't have a .vimrc file in my home folder. I created one and was able to set user defaults for vim.
However, for Debian 7, another way is to edit /etc/vim/vimrc
Here is a comment block in that file:
" All system-wide defaults are set in $VIMRUNTIME/debian.vim (usually just
" /usr/share/vim/vimcurrent/debian.vim) and sourced by the call to :runtime
" you can find below. If you wish to change any of those settings, you should
" do it in this file (/etc/vim/vimrc), since debian.vim will be overwritten
" everytime an upgrade of the vim packages is performed. It is recommended to
" make changes after sourcing debian.vim since it alters the value of the
" 'compatible' option.
You can add new function to your jQuery library by adding these line on your own script file and you can easily use fadeSlideRight()
and fadeSlideLeft()
.
Note: you can change width of animation as you like instance of 750px.
$.fn.fadeSlideRight = function(speed,fn) {
return $(this).animate({
'opacity' : 1,
'width' : '750px'
},speed || 400, function() {
$.isFunction(fn) && fn.call(this);
});
}
$.fn.fadeSlideLeft = function(speed,fn) {
return $(this).animate({
'opacity' : 0,
'width' : '0px'
},speed || 400,function() {
$.isFunction(fn) && fn.call(this);
});
}
As an improvement to Paul Egan's answer, this can be accomplished as follows:
sqlite3 database.db3 '.dump "table1" "table2"' | grep '^INSERT'
--or--
sqlite3 database.db3 '.dump "table1" "table2"' | grep -v '^CREATE'
The caveat, of course, is that you have to have grep installed.
Unless you have native code (machine code compiled for a specific arcitechture) your code will run equally well in a 32-bit and 64-bit JVM.
Note, however, that due to the larger adresses (32-bit is 4 bytes, 64-bit is 8 bytes) a 64-bit JVM will require more memory than a 32-bit JVM for the same task.
ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.
fileUpload = (e) => {
let data = e.target.files
if(e.target.files[0]!=null){
this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
}
}
here fileUpload is a different js file which accepts two params like this
export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);
return dispatch => {
axios.put(BaseUrl.RestUrl + "ur/url", formData)
.then(response => {
callback(response.data);
}).catch(error => {
console.log("***** "+error)
});
}
}
don't forget to bind method in the constructor. Let me know if you need more help in this.
Here's a quote from a recent blog post from Dare Obasanjo.
SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.
However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.
To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.
Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.
Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)
I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL
The link posted by Jose has been updated and pylab now has a tight_layout()
function that does this automatically (in matplotlib version 1.1.0).
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout
http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout
The Apple Tech Note also described you can restore the device to reset the Push Notification dialog.
It does not say that you can also use the option "General -> Reset -> Erase All Content And Settings" on the device itself (iOS 5.x).
If you are looking for UML sequence diagrams, try searching for UML Sequence in the search box and add them.
You can either browse through My shapes to access them. They will be available in the in the sidebar nevertheless once you search.
You're probably going to have to resize the button programmatically. You'll need to explicitly load the image in your onCreate() method, and resize the button there:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageButton myButton = (ImageButton) findViewById(R.id.button);
Bitmap image = BitmapFactory.decodeResource(R.drawable.eye);
myButton.setBitmap(image);
myButton.setMinimumWidth(image.getWidth());
myButton.setMinimumHeight(image.getHeight());
...
}
It's not guaranteed to work, according to the specifications for setMinimumX (since the width and height are still dependent on the parent view), but it should work pretty well for almost every situation.
Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.
Use this markup:
<div id="background">
<img src="img.jpg" class="stretch" alt="" />
</div>
with the following CSS:
#background {
width: 100%;
height: 100%;
position: absolute;
left: 0px;
top: 0px;
z-index: 0;
}
.stretch {
width:100%;
height:100%;
}
and you should be done!
In order to scale the image to be "full bleed" and maintain the aspect ratio, you can do this instead:
.stretch { min-width:100%; min-height:100%; width:auto; height:auto; }
It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I've tested it in Firefox, Webkit, and Internet Explorer 8.
Here's a thread safe way of doing it:
// Foo.h
@interface Foo {
}
+(NSDictionary*) dictionary;
// Foo.m
+(NSDictionary*) dictionary
{
static NSDictionary* fooDict = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
// create dict
});
return fooDict;
}
These edits ensure that fooDict is only created once.
From Apple documentation: "dispatch_once - Executes a block object once and only once for the lifetime of an application."
If you simply need to answer "y" to all the overwrite prompts, try this:
y | mv srcdir/* targetdir/
The JPanel
is actually only a container where you can put different elements in it (even other JPanels
). So in your case I would suggest one big JPanel
as some sort of main container for your window. That main panel you assign a Layout
that suits your needs ( here is an introduction to the layouts).
After you set the layout to your main panel you can add the paint panel and the other JPanels you want (like those with the text in it..).
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel paintPanel = new JPanel();
JPanel textPanel = new JPanel();
mainPanel.add(paintPanel);
mainPanel.add(textPanel);
This is just an example that sorts all sub panels vertically (Y-Axis). So if you want some other stuff at the bottom of your mainPanel (maybe some icons or buttons) that should be organized with another layout (like a horizontal layout), just create again a new JPanel as a container for all the other stuff and set setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS)
.
As you will find out, the layouts are quite rigid and it may be difficult to find the best layout for your panels. So don't give up, read the introduction (the link above) and look at the pictures – this is how I do it :)
Or you can just use NetBeans to write your program. There you have a pretty easy visual editor (drag and drop) to create all sorts of Windows and Frames. (only understanding the code afterwards is ... tricky sometimes.)
Since there are some many people interested in this question, I wanted to provide a complete example of how to layout a JFrame to make it look like OP wants it to.
The class is called MyFrame and extends swings JFrame
public class MyFrame extends javax.swing.JFrame{
// these are the components we need.
private final JSplitPane splitPane; // split the window in top and bottom
private final JPanel topPanel; // container panel for the top
private final JPanel bottomPanel; // container panel for the bottom
private final JScrollPane scrollPane; // makes the text scrollable
private final JTextArea textArea; // the text
private final JPanel inputPanel; // under the text a container for all the input elements
private final JTextField textField; // a textField for the text the user inputs
private final JButton button; // and a "send" button
public MyFrame(){
// first, lets create the containers:
// the splitPane devides the window in two components (here: top and bottom)
// users can then move the devider and decide how much of the top component
// and how much of the bottom component they want to see.
splitPane = new JSplitPane();
topPanel = new JPanel(); // our top component
bottomPanel = new JPanel(); // our bottom component
// in our bottom panel we want the text area and the input components
scrollPane = new JScrollPane(); // this scrollPane is used to make the text area scrollable
textArea = new JTextArea(); // this text area will be put inside the scrollPane
// the input components will be put in a separate panel
inputPanel = new JPanel();
textField = new JTextField(); // first the input field where the user can type his text
button = new JButton("send"); // and a button at the right, to send the text
// now lets define the default size of our window and its layout:
setPreferredSize(new Dimension(400, 400)); // let's open the window with a default size of 400x400 pixels
// the contentPane is the container that holds all our components
getContentPane().setLayout(new GridLayout()); // the default GridLayout is like a grid with 1 column and 1 row,
// we only add one element to the window itself
getContentPane().add(splitPane); // due to the GridLayout, our splitPane will now fill the whole window
// let's configure our splitPane:
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); // we want it to split the window verticaly
splitPane.setDividerLocation(200); // the initial position of the divider is 200 (our window is 400 pixels high)
splitPane.setTopComponent(topPanel); // at the top we want our "topPanel"
splitPane.setBottomComponent(bottomPanel); // and at the bottom we want our "bottomPanel"
// our topPanel doesn't need anymore for this example. Whatever you want it to contain, you can add it here
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS will arrange the content vertically
bottomPanel.add(scrollPane); // first we add the scrollPane to the bottomPanel, so it is at the top
scrollPane.setViewportView(textArea); // the scrollPane should make the textArea scrollable, so we define the viewport
bottomPanel.add(inputPanel); // then we add the inputPanel to the bottomPanel, so it under the scrollPane / textArea
// let's set the maximum size of the inputPanel, so it doesn't get too big when the user resizes the window
inputPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75)); // we set the max height to 75 and the max width to (almost) unlimited
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS)); // X_Axis will arrange the content horizontally
inputPanel.add(textField); // left will be the textField
inputPanel.add(button); // and right the "send" button
pack(); // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
}
public static void main(String args[]){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
new MyFrame().setVisible(true);
}
});
}
}
Please be aware that this is only an example and there are multiple approaches to layout a window. It all depends on your needs and if you want the content to be resizable / responsive. Another really good approach would be the GridBagLayout which can handle quite complex layouting, but which is also quite complex to learn.
You may want to look at how you can use the built-in features of .NET to serialize and deserialize an object into XML, rather than creating a ToXML()
method on every class that is essentially just a Data Transfer Object.
I have used these techniques successfully on a couple of projects but don’t have the implementation details handy right now. I will try to update my answer with my own examples sometime later.
Here's a couple of examples that Google returned:
XML Serialization in .NET by Venkat Subramaniam http://www.agiledeveloper.com/articles/XMLSerialization.pdf
How to Serialize and Deserialize an object into XML http://www.dotnetfunda.com/articles/article98.aspx
Customize your .NET object XML serialization with .NET XML attributes http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx
It subjects to architecture of the server on which PHP runs. For 64-bit,
print PHP_INT_MIN . ", ” . PHP_INT_MAX;
yields -9223372036854775808, 9223372036854775807
No, you don't need to copy all 387 constructors to Bar and Bah. Bar and Bah can have as many or as few constructors as you want independent of how many you define on Foo. For example, you could choose to have just one Bar constructor which constructs Foo with Foo's 212th constructor.
Yes, any constructors you change in Foo that Bar or Bah depend on will require you to modify Bar and Bah accordingly.
No, there is no way in .NET to inherit constructors. But you can achieve code reuse by calling a base class's constructor inside the subclass's constructor or by calling a virtual method you define (like Initialize()).
I personally would return null, because that is how I would expect the DAL/Repository layer to act.
If it doesn't exist, don't return anything that could be construed as successfully fetching an object, null
works beautifully here.
The most important thing is to be consistant across your DAL/Repos Layer, that way you don't get confused on how to use it.
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
You can use JavaScript (don't need jQuery)
document.querySelectorAll('#selected li').length;
Use the java.io.InputStream.transferTo(OutputStream) supported in Java 9 and the ByteArrayOutputStream.toString(String) which takes the charset name:
public static String gobble(InputStream in, String charsetName) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in.transferTo(bos);
return bos.toString(charsetName);
}
If the IN clause is a parameter (either to SP or hot-built SQL), then this can always be done:
SELECT (SELECT COUNT(1)
FROM product_a
WHERE product_id IN (1, 8, 100)
) = (number of commas in product_id as constant)
If the IN clause is a table, then this can always be done:
SELECT (SELECT COUNT(*)
FROM product_a
WHERE product_id IN (SELECT Products
FROM #WorkTable)
) = (SELECT COUNT(*)
FROM #WorkTable)
If the IN clause is complex then either spool it into a table or write it twice.
OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.
Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.
But the real cause of your problem is that you are using when
on two different objects, before you complete the stubbing. When you call when
, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn
part. Each call to when
must be followed by one and only one call to thenReturn
, before you do any more calls to when
. You made two calls to when
without calling thenReturn
- that's your error.
I like Mozzi's answer but found that it did not retain the default fonts that are user specific. The text all appeared in a system font as normal text. The code below retains the user's favourite fonts, while making it only a little longer. It is based on Mozzi's approach, uses a regular expression to replace the default body text and places the user's chosen Body text where it belongs by using GetInspector.WordEditor. I found that the call to GetInspector did not populate the HTMLbody as dimitry streblechenko says above in this thread, at least, not in Office 2010, so the object is still displayed in my code. In passing, please note that it is important that the MailItem is created as an Object, not as a straightforward MailItem - see here for more. (Oh, and sorry to those of different tastes, but I prefer longer descriptive variable names so that I can find routines!)
Public Function GetSignedMailItemAsObject(ByVal ToAddress As String, _
ByVal Subject As String, _
ByVal Body As String, _
SignatureName As String) As Object
'================================================================================================================='Creates a new MailItem in HTML format as an Object.
'Body, if provided, replaces all text in the default message.
'A Signature is appended at the end of the message.
'If SignatureName is invalid any existing default signature is left in place.
'=================================================================================================================
' REQUIRED REFERENCES
' VBScript regular expressions (5.5)
' Microsoft Scripting Runtime
'=================================================================================================================
Dim OlM As Object 'Do not define this as Outlook.MailItem. If you do, some things will work and some won't (i.e. SendUsingAccount)
Dim Signature As String
Dim Doc As Word.Document
Dim Regex As New VBScript_RegExp_55.RegExp '(can also use use Object if VBScript is not Referenced)
Set OlM = Application.CreateItem(olMailItem)
With OlM
.To = ToAddress
.Subject = Subject
'SignatureName is the exactname that you gave your signature in the Message>Insert>Signature Dialog
Signature = GetSignature(SignatureName)
If Signature <> vbNullString Then
' Should really strip the terminal </body tag out of signature by removing all characters from the start of the tag
' but Outlook seems to handle this OK if you don't bother.
.Display 'Needed. Without it, there is no existing HTMLbody available to work with.
Set Doc = OlM.GetInspector.WordEditor 'Get any existing body with the WordEditor and delete all of it
Doc.Range(Doc.Content.Start, Doc.Content.End) = vbNullString 'Delete all existing content - we don't want any default signature
'Preserve all local email formatting by placing any new body text, followed by the Signature, into the empty HTMLbody.
With Regex
.IgnoreCase = True 'Case insensitive
.Global = False 'Regex finds only the first match
.MultiLine = True 'In case there are stray EndOfLines (there shouldn't be in HTML but Word exports of HTML can be dire)
.Pattern = "(<body.*)(?=<\/body)" 'Look for the whole HTMLbody but do NOT include the terminal </body tag in the value returned
OlM.HTMLbody = .Replace(OlM.HTMLbody, "$1" & Signature)
End With ' Regex
Doc.Range(Doc.Content.Start, Doc.Content.Start) = Body 'Place the required Body before the signature (it will get the default style)
.Close olSave 'Close the Displayed MailItem (actually Object) and Save it. If it is left open some later updates may fail.
End If ' Signature <> vbNullString
End With ' OlM
Set GetSignedMailItemAsObject = OlM
End Function
Private Function GetSignature(sigName As String) As String
Dim oTextStream As Scripting.TextStream
Dim oSig As Object
Dim appDataDir, Signature, sigPath, fileName As String
Dim FileSys As Scripting.FileSystemObject 'Requires Microsoft Scripting Runtime to be available
appDataDir = Environ("APPDATA") & "\Microsoft\Signatures"
sigPath = appDataDir & "\" & sigName & ".htm"
Set FileSys = CreateObject("Scripting.FileSystemObject")
Set oTextStream = FileSys.OpenTextFile(sigPath)
Signature = oTextStream.ReadAll
' fix relative references to images, etc. in Signature
' by making them absolute paths, OL will find the image
fileName = Replace(sigName, ".htm", "") & "_files/"
Signature = Replace(Signature, fileName, appDataDir & "\" & fileName)
GetSignature = Signature
End Function
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]
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");
});
They are both examples of floating point input/output.
%g and %G are simplifiers of the scientific notation floats %e and %E.
%g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two.
The output of your print statement will depend on the value of sum.
Per Debian policy, python
refers to Python 2 and python3
refers to Python 3. Don't try to change this system-wide or you are in for the sort of trouble you already discovered.
Virtual environments allow you to run an isolated Python installation with whatever version of Python and whatever libraries you need without messing with the system Python install.
With recent Python 3, venv
is part of the standard library; with older versions, you might need to install python3-venv
or a similar package.
$HOME~$ python --version
Python 2.7.11
$HOME~$ python3 -m venv myenv
... stuff happens ...
$HOME~$ . ./myenv/bin/activate
(myenv) $HOME~$ type python # "type" is preferred over which; see POSIX
python is /home/you/myenv/bin/python
(myenv) $HOME~$ python --version
Python 3.5.1
A common practice is to have a separate environment for each project you work on, anyway; but if you want this to look like it's effectively system-wide for your own login, you could add the activation stanza to your .profile
or similar.
This is a job for numpy
.
And here's a tutorial demonstrating how pincipal component analysis can be done using numpy
's built-in modules like mean,cov,double,cumsum,dot,linalg,array,rank
.
http://glowingpython.blogspot.sg/2011/07/principal-component-analysis-with-numpy.html
Notice that scipy
also has a long explanation here
- https://github.com/scikit-learn/scikit-learn/blob/babe4a5d0637ca172d47e1dfdd2f6f3c3ecb28db/scikits/learn/utils/extmath.py#L105
with the scikit-learn
library having more code examples -
https://github.com/scikit-learn/scikit-learn/blob/babe4a5d0637ca172d47e1dfdd2f6f3c3ecb28db/scikits/learn/utils/extmath.py#L105
I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter
:
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
You can see a list of supported browsers here.
In the future with ES6, you'll be able to use array.find.
// create table
var dt = new System.Data.DataTable("tableName");
// create fields
dt.Columns.Add("field1", typeof(int));
dt.Columns.Add("field2", typeof(string));
dt.Columns.Add("field3", typeof(DateTime));
// insert row values
dt.Rows.Add(new Object[]{
123456,
"test",
DateTime.Now
});
I was searching for solution to the very same problem and un-ticking "Sign the assembly" option works for me:
(as you may notice screenshot comes from VS2010 but hopefully it will help someone)