Removing rounded corners from a <select> element in Chrome/Webkit
I used jordan314's solution, but then I added "border-light" class to select. If you have default border-light class defined in css, you can directly use it. It just defines the border as white). I changed the border to square/remove the radius, and maintained the arrow.
Here is what I did:
<select class="form-control border border-light" id="type">
<option>Select</option>
<option value="mobile">Apple</option>
</select>
if you don't have the predefined border-light, just add in your css:
<style>
.border-light{
border-color:#f8f9fa!important
}
#type {
border:0;
outline:1px solid #ddd;
background-color:white;
}
</style>
Unsafe JavaScript attempt to access frame with URL
I found that using the XFBML version of the Facebook like button instead of the HTML5 version fixed this problem. Add the below code where you want the button to appear:
<div id="fb-root"></div>
<script>(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<fb:like send="true" layout="button_count" width="50" show_faces="false" font="arial"></fb:like>
Then add this to your HTML tag:
xmlns:fb="http://ogp.me/ns/fb#"
Twitter Bootstrap modal on mobile devices
My solution...
Ver en jsfiddle
//Fix modal mobile Boostrap 3
function Show(id){
//Fix CSS
$(".modal-footer").css({"padding":"19px 20px 20px","margin-top":"15px","text-align":"right","border-top":"1px solid #e5e5e5"});
$(".modal-body").css("overflow-y","auto");
//Fix .modal-body height
$('#'+id).on('shown.bs.modal',function(){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").css("height","auto");
h1=$("#"+id+">.modal-dialog").height();
h2=$(window).height();
h3=$("#"+id+">.modal-dialog>.modal-content>.modal-body").height();
h4=h2-(h1-h3);
if($(window).width()>=768){
if(h1>h2){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
}
$("#"+id+">.modal-dialog").css("margin","30px auto");
$("#"+id+">.modal-dialog>.modal-content").css("border","1px solid rgba(0,0,0,0.2)");
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",6);
if($("#"+id+">.modal-dialog").height()+30>h2){
$("#"+id+">.modal-dialog").css("margin-top","0px");
$("#"+id+">.modal-dialog").css("margin-bottom","0px");
}
}
else{
//Fix full-screen in mobiles
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
$("#"+id+">.modal-dialog").css("margin",0);
$("#"+id+">.modal-dialog>.modal-content").css("border",0);
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",0);
}
//Aply changes on screen resize (example: mobile orientation)
window.onresize=function(){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").css("height","auto");
h1=$("#"+id+">.modal-dialog").height();
h2=$(window).height();
h3=$("#"+id+">.modal-dialog>.modal-content>.modal-body").height();
h4=h2-(h1-h3);
if($(window).width()>=768){
if(h1>h2){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
}
$("#"+id+">.modal-dialog").css("margin","30px auto");
$("#"+id+">.modal-dialog>.modal-content").css("border","1px solid rgba(0,0,0,0.2)");
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",6);
if($("#"+id+">.modal-dialog").height()+30>h2){
$("#"+id+">.modal-dialog").css("margin-top","0px");
$("#"+id+">.modal-dialog").css("margin-bottom","0px");
}
}
else{
//Fix full-screen in mobiles
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
$("#"+id+">.modal-dialog").css("margin",0);
$("#"+id+">.modal-dialog>.modal-content").css("border",0);
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",0);
}
};
});
//Free event listener
$('#'+id).on('hide.bs.modal',function(){
window.onresize=function(){};
});
//Mobile haven't scrollbar, so this is touch event scrollbar implementation
var y1=0;
var y2=0;
var div=$("#"+id+">.modal-dialog>.modal-content>.modal-body")[0];
div.addEventListener("touchstart",function(event){
y1=event.touches[0].clientY;
});
div.addEventListener("touchmove",function(event){
event.preventDefault();
y2=event.touches[0].clientY;
var limite=div.scrollHeight-div.clientHeight;
var diff=div.scrollTop+y1-y2;
if(diff<0)diff=0;
if(diff>limite)diff=limite;
div.scrollTop=diff;
y1=y2;
});
//Fix position modal, scroll to top.
$('html, body').scrollTop(0);
//Show
$("#"+id).modal('show');
}
com.apple.WebKit.WebContent drops 113 error: Could not find specified service
Mine was different again. I was setting the user-agent like so:
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
This was causing something on the web page to freak out and leak memory. Not sure why but removing this sorted the issue for me.
CSS full screen div with text in the middle
text-align: center
will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0;
(you will probably also have to give the span a display: block
property)
Interpreting segfault messages
This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).
If this were a program, not a shared library
Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d
(and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.
Since it's a shared library
You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb
.
What the error means
Here's the breakdown of the fields:
address
(after the at
) - the location in memory the code is trying to access (it's likely that 10
and 11
are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0
)
ip
- instruction pointer, ie. where the code which is trying to do this lives
sp
- stack pointer
error
- An error code for page faults; see below for what this means on x86.
/*
* Page fault error code bits:
*
* bit 0 == 0: no page found 1: protection fault
* bit 1 == 0: read access 1: write access
* bit 2 == 0: kernel-mode access 1: user-mode access
* bit 3 == 1: use of reserved bit detected
* bit 4 == 1: fault was an instruction fetch
*/
text-align: right on <select> or <option>
The best solution for me was to make
select {
direction: rtl;
}
and then
option {
direction: ltr;
}
again. So there is no change in how the text is read in a screen reader or and no formatting-problem.
Rotate and translate
There is no need for that, as you can use css 'writing-mode' with values 'vertical-lr' or 'vertical-rl' as desired.
.item {
writing-mode: vertical-rl;
}
Video auto play is not working in Safari and Chrome desktop browser
On safari iPhone when battery is low and iPhone is on Low Power Mode it won`t autoplay, even if you have the following attributes: autoplay, loop, muted, playsinline set on your video html tag.
Walk around I found working is to have user gesture event to trigger video play:
document.body.addEventListener("touchstart", function () {
var allVideos = document.querySelectorAll('video');
for (var i = 0; i < allVideos.length; i++) {
allVideos[i].play();
}
},{ once: true });
You can read more about user gesture and Video Policies for iOS in webkit site:
https://webkit.org/blog/6784/new-video-policies-for-ios/
Add custom headers to WebView resource requests - android
I came accross the same problem and solved.
As said before you need to create your custom WebViewClient and override the shouldInterceptRequest method.
WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)
That method should issue a webView.loadUrl while returning an "empty" WebResourceResponse.
Something like this:
@Override
public boolean shouldInterceptRequest(WebView view, WebResourceRequest request) {
// Check for "recursive request" (are yor header set?)
if (request.getRequestHeaders().containsKey("Your Header"))
return null;
// Add here your headers (could be good to import original request header here!!!)
Map<String, String> customHeaders = new HashMap<String, String>();
customHeaders.put("Your Header","Your Header Value");
view.loadUrl(url, customHeaders);
return new WebResourceResponse("", "", null);
}
How can I force WebKit to redraw/repaint to propagate style changes?
I had this problem with a a number of divs that were inserted in another div with position: absolute
, the inserted divs had no position attribute. When I changed this to position:relative
it worked fine. (was really hard to pinpoint the problem)
In my case the elements where inserted by Angular with ng-repeat
.
css3 transition animation on load?
Ok I have managed to achieve an animation when the page loads using only css transitions (sort of!):
I have created 2 css style sheets:
the first is how I want the html styled before the animation...
and the second is how I want the page to look after the animation has been carried out.
I don't fully understand how I have accomplished this but it only works when the two css files (both in the head of my document) are separated by some javascript as follows.
I have tested this with Firefox, safari and opera. Sometimes the animation works, sometimes it skips straight to the second css file and sometimes the page appears to be loading but nothing is displayed (perhaps it is just me?)
<link media="screen,projection" type="text/css" href="first-css-file.css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="../js/jQuery JavaScript Library v1.3.2.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
// iOS Hover Event Class Fix
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) ||
(navigator.userAgent.match(/iPad/i))) {
$(".container .menu-text").click(function(){ // Update class to point at the head of the list
});
}
});
</script>
<link media="screen,projection" type="text/css" href="second-css-file.css" rel="stylesheet" />
Here is a link to my work-in-progress website: http://www.hankins-design.co.uk/beta2/test/index.html
Maybe I'm wrong but I thought browsers that do not support css transitions should not have any issues as they should skip straight to the second css file without delay or duration.
I am interested to know views on how search engine friendly this method is. With my black hat on I suppose I could fill a page with keywords and apply a 9999s delay on its opacity.
I would be interested to know how search engines deal with the transition-delay attribute and whether, using the method above, they would even see the links and information on the page.
More importantly I would really like to know why this is not consistent each time the page loads and how I can rectify this!
I hope this can generate some views and opinions if nothing else!
What are -moz- and -webkit-?
What are -moz- and -webkit-?
CSS properties starting with -webkit-
, -moz-
, -ms-
or -o-
are called vendor prefixes.
Why do different browsers add different prefixes for the same effect?
A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:
Originally, the point of vendor prefixes was to allow browser makers
to start supporting experimental CSS declarations.
Let's say a W3C working group is discussing a grid declaration (which,
incidentally, wouldn't be such a bad idea). Let's furthermore say that
some people create a draft specification, but others disagree with
some of the details. As we know, this process may take ages.
Let's furthermore say that Microsoft as an experiment decides to
implement the proposed grid. At this point in time, Microsoft cannot
be certain that the specification will not change. Therefore, instead
of adding the grid to its CSS, it adds -ms-grid
.
The vendor prefix kind of says "this is the Microsoft interpretation
of an ongoing proposal." Thus, if the final definition of the grid is
different, Microsoft can add a new CSS property grid without breaking
pages that depend on -ms-grid.
UPDATE AS OF THE YEAR 2016
As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.
As mentioned in this glossary about Mozilla's view on Vendor Prefix
on May 3, 2016
,
Browser vendors are now trying to get rid of vendor prefix for experimental
features. They noticed that Web developers were using them on
production Web sites, polluting the global space and making it more
difficult for underdogs to perform well.
For example, just a few years ago, to set a rounded corner on a box you had to write:
-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;
But now that browsers have come to fully support this feature, you really only need the standardized version:
border-radius: 10px 5px;
Finding the right rules for all browsers
As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.
You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.
Input:
a {
column-count: 3;
column-gap: 10px;
column-fill: auto;
}
Output:
a {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
-webkit-column-gap: 10px;
-moz-column-gap: 10px;
column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-fill: auto;
column-fill: auto;
}
CSS transition shorthand with multiple properties?
By having the .5s delay on transitioning the opacity property, the element will be completely transparent (and thus invisible) the whole time its height is transitioning. So the only thing you will actually see is the opacity changing. So you will get the same effect as leaving the height property out of the transition :
"transition: opacity .5s .5s;"
Is that what you're wanting? If not, and you're wanting to see the height transition, you can't have an opacity of zero during the whole time that it's transitioning.
Background color not showing in print preview
Chrome will not render background-color, or several other styles, when printing if the background graphics setting is turned off.
This has nothing to do with css, @media, or specificity. You can probably hack your way around it, but the easiest way to get chrome to show the background-color and other graphics is to properly check this checkbox under More Settings.
What is WebKit and how is it related to CSS?
WebKit is a layout engine designed to
allow web browsers to render web
pages. The WebKit engine provides a
set of classes to display web content
in windows, and implements browser
features such as following links when
clicked by the user, managing a
back-forward list, and managing a
history of pages recently visited.
WebKit was originally created as a
fork of KHTML as the layout engine for
Apple's Safari; it is portable to many
other computing platforms. It is also
used in Google's Chrome Browser.
WebKit's WebCore and JavaScriptCore
components are available under the GNU
Lesser General Public License, and the
rest of WebKit is available under a
BSD-style license.
Source Wikipedia
For further information about layout engines you can look here
Custom CSS Scrollbar for Firefox
Firefox 64 adds support for the spec draft CSS Scrollbars Module Level 1, which adds two new properties of scrollbar-width
and scrollbar-color
which give some control over how scrollbars are displayed.
You can set scrollbar-color
to one of the following values (descriptions from MDN):
auto
Default platform rendering for the track portion of the scrollbar, in the absence of any other related scrollbar color properties.
dark
Show a dark scrollbar, which can be either a dark variant of scrollbar provided by the platform, or a custom scrollbar with dark colors.
light
Show a light scrollbar, which can be either a light variant of scrollbar provided by the platform, or a custom scrollbar with light colors.
<color>
<color>
Applies the first color to the scrollbar thumb, the second to the scrollbar track.
Note that dark
and light
values are not currently implemented in Firefox.
macOS notes:
The auto-hiding semi-transparent scrollbars that are the macOS default cannot be colored with this rule (they still choose their own contrasting color based on the background). Only the permanently showing scrollbars (System Preferences > Show Scroll Bars > Always) are colored.
Visual Demo:
_x000D_
_x000D_
.scroll {_x000D_
width: 20%;_x000D_
height: 100px;_x000D_
border: 1px solid grey;_x000D_
overflow: scroll;_x000D_
display: inline-block;_x000D_
}_x000D_
.scroll-color-auto {_x000D_
scrollbar-color: auto;_x000D_
}_x000D_
.scroll-color-dark {_x000D_
scrollbar-color: dark;_x000D_
}_x000D_
.scroll-color-light {_x000D_
scrollbar-color: light;_x000D_
}_x000D_
.scroll-color-colors {_x000D_
scrollbar-color: orange lightyellow;_x000D_
}
_x000D_
<div class="scroll scroll-color-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-dark">_x000D_
<p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-light">_x000D_
<p>light</p><p>light</p><p>light</p><p>light</p><p>light</p><p>light</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-colors">_x000D_
<p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_
You can set scrollbar-width
to one of the following values (descriptions from MDN):
auto
The default scrollbar width for the platform.
thin
A thin scrollbar width variant on platforms that provide that option, or a thinner scrollbar than the default platform scrollbar width.
none
No scrollbar shown, however the element will still be scrollable.
You can also set a specific length value, according to the spec. Both thin
and a specific length may not do anything on all platforms, and what exactly it does is platform-specific. In particular, Firefox doesn't appear to be currently support a specific length value (this comment on their bug tracker seems to confirm this). The thin
keywork does appear to be well-supported however, with macOS and Windows support at-least.
It's probably worth noting that the length value option and the entire scrollbar-width
property are being considered for removal in a future draft, and if that happens this particular property may be removed from Firefox in a future version.
Visual Demo:
_x000D_
_x000D_
.scroll {_x000D_
width: 30%;_x000D_
height: 100px;_x000D_
border: 1px solid grey;_x000D_
overflow: scroll;_x000D_
display: inline-block;_x000D_
}_x000D_
.scroll-width-auto {_x000D_
scrollbar-width: auto;_x000D_
}_x000D_
.scroll-width-thin {_x000D_
scrollbar-width: thin;_x000D_
}_x000D_
.scroll-width-none {_x000D_
scrollbar-width: none;_x000D_
}
_x000D_
<div class="scroll scroll-width-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-thin">_x000D_
<p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-none">_x000D_
<p>none</p><p>none</p><p>none</p><p>none</p><p>none</p><p>none</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_
HTML5 placeholder css padding
I've created a fiddle using your screenshot as a background image and stripping out the extra mark-up, and it seems to work fine
http://jsfiddle.net/fLdQG/2/ (webkit browser required)
Does this work for you? If not, can you update the fiddle with your exact mark-up and CSS?
Javascript / Chrome - How to copy an object from the webkit inspector as code
You can copy an object to your clip board using copy(JSON.stringify(Object_Name)); in the console.
Eg:- Copy & Paste the below code in your console and press ENTER. Now, try to paste(CTRL+V for Windows or CMD+V for mac) it some where else and you will get {"name":"Daniel","age":25}
var profile = {
name: "Daniel",
age: 25
};
copy(JSON.stringify(profile));
Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink
The appearance of the scroll bars can be controlled with WebKit's -webkit-scrollbar
pseudo-elements [blog]. You can disable the default appearance and behaviour by setting -webkit-appearance
[docs] to none
.
Because you're removing the default style, you'll also need to specify the style yourself or the scroll bar will never show up. The following CSS recreates the appearance of the hiding scroll bars:
CSS
.frame::-webkit-scrollbar {
-webkit-appearance: none;
}
.frame::-webkit-scrollbar:vertical {
width: 11px;
}
.frame::-webkit-scrollbar:horizontal {
height: 11px;
}
.frame::-webkit-scrollbar-thumb {
border-radius: 8px;
border: 2px solid white; /* should match background, can't be transparent */
background-color: rgba(0, 0, 0, .5);
}
.frame::-webkit-scrollbar-track {
background-color: #fff;
border-radius: 8px;
}
WebKit (Chrome) Screenshot
Convert Data URI to File then append to FormData
Firefox has canvas.toBlob() and canvas.mozGetAsFile() methods.
But other browsers do not.
We can get dataurl from canvas and then convert dataurl to blob object.
Here is my dataURLtoBlob()
function. It's very short.
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
Use this function with FormData to handle your canvas or dataurl.
For example:
var dataurl = canvas.toDataURL('image/jpeg',0.8);
var blob = dataURLtoBlob(dataurl);
var fd = new FormData();
fd.append("myFile", blob, "thumb.jpg");
Also, you can create a HTMLCanvasElement.prototype.toBlob
method for non gecko engine browser.
if(!HTMLCanvasElement.prototype.toBlob){
HTMLCanvasElement.prototype.toBlob = function(callback, type, encoderOptions){
var dataurl = this.toDataURL(type, encoderOptions);
var bstr = atob(dataurl.split(',')[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
var blob = new Blob([u8arr], {type: type});
callback.call(this, blob);
};
}
Now canvas.toBlob()
works for all modern browsers not only Firefox.
For example:
canvas.toBlob(
function(blob){
var fd = new FormData();
fd.append("myFile", blob, "thumb.jpg");
//continue do something...
},
'image/jpeg',
0.8
);
Maximum call stack size exceeded error
For me as a beginner in TypeScript, it was a problem in the getter and the setter of _var1.
class Point2{
constructor(private _var1?: number, private y?: number){}
set var1(num: number){
this._var1 = num // problem was here, it was this.var1 = num
}
get var1(){
return this._var1 // this was return this.var1
}
}
Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image
try this
_x000D_
_x000D_
ul.a {_x000D_
list-style-type: circle;_x000D_
}_x000D_
_x000D_
ul.b {_x000D_
list-style-type: square;_x000D_
}_x000D_
_x000D_
ol.c {_x000D_
list-style-type: upper-roman;_x000D_
}_x000D_
_x000D_
ol.d {_x000D_
list-style-type: lower-alpha;_x000D_
}_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p>Example of unordered lists:</p>_x000D_
<ul class="a">_x000D_
<li>Coffee</li>_x000D_
<li>Tea</li>_x000D_
<li>Coca Cola</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="b">_x000D_
<li>Coffee</li>_x000D_
<li>Tea</li>_x000D_
<li>Coca Cola</li>_x000D_
</ul>_x000D_
_x000D_
<p>Example of ordered lists:</p>_x000D_
<ol class="c">_x000D_
<li>Coffee</li>_x000D_
<li>Tea</li>_x000D_
<li>Coca Cola</li>_x000D_
</ol>_x000D_
_x000D_
<ol class="d">_x000D_
<li>Coffee</li>_x000D_
<li>Tea</li>_x000D_
<li>Coca Cola</li>_x000D_
</ol>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
Firing a Keyboard Event in Safari, using JavaScript
The Mozilla Developer Network provides the following explanation:
- Create an event using
event = document.createEvent("KeyboardEvent")
- Init the keyevent
using:
event.initKeyEvent (type, bubbles, cancelable, viewArg,
ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg,
keyCodeArg, charCodeArg)
- Dispatch the event using
yourElement.dispatchEvent(event)
I don't see the last one in your code, maybe that's what you're missing. I hope this works in IE as well...
Get the real width and height of an image with JavaScript? (in Safari/Chrome)
As stated before, Xavi answer won't work if images are in the cache. The issue responds to webkit not firing the load event on cached images, so if the width/height attrs are no explicitly set in the img tag, the only reliable way to get the images is to wait for the window.load
event to be fired.
The window.load
event will fire always, so it's safe to access the width/height of and img after that without any trick.
$(window).load(function(){
//these all work
$('img#someId').css('width');
$('img#someId').width();
$('img#someId').get(0).style.width;
$('img#someId').get(0).width;
});
If you need to get the size of dynamically loaded images that might get cached (previously loaded), you can use Xavi method plus a query string to trigger a cache refresh. The downside is that it will cause another request to the server, for an img that is already cached and should be already available. Stupid Webkit.
var pic_real_width = 0,
img_src_no_cache = $('img#someId').attr('src') + '?cache=' + Date.now();
$('<img/>').attr('src', img_src_no_cache).load(function(){
pic_real_width = this.width;
});
ps: if you have a QueryString in the img.src
already, you will have to parse it and add the extra param to clear the cache.
What does the shrink-to-fit viewport meta attribute do?
It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:
Viewport Changes
Viewport meta tags using "width=device-width"
cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no"
to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.
Example
Here's a worked visual example which shows the difference upon loading the page in the two configurations.
The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw
). Note how in the first example the page is zoomed to fit when shrink-to-fit=no
is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.
The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.
Without shrink-to-fit specified
With shrink-to-fit=no
CSS media query to target iPad and iPad only?
Finally found a solution from : Detect different device platforms using CSS
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />
To reduce HTTP call, this can also be used inside you existing common CSS file:
@media all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait) {
.ipad-portrait { color: red; } /* your css rules for ipad portrait */
}
@media all and (device-width: 1024px) and (device-height: 768px) and (orientation:landscape) {
.ipad-landscape { color: blue; } /* your css rules for ipad landscape */
}
Hope this helps.
Other references:
How to style HTML5 range input to have different color before and after slider?
Pure CSS solution:
- Chrome: Hide the overflow from
input[range]
, and fill all the space left to
thumb with shadow color.
- IE: no need to reinvent the wheel:
::-ms-fill-lower
- Firefox no need to reinvent the wheel:
::-moz-range-progress
_x000D_
_x000D_
/*Chrome*/_x000D_
@media screen and (-webkit-min-device-pixel-ratio:0) {_x000D_
input[type='range'] {_x000D_
overflow: hidden;_x000D_
width: 80px;_x000D_
-webkit-appearance: none;_x000D_
background-color: #9a905d;_x000D_
}_x000D_
_x000D_
input[type='range']::-webkit-slider-runnable-track {_x000D_
height: 10px;_x000D_
-webkit-appearance: none;_x000D_
color: #13bba4;_x000D_
margin-top: -1px;_x000D_
}_x000D_
_x000D_
input[type='range']::-webkit-slider-thumb {_x000D_
width: 10px;_x000D_
-webkit-appearance: none;_x000D_
height: 10px;_x000D_
cursor: ew-resize;_x000D_
background: #434343;_x000D_
box-shadow: -80px 0 0 80px #43e5f7;_x000D_
}_x000D_
_x000D_
}_x000D_
/** FF*/_x000D_
input[type="range"]::-moz-range-progress {_x000D_
background-color: #43e5f7; _x000D_
}_x000D_
input[type="range"]::-moz-range-track { _x000D_
background-color: #9a905d;_x000D_
}_x000D_
/* IE*/_x000D_
input[type="range"]::-ms-fill-lower {_x000D_
background-color: #43e5f7; _x000D_
}_x000D_
input[type="range"]::-ms-fill-upper { _x000D_
background-color: #9a905d;_x000D_
}
_x000D_
<input type="range"/>
_x000D_
_x000D_
_x000D_
JavaScript: Is there a way to get Chrome to break on all errors?
Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.
Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.
If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error
object given to the catch block has a stack
property that shows where the exception happened.
How to create a pulse effect using -webkit-animation - outward rings
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
jQuery get the location of an element relative to window
Try this to get the location of an element relative to window.
_x000D_
_x000D_
$("button").click(function(){_x000D_
var offset = $("#simplebox").offset();_x000D_
alert("Current position of the box is: (left: " + offset.left + ", top: " + offset.top + ")");_x000D_
});
_x000D_
#simplebox{_x000D_
width:150px;_x000D_
height:100px;_x000D_
background: #FBBC09;_x000D_
margin: 150px 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button type="button">Get Box Position</button>_x000D_
<p><strong>Note:</strong> Play with the value of margin property to see how the jQuery offest() method works.</p>_x000D_
<div id="simplebox"></div>
_x000D_
_x000D_
_x000D_
See more @ Get the position of an element relative to the document with jQuery
How can I get an int from stdio in C?
The solution is quite simple ... you're reading getchar() which gives you the first character in the input buffer, and scanf just parsed it (really don't know why) to an integer, if you just forget the getchar for a second, it will read the full buffer until a newline char.
printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);
Outputs
> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234
Protect image download
As some people already said that it is not possible to prevent people to download your pictures, a trick could be something like this:
$(document).ready(function()
{
$('img').bind('contextmenu', function(e){
return false;
});
});
This trick prevents from the right click on all img. Obviously people can open the source code and download the images using links in your source code.
Creating a custom JButton in Java
I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit javax.swing.AbstractButton
and create your own. Should be pretty simple to wire something together with their existing framework.
WAITING at sun.misc.Unsafe.park(Native Method)
unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.
So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.
Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.
How do I create and access the global variables in Groovy?
I think you are talking about class level variables.
As mentioned above using global variable/class level variables are not a good practice.
If you really want to use it. and if you are sure that there will not be impact...
Declare any variable out side the method. at the class level with out the variable type
eg:
{
method()
{
a=10
print(a)
}
// def a or int a wont work
a=0
}
How do I link to part of a page? (hash?)
You have two options:
You can either put an anchor in your document as follows:
<a name="ref"></a>
Or else you give an id to a any HTML element:
<h1 id="ref">Heading</h1>
Then simply append the hash #ref
to the URL of your link to jump to the desired reference. Example:
<a href="document.html#ref">Jump to ref in document.html</a>
How to Set the Background Color of a JButton on the Mac OS
I own a mac too! here is the code that will work:
myButton.setBackground(Color.RED);
myButton.setOpaque(true); //Sets Button Opaque so it works
before doing anything or adding any components set the look and feel so it looks better:
try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(Exception e){
e.printStackTrace();
}
That is Supposed to change the look and feel to the cross platform look and feel, hope i helped! :)
No module named 'openpyxl' - Python 3.4 - Ubuntu
@zetysz and @Manish already fixed the problem. I am just putting this in an answer for future reference:
pip
refers to Python 2 as a default in Ubuntu, this means that pip install x
will install the module for Python 2 and not for 3
pip3
refers to Python 3, it will install the module for Python 3
How to create a generic array in Java?
The forced cast suggested by other people did not work for me, throwing an exception of illegal casting.
However, this implicit cast worked fine:
Item<K>[] array = new Item[SIZE];
where Item is a class I defined containing the member:
private K value;
This way you get an array of type K (if the item only has the value) or any generic type you want defined in the class Item.
++i or i++ in for loops ??
++i
is slightly more efficient due to its semantics:
++i; // Fetch i, increment it, and return it
i++; // Fetch i, copy it, increment i, return copy
For int-like indices, the efficiency gain is minimal (if any). For iterators and other heavier-weight objects, avoiding that copy can be a real win (particularly if the loop body doesn't contain much work).
As an example, consider the following loop using a theoretical BigInteger class providing arbitrary precision integers (and thus some sort of vector-like internals):
std::vector<BigInteger> vec;
for (BigInteger i = 0; i < 99999999L; i++) {
vec.push_back(i);
}
That i++ operation includes copy construction (i.e. operator new, digit-by-digit copy) and destruction (operator delete) for a loop that won't do anything more than essentially make one more copy of the index object. Essentially you've doubled the work to be done (and increased memory fragmentation most likely) by simply using the postfix increment where prefix would have been sufficient.
Calling a particular PHP function on form submit
In the following line
<form method="post" action="display()">
the action should be the name of your script and you should call the function, Something like this
<form method="post" action="yourFileName.php">
<input type="text" name="studentname">
<input type="submit" value="click" name="submit"> <!-- assign a name for the button -->
</form>
<?php
function display()
{
echo "hello ".$_POST["studentname"];
}
if(isset($_POST['submit']))
{
display();
}
?>
git remote prune – didn't show as many pruned branches as I expected
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)
refs/heads/feature
(short name feature
)
refs/remotes/origin/master
(short name origin/master
)
refs/remotes/origin/feature
(short name origin/feature
)
Now, a typical scenario:
- Some other developer finishes all work on the
feature
, merges it into master
and removes feature
branch from remote repository.
- By default, when you do
git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.
- You decide to clean them up, and run
git remote prune origin
.
- git detects that
feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed.
- Now you have 3 references, including
refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.
It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
jQuery animate scroll
There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check out AnimatedScroll.js.
Getting realtime output using subprocess
Real Time Output Issue resolved:
I encountered a similar issue in Python, while capturing the real time output from C program. I added fflush(stdout);
in my C code. It worked for me. Here is the code.
C program:
#include <stdio.h>
void main()
{
int count = 1;
while (1)
{
printf(" Count %d\n", count++);
fflush(stdout);
sleep(1);
}
}
Python program:
#!/usr/bin/python
import os, sys
import subprocess
procExe = subprocess.Popen(".//count", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
while procExe.poll() is None:
line = procExe.stdout.readline()
print("Print:" + line)
Output:
Print: Count 1
Print: Count 2
Print: Count 3
How to turn off caching on Firefox?
If you're working with server side code you could generate a random number and append it to the end of the src in the following manner....
src="yourJavascriptFile.js?randomNumber=434534"
with the randomNumber being randomly generated each time.
How do I add a reference to the MySQL connector for .NET?
"Add a reference to MySql.Data.dll" means you need to add a library reference to the downloaded connector. The IDE will link the database connection library with your application when it compiles.
Step-by-Step Example
I downloaded the binary (no installer) zip package from the MySQL web site, extracted onto the desktop, and did the following:
- Create a new project in Visual Studio
- In the Solution Explorer, under the project name, locate References and right-click on it. Select "Add Reference".
- In the "Add Reference" dialog, switch to the "Browse" tab and browse to the folder containing the downloaded connector. Navigate to the "bin" folder, and select the "MySql.Data.dll" file. Click OK.
- At the top of your code, add
using MySql.Data.MySqlClient;
. If you've added the reference correctly, IntelliSense should offer to complete this for you.
Returning a file to View/Download in ASP.NET MVC
Action method needs to return FileResult with either a stream, byte[], or virtual path of the file. You will also need to know the content-type of the file being downloaded. Here is a sample (quick/dirty) utility method. Sample video link
How to download files using asp.net core
[Route("api/[controller]")]
public class DownloadController : Controller
{
[HttpGet]
public async Task<IActionResult> Download()
{
var path = @"C:\Vetrivel\winforms.png";
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
var ext = Path.GetExtension(path).ToLowerInvariant();
return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
...
};
}
}
MS-access reports - The search key was not found in any record - on save
Another potential cause for this error is Sandbox Mode, which prevents MS Access from running certain statements that are considered unsafe. This can be disabled by setting the following registry key...
HKLM\Software\Microsoft\Office\12.0\Access Connectivity Engine\Engines
SandboxMode (DWORD Value)
...to either 0 or 2:
SETTING DESCRIPTION
0 Sandbox mode is disabled at all times.
1 Sandbox mode is used for Access, but not for non-Access programs.
2 Sandbox mode is used for non-Access programs, but not for Access.
3 Sandbox mode is used at all times. This is the default value.
Unit Testing: DateTime.Now
I got same problem, but i was thinking we should not use the set datetime things on the same class. because it could lead to misuse one day. so i have used the provider like
public class DateTimeProvider
{
protected static DateTime? DateTimeNow;
protected static DateTime? DateTimeUtcNow;
public DateTime Now
{
get
{
return DateTimeNow ?? System.DateTime.Now;
}
}
public DateTime UtcNow
{
get
{
return DateTimeUtcNow ?? System.DateTime.UtcNow;
}
}
public static DateTimeProvider DateTime
{
get
{
return new DateTimeProvider();
}
}
protected DateTimeProvider()
{
}
}
For tests, at test project made a helper which will deal with set things,
public class MockDateTimeProvider : DateTimeProvider
{
public static void SetNow(DateTime now)
{
DateTimeNow = now;
}
public static void SetUtcNow(DateTime utc)
{
DateTimeUtcNow = utc;
}
public static void RestoreAsDefault()
{
DateTimeNow = null;
DateTimeUtcNow = null;
}
}
on code
var dateTimeNow = DateTimeProvider.DateTime.Now //not DateTime.Now
var dateTimeUtcNow = DateTimeProvider.DateTime.UtcNow //not DateTime.UtcNow
and on tests
[Test]
public void Mocked_Now()
{
DateTime now = DateTime.Now;
MockDateTimeProvider.SetNow(now); //set to mock
Assert.AreEqual(now, DateTimeProvider.DateTime.Now);
Assert.AreNotEqual(now, DateTimeProvider.DateTime.UtcNow);
}
[Test]
public void Mocked_UtcNow()
{
DateTime utcNow = DateTime.UtcNow;
MockDateTimeProvider.SetUtcNow(utcNow); //set to mock
Assert.AreEqual(utcNow, DateTimeProvider.DateTime.UtcNow);
Assert.AreNotEqual(utcNow, DateTimeProvider.DateTime.Now);
}
But need to remember one thing, sometime the real DateTime and provider's DateTime doesn't act same
[Test]
public void Now()
{
Assert.AreEqual(DateTime.Now.Kind, DateTimeProvider.DateTime.Now.Kind);
Assert.LessOrEqual(DateTime.Now, DateTimeProvider.DateTime.Now);
Assert.LessOrEqual(DateTimeProvider.DateTime.Now - DateTime.Now, TimeSpan.FromMilliseconds(1));
}
I assumed the deference would be maximum TimeSpan.FromMilliseconds(0.00002). But most of the time it's even less
Find the sample at MockSamples
How to hide image broken Icon using only CSS/HTML?
Using CSS only is tough, but you could use CSS's background-image
instead of <img>
tags...
Something like this:
HTML
<div id="image"></div>
CSS
#image {
background-image: url(Error.src);
width: //width of image;
height: //height of image;
}
Here is a working fiddle.
Note: I added the border in the CSS on the fiddle just to demonstrate where the image would be.
Save Javascript objects in sessionStorage
You can create 2 wrapper methods for saving and retrieving object from session storage.
function saveSession(obj) {
sessionStorage.setItem("myObj", JSON.stringify(obj));
return true;
}
function getSession() {
var obj = {};
if (typeof sessionStorage.myObj !== "undefined") {
obj = JSON.parse(sessionStorage.myObj);
}
return obj;
}
Use it like this:- Get object, modify some data, and save back.
var obj = getSession();
obj.newProperty = "Prod"
saveSession(obj);
MySQL - Selecting data from multiple tables all with same structure but different data
Your original attempt to span both tables creates an implicit JOIN. This is frowned upon by most experienced SQL programmers because it separates the tables to be combined with the condition of how.
The UNION
is a good solution for the tables as they are, but there should be no reason they can't be put into the one table with decent indexing. I've seen adding the correct index to a large table increase query speed by three orders of magnitude.
Configuring so that pip install can work from github
If you want to use requirements.txt
file, you will need git
and something like the entry below to anonymously fetch the master branch in your requirements.txt
.
For regular install:
git+git://github.com/celery/django-celery.git
-e git://github.com/celery/django-celery.git#egg=django-celery
Editable mode downloads the project's source code into ./src
in the current directory. It allows pip freeze
to output the correct github location of the package.
Python pandas: how to specify data types when reading an Excel file?
If you are able to read the excel file correctly and only the integer values are not showing up. you can specify like this.
df = pd.read_excel('my.xlsx',sheetname='Sheet1', engine="openpyxl", dtype=str)
this should change your integer values into a string and show in dataframe
two divs the same line, one dynamic width, one fixed
@Yijie; Check the link maybe that's you want http://jsfiddle.net/sandeep/NCkL4/7/
EDIT:
http://jsfiddle.net/sandeep/NCkL4/8/
OR SEE THE FOLLOWING SNIPPET
_x000D_
_x000D_
#parent{_x000D_
overflow:hidden;_x000D_
background:yellow;_x000D_
position:relative;_x000D_
display:table;_x000D_
}_x000D_
.left{_x000D_
display:table-cell;_x000D_
}_x000D_
.right{_x000D_
background:red;_x000D_
width:50px;_x000D_
height:100%;_x000D_
display:table-cell;_x000D_
}_x000D_
body{_x000D_
margin:0;_x000D_
padding:0;_x000D_
}
_x000D_
<div id="parent">_x000D_
<div class="left">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>_x000D_
<div class="right">fixed</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Appending an id to a list if not already present in a string
Your id variable is a number where your list only has one element. It's a string that contains your other IDs. You either need to check if id is in that string, or pull the numbers out of the string and store them in the list separately
list = [350882, 348521, 350166]
Reset identity seed after deleting records in SQL Server
@jacob
DBCC CHECKIDENT ('[TestTable]', RESEED,0)
DBCC CHECKIDENT ('[TestTable]', RESEED)
Worked for me, I just had to clear all entries first from the table, then added the above in a trigger point after delete. Now whenever i delete an entry is taken from there.
using CASE in the WHERE clause
This is working Oracle example but it should work in MySQL too.
You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.
SELECT empno, ename, job
FROM scott.emp
WHERE (CASE WHEN job = 'MANAGER' THEN '1'
WHEN job = 'CLERK' THEN '2'
ELSE '0' END) IN (1, 2)
JavaScript - cannot set property of undefined
In javascript almost everything is an object, null
and undefined
are exception.
Instances of Array
is an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOT an object
Locating child nodes of WebElements in selenium
For Finding All the ChildNodes you can use the below Snippet
List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));
for (WebElement e : childs)
{
System.out.println(e.getTagName());
}
Note that this will give all the Child Nodes at same level ->
Like if you have structure like this :
<Html>
<body>
<div> ---suppose this is current WebElement
<a>
<a>
<img>
<a>
<img>
<a>
It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with
MyCurrentWebElement.findElements(By.xpath(".//*"));
Hope That Helps !!
How to rename a class and its corresponding file in Eclipse?
Simply select the class, right click and choose rename (probably F2 will also do). You can also select the class name in the source file, right click, choose Source, Refactor and rename. In both cases, both the class and the filename will be changed.
How to set width and height dynamically using jQuery
I tried all of the suggestions above and none of them worked for me, they changed the clientWidth and clientHeight not the actual width and height.
The jQuery docs for $().width and height methods says: "Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property."
The css approach did the same thing so I had to use the $().attr() methods instead.
_canvas.attr('width', 100);
_canvas.attr('height', 200);
I don't know is this affect me because I was trying to resize a element and it is some how different or not.
How, in general, does Node.js handle 10,000 concurrent requests?
What you seem to be thinking is that most of the processing is handled in the node event loop. Node actually farms off the I/O work to threads. I/O operations typically take orders of magnitude longer than CPU operations so why have the CPU wait for that? Besides, the OS can handle I/O tasks very well already. In fact, because Node does not wait around it achieves much higher CPU utilisation.
By way of analogy, think of NodeJS as a waiter taking the customer orders while the I/O chefs prepare them in the kitchen. Other systems have multiple chefs, who take a customers order, prepare the meal, clear the table and only then attend to the next customer.
How to set caret(cursor) position in contenteditable element (div)?
I think it's not simple to set caret to some position in contenteditable element. I wrote my own code for this. It bypasses the node tree calcing how many characters left and sets caret in needed element. I didn't test this code much.
//Set offset in current contenteditable field (for start by default or for with forEnd=true)
function setCurSelectionOffset(offset, forEnd = false) {
const sel = window.getSelection();
if (sel.rangeCount !== 1 || !document.activeElement) return;
const firstRange = sel.getRangeAt(0);
if (offset > 0) {
bypassChildNodes(document.activeElement, offset);
}else{
if (forEnd)
firstRange.setEnd(document.activeElement, 0);
else
firstRange.setStart(document.activeElement, 0);
}
//Bypass in depth
function bypassChildNodes(el, leftOffset) {
const childNodes = el.childNodes;
for (let i = 0; i < childNodes.length && leftOffset; i++) {
const childNode = childNodes[i];
if (childNode.nodeType === 3) {
const curLen = childNode.textContent.length;
if (curLen >= leftOffset) {
if (forEnd)
firstRange.setEnd(childNode, leftOffset);
else
firstRange.setStart(childNode, leftOffset);
return 0;
}else{
leftOffset -= curLen;
}
}else
if (childNode.nodeType === 1) {
leftOffset = bypassChildNodes(childNode, leftOffset);
}
}
return leftOffset;
}
}
I also wrote code to get current caret position (didn't test):
//Get offset in current contenteditable field (start offset by default or end offset with calcEnd=true)
function getCurSelectionOffset(calcEnd = false) {
const sel = window.getSelection();
if (sel.rangeCount !== 1 || !document.activeElement) return 0;
const firstRange = sel.getRangeAt(0),
startContainer = calcEnd ? firstRange.endContainer : firstRange.startContainer,
startOffset = calcEnd ? firstRange.endOffset : firstRange.startOffset;
let needStop = false;
return bypassChildNodes(document.activeElement);
//Bypass in depth
function bypassChildNodes(el) {
const childNodes = el.childNodes;
let ans = 0;
if (el === startContainer) {
if (startContainer.nodeType === 3) {
ans = startOffset;
}else
if (startContainer.nodeType === 1) {
for (let i = 0; i < startOffset; i++) {
const childNode = childNodes[i];
ans += childNode.nodeType === 3 ? childNode.textContent.length :
childNode.nodeType === 1 ? childNode.innerText.length :
0;
}
}
needStop = true;
}else{
for (let i = 0; i < childNodes.length && !needStop; i++) {
const childNode = childNodes[i];
ans += bypassChildNodes(childNode);
}
}
return ans;
}
}
You also need to be aware of range.startOffset and range.endOffset contain character offset for text nodes (nodeType === 3) and child node offset for element nodes (nodeType === 1). range.startContainer and range.endContainer may refer to any element node of any level in the tree (of course they also can refer to text nodes).
100% width table overflowing div container
Try adding
word-break: break-all
to the CSS on your table element.
That will get the words in the table cells to break such that the table does not grow wider than its containing div, yet the table columns are still sized dynamically. jsfiddle demo.
How to style SVG with external CSS?
"I am actually going to change the colors of these images based on what color scheme the user has chosen for my site." - Jordan 10 hours ago
I suggest you to use PHP for this. There's really no better way to do this without icon fonts, and if you resist using them, you could try this:
<?php
header('Content-Type: image/svg+xml');
echo '<?xml version="1.0" encoding="utf-8"?>';
$color = $_GET['color'];
?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">
<g>
<path fill="<?php echo $color; ?>" d="M28.44..."/>
</g>
</svg>
And later you could use this file as filename.php?color=#ffffff
to get the svg file in the desired color.
SQL QUERY replace NULL value in a row with a value from the previous known value
This will work on Snowflake (credit to Darren Gardner):
create temp table ss (id int, val int);
insert into ss (id,val) select 1, 3;
insert into ss (id,val) select 2, null;
insert into ss (id,val) select 3, 5;
insert into ss (id,val) select 4, null;
insert into ss (id,val) select 5, null;
insert into ss (id,val) select 6, 2;
select *
,last_value(val ignore nulls) over
(order by id rows between unbounded preceding and current row) as val2
from ss;
Use of exit() function
on unix like operating systems exit belongs to group of system calls. system calls are special calls which enable user code (your code) to call kernel code. so exit call makes some OS specific clean-up actions before returning control to OS, it terminates the program.
#include <stdlib.h>
// example 1
int main(int argc, char *argv){
exit(EXIT_SUCCESS);
}
// example 2
int main(int argc, char *argv){
return 0;
}
Some compilers will give you the same opcode from both of these examples but some won't. For example opcode from first function will not include any kind of stack positioning opcode which will be included in the second example like for any other function. You could compile both examples and disassemble them and you will see the difference.
You can use exit from any part of your code and be sure that process terminates. Don't forget to include integer parameter.
Visual Studio 2013 error MS8020 Build tools v140 cannot be found
That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.
To change your Platform Toolset:
- Right click your project, go to Properties.
- Under Configuration Properties, go to General.
- Change your Platform Toolset to one of the available ones.
Sending a mail from a linux shell script
If both exim and ssmtp are running, you may enter into troubles. So if you just want to run a simple MTA, just to have a simple smtp client to send email notifications for insistance, you shall purge the eventually preinstalled MTA like exim or postfix first and reinstall ssmtp.
Then it's quite straight forward, configuring only 2 files (revaliases and ssmtp.conf) - See ssmtp doc - , and usage in your bash or bourne script is like :
#!/bin/sh
SUBJECT=$1
RECEIVER=$2
TEXT=$3
SERVER_NAME=$HOSTNAME
SENDER=$(whoami)
USER="noreply"
[[ -z $1 ]] && SUBJECT="Notification from $SENDER on server $SERVER_NAME"
[[ -z $2 ]] && RECEIVER="another_configured_email_address"
[[ -z $3 ]] && TEXT="no text content"
MAIL_TXT="Subject: $SUBJECT\nFrom: $SENDER\nTo: $RECEIVER\n\n$TEXT"
echo -e $MAIL_TXT | sendmail -t
exit $?
Obviously do not forget to open your firewall output to the smtp port (25).
Read an Excel file directly from a R script
Let me reiterate what @Chase recommended: Use XLConnect.
The reasons for using XLConnect are, in my opinion:
- Cross platform. XLConnect is written in Java and, thus, will run on Win, Linux, Mac with no change of your R code (except possibly path strings)
- Nothing else to load. Just install XLConnect and get on with life.
- You only mentioned reading Excel files, but XLConnect will also write Excel files, including changing cell formatting. And it will do this from Linux or Mac, not just Win.
XLConnect is somewhat new compared to other solutions so it is less frequently mentioned in blog posts and reference docs. For me it's been very useful.
How to call an element in a numpy array?
If you are using numpy
and your array is an np.array
of np.array
elements like:
A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
and you want to access the inner elements (like 10,11,12 13,14.......
) then use:
A[0][0]
instead of A[0,0]
For example:
>>> import numpy as np
>>>A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
>>> A[0][0]
>>> 10
>>> A[0,0]
>>> Throws ERROR
(P.S.: Might be useful when using numpy.array_split()
)
If else embedding inside html
<?php if ($foo) { ?>
<div class="mydiv">Condition is true</div>
<?php } else { ?>
<div class="myotherdiv">Condition is false</div>
<?php } ?>
Accept function as parameter in PHP
According to @zombat's answer, it's better to validate the Anonymous Functions first:
function exampleMethod($anonFunc) {
//execute anonymous function
if (is_callable($anonFunc)) {
$anonFunc();
}
}
Or validate argument type since PHP 5.4.0:
function exampleMethod(callable $anonFunc) {}
ReactJS: Maximum update depth exceeded error
You should pass the event object when calling the function :
{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}
If you don't need to handle onClick event you can also type :
{<td><span onClick={(e) => this.toggle()}>Details</span></td>}
Now you can also add your parameters within the function.
javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context
This errors occurs when we use same method name for Jaxb2Marshaller
for exemple:
@Bean
public Jaxb2Marshaller marshallerClient() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
// this package must match the package in the <generatePackage> specified in
// pom.xml
marshaller.setContextPath("library.io.github.walterwhites.loans");
return marshaller;
}
And on other file
@Bean
public Jaxb2Marshaller marshallerClient() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
// this package must match the package in the <generatePackage> specified in
// pom.xml
marshaller.setContextPath("library.io.github.walterwhites.client");
return marshaller;
}
Even It's different class, you should named them differently
How to view the dependency tree of a given npm module?
To get it as a list:
% npx npm-remote-ls --flatten dugite -d false -o false
[
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'@szmarczak/[email protected]',
'[email protected]',
'@sindresorhus/[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
]
Use a JSON array with objects with javascript
_x000D_
_x000D_
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];_x000D_
document.writeln("<table border = '1' width = 100 >");_x000D_
document.writeln("<tr><td>No Id</td><td>Title</td></tr>"); _x000D_
for(var i=0;i<datas.length;i++){_x000D_
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");_x000D_
}_x000D_
document.writeln("</table>");
_x000D_
_x000D_
_x000D_
sequelize findAll sort order in nodejs
If you are using MySQL, you can use order by FIELD(id, ...)
approach:
Company.findAll({
where: {id : {$in : companyIds}},
order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})
Keep in mind, it might be slow. But should be faster, than manual sorting with JS.
Convert character to ASCII numeric value in java
Very simple. Just cast your char
as an int
.
char character = 'a';
int ascii = (int) character;
In your case, you need to get the specific Character from the String first and then cast it.
char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.
Though cast is not required explicitly, but its improves readability.
int ascii = character; // Even this will do the trick.
how to replace an entire column on Pandas.DataFrame
For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.
Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4
columns_to_overwrite = ["column_1", "column_3"]
First delete the columns that you intend to replace...
original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)
... then re-insert the columns, but using the values that you intended to overwrite
original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]
How to search in a List of Java object
You can give a try to Apache Commons Collections.
There is a class CollectionUtils that allows you to select or filter items by custom Predicate.
Your code would be like this:
Predicate condition = new Predicate() {
boolean evaluate(Object sample) {
return ((Sample)sample).value3.equals("three");
}
};
List result = CollectionUtils.select( list, condition );
Update:
In java8, using Lambdas and StreamAPI this should be:
List<Sample> result = list.stream()
.filter(item -> item.value3.equals("three"))
.collect(Collectors.toList());
much nicer!
How to create a stacked bar chart for my DataFrame using seaborn?
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
java.lang.ClassNotFoundException: org.apache.jsp.index_jsp
What version of tomcat are you using ? What appears to me is that the tomcat version is not supporting the servlet & jsp versions you're using. You can change to something like below or look into your version of tomcat on what it supports and change the versions accordingly.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
How do I run a file on localhost?
Think of it this way.
Anything that you type after localhost/
is the path inside the root directory of your server(www or htdocs).
You don't need to specify the complete path of the file you want to run but just the path after the root folder because putting localhost/
takes you inside the root folder itself.
Execute JavaScript using Selenium WebDriver in C#
public static class Webdriver
{
public static void ExecuteJavaScript(string scripts)
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript(scripts);
}
public static T ExecuteJavaScript<T>(string scripts)
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
return (T)js.ExecuteScript(scripts);
}
}
In your code you can then do
string test = Webdriver.ExecuteJavaScript<string>(" return 'hello World'; ");
int test = Webdriver.ExecuteJavaScript<int>(" return 3; ");
How To Set Up GUI On Amazon EC2 Ubuntu server
For LXDE/Lubuntu
1. connect to your instance (local forwarding port 5901)
ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]
2. Install packages
sudo apt update && sudo apt upgrade
sudo apt-get install xorg lxde vnc4server lubuntu-desktop
3. Create /etc/lightdm/lightdm.conf
sudo nano /etc/lightdm/lightdm.conf
4. Copy and paste the following into the lightdm.conf and save
[SeatDefaults]
allow-guest=false
user-session=LXDE
#user-session=Lubuntu
5. setup vncserver (you will be asked to create a password for the vncserver)
vncserver
sudo echo "lxpanel & /usr/bin/lxsession -s LXDE &" >> ~/.vnc/xstartup
6. Restart your instance and reconnect
sudo reboot
ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]
7. Start vncserver
vncserver -geometry 1280x800
8. In your Remote Desktop Client (e.g. Remmina) set Server to localhost:5901 and protocol to VNC
Show Console in Windows Application?
Actually AllocConsole with SetStdHandle in a GUI application might be a safer approach. The problem with the "console hijacking" already mentioned, is that the console might not be a foreground window at all, (esp. considering the influx of new window managers in Vista/Windows 7) among other things.
C++: Print out enum value as text
Using map:
#include <iostream>
#include <map>
#include <string>
enum Errors {ErrorA=0, ErrorB, ErrorC};
std::ostream& operator<<(std::ostream& out, const Errors value){
static std::map<Errors, std::string> strings;
if (strings.size() == 0){
#define INSERT_ELEMENT(p) strings[p] = #p
INSERT_ELEMENT(ErrorA);
INSERT_ELEMENT(ErrorB);
INSERT_ELEMENT(ErrorC);
#undef INSERT_ELEMENT
}
return out << strings[value];
}
int main(int argc, char** argv){
std::cout << ErrorA << std::endl << ErrorB << std::endl << ErrorC << std::endl;
return 0;
}
Using array of structures with linear search:
#include <iostream>
#include <string>
enum Errors {ErrorA=0, ErrorB, ErrorC};
std::ostream& operator<<(std::ostream& out, const Errors value){
#define MAPENTRY(p) {p, #p}
const struct MapEntry{
Errors value;
const char* str;
} entries[] = {
MAPENTRY(ErrorA),
MAPENTRY(ErrorB),
MAPENTRY(ErrorC),
{ErrorA, 0}//doesn't matter what is used instead of ErrorA here...
};
#undef MAPENTRY
const char* s = 0;
for (const MapEntry* i = entries; i->str; i++){
if (i->value == value){
s = i->str;
break;
}
}
return out << s;
}
int main(int argc, char** argv){
std::cout << ErrorA << std::endl << ErrorB << std::endl << ErrorC << std::endl;
return 0;
}
Using switch/case:
#include <iostream>
#include <string>
enum Errors {ErrorA=0, ErrorB, ErrorC};
std::ostream& operator<<(std::ostream& out, const Errors value){
const char* s = 0;
#define PROCESS_VAL(p) case(p): s = #p; break;
switch(value){
PROCESS_VAL(ErrorA);
PROCESS_VAL(ErrorB);
PROCESS_VAL(ErrorC);
}
#undef PROCESS_VAL
return out << s;
}
int main(int argc, char** argv){
std::cout << ErrorA << std::endl << ErrorB << std::endl << ErrorC << std::endl;
return 0;
}
problem with php mail 'From' header
I realize this is an old thread, but i had the same problem since i moved to bluehost yesterday. It may not have been the selected answer but i support the bluehost article 206 reply.
I created a valid email in control panel and used it as my From address and it worked.
C# ASP.NET MVC Return to Previous Page
For ASP.NET Core
You can use asp-route-* attribute:
<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">
An example:
Imagine that you have a Vehicle Controller with actions
Index
Details
Edit
and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit
and if you clicked edit from details you must return to details after edit.
//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
{
..............
..............
public string ReturnUrl {get;set;}
}
Details.cshtml
<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>
Index.cshtml
<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>
Edit.cshtml
<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
<div class="box-footer">
<a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
<button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
</div>
</form>
In your controller:
// GET: Vehicle/Edit/5
public ActionResult Edit(int id,string previous)
{
var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
//or by this code if you are not use automapper
var viewModel = new VehicleViewModel();
if (!string.IsNullOrWhiteSpace(previous)
viewModel.ReturnUrl = previous;
else
viewModel.ReturnUrl = "Index";
return View(viewModel);
}
[HttpPost]
public IActionResult Edit(VehicleViewModel model, string previous)
{
if (!string.IsNullOrWhiteSpace(previous))
model.ReturnUrl = previous;
else
model.ReturnUrl = "Index";
.............
.............
return RedirectToAction(model.ReturnUrl);
}
Spring jUnit Testing properties file
As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:
@TestPropertySource("classpath:application-test.properties")
Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource
With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?
Total no of Binary Trees are =
Summing over i gives the total number of binary search trees with n nodes.
The base case is t(0) = 1 and t(1) = 1, i.e. there is one empty BST and there is one BST with one node.
So, In general you can compute total no of Binary Search Trees using above formula.
I was asked a question in Google interview related on this formula.
Question was how many total no of Binary Search Trees are possible with 6 vertices.
So Answer is t(6) = 132
I think that I gave you some idea...
How to get HTTP response code for a URL in Java?
This has worked for me :
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
HttpClient client = new DefaultHttpClient();
//args[0] ="http://hostname:port/xyz/zbc";
HttpGet request1 = new HttpGet(args[0]);
HttpResponse response1 = client.execute(request1);
int code = response1.getStatusLine().getStatusCode();
try(BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));){
// Read in all of the post results into a String.
String output = "";
Boolean keepGoing = true;
while (keepGoing) {
String currentLine = br.readLine();
if (currentLine == null) {
keepGoing = false;
} else {
output += currentLine;
}
}
System.out.println("Response-->"+output);
}
catch(Exception e){
System.out.println("Exception"+e);
}
}
How to check if a double is null?
Firstly, a Java double
cannot be null, and cannot be compared with a Java null
. (The double
type is a primitive (non-reference) type and primitive types cannot be null.)
Next, if you call ResultSet.getDouble(...)
, that returns a double
not a Double
, the documented behaviour is that a NULL (from the database) will be returned as zero. (See javadoc linked above.) That is no help if zero is a legitimate value for that column.
So your options are:
The getObject
method will deliver the value as a Double
(assuming that the column type is double
), and is documented to return null
for a NULL. (For more information, this page documents the default mappings of SQL types to Java types, and therefore what actual type you should expect getObject
to deliver.)
Differences between cookies and sessions?
Google JSESSIONID. This will explain how the Servlet API initially uses URL re-writing and then, if cookies are enabled, cookies to manage sessions.
HTTP is stateless so the client browser must send the id of its session to the server with each request. The server, through whatever means, uses this id to retrieve any data for that session making it available for the lifetime of the request.
Logout button php
When you want to destroy a session completely, you need to do more then just
session_destroy();
First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:
<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>
The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.
Edit:
You need to remove the () from your exit code near the top of your script. it should just be
exit;
HttpServletRequest - how to obtain the referring URL?
It's available in the HTTP referer
header. You can get it in a servlet as follows:
String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.
You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.
For the interested, background about the misspelling can be found in Wikipedia.
"Could not load type [Namespace].Global" causing me grief
I had a similar issues where I was receiving this error on a project.
“Could not load type [Namespace].Global
Error in Line 1 etc etc
After spending some time I suspect a function with possible errors in a Class ..later commenting that specific function my problem get resolved.
I dont know why Visual Studio did't give me that specific error at debugging time. But this error might occure due to some errors in class file..
TypeError: Can't convert 'int' object to str implicitly
You cannot concatenate a string
with an int
. You would need to convert your int
to a string
using the str
function, or use formatting
to format your output.
Change: -
print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")
to: -
print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))
or: -
print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")
or as per the comment, use ,
to pass different strings to your print
function, rather than concatenating using +
: -
print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")
Order by descending date - month, day and year
Assuming that you have the power to make schema changes the only acceptable answer to this question IMO is to change the base data type to something more appropriate (e.g. date
if SQL Server 2008).
Storing dates as mm/dd/yyyy
strings is space inefficient, difficult to validate correctly and makes sorting and date calculations needlessly painful.
Gson: Is there an easier way to serialize a map
Only the TypeToken
part is neccesary (when there are Generics involved).
Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");
Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap);
System.out.println(json);
Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));
Output:
{"two":"world","one":"hello"}
hello
world
Print to the same line and not a new line?
import time
import sys
def update_pct(w_str):
w_str = str(w_str)
sys.stdout.write("\b" * len(w_str))
sys.stdout.write(" " * len(w_str))
sys.stdout.write("\b" * len(w_str))
sys.stdout.write(w_str)
sys.stdout.flush()
for pct in range(0, 101):
update_pct("{n}%".format(n=str(pct)))
time.sleep(0.1)
\b
will move the location of the cursor back one space
So we move it back all the way to the beginning of the line
We then write spaces to clear the current line - as we write spaces the cursor moves forward/right by one
So then we have to move the cursor back at the beginning of the line before we write our new data
Tested on Windows cmd using Python 2.7
How to set up a squid Proxy with basic username and password authentication?
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
Basic squid conf
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
squid 2.x
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Setting up a user
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
squid 2.x
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
htdigest vs htpasswd
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.
htpasswd
stores the password hashed (various hashing algos are available)
Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
MacOS
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
How to disable auto-play for local video in iframe
Just replace
<iframe width="465" height="315" src="videos/example.mp4"></iframe>
by
<video src="videos/example.mp4" controls></video>
Here is an example using bootstrap 4:
<div class="embed-responsive embed-responsive-4by3">
<video src="videos/example.mp4" controls></video>
</div>
Summarizing count and conditional aggregate functions on the same factor
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
data
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
AppendChild() is not a function javascript
Your div
variable is a string, not a DOM element object:
var div = '<div>top div</div>';
Strings don't have an appendChild
method. Instead of creating a raw HTML string, create the div as a DOM element and append a text node, then append the input element:
var div = document.createElement('div');
div.appendChild(document.createTextNode('top div'));
div.appendChild(element);
How to make several plots on a single page using matplotlib?
@doug & FS.'s answer are very good solutions. I want to share the solution for iteration on pandas.dataframe.
import pandas as pd
df=pd.DataFrame([[1, 2], [3, 4], [4, 3], [2, 3]])
fig = plt.figure(figsize=(14,8))
for i in df.columns:
ax=plt.subplot(2,1,i+1)
df[[i]].plot(ax=ax)
print(i)
plt.show()
Unexpected 'else' in "else" error
I would suggest to read up a bit on the syntax. See here.
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
How do you compare structs for equality in C?
If the structs only contain primitives or if you are interested in strict equality then you can do something like this:
int my_struct_cmp(const struct my_struct * lhs, const struct my_struct * rhs)
{
return memcmp(lhs, rsh, sizeof(struct my_struct));
}
However, if your structs contain pointers to other structs or unions then you will need to write a function that compares the primitives properly and make comparison calls against the other structures as appropriate.
Be aware, however, that you should have used memset(&a, sizeof(struct my_struct), 1) to zero out the memory range of the structures as part of your ADT initialization.
Difference between private, public, and protected inheritance
I have tried explaining inheritance using a picture below.
The main gist is that the private members of parent class are never directly accessible from derived/child class but you can use parent class's member function to access the private members of parent class.
Private variables are always present in derived class but it cannot be accessed by derived class. Its like its their but you cannot see with your own eyes but if you ask someone form the parent class then he can describe it to you.
What is /dev/null 2>&1?
Let's break >> /dev/null 2>&1
statement into parts:
Part 1: >>
output redirection
This is used to redirect the program output and append the output at the end of the file. More...
Part 2: /dev/null
special file
This is a Pseudo-devices special file.
Command ls -l /dev/null
will give you details of this file:
crw-rw-rw-. 1 root root 1, 3 Mar 20 18:37 /dev/null
Did you observe crw
? Which means it is a pseudo-device file which is of character-special-file type that provides serial access.
/dev/null
accepts and discards all input; produces no output (always returns an end-of-file indication on a read). Reference: Wikipedia
Part 3: 2>&1
file descriptor
Whenever you execute a program, the operating system always opens three files, standard input, standard output, and standard error as we know whenever a file is opened, the operating system (from kernel) returns a non-negative integer called a file descriptor. The file descriptor for these files are 0, 1, and 2, respectively.
So 2>&1
simply says redirect standard error to standard output.
&
means whatever follows is a file descriptor, not a filename.
In short, by using this command you are telling your program not to shout while executing.
What is the importance of using 2>&1
?
If you don't want to produce any output, even in case of some error produced in the terminal. To explain more clearly, let's consider the following example:
$ ls -l > /dev/null
For the above command, no output was printed in the terminal, but what if this command produces an error:
$ ls -l file_doesnot_exists > /dev/null
ls: cannot access file_doesnot_exists: No such file or directory
Despite I'm redirecting output to /dev/null
, it is printed in the terminal. It is because we are not redirecting error output to /dev/null
, so in order to redirect error output as well, it is required to add 2>&1
:
$ ls -l file_doesnot_exists > /dev/null 2>&1
How to comment multiple lines with space or indent
Pressing Ctrl+K+C or Ctrl+E+C After selecting the lines you want to comment will not give space after slashes. you can use multiline select to provide space as suggested by Habib
Perhaps, you can use /* before the lines you want to comment and after */ in that case you might not need to provide spaces.
/*
First Line to Comment
Second Line to Comment
Third Line to Comment
*/
Plotting time-series with Date labels on x-axis
You can rotate the dates by hacking axis notations with text()
Lines <- "Date Visits
11/1/2010 696537
11/2/2010 718748
11/3/2010 799355
11/4/2010 805800
11/5/2010 701262
11/6/2010 531579
11/7/2010 690068
11/8/2010 756947
11/9/2010 718757
11/10/2010 701768
11/11/2010 820113
11/12/2010 645259"
dm <- read.table(textConnection(Lines), header = TRUE)
dm$Date <- as.Date(dm$Date, "%m/%d/%Y")
plot(Visits ~ Date, dm, xaxt = "n", type = "l")
axis(1,at=NULL, labels=F)
text(x = dm$Date, par("usr")[3]*.97, labels = paste(dm$Date,' '), srt = 45, pos = 1, xpd = TRUE,cex=.7)
Print number of keys in Redis
After Redis 2.6, the result of INFO command are splitted by sections. In the "keyspace" section, there are "keys" and "expired keys" fields to tell how many keys are there.
Python unittest - opposite of assertRaises?
Just call the function. If it raises an exception, the unit test framework will flag this as an error. You might like to add a comment, e.g.:
sValidPath=AlwaysSuppliesAValidPath()
# Check PathIsNotAValidOne not thrown
MyObject(sValidPath)
How does "304 Not Modified" work exactly?
When the browser puts something in its cache, it also stores the Last-Modified
or ETag
header from the server.
The browser then sends a request with the If-Modified-Since
or If-None-Match
header, telling the server to send a 304 if the content still has that date or ETag.
The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.
Android - Pulling SQlite database android device
If you are trying to do it on android 6 request the permission and use the code of the answer of this question
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
return;
}
Once it is granted
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_RC) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted start reading or writing database
} else {
Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
}
}
}
Powershell: Get FQDN Hostname
If you have more than one network adapter and more than one adapter is active (f.e WLAN + VPN) you need a bit more complex check. You can use this one-liner:
[System.Net.DNS]::GetHostByAddress(([System.Net.DNS]::GetHostAddresses([System.Environment]::MachineName) | Where-Object { $_.AddressFamily -eq "InterNetwork" } | Select-Object IPAddressToString)[0].IPAddressToString).HostName.ToLower()
Play audio file from the assets directory
This function will work properly :)
// MediaPlayer m; /*assume, somewhere in the global scope...*/
public void playBeep() {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("beepbeep.mp3");
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
How to add SHA-1 to android application
If you are using Google Play App Signing, you don't need to add your SHA-1 keys manually, just login into Firebase go into "project settings"->"integration" and press a button to link Google Play with firebase, SHA-1 will be added automatically.
How to change font-size of a tag using inline css?
Strange it doesn't change, as inline styles
are most specific, if style sheet has !important
declared, it wont over ride, try this and see
<span style="font-size: 11px !important; color: #aaaaaa;">Hello</span>
How to round up with excel VBA round()?
Try this function, it's ok to round up a double
'---------------Start -------------
Function Round_Up(ByVal d As Double) As Integer
Dim result As Integer
result = Math.Round(d)
If result >= d Then
Round_Up = result
Else
Round_Up = result + 1
End If
End Function
'-----------------End----------------
Run a JAR file from the command line and specify classpath
Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp
or specify the main class. In your case it would contain lines like this:
Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar
Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar
.
Then execute it with
java -jar MyJar.jar
How to show the "Are you sure you want to navigate away from this page?" when changes committed?
here is my html
<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="myFunction()">
<h1 id="belong">
Welcome To My Home
</h1>
<p>
<a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
</p>
</body>
And so this is how I did something similar in javaScript
var myGlobalNameHolder ="";
function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
myGlobalNameHolder = myString;
if (myString != null) {
document.getElementById("replaceME").innerHTML =
"Hello " + myString + ". Welcome to my site";
document.getElementById("belong").innerHTML =
"A place you belong";
}
}
// create a function to pass our event too
function myFunction2(event) {
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}
Running SSH Agent when starting Git Bash on Windows
As I don't like using putty in Windows as a workaround, I created a very simple utility ssh-agent-wrapper. It scans your .ssh folders and adds all your keys to the agent. You simply need to put it into Windows startup folder for it to work.
Assumptions:
- ssh-agent in path
- shh-add in path (both by choosing the "RED" option when installing git
- private keys are in %USERPROFILE%/.ssh folder
- private keys names start with id (e.g. id_rsa)
Postgres integer arrays as parameters?
Full Coding Structure
postgresql function
CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
item_head_list int[])
RETURNS TABLE(item_display_id integer)
LANGUAGE 'sql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);
$BODY$;
Model
public class CampaignCreator
{
public int item_display_id { get; set; }
public List<int> pitem_head_id { get; set; }
}
.NET CORE function
DynamicParameters _parameter = new DynamicParameters();
_parameter.Add("@item_head_list",obj.pitem_head_id);
string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
response.data = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);
React - uncaught TypeError: Cannot read property 'setState' of undefined
This is due to this.delta
not being bound to this
.
In order to bind set this.delta = this.delta.bind(this)
in the constructor:
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta = this.delta.bind(this);
}
Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value.
Reverse colormap in matplotlib
As of Matplotlib 2.0, there is a reversed()
method for ListedColormap
and LinearSegmentedColorMap
objects, so you can just do
cmap_reversed = cmap.reversed()
Here is the documentation.
Remove git mapping in Visual Studio 2015
The solution is much simpler than that. You simply need to remove three files from the project UNC Path.
Navigate to your solution's UNC Path.
Example: C:\Users\Your User Name\Documents\Visual Studio 2015\Projects\Your Project Folder
Then permanently delete ("SHIFT + DEL") the .git*
files and folder. There are two files and one folder, which may be hidden so ensure you have your folders and search options > View > show hidden files, folder, and drives (Radio Button) Selected.
The files to permanently delete are:
.gitignore (file)
.gitattributes (file)
.git (folder)
Reopen Visual Studio and there is no more relationship to the Git Source Control. If you wanted to take it as far as removing it from the registry as mentioned above, you could, but that shouldn't be necessary aside from the "house keeping" of your machine.
Convert float to string with precision & number of decimal digits specified?
Here a solution using only std. However, note that this only rounds down.
float number = 3.14159;
std::string num_text = std::to_string(number);
std::string rounded = num_text.substr(0, num_text.find(".")+3);
For rounded
it yields:
3.14
The code converts the whole float to string, but cuts all characters 2 chars after the "."
SVN 405 Method Not Allowed
I also met this problem just now and solved it in this way. So I recorded it here, and I wish it be useful for others.
Scenario:
- Before I commit the code, revision: 100
- (Someone else commits the code... revision increased to 199)
- I (forgot to run "svn up", ) commit the code, now my revision: 200
- I run "svn up".
The error occurred.
Solution:
- $ mv current_copy copy_back # Rename the current code copy
- $ svn checkout current_copy # Check it out again
- $ cp copy_back/ current_copy # Restore your modifications
How do I protect javascript files?
I know that this is the wrong time to be answering this question but i just thought of something
i know it might be stressful but atleast it might still work
Now the trick is to create a lot of server side encoding scripts, they have to be decodable(for example a script that replaces all vowels with numbers and add the letter 'a' to every consonant so that the word 'bat' becomes ba1ta) then create a script that will randomize between the encoding scripts and create a cookie with the name of the encoding script being used (quick tip: try not to use the actual name of the encoding script for the cookie for example if our cookie is name 'encoding_script_being_used' and the randomizing script chooses an encoding script named MD10 try not to use MD10 as the value of the cookie but 'encoding_script4567656' just to prevent guessing) then after the cookie has been created another script will check for the cookie named 'encoding_script_being_used' and get the value, then it will determine what encoding script is being used.
Now the reason for randomizing between the encoding scripts was that the server side language will randomize which script to use to decode your javascript.js and then create a session or cookie to know which encoding scripts was used
then the server side language will also encode your javascript .js and put it as a cookie
so now let me summarize with an example
PHP randomizes between a list of encoding scripts and encrypts javascript.js then it create a cookie telling the client side language which encoding script was used then client side language decodes the javascript.js cookie(which is obviously encoded)
so people can't steal your code
but i would not advise this because
- it is a long process
- It is too stressful
Calling a Sub in VBA
For anyone still coming to this post, the other option is to simply omit the parentheses:
Sub SomeOtherSub(Stattyp As String)
'Daty and the other variables are defined here
CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2
End Sub
The Call
keywords is only really in VBA for backwards compatibilty and isn't actually required.
If however, you decide to use the Call
keyword, then you have to change your syntax to suit.
'// With Call
Call Foo(Bar)
'// Without Call
Foo Bar
Both will do exactly the same thing.
That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call
keyword and the parentheses
How to use HTML to print header and footer on every printed page of a document?
If you are using a template engine like Asp.net Razor Engine or Angular,
I think you must re-generate your page and split the page in several pages and then you can freely markup each page and put header and footer on theme.
one example could be as bellow:
_x000D_
_x000D_
@page {_x000D_
size: A4; _x000D_
margin: .9cm;_x000D_
}_x000D_
_x000D_
_x000D_
@media print {_x000D_
_x000D_
body.print-paper-a4 {_x000D_
width: 210mm;_x000D_
height: 297mm;_x000D_
}_x000D_
_x000D_
body {_x000D_
background: white;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.print-stage,_x000D_
.no-print {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
_x000D_
body.print-paper.a4 .print-paper {_x000D_
width: 210mm;_x000D_
height: 297mm;_x000D_
}_x000D_
_x000D_
.print-paper {_x000D_
page-break-after: always;_x000D_
margin: 0;_x000D_
padding: .8cm;_x000D_
border:none;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
.print-papers {_x000D_
display: block;_x000D_
z-index: 2000;_x000D_
margin: auto;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
body.print-paper-a4 .print-paper {_x000D_
width: 21cm;_x000D_
height:27cm;_x000D_
}_x000D_
_x000D_
_x000D_
.print-paper {_x000D_
margin: auto;_x000D_
background: white;_x000D_
border: 1px dotted black;_x000D_
box-sizing: border-box;_x000D_
margin: 1cm auto;_x000D_
padding: .8cm;_x000D_
overflow: hidden; _x000D_
}_x000D_
_x000D_
_x000D_
body.print-mode .no-print-preview {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
body.print-mode .print-preview {_x000D_
display: block;_x000D_
}
_x000D_
<body class="print-mode print-paper-a4">_x000D_
_x000D_
<div class="print-papers print-preview">_x000D_
<div class="print-paper">_x000D_
<div style="font-size: 5cm">_x000D_
HELLO_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
<div class="print-paper">_x000D_
<div class="page-header">_x000D_
</div>_x000D_
_x000D_
_x000D_
</div>_x000D_
<div class="print-paper">_x000D_
_x000D_
_x000D_
_x000D_
</div> _x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_
Right align text in android TextView
Make sure that you are not using android:layout_width="wrap_content"
if so then it won't be able to set the gravity because you are not having enough space for the text to align. Instead use android:layout_width="fill_parent"
Sending string via socket (python)
client.py
import socket
s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
str = raw_input("S: ")
s.send(str.encode());
if(str == "Bye" or str == "bye"):
break
print "N:",s.recv(1024).decode()
s.close()
server.py
import socket
s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
rcvdData = c.recv(1024).decode()
print "S:",rcvdData
sendData = raw_input("N: ")
c.send(sendData.encode())
if(sendData == "Bye" or sendData == "bye"):
break
c.close()
This should be the code for a small prototype for the chatting app you wanted.
Run both of them in separate terminals but then just check for the ports.
How to extract a substring using regex
Assuming you want the part between single quotes, use this regular expression with a Matcher
:
"'(.*?)'"
Example:
String mydata = "some string with 'the data i want' inside";
Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
System.out.println(matcher.group(1));
}
Result:
the data i want
Breaking to a new line with inline-block?
Set the items into display: inline
and use :after
:
.text span { display: inline }
.break-after:after { content: '\A'; white-space:pre; }
and add the class into your html spans:
<span class="medium break-after">We</span>
Editable text to string
Based on this code (which you provided in response to Alex's answer):
Editable newTxt=(Editable)userName1.getText();
String newString = newTxt.toString();
It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:
String newString = userName1.getText().toString();
How can I get the current contents of an element in webdriver
My answer is based on this answer: How can I get the current contents of an element in webdriver
just more like copy-paste.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')
element_text = element.text
element_attribute_value = element.get_attribute('value')
print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
element = driver.find_element_by_css_selector('.description.expand_description > p')
element_text = element.text
element_attribute_value = element.get_attribute('value')
print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
driver.quit()
How do I trim whitespace?
try translate
>>> import string
>>> print '\t\r\n hello \r\n world \t\r\n'
hello
world
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr)
' hello world '
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'
angular2: Error: TypeError: Cannot read property '...' of undefined
That's because abc
is undefined at the moment of the template rendering. You can use safe navigation operator (?
) to "protect" template until HTTP call is completed:
{{abc?.xyz?.name}}
You can read more about safe navigation operator here.
Update:
Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf
directive to overcome this problem:
<div *ngIf="arr && arr.length > 0">
{{arr[0].name}}
</div>
Read more about NgIf
directive here.
Hashing a string with Sha256
This work for me in .NET Core 3.1.
But not in .NET 5 preview 7.
using System;
using System.Security.Cryptography;
using System.Text;
namespace PortalAplicaciones.Shared.Models
{
public class Encriptar
{
public static string EncriptaPassWord(string Password)
{
try
{
SHA256Managed hasher = new SHA256Managed();
byte[] pwdBytes = new UTF8Encoding().GetBytes(Password);
byte[] keyBytes = hasher.ComputeHash(pwdBytes);
hasher.Dispose();
return Convert.ToBase64String(keyBytes);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
}
}
Load More Posts Ajax Button in WordPress
UPDATE 24.04.2016.
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
EDIT
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script
. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat
. This will be in the $_POST
array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready();
enviroment
var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;
) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts()
function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100
or $('footer').offset().top
for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.log
s in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
How to select clear table contents without destroying the table?
How about:
ACell.ListObject.DataBodyRange.Rows.Delete
That will keep your table structure and headings, but clear all the data and rows.
EDIT: I'm going to just modify a section of my answer from your previous post, as it does mostly what you want. This leaves just one row:
With loSource
.Range.AutoFilter
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
.DataBodyRange.Rows(1).Specialcells(xlCellTypeConstants).ClearContents
End With
If you want to leave all the rows intact with their formulas and whatnot, just do:
With loSource
.Range.AutoFilter
.DataBodyRange.Specialcells(xlCellTypeConstants).ClearContents
End With
Which is close to what @Readify suggested, except it won't clear formulas.
Installing Homebrew on OS X
Here is a version that wraps the homebrew installer in a bash function that can be run from your deployment scripts:
install_homebrew_if_not_present() {
echo "Checking for homebrew installation"
which -s brew
if [[ $? != 0 ]] ; then
echo "Homebrew not found. Installing..."
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
else
echo "Homebrew already installed! Updating..."
brew update
fi
}
And another function which will install a homebrew formula if it is not already installed:
brew_install () {
if brew ls --versions $1 > /dev/null; then
echo "already installed: $1"
else
echo "Installing forumula: $1..."
brew install $1
fi
}
Once you have these functions defined you can use them as follows in your bash script:
install_homebrew_if_not_present
brew_install wget
brew_install openssl
...
Check if Key Exists in NameValueCollection
queryItems.AllKeys.Contains(key)
Be aware that key may not be unique and that the comparison is usually case sensitive. If you want to just get the value of the first matching key and not bothered about case then use this:
public string GetQueryValue(string queryKey)
{
foreach (string key in QueryItems)
{
if(queryKey.Equals(key, StringComparison.OrdinalIgnoreCase))
return QueryItems.GetValues(key).First(); // There might be multiple keys of the same name, but just return the first match
}
return null;
}
HttpWebRequest-The remote server returned an error: (400) Bad Request
What type of authentication do you use?
Send the credentials using the properties Ben said before and setup a cookie handler.
You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
How can I set an SQL Server connection string?
They are a number of things to worry about when connecting to SQL Server on another machine.
- Host/IP address of the machine
- Initial catalog (database name)
- Valid username/password
Very often SQL Server may be running as a default instance which means you can simply specify the hostname/IP address, but you may encounter a scenario where it is running as a named instance (SQL Server Express Edition for instance). In this scenario you'll have to specify the hostname/instance name.
JOptionPane Yes or No window
You are always checking for a true condition, hence your message will always show.
You should replace your if (true)
statement with if ( n == JOptionPane.YES_OPTION)
When one of the showXxxDialog methods returns an integer, the possible
values are:
YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION
From here
AngularJS : How do I switch views from a controller function?
Without doing a full revamp of the default routing (#/ViewName) environment, I was able to do a slight modification of Cody's tip and got it working great.
the controller
.controller('GeneralCtrl', ['$route', '$routeParams', '$location',
function($route, $routeParams, $location) {
...
this.goToView = function(viewName){
$location.url('/' + viewName);
}
}]
);
the view
...
<li ng-click="general.goToView('Home')">HOME</li>
...
What brought me to this solution was when I was attempting to integrate a Kendo Mobile UI widget into an angular environment I was losing the context of my controller and the behavior of the regular anchor tag was also being hijacked. I re-established my context from within the Kendo widget and needed to use a method to navigate...this worked.
Thanks for the previous posts!
Replace a string in shell script using a variable
To let your shell expand the variable, you need to use double-quotes like
sed -i "s#12345678#$replace#g" file.txt
This will break if $replace
contain special sed
characters (#
, \
). But you can preprocess $replace
to quote them:
replace_quoted=$(printf '%s' "$replace" | sed 's/[#\]/\\\0/g')
sed -i "s#12345678#$replace_quoted#g" file.txt
Can table columns with a Foreign Key be NULL?
I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer
.
Find the below example-
CREATE TABLE parent (
id int(10) UNSIGNED NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id int(10) UNSIGNED NOT NULL,
parent_id int(10) UNSIGNED DEFAULT NULL,
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;
7-Zip command to create and extract a password-protected ZIP file on Windows?
General Syntax:
7z a archive_name target parameters
Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.
Parameters:
- -p encrypt and prompt for PW.
- -pPUT_PASSWORD_HERE (this replaces -p) if you want to preset the PW with no prompt.
- -mhe=on to hide file structure, otherwise file structure and names will be visible by default.
Eg. This will prompt for a PW and hide file structures:
7z a archive_name target -p -mhe=on
Eg. No prompt, visible file structure:
7z a archive_name target -pPUT_PASSWORD_HERE
And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.
Handling warning for possible multiple enumeration of IEnumerable
If your data is always going to be repeatable, perhaps don't worry about it. However, you can unroll it too - this is especially useful if the incoming data could be large (for example, reading from disk/network):
if(objects == null) throw new ArgumentException();
using(var iter = objects.GetEnumerator()) {
if(!iter.MoveNext()) throw new ArgumentException();
var firstObject = iter.Current;
var list = DoSomeThing(firstObject);
while(iter.MoveNext()) {
list.Add(DoSomeThingElse(iter.Current));
}
return list;
}
Note I changed the semantic of DoSomethingElse a bit, but this is mainly to show unrolled usage. You could re-wrap the iterator, for example. You could make it an iterator block too, which could be nice; then there is no list
- and you would yield return
the items as you get them, rather than add to a list to be returned.
What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?
2019 update: Use NVM to install node, not Homebrew
In most of the answers , recommended way to install nvm is to use Homebrew
Do not do that
At Github Page for nvm it is clearly called out:
Homebrew installation is not supported. If you have issues with
homebrew-installed nvm, please brew uninstall it, and install it using
the instructions below, before filing an issue.
Use the following method instead
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
The script clones the nvm repository to ~/.nvm and adds the source line to your profile (~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc).
And then use nvm to install node. For example to install latest LTS version do:
nvm install v8.11.1
Clean and hassle free. It would mark this as your default node version as well so you should be all set
TypeError: ObjectId('') is not JSON serializable
For those who need to return the data thru Jsonify with Flask:
cursor = db.collection.find()
data = []
for doc in cursor:
doc['_id'] = str(doc['_id']) # This does the trick!
data.append(doc)
return jsonify(data)
init-param and context-param
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/META-INF/PersistenceContext.xml
</param-value>
</context-param>
I have initialized my PersistenceContext.xml
within <context-param>
because all my servlets will be interacting with database in MVC framework.
Howerver,
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:ApplicationContext.xml
</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.organisation.project.rest</param-value>
</init-param>
</servlet>
in the aforementioned code, I am configuring jersey and the ApplicationContext.xml
only to rest layer. For the same I am using </init-param>
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
how to evenly distribute elements in a div next to each other?
In the 'old days' you'd use a table and your menu items would be evenly spaced without having to explicitly state the width for the number of items.
If it wasn't for IE 6 and 7 (if that is of concern) then you can do the same in CSS.
<div class="demo">
<span>Span 1</span>
<span>Span 2</span>
<span>Span 3</span>
</div>
CSS:
div.demo {
display: table;
width: 100%;
table-layout: fixed; /* For cells of equal size */
}
div.demo span {
display: table-cell;
text-align: center;
}
Without having to adjust for the number of items.
Example without table-layout:fixed
- the cells are evenly distributed across the full width, but they are not necessarily of equal size since their width is determined by their contents.
Example with table-layout:fixed
- the cells are of equal size, regardless of their contents. (Thanks to @DavidHerse in comments for this addition.)
If you want the first and last menu elements to be left and right justified, then you can add the following CSS:
div.demo span:first-child {
text-align: left;
}
div.demo span:last-child {
text-align: right;
}
Filter by Dates in SQL
Well you are trying to compare Date with Nvarchar which is wrong. Should be
Where dates between date1 And date2
-- both date1 & date2 should be date/datetime
If date1,date2 strings; server will convert them to date type before filtering.
WebAPI Multiple Put/Post parameters
[HttpPost]
public string MyMethod([FromBody]JObject data)
{
Customer customer = data["customerData"].ToObject<Customer>();
Product product = data["productData"].ToObject<Product>();
Employee employee = data["employeeData"].ToObject<Employee>();
//... other class....
}
using referance
using Newtonsoft.Json.Linq;
Use Request for JQuery Ajax
var customer = {
"Name": "jhon",
"Id": 1,
};
var product = {
"Name": "table",
"CategoryId": 5,
"Count": 100
};
var employee = {
"Name": "Fatih",
"Id": 4,
};
var myData = {};
myData.customerData = customer;
myData.productData = product;
myData.employeeData = employee;
$.ajax({
type: 'POST',
async: true,
dataType: "json",
url: "Your Url",
data: myData,
success: function (data) {
console.log("Response Data ?");
console.log(data);
},
error: function (err) {
console.log(err);
}
});
jQuery datepicker to prevent past date
I am using following code to format date and show 2 months in calendar...
<script>
$(function() {
var dates = $( "#from, #to" ).datepicker({
showOn: "button",
buttonImage: "imgs/calendar-month.png",
buttonImageOnly: true,
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 2,
onSelect: function( selectedDate ) {
$( ".selector" ).datepicker({ defaultDate: +7 });
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", "dateFormat", 'yy-mm-dd' );
}
});
});
</script>
The problem is I am not sure how to restrict previous dates selection.
Using variables inside strings
This functionality is not built-in to C# 5 or below.
Update: C# 6 now supports string interpolation, see newer answers.
The recommended way to do this would be with String.Format
:
string name = "Scott";
string output = String.Format("Hello {0}", name);
However, I wrote a small open-source library called SmartFormat that extends String.Format
so that it can use named placeholders (via reflection). So, you could do:
string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".
Hope you like it!
Adding a caption to an equation in LaTeX
You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat
I say this because captions are usually applied to floats.
Straight ahead equations (those written with $ ... $
, $$ ... $$
, begin{equation}...
) are in-line objects that do not support \caption
.
This can be done using the following snippet just before \begin{document}
\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}
\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
\let\ORIGINALcaption\caption
\def\caption{%
\addtocounter{equation}{-1}%
\ORIGINALcaption
}%
\ORGeqfloat
}
and when adding an equation use something like
\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}
How to remove white space characters from a string in SQL Server
Using ASCII(RIGHT(ProductAlternateKey, 1))
you can see that the right most character in row 2 is a Line Feed or Ascii Character 10.
This can not be removed using the standard LTrim
RTrim
functions.
You could however use (REPLACE(ProductAlternateKey, CHAR(10), '')
You may also want to account for carriage returns and tabs. These three (Line feeds, carriage returns and tabs) are the usual culprits and can be removed with the following :
LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(ProductAlternateKey, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))
If you encounter any more "white space" characters that can't be removed with the above then try one or all of the below:
--NULL
Replace([YourString],CHAR(0),'');
--Horizontal Tab
Replace([YourString],CHAR(9),'');
--Line Feed
Replace([YourString],CHAR(10),'');
--Vertical Tab
Replace([YourString],CHAR(11),'');
--Form Feed
Replace([YourString],CHAR(12),'');
--Carriage Return
Replace([YourString],CHAR(13),'');
--Column Break
Replace([YourString],CHAR(14),'');
--Non-breaking space
Replace([YourString],CHAR(160),'');
This list of potential white space characters could be used to create a function such as :
Create Function [dbo].[CleanAndTrimString]
(@MyString as varchar(Max))
Returns varchar(Max)
As
Begin
--NULL
Set @MyString = Replace(@MyString,CHAR(0),'');
--Horizontal Tab
Set @MyString = Replace(@MyString,CHAR(9),'');
--Line Feed
Set @MyString = Replace(@MyString,CHAR(10),'');
--Vertical Tab
Set @MyString = Replace(@MyString,CHAR(11),'');
--Form Feed
Set @MyString = Replace(@MyString,CHAR(12),'');
--Carriage Return
Set @MyString = Replace(@MyString,CHAR(13),'');
--Column Break
Set @MyString = Replace(@MyString,CHAR(14),'');
--Non-breaking space
Set @MyString = Replace(@MyString,CHAR(160),'');
Set @MyString = LTRIM(RTRIM(@MyString));
Return @MyString
End
Go
Which you could then use as follows:
Select
dbo.CleanAndTrimString(ProductAlternateKey) As ProductAlternateKey
from DimProducts
How do I use IValidatableObject?
Just to add a couple of points:
Because the Validate()
method signature returns IEnumerable<>
, that yield return
can be used to lazily generate the results - this is beneficial if some of the validation checks are IO or CPU intensive.
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.Enable)
{
// ...
if (this.Prop1 > this.Prop2)
{
yield return new ValidationResult("Prop1 must be larger than Prop2");
}
Also, if you are using MVC ModelState
, you can convert the validation result failures to ModelState
entries as follows (this might be useful if you are doing the validation in a custom model binder):
var resultsGroupedByMembers = validationResults
.SelectMany(vr => vr.MemberNames
.Select(mn => new { MemberName = mn ?? "",
Error = vr.ErrorMessage }))
.GroupBy(x => x.MemberName);
foreach (var member in resultsGroupedByMembers)
{
ModelState.AddModelError(
member.Key,
string.Join(". ", member.Select(m => m.Error)));
}
mat-form-field must contain a MatFormFieldControl
This can also happen if you have a proper input within a mat-form-field, but it has a ngIf
on it. E.g.:
<mat-form-field>
<mat-chip-list *ngIf="!_dataLoading">
<!-- other content here -->
</mat-chip-list>
</mat-form-field>
In my case, mat-chip-list
is supposed to "appear" only after its data is loaded. However, the validation is performed and mat-form-field
complains with
mat-form-field must contain a MatFormFieldControl
To fix it, the control must be there, so I have used [hidden]
:
<mat-form-field>
<mat-chip-list [hidden]="_dataLoading">
<!-- other content here -->
</mat-chip-list>
</mat-form-field>
An alternative solution is proposed by Mosta
: move *ngIf for mat-form-field
:
<mat-form-field *ngIf="!_dataLoading">
<mat-chip-list >
<!-- other content here -->
</mat-chip-list>
</mat-form-field>
Is there a "theirs" version of "git merge -s ours"?
See Junio Hamano's widely cited answer: if you're going to discard committed content, just discard the commits, or at any rate keep it out of the main history. Why bother everyone in the future reading commit messages from commits that have nothing to offer?
But sometimes there are administrative requirements, or perhaps some other reason. For those situations where you really have to record commits that contribute nothing, you want:
(edit: wow, did I manage to get this wrong before. This one works.)
git update-ref HEAD $(
git commit-tree -m 'completely superseding with branchB content' \
-p HEAD -p branchB branchB:
)
git reset --hard
Button Listener for button in fragment in android
Simply pass view object into onButtonClicked function. getView() does not seem to work as expected inside fragment.
Try this code for your FragmentOne fragment
PS. you have redefined object view in your original FragmentOne code.
package com.example.fragmenttutorial;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
onButtonClicked(view);
return view;
}
protected void onButtonClicked(View view)
{
if(view.getId() == R.id.buttonSayHi){
Fragment fragmentTwo = new FragmentTwo();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
Difference between string and char[] types in C++
One of the difference is Null termination (\0).
In C and C++, char* or char[] will take a pointer to a single char as a parameter and will track along the memory until a 0 memory value is reached (often called the null terminator).
C++ strings can contain embedded \0 characters, know their length without counting.
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
void NullTerminatedString(string str){
int NUll_term = 3;
str[NUll_term] = '\0'; // specific character is kept as NULL in string
cout << str << endl <<endl <<endl;
}
void NullTerminatedChar(char *str){
int NUll_term = 3;
str[NUll_term] = 0; // from specific, all the character are removed
cout << str << endl;
}
int main(){
string str = "Feels Happy";
printf("string = %s\n", str.c_str());
printf("strlen = %d\n", strlen(str.c_str()));
printf("size = %d\n", str.size());
printf("sizeof = %d\n", sizeof(str)); // sizeof std::string class and compiler dependent
NullTerminatedString(str);
char str1[12] = "Feels Happy";
printf("char[] = %s\n", str1);
printf("strlen = %d\n", strlen(str1));
printf("sizeof = %d\n", sizeof(str1)); // sizeof char array
NullTerminatedChar(str1);
return 0;
}
Output:
strlen = 11
size = 11
sizeof = 32
Fee s Happy
strlen = 11
sizeof = 12
Fee
Calling a stored procedure in Oracle with IN and OUT parameters
I had the same problem. I used a trigger and in that trigger I called a procedure which computed some values into 2 OUT variables. When I tried to print the result in the trigger body, nothing showed on screen. But then I solved this problem by making 2 local variables in a function, computed what I need with them and finally, copied those variables in your OUT procedure variables. I hope it'll be useful and successful!
How to get the return value from a thread in python?
Here is the version that I created of @Kindall's answer https://stackoverflow.com/a/6894023/12900787
This version makes it so that all you have to do is input your command with arguments to create the new thread.
(I have also included a couple of tests)
this was made with python 3.8
from threading import Thread
from typing import Any
#def threader(com): # my original Version (Ignore this)
# try:
# threader = Thread(target = com)
# threader.start()
# except Exception as e:
# print(e)
# print('Could not start thread')
def test(plug, plug2, plug3):
print(f"hello {plug}")
print(f'I am the second plug : {plug2}')
print(plug3)
return 'I am the return Value!'
def test2(msg):
return f'I am from the second test: {msg}'
def test3():
print('hello world')
def NewThread(com, Returning: bool, *arguments) -> Any:
"""
Will create a new thread for a function/command.
:param com: Command to be Executed
:param arguments: Arguments to be sent to Command
:param Returning: True/False Will this command need to return anything
"""
class NewThreadWorker(Thread):
def __init__(self, group = None, target = None, name = None, args = (), kwargs = None, *,
daemon = None):
Thread.__init__(self, group, target, name, args, kwargs, daemon = daemon)
self._return = None
def run(self):
if self._target is not None:
self._return = self._target(*self._args, **self._kwargs)
def join(self):
Thread.join(self)
return self._return
ntw = NewThreadWorker(target = com, args = (*arguments,))
ntw.start()
if Returning:
return ntw.join()
if __name__ == "__main__":
# threader(test('world'))
print(NewThread(test, True, 'hi', 'test', test2('hi')))
NewThread(test3, True)
Hope that this is useful to someone :)