Try this in your css:
.card-img-top {
width: 100%;
height: 15vw;
object-fit: cover;
}
Adjust the height vw as you see fit. The object-fit: cover enables zoom instead of image stretching.
Add w-auto native bootstrap 4 class to the table element and your table will fit its content.
OK! I'm really sorry to those that have actually submitted comments and answers, but I found the problem. I don't think this will help a lot of others trying to track down their personal SIGSEGV, but mine (and it was very hard) was entirely related to this:
https://code.google.com/p/android/issues/detail?id=8709
The libcrypto.so in my dump kind of clued me in. I do a MD5 hash of packet data when trying to determine if I've already seen the packet, and skipping it if I had. I thought at one point this was an ugly threading issue related to tracking those hashes, but it turned out it was the java.security.MessageDigest class! It's not thread safe!
I swapped it out with a UID I was stuffing in every packet based on the device UUID and a timestamp. No problems since.
I guess the lesson I can impart to those that were in my situation is, even if you're a 100% Java application, pay attention to the native library and symbol noted in the crash dump for clues. Googling for SIGSEGV + the lib .so name will go a lot farther than the useless code=1, etc... Next think about where your Java app could touch native code, even if it's nothing you're doing. I made the mistake of assuming it was a Service + UI threading issue where the Canvas was drawing something that was null, (the most common case I Googled on SIGSEGV) and ignored the possibility it could have been completely related to code I wrote that was related to the lib .so in the crash dump. Naturally java.security would use a native component in libcrypto.so for speed, so once I clued in, I Googled for Android + SIGSEGV + libcrypto.so and found the documented issue. Good luck!
In this Eclipse Preferences panel you can change the compiler compatibility from 1.7 to 1.6. This solved the similar message I was getting. For Eclipse, it is under: Preferences -> Java -> Compiler: 'Compiler compliance level'
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);
I need to share, as I spent too much time looking for a solution
Here was the solution : https://unix.stackexchange.com/a/351742/215375
I was using this command :
ssh-keygen -o -t rsa -b 4096 -C "[email protected]"
gnome-keyring does not support the generated key.
Removing the -o
argument solved the problem.
You can use the following css to resize the image for mobile view
object-fit: scale-down; max-width: 100%
You can disable the check (if you're really sure you know what you're doing) by using the --force
option to git push
.
It's quite simple.
All you need to do is:
An example taken form here:
When an Employee
entity object is removed, the remove operation is cascaded to the referenced Address
entity object. In this regard, orphanRemoval=true
and cascade=CascadeType.REMOVE
are identical, and if orphanRemoval=true
is specified, CascadeType.REMOVE
is redundant.
The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null
or to another Address
object.
If orphanRemoval=true
is specified the disconnected Address
instance
is automatically removed. This is useful for cleaning up dependent
objects (e.g. Address
) that should not exist without a reference from
an owner object (e.g. Employee
).
If only cascade=CascadeType.REMOVE
is specified, no automatic action
is taken since disconnecting a relationship is not a remove
operation.
To avoid dangling references as a result of orphan removal, this feature should only be enabled for fields that hold private non shared dependent objects.
I hope this makes it more clear.
This is a for loop, but maintains the object reference in the loop just like a forEach() but you can break out.
var arr = [1,2,3];
for (var i = 0, el; el = arr[i]; i++) {
if(el === 1) break;
}
Edit: From the git help stash
documentation in the pop section:
Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards.
If the --index option is used, then tries to reinstate not only the working tree's changes, but also the index's ones. However, this can fail, when you have conflicts (which are stored in the index, where you therefore can no longer apply the changes as they were originally).
Try hardcopying all your repo into a new dir (so you have a copy of it) and run:
git stash show
and save that output somewhere if you care about it.
then: git stash drop
to drop the conflicting stash
then: git reset HEAD
That should leave your repo in the state it was before (hopefully, I still haven't been able to repro your problem)
===
I am trying to repro your problem but all I get when usin git stash pop
is:
error: Your local changes to the following files would be overwritten by merge:
...
Please, commit your changes or stash them before you can merge.
Aborting
In a clean dir:
git init
echo hello world > a
git add a & git commit -m "a"
echo hallo welt >> a
echo hello world > b
git add b & git commit -m "b"
echo hallo welt >> b
git stash
echo hola mundo >> a
git stash pop
I don't see git trying to merge my changes, it just fails. Do you have any repro steps we can follow to help you out?
I followed instructions on http://opencv.willowgarage.com/wiki/VisualC%2B%2B_VS2010 but was still stuck on exactly the same problem, so here's how I resolved it.
Fetched MSVC 2010 express edition.
Fetched Win 32 OpenCV 2.2 binaries and installed in default location.
Created new project.
Project setup
Project -> OpenCV_Helloworld Properties...Configuration Properties -> VC++ Directories
Include Directories... add: C:\OpenCV2.2\include\;
Library Directories... add: C:\OpenCV2.2\lib;C:\OpenCV2.2\bin;
Source Directories... add:
C:\OpenCV2.2\modules\calib3d\src;C:\OpenCV2.2\modules\contrib\src;C:\OpenCV2.2\modules\core\src;C:\OpenCV2.2\modules\features2d\src;C:\OpenCV2.2\modules\flann\src;C:\OpenCV2.2\modules\gpu\src;C:\OpenCV2.2\modules\gpu\src;C:\OpenCV2.2\modules\highgui\src;C:\OpenCV2.2\modules\imgproc\src;C:\OpenCV2.2\modules\legacy\src;C:\OpenCV2.2\modules\ml\src;C:\OpenCV2.2\modules\objdetect\src;C:\OpenCV2.2\modules\video\src;
Linker -> Input -> Additional Dependencies...
For Debug Builds... add:
opencv_calib3d220d.lib;opencv_contrib220d.lib;opencv_core220d.lib;opencv_features2d220d.lib;opencv_ffmpeg220d.lib;opencv_flann220d.lib;opencv_gpu220d.lib;opencv_highgui220d.lib;opencv_imgproc220d.lib;opencv_legacy220d.lib;opencv_ml220d.lib;opencv_objdetect220d.lib;opencv_video220d.lib;
At this point I thought I was done, but ran into the problem you described when running the exe in debug mode. The final step is obvious once you see it, select:
Linker -> General ... Set 'Use Library Dependency Inputs' to 'Yes'
Hope this helps.
You should use .Load
and not .LoadXML
"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."
ref : Link
std::string replace(std::string str, const std::string& sub1, const std::string& sub2)
{
if (sub1.empty())
return str;
std::size_t pos;
while ((pos = str.find(sub1)) != std::string::npos)
str.replace(pos, sub1.size(), sub2);
return str;
}
you can add "+" in your variable,
example :
$numString = "0000001123000";
echo +$numString;
This has not been tested but I think this should work using mod_rewrite
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.
It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!
The only times you should need to escape are when trying to put "
inside a string, or '
in a character:
String quotes = "He said \"Hello, World!\"";
char quote = '\'';
Yes , Its easy to way we call the function inside the store procedure.
for e.g. create user define Age function and use in select query.
select dbo.GetRegAge(R.DateOfBirth, r.RegistrationDate) as Age,R.DateOfBirth,r.RegistrationDate from T_Registration R
Finally I imported my Gradle project. These are the steps:
JAVA_HOME
to JDK 8 (it was 7th previously) as I had
figured out by experiments that Gradle Wrapper could process the
project with JDK 8 only. org.gradle.java.home
variable) in windows user .gradle directory
as, I guessed, it didn't bring any additional value to Gradle.find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -I 'pigz -9' -cf target.tgz
for multicore or just for one core:
find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -czf target.tgz
button.setVisibility(button.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
Makes it visible if invisible and invisible if visible
You can simply access like
Context mContext;
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mContext = getActivity();
}
and then use
FragmentManager fm = ((FragmentActivity) mContext)
.getSupportFragmentManager();
There was same issue with me
In my case, steps are as below-
U project/app/pages/file1/file.ts
U project/www/assets/file1/file-name.html
$ git pull origin master
$ git status
Here is the message which It appeared-
and have 2 and 1 different commit each, respectively.
(use "git pull" to merge the remote branch into yours)
You have unmerged paths.
(fix conflicts and run "git commit")
Unmerged paths:
(use "git add ..." to mark resolution)
both modified: project/app/pages/file1/file.ts
both modified: project/www/assets/file1/file-name.html
$ git add project/app/pages/file1/file.ts
project/www/assets/file1/file-name.html
$ git commit -am "resolved conflict of the app."
$ git push origin master
Most likely, the userdata()
function is returning an object, not a string. Look into the documentation (or var_dump the return value) to find out which value you need to use.
easy
batch file:
FOR %%A IN (1 2 3) DO ECHO %%A
command line:
FOR %A IN (1 2 3) DO ECHO %A
output:
1
2
3
Looks like this is quite a solved question but I recently found out that callee is not allowed in 'strict mode' so for my own use I wrote a class that will get the path from where it is called. It's part of a small helper lib and if you want to use the code standalone change the offset used to return the stack trace of the caller (use 1 instead of 2)
function ScriptPath() {
var scriptPath = '';
try {
//Throw an error to generate a stack trace
throw new Error();
}
catch(e) {
//Split the stack trace into each line
var stackLines = e.stack.split('\n');
var callerIndex = 0;
//Now walk though each line until we find a path reference
for(var i in stackLines){
if(!stackLines[i].match(/http[s]?:\/\//)) continue;
//We skipped all the lines with out an http so we now have a script reference
//This one is the class constructor, the next is the getScriptPath() call
//The one after that is the user code requesting the path info (so offset by 2)
callerIndex = Number(i) + 2;
break;
}
//Now parse the string for each section we want to return
pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
}
this.fullPath = function() {
return pathParts[1];
};
this.path = function() {
return pathParts[2];
};
this.file = function() {
return pathParts[3];
};
this.fileNoExt = function() {
var parts = this.file().split('.');
parts.length = parts.length != 1 ? parts.length - 1 : 1;
return parts.join('.');
};
}
Isn't this the normal way to free the memory associated with an object?
Yes, it is.
I realized that it automatically invokes the destructor... is this normal?
Make sure that you did not double delete your object.
Hope this helps you:
import com.sun.org.apache.xml.internal.security.utils.Base64;
String str="Hello World";
String base64_str=Base64.encode(str.getBytes("UTF-8"));
Or:
String str="Hello World";
String base64_str="";
try
{base64_str=(String)Class.forName("java.util.prefs.Base64").getDeclaredMethod("byteArrayToBase64", new Class[]{byte[].class}).invoke(null, new Object[]{str.getBytes("UTF-8")});
}
catch (Exception ee) {}
java.util.prefs.Base64
works on local rt.jar
,
But it is not in The JRE Class White List
and not in Available classes not listed in the GAE/J white-list
What a pity!
PS. In android, it's easy because that android.util.Base64
has been included since Android API Level 8.
I guess you hate to write more selectors and divide them by a comma?
.registration_form_right input:not([type="radio"]),
.registration_form_right input:not([type="checkbox"])
{
}
and BTW this
not([type="radio" && type="checkbox"])
looks to me more like "input which does not have both these types" :)
grep -Fxvf file1 file2
What the flags mean:
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
-x, --line-regexp
Select only those matches that exactly match the whole line.
-v, --invert-match
Invert the sense of matching, to select non-matching lines.
-f FILE, --file=FILE
Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing.
I implemented UIGestureRecognizerDelegate methods to detect both singleTap and doubleTap.
Just do this .
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTapGesture:)];
[doubleTap setDelegate:self];
doubleTap.numberOfTapsRequired = 2;
[self.headerView addGestureRecognizer:doubleTap];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTapGesture:)];
singleTap.numberOfTapsRequired = 1;
[singleTap setDelegate:self];
[doubleTap setDelaysTouchesBegan:YES];
[singleTap setDelaysTouchesBegan:YES];
[singleTap requireGestureRecognizerToFail:doubleTap];
[self.headerView addGestureRecognizer:singleTap];
Then implement these delegate methods.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
I think it's important to add a thing, if you use the layout inflation that constructor in the drawview is not correct, add these constructors in the class:
public DrawingView(Context c, AttributeSet attrs) {
super(c, attrs);
...
}
public DrawingView(Context c, AttributeSet attrs, int defStyle) {
super(c, attrs, defStyle);
...
}
or the android system fails to inflate the layout file. I hope this could to help.
"How to attach url link to an image?"
You do it like this:
<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>
See it in action.
You could try Jsonium tool http://jsonium.org- nice free tool specialized on requests with JSON in bodies and responses
From the article Override equals and hashCode in Java:
Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object.
Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic: example:
many classes in Java standard library does override it e.g. String overrides equals, whose implementation of equals() method return true if content of two String objects are exactly same
Integer wrapper class overrides equals to perform numerical comparison etc.
You can also do this with positioning, set parent div to relative and child div to absolute.
.wrapper {
position: relative;
}
.childDiv {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?
var ele = /*Your Form Element*/;
if(ele.addEventListener){
ele.addEventListener("submit", callback, false); //Modern browsers
}else if(ele.attachEvent){
ele.attachEvent('onsubmit', callback); //Old IE
}
callback
is a function that you want to call when the form is being submitted.
About EventTarget.addEventListener
, check out this documentation on MDN.
To cancel the native submit
event (prevent the form from being submitted), use .preventDefault()
in your callback function,
document.querySelector("#myForm").addEventListener("submit", function(e){
if(!isValid){
e.preventDefault(); //stop form from submitting
}
});
submit
event with librariesIf for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:
jQuery
$(ele).submit(callback);
Where ele
is the form element reference, and callback
being the callback function reference. Reference
<iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>
_x000D_
AngularJS (1.x)
<form ng-submit="callback()">
$scope.callback = function(){ /*...*/ };
Very straightforward, where $scope
is the scope provided by the framework inside your controller. Reference
React
<form onSubmit={this.handleSubmit}>
class YourComponent extends Component {
// stuff
handleSubmit(event) {
// do whatever you need here
// if you need to stop the submit event and
// perform/dispatch your own actions
event.preventDefault();
}
// more stuff
}
Simply pass in a handler to the onSubmit
prop. Reference
Other frameworks/libraries
Refer to the documentation of your framework.
You can always do your validation in JavaScript, but with HTML5 we also have native validation.
<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">
You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.
Here's another way without using calc()
.
// 4 PER ROW
// 100 divided by 4 is 25. Let's use 21% for width, and the remainder 4% for left & right margins...
.child {
margin: 0 2% 0 2%;
width: 21%;
}
// 3 PER ROW
// 100 divided by 3 is 33.3333... Let's use 30% for width, and remaining 3.3333% for sides (hint: 3.3333 / 2 = 1.66666)
.child {
margin: 0 1.66666% 0 1.66666%;
width: 30%;
}
// and so on!
That's all there is to it. You can get fancy with the dimensions to get a more aesthetic sizes but this is the idea.
Os X Mojave 10.14 has:
Error: The Command Line Tools header package must be installed on Mojave.
Solution. Go to
/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
location and install the package manually. And brew will start working and we can run:
brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git
with pygame:
dy = p1.y - p2.y
dX = p2.x - p1.x
rads = atan2(dy,dx)
degs = degrees(rads)
if degs < 0 :
degs +=90
it work for me
CATALINA_BASE is optional.
However, in the following scenarios it helps to setup CATALINA_BASE that is separate from CATALINA_HOME.
When more than 1 instances of tomcat are running on same host
Separation of concern (Single responsibility)
You can run npm list -g
to see which global libraries are installed and where they're located. Use npm list -g | head -1
for truncated output showing just the path. If you want to display only main packages not its sub-packages which installs along with it - you can use - npm list --depth=0
which will show all packages and for getting only globally installed packages, just add -g i.e. npm list -g --depth=0
.
On Unix systems they are normally placed in /usr/local/lib/node
or /usr/local/lib/node_modules
when installed globally. If you set the NODE_PATH
environment variable to this path, the modules can be found by node.
Windows XP - %USERPROFILE%\AppData\npm\node_modules
Windows 7, 8 and 10 - %USERPROFILE%\AppData\Roaming\npm\node_modules
Non-global libraries are installed the node_modules
sub folder in the folder you are currently in.
You can run npm list
to see the installed non-global libraries for your current location.
npm install -g pm2
- pm2 will be installed globally. It will then typically be found in /usr/local/lib/node_modules
(Use npm root -g
to check where.)
npm install pm2
- pm2 will be installed locally. It will then typically be found in the local directory in /node_modules
In the end I had had to make changes to the content of the page behind the modal screen to ensure that it never got long enough to scroll the page.
Once I did that, the problems I encountered when applying position: absolute
to the dialog were resolved as the user could no longer scroll down the page.
I have occasion to go a step further and determine if the site I'm connecting to is SSL capable (one project asks the user for their URL and we need to verify they have installed our API pack on a http or https site).
Here's the function I use - basically, just call the URL via cURL to see if https works!
function hasSSL($url)
{
// take the URL down to the domain name
$domain = parse_url($url, PHP_URL_HOST);
$ch = curl_init('https://' . $domain);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); //its a HEAD
curl_setopt($ch, CURLOPT_NOBODY, true); // no body
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // in case of redirects
curl_setopt($ch, CURLOPT_VERBOSE, 0); //turn on if debugging
curl_setopt($ch, CURLOPT_HEADER, 1); //head only wanted
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // we dont want to wait forever
curl_exec($ch);
$header = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($header === 200) {
return true;
}
return false;
}
This is the most reliable way I have found to not only find out IF you are using https (as the question asks), but if you COULD (or even SHOULD) be using https.
NOTE: it is possible (though not really likely...) that a site could have different http and https pages (so if you are told to use http, maybe you don't need to change..) The vast majority of sites are the same, and probably should reroute you themselves, but this additional check has its use (certainly as I said, in the project where the user inputs their site info and you want to make sure from the server side)
Here is my solution. The time complexity is o(n^2)
public String removeDuplicates(char[] arr) {
StringBuilder sb = new StringBuilder();
if (arr == null)
return null;
int len = arr.length;
if (arr.length < 2)
return sb.append(arr[0]).toString();
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (arr[i] == arr[j]) {
arr[j] = 0;
}
}
if (arr[i] != 0)
sb.append(arr[i]);
}
return sb.toString().trim();
}
The question "Why do we need to install gulp globally and locally?" can be broken down into the following two questions:
Why do I need to install gulp locally if I've already installed it globally?
Why do I need to install gulp globally if I've already installed it locally?
Several others have provided excellent answers to theses questions in isolation, but I thought it would be beneficial to consolidate the information in a unified answer.
Why do I need to install gulp locally if I've already installed it globally?
The rationale for installing gulp locally is comprised of several reasons:
Why do I need to install gulp globally if I've already installed it locally?
To avoid installing locally you can use npm link [package]
, but the link command as well as the install --global
command doesn't seem to support the --save-dev
option which means there doesn't appear to be an easy way to install gulp globally and then easily add whatever version that is to your local package.json file.
Ultimately, I believe it makes more sense to have the option of using global modules to avoid having to duplicate the installation of common tools across all your projects, especially in the case of development tools such as grunt, gulp, jshint, etc. Unfortunately it seems you end up fighting the tools a bit when you go against the grain.
Problem solved!
Final .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
# BEGIN WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:
$('td').click(function(){
var row_index = $(this).closest("tr").index();
var col_index = $(this).index();
});
Quick and dirty way is to do a global search for '\n'
. You can filter it any way you like on file extensions etc.
Ctrl-Shift-F -> Text to find = '\n'
-> Find.
Edit: And 'regular expression' has to be checked.
CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf
, and upload it to your remote server where your blog or website is hosted.
@font-face {
font-family: myfont;
src: url('myfont.ttf');
}
<context:property-placeholder location="classpath*:spring/*.properties" />
If you place it somewhere in the classpath in a directory named spring (change names/dirs accordingly), you can access with above
<property name="locations" value ="config/springcontext.properties" />
this will be pointing to web-inf/classes/config/springcontext.properties
This will solve the problem. No need to write code in controller. And remove your css styles display:none
<div><button id="mybutton" ng-click="myvalue=true">Click me</button></div>
This the simplest way to assign an async
arrow function expression to a named variable:
const foo = async () => {
// do something
}
(Note that this is not strictly equivalent to async function foo() { }
. Besides the differences between the function
keyword and an arrow expression, the function in this answer is not "hoisted to the top".)
As far as the client certificate approach goes, it would not be terribly difficult to implement while still allowing the users without client certificates in.
If you did in fact create your own self-signed Certification Authority, and issued client certs to each client service, you would have an easy way of authenticating those services.
Depending on the web server you are using, there should be a method to specify client authentication that will accept a client cert, but does not require one. For example, in Tomcat when specifying your https connector, you can set 'clientAuth=want', instead of 'true' or 'false'. You would then make sure to add your self signed CA certificate to your truststore (by default the cacerts file in the JRE you are using, unless you specified another file in your webserver configuration), so the only trusted certificates would be those issued off of your self signed CA.
On the server side, you would only allow access to the services you wish to protect if you are able to retrieve a client certificate from the request (not null), and passes any DN checks if you prefer any extra security. For the users without client certs, they would still be able to access your services, but will simply have no certificates present in the request.
In my opinion this is the most 'secure' way, but it certainly has its learning curve and overhead, so may not necessarily be the best solution for your needs.
Well, you can use the CASE statement:
SELECT
CASE
WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
ELSE Date1
END AS MostRecentDate
[For Microsoft SQL Server 2008 and above, you may consider Sven's simpler answer below.]
MySQL, SQL Server, PostgreSQL, SQLite support using the percent sign as the modulus:
WHERE column % 2 = 1
For Oracle, you have to use the MOD function:
WHERE MOD(column, 2) = 1
If you are using FireFox you can use the File HandleAPI
https://developer.mozilla.org/en-US/docs/Web/API/File_Handle_API
I had just tested it out and it works!
The answer given by H Dog is great, but this approach was actually giving me some modal flicker in Internet Explorer 11. Bootstrap will first hide the modal removing the 'modal-open' class, and then (using H Dogs solution) we add the 'modal-open' class again. I suspect this is somehow causing the flicker I was seeing, maybe due to some slow HTML/CSS rendering.
Another solution is to prevent bootstrap in removing the 'modal-open' class from the body element in the first place. Using Bootstrap 3.3.7, this override of the internal hideModal function works perfectly for me.
$.fn.modal.Constructor.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
if ($(".modal:visible").length === 0) {
that.$body.removeClass('modal-open')
}
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
In this override, the 'modal-open' class is only removed when there are no visible modals on the screen. And you prevent one frame of removing and adding a class to the body element.
Just include the override after bootstrap have been loaded.
Since the question on how to convert from ISO-8859-1 to UTF-8 is closed because of this one I'm going to post my solution here.
The problem is when you try to GET anything by using XMLHttpRequest, if the XMLHttpRequest.responseType is "text" or empty, the XMLHttpRequest.response is transformed to a DOMString and that's were things break up. After, it's almost impossible to reliably work with that string.
Now, if the content from the server is ISO-8859-1 you'll have to force the response to be of type "Blob" and later convert this to DOMSTring. For example:
var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'blob';
ajax.onreadystatechange = function(){
...
if(ajax.responseType === 'blob'){
// Convert the blob to a string
var reader = new window.FileReader();
reader.addEventListener('loadend', function() {
// For ISO-8859-1 there's no further conversion required
Promise.resolve(reader.result);
});
reader.readAsBinaryString(ajax.response);
}
}
Seems like the magic is happening on readAsBinaryString so maybe someone can shed some light on why this works.
One can also try this solution :
To find the value, which is written in span of table
htmlContent
<table>
<tr>
<th>
ID
</th>
<th>
Name
</th>
</tr>
<tr>
<td>
<span name="spanId" class="spanclass">ID123</span>
</td>
<td>
<span>Bonny</span>
</td>
</tr>
</table>
Python code
soup = BeautifulSoup(htmlContent, "lxml")
soup.prettify()
tables = soup.find_all("table")
for table in tables:
storeValueRows = table.find_all("tr")
thValue = storeValueRows[0].find_all("th")[0].string
if (thValue == "ID"): # with this condition I am verifying that this html is correct, that I wanted.
value = storeValueRows[1].find_all("span")[0].string
value = value.strip()
# storeValueRows[1] will represent <tr> tag of table located at first index and find_all("span")[0] will give me <span> tag and '.string' will give me value
# value.strip() - will remove space from start and end of the string.
# find using attribute :
value = storeValueRows[1].find("span", {"name":"spanId"})['class']
print value
# this will print spanclass
if(strcmp(aString, bString) == 0){
//strings are the same
}
godspeed
if (Data_Array["XML_File"] != "") String xmlfile = Data_Array["XML_File"];
import os
os.system("pip install beautifulsoup4")
or
import subprocess
exe = subprocess.Popen("pip install beautifulsoup4")
exe_out = exe.communicate()
print(exe_out)
Not the cleanest way, but you could wrap the callback code in a condition that checks the Rails environment.
if Rails.env == 'production'
...
If (1) you need a favicon that is different for some parts of the domain, or (2) you want this to work with IE 8 or older (haven't tested any newer version), then you have to edit the html to specify the favicon
you can use:
define("PATH_ROOT", dirname(__FILE__));
include_once PATH_ROOT . "/PoliticalForum/headerSite.php";
I would go for the second, the token system.
Did you know about ember-auth or ember-simple-auth? They both use the token based system, like ember-simple-auth states:
A lightweight and unobtrusive library for implementing token based authentication in Ember.js applications. http://ember-simple-auth.simplabs.com
They have session management, and are easy to plug into existing projects too.
There is also an Ember App Kit example version of ember-simple-auth: Working example of ember-app-kit using ember-simple-auth for OAuth2 authentication.
This should help you.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(train_set)
print tfidf_matrix
cosine = cosine_similarity(tfidf_matrix[length-1], tfidf_matrix)
print cosine
and output will be:
[[ 0.34949812 0.81649658 1. ]]
time.monotonic() (basically your computer's uptime in seconds) is guarranteed to not misbehave when your computer's clock is adjusted (such as when transitioning to/from daylight saving time).
>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> a = time.monotonic()
>>> time.sleep(1)
>>> b = time.monotonic()
>>> print(b-a)
1.001658110995777
Why aren't you doing this:
[chr(x) for x in [66,53,0,94]]
It's called a list comprehension. You can find plenty of information on Google, but here's the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.
To dynamically change the color of a text box goto properties, goto font/Color and set the following expression
=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)
Same way for tolerance
=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")
To set the color of a font, you must first initialize the color by doing this:
Color maroon = new Color (128, 0, 0);
Once you've done that, you then put:
Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string
Note: The 1 represents the type of font and this can be used to replace Font.PLAIN and the 25 represents the size of your font.
Try using the QueryDefs. Create the query with parameters. Then use something like this:
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("Your Query Name")
qdf.Parameters("Parameter 1").Value = "Parameter Value"
qdf.Parameters("Parameter 2").Value = "Parameter Value"
qdf.Execute
qdf.Close
Set qdf = Nothing
Set dbs = Nothing
My variation that I find to be more flexible.
str_Key = ""
str_FullKey = ""
str_CharacterPool = "01234ABCDEFfghij~-)"
for int_I in range(64):
str_Key = random.choice(str_CharacterPool)
str_FullKey = str_FullKey + str_Key
This is for them who has two different pem file and for any security purpose want to discard one of the two. Let's say we want to discard 1.pem
My problem was with x64 compilations deployed to a remote testing machine. I found the x64 versions of msvp120d.dll and msvcr120d.dll in
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\redist\Debug_NonRedist\x64\Microsoft.VC120.DebugCRT
Yes, MySQL has a REPLACE() function:
mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
-> 'WwWwWw.mysql.com'
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
Note that it's easier if you make that an alias when using SELECT
SELECT REPLACE(string_column, 'search', 'replace') as url....
group by default order by pk id,so the result
username point avg_time
demo123 100 90 ---> id = 4
demo123456 100 100 ---> id = 7
demo 90 120 ---> id = 1
select id,
NewsHeadline as news_headline,
NewsText as news_text,
state,
CreatedDate as created_on
from News
WHERE CreatedDate>=DATEADD(DAY,-7,GETDATE())
Try this on Ruby. It will return a new date/time the specified number of days in the future
DateTime.now.days_since(10)
You can add multiple base packages (see axtavt's answer), but you can also filter what's scanned inside the base package:
<context:component-scan base-package="x.y.z">
<context:include-filter type="regex" expression="(service|controller)\..*"/>
</context:component-scan>
In windows using "Windows PowerShell" I used the command mentioned below to achieve this
Get-Content .\file.txt | Group-Object | Select Name, Count
Also we can use the where-object Cmdlet to filter the result
Get-Content .\file.txt | Group-Object | Where-Object { $_.Count -gt 1 } | Select Name, Count
Try this simple class for customizing a dialog to your liking:
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
public CustomDialog()
{
components = new ArrayList<>();
setTitle("Custom dialog");
setMessageType(JOptionPane.PLAIN_MESSAGE);
setRootPane(null);
setOptions(new String[] { "OK", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
JLabel label = new JLabel("<html>" + messageText + "</html>");
components.add(label);
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public int show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
return selection;
}
public static String getLineBreak()
{
return "<br>";
}
}
Use JSON to transfer data types (arrays and objects) between client and server.
In PHP:
In JavaScript:
PHP:
echo json_encode($id_numbers);
JavaScript:
id_numbers = JSON.parse(msg);
As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.
id_numbers = new Array();
$.ajax({
url:"Example.php",
type:"POST",
success:function(msg){
id_numbers = msg;
},
dataType:"json"
});
As per answer by @ProVi just change to suit the formatting you require
echo %DATE:~10,4%-%DATE:~7,2%-%DATE:~4,2% %TIME:~0,2%:%TIME:~3,2%:%TIME:~6,2%
will return
yyyy-MM-dd hh:mm:ss
2015-09-15 18:36:11
EDIT As per @Jeb comment, whom is correct the above time format will only work if your DATE /T command returns
ddd dd/mm/yyyy
Thu 17/09/2015
It is easy to edit to suit your locale however, by using the indexing of each character in the string returned by the relevant %DATE% environment variable you can extract the parts of the string you need.
eg. Using %DATE~10,4% would expand the DATE environment variable, and then use only the 4 characters that begin at the 11th (offset 10) character of the expanded result
For example if using US styled dates then the following applies
ddd mm/dd/yyyy
Thu 09/17/2015
echo %DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2% %TIME:~0,2%:%TIME:~3,2%:%TIME:~6,2%
2015-09-17 18:36:11
Add this line top of the header
#pragma warning(disable : 4996)
the reason why it returns < filter object >
is that, filter is class instead of built-in function.
help(filter)
you will get following:
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
Another solution, it covered the problem I had with clicking descendants of the popover:
$(document).mouseup(function (e) {
// The target is not popover or popover descendants
if (!$(".popover").is(e.target) && 0 === $(".popover").has(e.target).length) {
$("[data-toggle=popover]").popover('hide');
}
});
Many things changed since 2009, but I can only find answers saying you need to use NamedParametersJDBCTemplate.
For me it works if I just do a
db.query(sql, new MyRowMapper(), StringUtils.join(listeParamsForInClause, ","));
using SimpleJDBCTemplate or JDBCTemplate
Usage:
//Searches file names (start with "temp" and extension ".txt")
//in the current directory and subdirectories recursively
Path initialPath = Paths.get(".");
PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
stream().forEach(System.out::println);
Source:
public final class PathUtils {
private static final String startsWithRegex = "(?<![_ \\-\\p{L}\\d\\[\\]\\(\\) ])";
private static final String endsWithRegex = "(?=[\\.\\n])";
private static final String containsRegex = "%s(?:[^\\/\\\\]*(?=((?i)%s(?!.))))";
public static List<Path> searchRegularFilesStartsWith(final Path initialPath,
final String fileName, final String fileExt) throws IOException {
return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
}
public static List<Path> searchRegularFilesEndsWith(final Path initialPath,
final String fileName, final String fileExt) throws IOException {
return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
}
public static List<Path> searchRegularFilesAll(final Path initialPath) throws IOException {
return searchRegularFiles(initialPath, "", "");
}
public static List<Path> searchRegularFiles(final Path initialPath,
final String fileName, final String fileExt)
throws IOException {
final String regex = String.format(containsRegex, fileName, fileExt);
final Pattern pattern = Pattern.compile(regex);
try (Stream<Path> walk = Files.walk(initialPath.toRealPath())) {
return walk.filter(path -> Files.isRegularFile(path) &&
pattern.matcher(path.toString()).find())
.collect(Collectors.toList());
}
}
private PathUtils() {
}
}
Try startsWith regex for \txt\temp\tempZERO0.txt:
(?<![_ \-\p{L}\d\[\]\(\) ])temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))
Try endsWith regex for \txt\temp\ZERO0temp.txt:
temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))
Try contains regex for \txt\temp\tempZERO0tempZERO0temp.txt:
temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))
Works fine for me
if (/^win/i.test(process.platform)) {
// TODO: Windows
} else {
// TODO: Linux, Mac or something else
}
The i modifier is used to perform case-insensitive matching.
Your query translates to:
SELECT name FROM users WHERE id IN ('Array');
Or something to that affect.
Try using prepared queries instead, something like:
$numbers = explode(',', $string);
$prepare = array_map(function(){ return '?'; }, $numbers);
$statement = mysqli_prepare($link , "SELECT name FROM users WHERE id IN ('".implode(',', $prepare)."')");
if($statement) {
$ints = array_map(function(){ return 'i'; }, $numbers);
call_user_func_array("mysqli_stmt_bind_param", array_merge(
array($statement, implode('', $ints)), $numbers
));
$results = mysqli_stmt_execute($statement);
// do something with results
// ...
}
I think, from my own experience on problems with more advanced data structures, that the most important thing you can do here, is to get a good knowledge on the general concept of tress as data structures. If you understand the basic mechanism behind the concept it will be quite easy to implement the solution that fits your problem. There are a lot of good sources out there describing the concept. What "saved" me years ago on this particular problem was section 2.3 in "The Art of Computer Programming".
Do display: inline-block
:
#report-upload-form label {
padding-left:26px;
width:125px;
text-transform: uppercase;
display:inline-block
}
The jsonify()
function in flask returns a flask.Response()
object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps()
method will just return an encoded string, which would require manually adding the MIME type header.
See more about the jsonify()
function here for full reference.
Edit:
Also, I've noticed that jsonify()
handles kwargs or dictionaries, while json.dumps()
additionally supports lists and others.
You can't have local functions in C++. However, C++11 has lambdas. Lambdas are basically variables that work like functions.
A lambda has the type std::function
(actually that's not quite true, but in most cases you can suppose it is). To use this type, you need to #include <functional>
. std::function
is a template, taking as template argument the return type and the argument types, with the syntax std::function<ReturnType(ArgumentTypes)>
. For example, std::function<int(std::string, float)>
is a lambda returning an int
and taking two arguments, one std::string
and one float
. The most common one is std::function<void()>
, which returns nothing and takes no arguments.
Once a lambda is declared, it is called just like a normal function, using the syntax lambda(arguments)
.
To define a lambda, use the syntax [captures](arguments){code}
(there are other ways of doing it, but I won't mention them here). arguments
is what arguments the lambda takes, and code
is the code that should be run when the lambda is called. Usually you put [=]
or [&]
as captures. [=]
means that you capture all variables in the scope in which the value is defined by value, which means that they will keep the value that they had when the lambda was declared. [&]
means that you capture all variables in the scope by reference, which means that they will always have their current value, but if they are erased from memory the program will crash. Here are some examples:
#include <functional>
#include <iostream>
int main(){
int x = 1;
std::function<void()> lambda1 = [=](){
std::cout << x << std::endl;
};
std::function<void()> lambda2 = [&](){
std::cout << x << std::endl;
};
x = 2;
lambda1(); //Prints 1 since that was the value of x when it was captured and x was captured by value with [=]
lambda2(); //Prints 2 since that's the current value of x and x was captured by reference with [&]
std::function<void()> lambda3 = [](){}, lambda4 = [](){}; //I prefer to initialize these since calling an uninitialized lambda is undefined behavior.
//[](){} is the empty lambda.
{
int y = 3; //y will be deleted from the memory at the end of this scope
lambda3 = [=](){
std::cout << y << endl;
};
lambda4 = [&](){
std::cout << y << endl;
};
}
lambda3(); //Prints 3, since that's the value y had when it was captured
lambda4(); //Causes the program to crash, since y was captured by reference and y doesn't exist anymore.
//This is a bit like if you had a pointer to y which now points nowhere because y has been deleted from the memory.
//This is why you should be careful when capturing by reference.
return 0;
}
You can also capture specific variables by specifying their names. Just specifying their name will capture them by value, specifying their name with a &
before will capture them by reference. For example, [=, &foo]
will capture all variables by value except foo
which will be captured by reference, and [&, foo]
will capture all variables by reference except foo
which will be captured by value. You can also capture only specific variables, for example [&foo]
will capture foo
by reference and will capture no other variables. You can also capture no variables at all by using []
. If you try to use a variable in a lambda that you didn't capture, it won't compile. Here is an example:
#include <functional>
int main(){
int x = 4, y = 5;
std::function<void(int)> myLambda = [y](int z){
int xSquare = x * x; //Compiler error because x wasn't captured
int ySquare = y * y; //OK because y was captured
int zSquare = z * z; //OK because z is an argument of the lambda
};
return 0;
}
You can't change the value of a variable that was captured by value inside a lambda (variables captured by value have a const
type inside the lambda). To do so, you need to capture the variable by reference. Here is an exampmle:
#include <functional>
int main(){
int x = 3, y = 5;
std::function<void()> myLambda = [x, &y](){
x = 2; //Compiler error because x is captured by value and so it's of type const int inside the lambda
y = 2; //OK because y is captured by reference
};
x = 2; //This is of course OK because we're not inside the lambda
return 0;
}
Also, calling uninitialized lambdas is undefined behavior and will usually cause the program to crash. For example, never do this:
std::function<void()> lambda;
lambda(); //Undefined behavior because lambda is uninitialized
Examples
Here is the code for what you wanted to do in your question using lambdas:
#include <functional> //Don't forget this, otherwise you won't be able to use the std::function type
int main(){
std::function<void()> a = [](){
// code
}
a();
return 0;
}
Here is a more advanced example of a lambda:
#include <functional> //For std::function
#include <iostream> //For std::cout
int main(){
int x = 4;
std::function<float(int)> divideByX = [x](int y){
return (float)y / (float)x; //x is a captured variable, y is an argument
}
std::cout << divideByX(3) << std::endl; //Prints 0.75
return 0;
}
Android ("vanilla" android without custom launchers and touch interfaces) does not allow changing of the application icon, because it is sealed in the .apk
tightly once the program is compiled. There is no way to change it to a 'drawable' programmatically using standard APIs. You may achieve your goal by using a widget instead of an icon. Widgets are customisable. Please read this :http://www.cnet.com/8301-19736_1-10278814-251.html and this http://developer.android.com/guide/topics/appwidgets/index.html.
Also look here: https://github.com/jgilfelt/android-viewbadger. It can help you.
As for badge numbers. As I said before - there is no standard way for doing this. But we all know that Android is an open operating system and we can do everything we want with it, so the only way to add a badge number - is either to use some 3-rd party apps or custom launchers, or front-end touch interfaces: Samsung TouchWiz or Sony Xperia's interface. Other answers use this capabilities and you can search for this on stackoverflow, e.g. here. But I will repeat one more time: there is no standard API for this and I want to say it is a bad practice. App's icon notification badge is an iOS pattern and it should not be used in Android apps anyway. In Andrioid there is a status bar notifications for these purposes:http://developer.android.com/guide/topics/ui/notifiers/notifications.html So, if Facebook or someone other use this - it is not a common pattern or trend we should consider. But if you insist anyway and don't want to use home screen widgets then look here, please:
How does Facebook add badge numbers on app icon in Android?
As you see this is not an actual Facebook app it's TouchWiz. In vanilla android this can be achieved with Nova Launcher http://forums.androidcentral.com/android-applications/199709-how-guide-global-badge-notifications.html So if you will see icon badges somewhere, be sure it is either a 3-rd party launcher or touch interface (frontend wrapper). May be sometime Google will add this capability to the standard Android API.
The most easy way as I saw:
Foreach ($Site in get-website) { Foreach ($Bind in $Site.bindings.collection) {[pscustomobject]@{name=$Site.name;Protocol=$Bind.Protocol;Bindings=$Bind.BindingInformation}}}
According to the docs for func (*Client) Do
:
"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.
When err is nil, resp always contains a non-nil resp.Body."
Then looking at this code:
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
I'm guessing that err
is not nil
. You're accessing the .Close()
method on res.Body
before you check for the err
.
The defer
only defers the function call. The field and method are accessed immediately.
So instead, try checking the error immediately.
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
Your query ($myQuery) is failing and therefore not producing a query resource, but instead producing FALSE.
To reveal what your dynamically generated query looks like and reveal the errors, try this:
$result2 = mysql_query($myQuery) or die($myQuery."<br/><br/>".mysql_error());
The error message will guide you to the solution, which from your comment below is related to using ORDER BY on a field that doesn't exist in the table you're SELECTing from.
Use the Java 8 solution. Note DatatypeConverter can still be used, but it is now within the java.xml.bind
module which will need to be included.
module org.example.foo {
requires java.xml.bind;
}
Java 8 now provides java.util.Base64
for encoding and decoding base64.
Encoding
byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
Decoding
byte[] decoded = Base64.getDecoder().decode("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// => hello world
Since Java 6 the lesser known class javax.xml.bind.DatatypeConverter
can be used. This is part of the JRE, no extra libraries required.
Encoding
byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
Decoding
byte[] decoded = DatatypeConverter.parseBase64Binary("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, "UTF-8"));
// => hello world
One of the best source of information on this topic is Paul Irish's Bulletproof @font-face syntax article.
Read it and you will end with something like:
/* definition */
@font-face {
font-family: EntezareZohoor2;
src: url('fonts/EntezareZohoor2.eot');
src: url('fonts/EntezareZohoor2.eot?') format('?'),
url('fonts/EntezareZohoor2.woff') format('woff'),
url('fonts/EntezareZohoor2.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
/* use */
body {
font-family: EntezareZohoor2, Tahoma, serif;
}
You should set both autoplay and autoplayTimeout properties. I used this code, and it works for me:
$('.owl-carousel').owlCarousel({
autoplay: true,
autoplayTimeout: 5000,
navigation: false,
margin: 10,
responsive: {
0: {
items: 1
},
600: {
items: 2
},
1000: {
items: 2
}
}
})
Watch out for the parentheses. As has been pointed out above, in Python 3, assert
is still a statement, so by analogy with print(..)
, one may extrapolate the same to assert(..)
or raise(..)
but you shouldn't.
This is important because:
assert(2 + 2 == 5, "Houston we've got a problem")
won't work, unlike
assert 2 + 2 == 5, "Houston we've got a problem"
The reason the first one will not work is that bool( (False, "Houston we've got a problem") )
evaluates to True
.
In the statement assert(False)
, these are just redundant parentheses around False
, which evaluate to their contents. But with assert(False,)
the parentheses are now a tuple, and a non-empty tuple evaluates to True
in a boolean context.
You will have to change the value of
post-max-size
upload-max-filesize
both of which you will find in php.ini
Restarting your server will help it start working. On a local test server running XAMIP, i had to stop the Apache server and restart it. It worked fine after that.
They're completely different. Objective C has more in common with Smalltalk than with C++ (well, except for the syntax, really).
Use django.utils.timezone.make_aware function to make your naive datetime objects timezone aware and avoid those warnings.
It converts naive datetime object (without timezone info) to the one that has timezone info (using timezone specified in your django settings if you don't specify it explicitly as a second argument):
import datetime
from django.conf import settings
from django.utils.timezone import make_aware
naive_datetime = datetime.datetime.now()
naive_datetime.tzinfo # None
settings.TIME_ZONE # 'UTC'
aware_datetime = make_aware(naive_datetime)
aware_datetime.tzinfo # <UTC>
As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.
Hibernate itself admits that its connection pooling strategy is minimal
Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html
I personally use C3P0
. however there are other alternatives available including DBCP
.
Check out
Below is a minimal configuration of C3P0 used in my application:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">1800</property> <!-- seconds -->
By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size
Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier.
The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:
Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)
# c3p0.properties
c3p0.testConnectionOnCheckout=true
With this configuration each connection is tested before being used. It however might affect the performance of the site.
You should use the for
command, here is an example:
@echo off
rem Commands go here
exit /b
:output
for /f "tokens=* useback" %%a in (`%~1`) do set "output=%%a"
and you can use call :output "Command goes here"
then the output will be in the %output%
variable.
Note: If you have a command output that is multiline, this tool will set
the output to the last line of your multiline command.
i know this is an old Question , but i faced this problem recently and i looked for it in google , and i came across this documentation here from slf4j website .
as it describes the following :
This error is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. This happens when no appropriate SLF4J binding could be found on the class path.
Placing one (and only one) of slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.
SINCE 1.6.0 As of SLF4J version 1.6, in the absence of a binding, SLF4J will default to a no-operation (NOP) logger implementation.
Hope that will help someone .
You can either use .remove() on option elements:
.remove() : Remove the set of matched elements from the DOM.
$('#models option').remove(); or $('#models').remove('option');
or use .empty() on select:
.empty() : Remove all child nodes of the set of matched elements from the DOM.
$('#models').empty();
however to repopulate deleted options, you need to store the option while deleting.
You can also achieve the same using show/hide:
$("#models option").hide();
and later on to show them:
$("#models option").show();
TLS 1.2
is only supported since OpenSSL 1.0.1
(see the Major version releases section), you have to update your OpenSSL
.
It is not necessary to set the CURLOPT_SSLVERSION
option. The request involves a handshake which will apply the newest TLS
version both server and client support. The server you request is using TLS 1.2
, so your php_curl
will use TLS 1.2
(by default) as well if your OpenSSL
version is (or newer than) 1.0.1
.
case the column isn't string, use astype to convert:
df['col'] = df['col'].astype(str).str[:9]
My solution was to make all the parents 100% and set a specific percentage for each row:
html, body,div[class^="container"] ,.column {
height: 100%;
}
.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}
|
is a metacharacter in regex. You'd need to escape it:
String[] value_split = rat_values.split("\\|");
You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.
CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4
Mind that you need to use the wildcards in PATINDEX on either side.
Note: The results below apply to older versions of iOS, but when testing on iOS 13 the stepping doesn't occur. I don't know for which version of iOS the stepping was removed.
When using CAGradientLayer
, as opposed to CGGradient
, the gradient is not smooth, but has noticeable stepping to it. See :
To get more attractive results it is better to use CGGradient
.
i=348842.
double i2=i/60000;
DecimalFormat dtime = new DecimalFormat("#.##");
i2= Double.valueOf(dtime.format(time));
v.setText(String.valueOf(i2));
Nor Kelsey, nor Brendan solutions does not works for me in Visual Studio 2015 Community.
Here is my brief steps how to create service with installer:
->
New->
ProjectDouble click serviceInstaller1. Visual Studio creates serviceInstaller1_AfterInstall
event. Write code:
private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
using (System.ServiceProcess.ServiceController sc = new
System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
{
sc.Start();
}
}
Build solution. Right click on project and select 'Open Folder in File Explorer'. Go to bin\Debug.
Create install.bat with below script:
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
@echo off
CLS
ECHO.
ECHO =============================
ECHO Running Admin shell
ECHO =============================
:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )
:getPrivileges
if '%1'=='ELEV' (shift & goto gotPrivileges)
ECHO.
ECHO **************************************
ECHO Invoking UAC for Privilege Escalation
ECHO **************************************
setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs"
ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs"
"%temp%\OEgetPrivileges.vbs"
exit /B
:gotPrivileges
::::::::::::::::::::::::::::
:START
::::::::::::::::::::::::::::
setlocal & pushd .
cd /d %~dp0
%windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "WindowsService1.exe"
pause
/i
to /u
)What about Bootstrap Email? This seems to really nice and compatible with bootstrap 4.
You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION
superglobal. Like this:
<?php
session_start();
echo $_SESSION['youritem'];
?>
You forgot the Session HELPER.
Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html
If you already have pods which are recreated, think to delete all deployments first
kubectl delete -n *NAMESPACE deployment *DEPLOYMENT
Just replace the NAMSPACE and the DEPLOYMENT to corresponding ones, you can get all deployments information by the following command
kubectl get deployments --all-namespaces
I found the answer, For those who are looking for the same thing here is how I did it. You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.
HTML CODE
<input type="file" name="imageUpload" id="imageUpload">
PHP CODE
if(isset($_POST['submit'])) {
//Process the image that is uploaded by the user
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable
//storind the data in your database
$query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
mysql_query($query);
require('heading.php');
echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
header( "Refresh:3; url=account.php", true, 303);
}
CODE TO DISPLAY THE IMAGE
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
echo "</tr>\n";
}
Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js
jsfunctions.js
var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}
Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
Invocable invocable = (Invocable) engine;
Object result;
result = invocable.invokeFunction("display", helloWorld);
System.out.println(result);
System.out.println(result.getClass());
} catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
e.printStackTrace();
}
}
}
Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.
One point not pointed out yet, is the speed. I know it's an old answered question, but I think this deserves direct comment/answer:
They would seem to be redundant as the same can be done with derived tables
When I used CTE the very first time I was absolutely stunned by it's speed. It was a case like from a textbook, very suitable for CTE, but in all ocurences I ever used CTE, there was a significant speed gain. My first query was complex with derived tables, taking long minutes to execute. With CTE it took fractions of seconds and left me shocked, that it is even possible.
<a class="navbar-brand" href="#" style="padding:0px;">
<img src="mylogo.png" style="height:100%;">
</a>
For including a text:
<a class="navbar-brand" href="#" style="padding:0px;">
<img src="mylogo.png" style="height:100%;display:inline-block;"><span>text</span>
</a>
just use the full url as href like this:
<a href="https://www.example.com/" target="_blank">page link</a>
borrowed this shamely from here
Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
More information here
The &
means that the function accepts the address (or reference) to a variable, instead of the value of the variable.
For example, note the difference between this:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
Very late to the game, but this is a version of Chris Pratt's answer that protects against race conditions while sacrificing performance, by using a transaction
block and select_for_update()
@receiver(pre_save, sender=MyModel)
@transaction.atomic
def do_something_if_changed(sender, instance, **kwargs):
try:
obj = sender.objects.select_for_update().get(pk=instance.pk)
except sender.DoesNotExist:
pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
else:
if not obj.some_field == instance.some_field: # Field has changed
# do something
Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml
contains the necessary slf4j dependencies, e.g.:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
It is super easy by changing the heap size as it was mentioned. Just easily by going to Pycharm HELP -> Edit custom VM option ... and change it to:
-Xms2048m
-Xmx2048m
Here, a more functional way: (if you use shift i to encode, then use -i to decode)
def ceasar(story, shift):
return ''.join([ # concentrate list to string
(lambda c, is_upper: c.upper() if is_upper else c) # if original char is upper case than convert result to upper case too
(
("abcdefghijklmnopqrstuvwxyz"*2)[ord(char.lower()) - ord('a') + shift % 26], # rotate char, this is extra easy since Python accepts list indexs below 0
char.isupper()
)
if char.isalpha() else char # if not in alphabet then don't change it
for char in story
])
I had the same problem with the BOM appearing in some of my PHP files ().
If you use PhpStorm you can set at hotkey to remove it in Settings -> IDE Settings -> Keymap -> Main Menu - > File -> Remove BOM.
git symbolic-ref -q --short HEAD
I use this in scripts that need the current branch name. It will show you the current short symbolic reference to HEAD, which will be your current branch name.
I have always used OLEDB
for this, something like...
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
The ACE.OLEDB
provider will read both .xls
and .xlsx
files and I have always found the speed quite good.
npm login
is required before publish
/**
* Converts a local Unix timestamp to GMT
*
* @param int Unix timestamp
* @return int
*/
function local_to_gmt($time = '')
{
if ($time === '')
{
$time = time();
}
return mktime(
gmdate('G', $time),
gmdate('i', $time),
gmdate('s', $time),
gmdate('n', $time),
gmdate('j', $time),
gmdate('Y', $time)
);
}
not that hard,
if you take a look at the page source, you'll see that it uses to stream the audio via shoutcast.
this is the stream url
which returns a JSON like that:
{
"Streams": [
{
"StreamId": 3244651,
"Reliability": 92,
"Bandwidth": 64,
"HasPlaylist": false,
"MediaType": "MP3",
"Url": "http://mp3hdfm32.hala.jo:8132",
"Type": "Live"
}
]
}
i believe that's the url you need: http://mp3hdfm32.hala.jo:8132
SELECT DATEDIFF(yyyy, '2011/08/25', '2017/08/25') AS DateDiff
It's gives you difference between two dates in Year
Here (2017-2011)=6 as a result
Syntax:
DATEDIFF(interval, date1, date2)
$(document).ready(function(){
$("div.width").append($("div.width").width()+" px");
$("div.innerWidth").append($("div.innerWidth").innerWidth()+" px");
$("div.outerWidth").append($("div.outerWidth").outerWidth()+" px");
});
<div class="width">Width of this div container without including padding is: </div>
<div class="innerWidth">width of this div container including padding is: </div>
<div class="outerWidth">width of this div container including padding and margin is: </div>
This is what helped me:
sudo apachectl stop
This command killed Apache server that was pre-installed on MAC OS X.
If you use the html approach:
don't add blank lines
Like this:
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
the markup will break.
Remove blank lines:
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
I faced the same issue and used the following steps to solve it
1) go Right side in solution explorer
2) Click on your Project Name
3) click on Reference
4) you can see yellow symbol on some DLL
5) Right click on that DLL and go to Property
6) Find Specific Version = True
replace it with Specific Version = False
and also change Copy Local = False
to Copy Local = True
you can git fetch nameofremoterepo
, then git log
and personally, I alias gitlog
to git log --graph --oneline --pretty --decorate --all
. try out and see if it fits you
$("body,html,document").scrollTop($("#map_canvas").position().top);
This works for Chrome 7, IE6, IE7, IE8, IE9, FF 3.6 and Safari 5.
2012 UPDATE
This is still good but I had to use it again. Sometimes position
doesn't work so this is an alternative:
$("body,html,document").scrollTop($("#map_canvas").offset().top);
Even though @Rick has the accepted answer for this question, there's actually a shorter way to do this, using the poorly named Uri.GetLeftPart()
method.
Uri url = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string output = url.GetLeftPart(UriPartial.Authority);
There is one catch to GetLeftPart()
, however. If the port is the default port for the scheme, it will strip it out. Since port 80 is the default port for http, the output of GetLeftPart()
in my example above will be http://www.mywebsite.com
.
If the port number had been something other than 80, it would be included in the result.
Try to apply the above suggested solution on pretty big document, replacing pretty short strings which might be present in innerHTML or even innerText, and your html design becomes broken at best
Therefore I firstly pickup only text node elements via HTML DOM nodes, like this
function textNodesUnder(node){
var all = [];
for (node=node.firstChild;node;node=node.nextSibling){
if (node.nodeType==3) all.push(node);
else all = all.concat(textNodesUnder(node));
}
return all;
}
textNodes=textNodesUnder(document.body)
for (i in textNodes) { textNodes[i].nodeValue = textNodes[i].nodeValue.replace(/hello/g, 'hi');
`and followingly I applied the replacement on all of them in cycle
MySQL doesn't allow selecting from a table and update in the same table at the same time. But there is always a workaround :)
This doesn't work >>>>
UPDATE table1 SET col1 = (SELECT MAX(col1) from table1) WHERE col1 IS NULL;
But this works >>>>
UPDATE table1 SET col1 = (SELECT MAX(col1) FROM (SELECT * FROM table1) AS table1_new) WHERE col1 IS NULL;
For project that does not use maven : This worked for me https://ihategeek.wordpress.com/2012/04/18/eclipse-junit-test-class-not-found/
Adding the jre and project src at the bottom in Order and exports in build path
what might get you where you want in plain SQL92:
select * from tbl where lower(answer) = upper(answer)
or, if you also want to be robust for leading/trailing spaces:
select * from tbl where lower(answer) = trim(upper(answer))
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host
and hostname
.
The following code does this:
var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;
if (isSubdomain) {
domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
domain = window.location.hostname;
}
#include <stdbool.h>
For someone like me here to copy and paste.
net use f: \\\VFServer"\HQ Publications" /persistent:yes
Note that the first quotation mark
goes before the leading \
and the second goes after the end of the folder name.
I had the same problem on XAMPP for Windows10 when I try to install composer.
Unable to load dynamic library '/xampp/php/ext/php_bz2.dll'
Then follow this steps
extension_dir="F:\xampp731\php\ext" (here finded_drive_name_from_the_file is F)
There's no built-in command for it, so I usually just do something like this:
#!/bin/bash
# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs. The first revision of the file is emitted as
# full text since there's not previous version to compare it to.
function history_of_file() {
url=$1 # current url of file
svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {
# first revision as full text
echo
read r
svn log -r$r $url@HEAD
svn cat -r$r $url@HEAD
echo
# remaining revisions as differences to previous revision
while read r
do
echo
svn log -r$r $url@HEAD
svn diff -c$r $url@HEAD
echo
done
}
}
Then, you can call it with:
history_of_file $1
find returns an integer representing the index of where the search item was found. If it isn't found, it returns -1.
haystack = 'asdf'
haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1
if haystack.find(needle) >= 0:
print 'Needle found.'
else:
print 'Needle not found.'
That is a constraint on the generic parameter T
. It must be a class
(reference type) and must have a public parameter-less default constructor.
That means T
can't be an int
, float
, double
, DateTime
or any other struct
(value type).
It could be a string
, or any other custom reference type, as long as it has a default or parameter-less constructor.
The error means, that Angular doesn't know what to do when you put a formControl
on a div
.
To fix this, you have two options.
formControlName
on an element, that is supported by Angular out of the box. Those are: input
, textarea
and select
.ControlValueAccessor
interface. By doing so, you're telling Angular "how to access the value of your control" (hence the name). Or in simple terms: What to do, when you put a formControlName
on an element, that doesn't naturally have a value associated with it.Now, implementing the ControlValueAccessor
interface can be a bit daunting at first. Especially because there isn't much good documentation of this out there and you need to add a lot of boilerplate to your code. So let me try to break this down in some simple-to-follow steps.
In order to implement the ControlValueAccessor
, you need to create a new component (or directive). Move the code related to your form control there. Like this it will also be easily reusable. Having a control already inside a component might be the reason in the first place, why you need to implement the ControlValueAccessor
interface, because otherwise you will not be able to use your custom component together with Angular forms.
Implementing the ControlValueAccessor
interface is quite verbose, here's the boilerplate that comes with it:
import {Component, OnInit, forwardRef} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';
@Component({
selector: 'app-custom-input',
templateUrl: './custom-input.component.html',
styleUrls: ['./custom-input.component.scss'],
// a) copy paste this providers property (adjust the component name in the forward ref)
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomInputComponent),
multi: true
}
]
})
// b) Add "implements ControlValueAccessor"
export class CustomInputComponent implements ControlValueAccessor {
// c) copy paste this code
onChange: any = () => {}
onTouch: any = () => {}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
// d) copy paste this code
writeValue(input: string) {
// TODO
}
So what are the individual parts doing?
ControlValueAccessor
interfaceControlValueAccessor
interfaceonChange
and onTouch
with it's own implementation during runtime, such that you can then call those functions. So this point is important to understand: You don't need to implement onChange and onTouch yourself (other than the initial empty implementation). The only thing your doing with (c) is to let Angular attach it's own functions to your class. Why? So you can then call the onChange
and onTouch
methods provided by Angular at the appropriate time. We'll see how this works down below.writeValue
method works in the next section, when we implement it. I've put it here, so all required properties on ControlValueAccessor
are implemented and your code still compiles.What writeValue
does, is to do something inside your custom component, when the form control is changed on the outside. So for example, if you have named your custom form control component app-custom-input
and you'd be using it in the parent component like this:
<form [formGroup]="form">
<app-custom-input formControlName="myFormControl"></app-custom-input>
</form>
then writeValue
gets triggered whenever the parent component somehow changes the value of myFormControl
. This could be for example during the initialization of the form (this.form = this.formBuilder.group({myFormControl: ""});
) or on a form reset this.form.reset();
.
What you'll typically want to do if the value of the form control changes on the outside, is to write it to a local variable which represents the form control value. For example, if your CustomInputComponent
revolves around a text based form control, it could look like this:
writeValue(input: string) {
this.input = input;
}
and in the html of CustomInputComponent
:
<input type="text"
[ngModel]="input">
You could also write it directly to the input element as described in the Angular docs.
Now you have handled what happens inside of your component when something changes outside. Now let's look at the other direction. How do you inform the outside world when something changes inside of your component?
The next step is to inform the parent component about changes inside of your CustomInputComponent
. This is where the onChange
and onTouch
functions from (c) from above come into play. By calling those functions you can inform the outside about changes inside your component. In order to propagate changes of the value to the outside, you need to call onChange with the new value as the argument. For example, if the user types something in the input
field in your custom component, you call onChange
with the updated value:
<input type="text"
[ngModel]="input"
(ngModelChange)="onChange($event)">
If you check the implementation (c) from above again, you'll see what's happening: Angular bound it's own implementation to the onChange
class property. That implementation expects one argument, which is the updated control value. What you're doing now is you're calling that method and thus letting Angular know about the change. Angular will now go ahead and change the form value on the outside. This is the key part in all this. You told Angular when it should update the form control and with what value by calling onChange
. You've given it the means to "access the control value".
By the way: The name onChange
is chosen by me. You could choose anything here, for example propagateChange
or similar. However you name it though, it will be the same function that takes one argument, that is provided by Angular and that is bound to your class by the registerOnChange
method during runtime.
Since form controls can be "touched", you should also give Angular the means to understand when your custom form control is touched. You can do it, you guessed it, by calling the onTouch
function. So for our example here, if you want to stay compliant with how Angular is doing it for the out-of-the-box form controls, you should call onTouch
when the input field is blurred:
<input type="text"
[(ngModel)]="input"
(ngModelChange)="onChange($event)"
(blur)="onTouch()">
Again, onTouch
is a name chosen by me, but what it's actual function is provided by Angular and it takes zero arguments. Which makes sense, since you're just letting Angular know, that the form control has been touched.
So how does that look when it comes all together? It should look like this:
// custom-input.component.ts
import {Component, OnInit, forwardRef} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';
@Component({
selector: 'app-custom-input',
templateUrl: './custom-input.component.html',
styleUrls: ['./custom-input.component.scss'],
// Step 1: copy paste this providers property
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomInputComponent),
multi: true
}
]
})
// Step 2: Add "implements ControlValueAccessor"
export class CustomInputComponent implements ControlValueAccessor {
// Step 3: Copy paste this stuff here
onChange: any = () => {}
onTouch: any = () => {}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
// Step 4: Define what should happen in this component, if something changes outside
input: string;
writeValue(input: string) {
this.input = input;
}
// Step 5: Handle what should happen on the outside, if something changes on the inside
// in this simple case, we've handled all of that in the .html
// a) we've bound to the local variable with ngModel
// b) we emit to the ouside by calling onChange on ngModelChange
}
// custom-input.component.html
<input type="text"
[(ngModel)]="input"
(ngModelChange)="onChange($event)"
(blur)="onTouch()">
// parent.component.html
<app-custom-input [formControl]="inputTwo"></app-custom-input>
// OR
<form [formGroup]="form" >
<app-custom-input formControlName="myFormControl"></app-custom-input>
</form>
Note that Control Value Accessors are NOT the right tool for nested form groups. For nested form groups you can simply use an @Input() subform
instead. Control Value Accessors are meant to wrap controls
, not groups
! See this example how to use an input for a nested form: https://stackblitz.com/edit/angular-nested-forms-input-2
Try out this package to tail all the queries (without oplog operations): https://www.npmjs.com/package/mongo-tail-queries
(Disclaimer: I wrote this package exactly for this need)
For Python 3, this is a much safer and Pythonic approach to convert from byte
to string
:
def byte_to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes): # Check if it's in bytes
print(bytes_or_str.decode('utf-8'))
else:
print("Object not of byte type")
byte_to_str(b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n')
Output:
total 0
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
Here is the process that I ended up using. The main tool I used was Inkscape which was able to convert text alright.
Using Adobe Acrobat Pro Actions (formerly Batch Processing) create a custom action to separate PDF pages into separate files. Alternatively you may be able to split up PDFs with GhostScript
/* Extract Pages to Folder */
var re = /.*\/|\.pdf$/ig;
var filename = this.path.replace(re,"");
{
for ( var i = 0; i < this.numPages; i++ )
this.extractPages
({
nStart: i,
nEnd: i,
cPath : filename + "_s" + ("000000" + (i+1)).slice (-3) + ".pdf"
});
};
Using Windows Cmd created batch file to loop through all PDF files in a folder and convert them to SVG
:: ===== SETUP =====
@echo off
CLS
echo Starting SVG conversion...
echo.
:: setup working directory (if different)
REM set "_work_dir=%~dp0"
set "_work_dir=%CD%"
:: setup counter
set "count=1"
:: setup file search and save string
set "_work_x1=pdf"
set "_work_x2=svg"
set "_work_file_str=*.%_work_x1%"
:: setup inkscape commands
set "_inkscape_path=D:\InkscapePortable\App\Inkscape\"
set "_inkscape_cmd=%_inkscape_path%inkscape.exe"
:: ===== FIND FILES IN WORKING DIRECTORY =====
:: Output from DIR last element is single carriage return character.
:: Carriage return characters are directly removed after percent expansion,
:: but not with delayed expansion.
pushd "%_work_dir%"
FOR /f "tokens=*" %%A IN ('DIR /A:-D /O:N /B %_work_file_str%') DO (
CALL :subroutine "%%A"
)
popd
:: ===== CONVERT PDF TO SVG WITH INKSCAPE =====
:subroutine
echo.
IF NOT [%1]==[] (
echo %count%:%1
set /A count+=1
start "" /D "%_work_dir%" /W "%_inkscape_cmd%" --without-gui --file="%~n1.%_work_x1%" --export-dpi=300 --export-plain-svg="%~n1.%_work_x2%"
) ELSE (
echo End of output
)
echo.
GOTO :eof
:: ===== INKSCAPE REFERENCE =====
:: print inkscape help
REM "%_inkscape_cmd%" --help > "%~dp0\inkscape_help.txt"
REM "%_inkscape_cmd%" --verb-list > "%~dp0\inkscape_verb_list.txt"
I realize it is not best practice to manually brute force edit SVG or XML tags or attributes due to potential variations and should use an XML parser instead. However I had a simple issue where the stroke width on one drawing was very small, and on another the font family was being incorrectly identified, so I basically modified the previous Windows Cmd batch script to do a simple find and replace. The only changes were to the search string definitions and changing to call a PowerShell command. The PowerShell command will perform a find and replace and save the modified file with an added suffix. I did find some other references that could be better used to parse or modify the resultant SVG files if some other minor cleanup is needed to be performed.
:: setup file search and save string
set "_work_x1=svg"
set "_work_x2=svg"
set "_work_s2=_mod"
set "_work_file_str=*.%_work_x1%"
powershell -Command "(Get-Content '%~n1.%_work_x1%') | ForEach-Object {$_ -replace 'stroke-width:0.06', 'stroke-width:1'} | ForEach-Object {$_ -replace 'font-family:Times Roman','font-family:Times New Roman'} | Set-Content '%~n1%_work_s2%.%_work_x2%'"
Hope this might help someone
Running the command prompt or Powershell ISE as an administrator fixed this for me.
Use the ToDictionary
method directly.
var result =
// as Jon Skeet pointed out, OrderBy is useless here, I just leave it
// show how to use OrderBy in a LINQ query
myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
.ToDictionary(mc => mc.KeyProp.ToString(),
mc => mc.ValueProp.ToString(),
StringComparer.OrdinalIgnoreCase);
You want to use the array_key_exists function.
You could use a Comparator with Java's built-in methods for sorting and binary search. Suppose you have a class like this, where a and b are the fields you want to use for sorting:
class Thing { String a, b, c, d; }
You would define your Comparator:
Comparator<Thing> comparator = new Comparator<Thing>() {
public int compare(Thing o1, Thing o2) {
if (o1.a.equals(o2.a)) {
return o1.b.compareTo(o2.b);
}
return o1.a.compareTo(o2.a);
}
};
Then sort your list:
Collections.sort(list, comparator);
And finally do the binary search:
int i = Collections.binarySearch(list, thingToFind, comparator);
Specify the ax
argument to matplotlib.pyplot.colorbar()
, e.g.
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
for i in range(2):
for j in range(2):
data = np.array([[i, j], [i+0.5, j+0.5]])
im = ax[i, j].imshow(data)
plt.colorbar(im, ax=ax[i, j])
plt.show()
I pipe the output from the accepted answer into dialog
, to give me an interactive list:
#!/bin/bash
TMP_FILE=/tmp/selected-git-branch
eval `resize`
dialog --title "Recent Git Branches" --menu "Choose a branch" $LINES $COLUMNS $(( $LINES - 8 )) $(git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short) %(committerdate:short)') 2> $TMP_FILE
if [ $? -eq 0 ]
then
git checkout $(< $TMP_FILE)
fi
rm -f $TMP_FILE
clear
Save as (e.g.) ~/bin/git_recent_branches.sh
and chmod +x
it. Then git config --global alias.rb '!git_recent_branches.sh'
to give me a new git rb
command.
EDIT:
The info below is only applicable to VS2008 and the 3.5 framework. VS2010 has a new registry location. Further details can be found on MSDN: How to Add or Remove References in Visual Studio.
ORIGINAL
It should be listed in the .NET tab of the Add Reference dialog. Assemblies that appear there have paths in registry keys under:
HKLM\Software\Microsoft\.NETFramework\AssemblyFolders\
I have a key there named Microsoft .NET Framework 3.5 Reference Assemblies with a string value of:
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\
Navigating there I can see the actual System.Web.Extensions dll.
EDIT:
I found my .NET 4.0 version in:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.Extensions.dll
I'm running Win 7 64 bit, so if you're on a 32 bit OS drop the (x86).
for loop:
1) need to specify the loop bounds( minimum or maximum).
2) executes a statement or a block of statements repeatedly
until a specified expression evaluates to false.
int K = 0;
for (int x = 1; x <= 9; x++){
k = k + x ;
}
foreach statement:
1)do not need to specify the loop bounds minimum or maximum.
2)repeats a group of embedded statements for
a)each element in an array
or b) an object collection.
int k = 0;
int[] tempArr = new int[] { 0, 2, 3, 8, 17 };
foreach (int i in tempArr){
k = k + i ;
}
You're calling both wait
and notifyAll
without using a synchronized
block. In both cases the calling thread must own the lock on the monitor you call the method on.
From the docs for notify
(wait
and notifyAll
have similar documentation but refer to notify
for the fullest description):
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.
Only one thread will be able to actually exit wait
at a time after notifyAll
as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.
In my opinion the other proposed solution is.
This approach will prevent the users to download the file.
so do the following edit my.cnf:
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = xxx.xxx.xxx.xxx
# skip-networking
after edit hit service mysqld restart
login into mysql and hit this query:
GRANT ALL ON foo.* TO bar@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';
thats it make sure your iptables allow connection from 3306 if not put the following:
iptables -A INPUT -i lo -p tcp --dport 3306 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 3306 -j ACCEPT
short answer you have to mix between them , use json for data that you are not going to make relations with them like contact data , address , products variabls
pgAdmin 4 is a powerful and popular web-based database management tool for PostgreSQL - http://www.pgadmin.org/
$i = 0;
foreach ($arr as $key => $val) {
if ($i === 0) {
// first index
}
// current index is $i
$i++;
}
Each object's lock is little different from Mutex/Semaphore design. For example there is no way to correctly implement traversing linked nodes with releasing previous node's lock and capturing next one. But with mutex it is easy to implement:
Node p = getHead();
if (p == null || x == null) return false;
p.lock.acquire(); // Prime loop by acquiring first lock.
// If above acquire fails due to interrupt, the method will
// throw InterruptedException now, so there is no need for
// further cleanup.
for (;;) {
Node nextp = null;
boolean found;
try {
found = x.equals(p.item);
if (!found) {
nextp = p.next;
if (nextp != null) {
try { // Acquire next lock
// while still holding current
nextp.lock.acquire();
}
catch (InterruptedException ie) {
throw ie; // Note that finally clause will
// execute before the throw
}
}
}
}finally { // release old lock regardless of outcome
p.lock.release();
}
Currently, there is no such class in java.util.concurrent
, but you can find Mutext implementation here Mutex.java. As for standard libraries, Semaphore provides all this functionality and much more.
Similar Question Here
Finalizers in Java are bad. They add a lot of overhead to garbage collection. Avoid them whenever possible.
The shutdownHook will only get called when the VM is shutting down. I think it very well may do what you want.
OK, first of all I'm not sure how it works when you create a div using (document.createElement('div'))
, so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?
If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?
Here's the code for my example:
HTML
<a href="#new">Click</a>
<div id="new">
Fade in ...
</div>
CSS
#new {
width: 100px;
height: 100px;
border: 1px solid #000000;
opacity: 0;
}
#new:target {
-webkit-transition: opacity 2.0s ease-in;
-moz-transition: opacity 2.0s ease-in;
-o-transition: opacity 2.0s ease-in;
opacity: 1;
}
... and here's a jsFiddle
you need to add 3 dependency ( API+ API implementation + log4j dependency)
Add also this
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.5</version>
</dependency>
# And to see log in command line , set log4j.properties
# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
#And to see log in file , set log4j.properties
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
There are couple of little visual studio extensions for this purpose:
In case of TFS 2012, looks like there is no need for 'Go offline' extensions. I read something about a new feature called local workspace for the similar purpose.
Alternatively I had good success with Git-TF. All the goodness of git and when you are ready, you can push it to TFS.
You can find the solution here!
Install the service named 'Tomcat7'
C:\>Tomcat\bin\service.bat install
There is a 2nd optional parameter that lets you specify the name of the service, as displayed in Windows services.
Install the service named 'MyTomcatService'
C:\>Tomcat\bin\service.bat install MyTomcatService
From the NumPy mailing list, here's another solution:
>>> a
array([[1, 2],
[0, 0],
[1, 0],
[0, 2],
[2, 1],
[1, 0],
[1, 0],
[0, 0],
[1, 0],
[2, 2]])
>>> a[np.lexsort(np.fliplr(a).T)]
array([[0, 0],
[0, 0],
[0, 2],
[1, 0],
[1, 0],
[1, 0],
[1, 0],
[1, 2],
[2, 1],
[2, 2]])
Xcode project -> goto info.plist and Click + Button then Add (App Transport Security Settings)Expand, Allow Arbitrary Loads Set YES. Thanks
I had the same problem.
I use project level connection managers and my packages run correctly in SSDT but when I deployed them and execute them through a job with sql server agent, I get "Connection not found" errors.
So I deploy the project and then the problem was solved, when you use project level connection managers but just deploy a single package from that project, and you call package through sql server agent, it could not recognize your connection managers so you should determine package level connection managers or you should first deploy your project.
I suggest using Object.prototype.constructor.name
:
Object.defineProperty(Object.prototype, "getClass", {
value: function() {
return this.constructor.name;
}
});
var x = new DOMParser();
console.log(x.getClass()); // `DOMParser'
var y = new Error("");
console.log(y.getClass()); // `Error'
After trying all solutions it worked only for me after specifying the host
mysql -u root -p -h127.0.0.1
when asking for password
Enter password:
press enter
and it will work , if everything is ok as above .
better to use touchstart
event with .on()
jQuery method:
$(window).load(function() { // better to use $(document).ready(function(){
$('.List li').on('click touchstart', function() {
$('.Div').slideDown('500');
});
});
And i don't understand why you are using $(window).load()
method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready()
method which does not wait for each element on the page to be loaded first.
Well, firstly it should be pointed out that:
public void blah() {
synchronized (this) {
// do stuff
}
}
is semantically equivalent to:
public synchronized void blah() {
// do stuff
}
which is one reason not to use synchronized(this)
. You might argue that you can do stuff around the synchronized(this)
block. The usual reason is to try and avoid having to do the synchronized check at all, which leads to all sorts of concurrency problems, specifically the double checked-locking problem, which just goes to show how difficult it can be to make a relatively simple check threadsafe.
A private lock is a defensive mechanism, which is never a bad idea.
Also, as you alluded to, private locks can control granularity. One set of operations on an object might be totally unrelated to another but synchronized(this)
will mutually exclude access to all of them.
synchronized(this)
just really doesn't give you anything.
private boolean isSameDay(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
return (sameDay && sameMonth && sameYear);
}
Late to the game maybe but I stumbled upon this semantics issue while trying to make a REST API.
To expand a little on Wrikken's answer, I think you could use either 409 Conflict
or 403 Forbidden
depending on the situation - in short, use a 403 error when the user can do absolutely nothing to resolve the conflict and complete the request (e.g. they can't send a DELETE
request to explicitly remove the resource), or use 409 if something could possibly be done.
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
Nowadays, someone says "403" and a permissions or authentication issue comes to mind, but the spec says that it's basically the server telling the client that it's not going to do it, don't ask it again, and here's why the client shouldn't.
As for PUT
vs. POST
... POST
should be used to create a new instance of a resource when the user has no means to or shouldn't create an identifier for the resource. PUT
is used when the resource's identity is known.
9.6 PUT
...
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,
it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
I haven’t actually done anything with font-face
, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.
The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.
Does Firefox download the font when you actually use it in a font
declaration? (e.g. h1 { font: 'DejaVu Serif';
)?
Alternatively, can use for particular table
<table style="width:1000px; height:100px;">
<tr>
<td align="center" valign="top">Text</td> //Remove it
<td class="tableFormatter">Text></td>
</tr>
</table>
Add this css in external file
.tableFormatter
{
width:100%;
vertical-align:top;
text-align:center;
}
For me the problem was caused by a gradle.properties file in the list of Gradle scripts. It showed as gradle.properties (global) and refered to a file in C:\users\.gradle\gradle.properties. I right-clicked on it and selected delete from the menu to delete it. It deleted the file from the hard disk and my project now builds and runs. I guess that the global file was overwriting something that was used to locate the package android.support
Never, never, never say
if something == True:
Never. It's crazy, since you're redundantly repeating what is redundantly specified as the redundant condition rule for an if-statement.
Worse, still, never, never, never say
if something == False:
You have not
. Feel free to use it.
Finally, doing a == None
is inefficient. Do a is None
. None
is a special singleton object, there can only be one. Just check to see if you have that object.
Let's say your primary key is an Integer and the object you save is "ticket", then you can get it like this. When you save the object, a Serializable id is always returned
Integer id = (Integer)session.save(ticket);
Apache PDFBox http://pdfbox.apache.org/
PDFMerger This application will take a list of pdf documents and merge them, saving the result in a new document.
usage: java -jar pdfbox-app-x.y.z.jar PDFMerger "Source PDF files (2 ..n)" "Target PDF file"
You error clearly says, you are trying to use locale something was not there.
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/locale.py", line 581, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
locale.Error: unsupported locale setting
To check available setting, use locale -a
deb@deb-Latitude-E7470:/ambot$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
POSIX
so you can use one among,
>>> locale.setlocale(locale.LC_ALL, 'en_AG.utf8')
'en_AG.utf8'
>>>
for de_DE
This file can either be adjusted manually or updated using the tool, update-locale.
update-locale LANG=de_DE.UTF-8
I answered my problem with a default width for all columns and cells, like below:
int width = 15; // Where width is number of caracters
sheet.setDefaultColumnWidth(width);
Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:
function map_init() {
var lt=48.451778;
var lg=31.646305;
var myLatlng = new google.maps.LatLng(lt,lg);
var mapOptions = {
center: new google.maps.LatLng(lt,lg),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var marker = new google.maps.Marker({
position:myLatlng,
map:map,
draggable:true
});
google.maps.event.addListener(
marker,
'drag',
function() {
document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
document.getElementById('zoom').innerHTML = mapObject.getZoom();
// Dynamically show it somewhere if needed
$(".x").text(marker.position.lat().toFixed(6));
$(".y").text(marker.position.lng().toFixed(6));
$(".z").text(map.getZoom());
}
);
}
An abstract class can not be directly instantiated, but must be derived from to be usable. A class MUST be abstract if it contains abstract methods: either directly
abstract class Foo {
abstract void someMethod();
}
or indirectly
interface IFoo {
void someMethod();
}
abstract class Foo2 implements IFoo {
}
However, a class can be abstract without containing abstract methods. Its a way to prevent direct instantation, e.g.
abstract class Foo3 {
}
class Bar extends Foo3 {
}
Foo3 myVar = new Foo3(); // illegal! class is abstract
Foo3 myVar = new Bar(); // allowed!
The latter style of abstract classes may be used to create "interface-like" classes. Unlike interfaces an abstract class is allowed to contain non-abstract methods and instance variables. You can use this to provide some base functionality to extending classes.
Another frequent pattern is to implement the main functionality in the abstract class and define part of the algorithm in an abstract method to be implemented by an extending class. Stupid example:
abstract class Processor {
protected abstract int[] filterInput(int[] unfiltered);
public int process(int[] values) {
int[] filtered = filterInput(values);
// do something with filtered input
}
}
class EvenValues extends Processor {
protected int[] filterInput(int[] unfiltered) {
// remove odd numbers
}
}
class OddValues extends Processor {
protected int[] filterInput(int[] unfiltered) {
// remove even numbers
}
}