I don't know why but animating only the visibility
property is not working on any browser.
What you can do is animate the opacity
property in such a way that the browser doesn't have enough frames to fade in or out the text.
Example:
span {_x000D_
opacity: 0;_x000D_
animation: blinking 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes blinking {_x000D_
from,_x000D_
49.9% {_x000D_
opacity: 0;_x000D_
}_x000D_
50%,_x000D_
to {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<span>I'm blinking text</span>
_x000D_
Just use the rgba
tag as your text color. You could use opacity
, but that would affect the whole element, not just the text. Say you have a border, it would make that transparent as well.
.text
{
font-family: Garamond, serif;
font-size: 12px;
color: rgba(0, 0, 0, 0.5);
}
You can use the onload=""
HTML attribute and use JavaScript to adjust the opacity style of your element.
Leave your CSS as you proposed. Edit your HTML code to:
<body onload="document.getElementById(test).style.opacity='1'">
<div id="test">
<p>?This is a test</p>
</div>
</body>
This also works to fade-in the complete page when finished loading:
HTML:
<body onload="document.body.style.opacity='1'">
</body>
CSS:
body{
opacity: 0;
transition: opacity 2s;
-webkit-transition: opacity 2s; /* Safari */
}
Check the W3Schools website: transitions and an article for changing styles with JavaScript.
try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b
jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
jQuery('#main').animate('opacity') = '0.6';
You can use CSS 3 :before
to have a semi-transparent background and you can do this with just one container. Use something like this
<article>
Text.
</article>
Then apply some CSS
article {
position: relative;
z-index: 1;
}
article::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: .4;
z-index: -1;
background: url(path/to/your/image);
}
Sample: http://codepen.io/anon/pen/avdsi
Note: You might need to adjust the z-index
values.
box-shadow: inset 1px 2000px rgba(208, 208, 208, 0.54);
Wrap your image with a span
element with a black background.
.img-wrapper {
display: inline-block;
background: #000;
}
.item-fade {
vertical-align: top;
transition: opacity 0.3s;
-webkit-transition: opacity 0.3s;
opacity: 1;
}
.item-fade:hover {
opacity: 0.2;
}
_x000D_
<span class="img-wrapper">
<img class="item-fade" src="http://placehold.it/100x100/cf5" />
</span>
_x000D_
This will work with every browser
div {
-khtml-opacity: .50;
-moz-opacity: .50;
-ms-filter: ”alpha(opacity=50)”;
filter: alpha(opacity=50);
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
opacity: .50;
}
If you don't want transparency to affect the entire container and its children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent to achieve this. CSS Opacity That Doesn’t Affect Child Elements
Check a working demo at CSS Opacity That Doesn't Affect "Children"
This suggestion is based on pixel manipulation in canvas 2d context.
From MDN:
You can directly manipulate pixel data in canvases at the byte level
To manipulate pixels we'll use two functions here - getImageData
and putImageData
.
getImageData
usage:
var myImageData = context.getImageData(left, top, width, height);
The putImageData
syntax:
context.putImageData(myImageData, x, y);
Where context
is your canvas 2d context, and x
and y
are the position on the canvas.
So to get red green blue and alpha values, we'll do the following:
var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];
Where x
is the horizontal offset, y
is the vertical offset.
The code making image half-transparent:
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
var ImageData = c.getImageData(0,0,img.width,img.height);
for(var i=0;i<img.height;i++)
for(var j=0;j<img.width;j++)
ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';
You can make you own "shaders" - see full MDN article here
You need to set Opacity first for standards-compliant browsers, then the various versions of IE. See Example:
but this opacity code not work in ie8
.slidedownTrigger
{
cursor: pointer;
opacity: .75; /* Standards Compliant Browsers */
filter: alpha(opacity=75); /* IE 7 and Earlier */
/* Next 2 lines IE8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=75);
}
Note that I eliminated -moz as Firefox is a Standards Compliant browser and that line is no longer necessary. Also, -khtml is depreciated, so I eliminated that style as well.
Furthermore, IE's filters will not validate to w3c standards, so if you want your page to validate, separate your standards stylesheet from your IE stylesheet by using an if IE statement like below:
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="http://www.mysite.com/css/ie.css" />
<![endif]-->
If you separate the ie quirks, your site will validate just fine.
Nowadays, it is possible to do it simply with CSS property "background-blend-mode".
<div id="content">Only one div needed</div>
div#content {
background-image: url(my_image.png);
background-color: rgba(255,255,255,0.6);
background-blend-mode: lighten;
/* You may add things like width, height, background-size... */
}
It will blend the background-color (which is white, 0.6 opacity) into the background image. Learn more here (W3S).
I think rgba is the quickest and easiest!
background: rgba(225, 225, 225, .8)
A bit late for this, but this thread comes up in Google as a top result when searching for an overlay method.
You could simply use a background-blend-mode
.foo {
background-image: url(images/image1.png), url(images/image2.png);
background-color: violet;
background-blend-mode: screen multiply;
}
What this does is it takes the second image, and it blends it with the background colour by using the multiply blend mode, and then it blends the first image with the second image and the background colour by using the screen blend mode. There are 16 different blend modes that you could use to achieve any overlay.
multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity.
As mentioned by Tom, background-color: rgba(229,229,229, 0.85)
can do the trick.
Place that on the style of the parent element and child wont be affected.
Other answers deal with the technical aspect of the border-opacity issue, while I'd like to present a hack(pure CSS and HTML only). Basically create a container div, having a border div and then the content div.
<div class="container">
<div class="border-box"></div>
<div class="content-box"></div>
</div>
And then the CSS:(set content border to none, take care of positioning such that border thickness is accounted for)
.container {
width: 20vw;
height: 20vw;
position: relative;
}
.border-box {
width: 100%;
height: 100%;
border: 5px solid black;
position: absolute;
opacity: 0.5;
}
.content-box {
width: 100%;
height: 100%;
border: none;
background: green;
top: 5px;
left: 5px;
position: absolute;
}
If you have to set the opacity only to the bullet, why don't you set the alpha channel directly into the image? By the way I don't think there is a way to set the opacity to a background image via css without changing the opacity of the whole element (and its children too).
Thanks @davy-landmann for https://stackoverflow.com/a/638064/417153. That's what I was looking for! Same effect with LESS code:
@searchResultMinHeight = 200px;
.searchResult {
min-height: @searchResultMinHeight;
position: relative;
.innerTrans {
background: white;
.opacity(0.5);
min-height: @searchResultMinHeight;
}
.innerBody {
padding: 0.5em;
position: absolute;
top: 0;
}
}
some comments says that it works and some say it doesn't
It works only for your form
background not any other controls
behind
when you want to brightness or darker of background-color, you can use this css code
.brighter-span {
filter: brightness(150%);
}
.darker-span {
filter: brightness(50%);
}
Based on Alexey Ishkov's answer, but in Swift
I used an extension of the UIImage class.
Swift 2:
UIImage Extension:
extension UIImage {
func imageWithAlpha(alpha: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
drawAtPoint(CGPointZero, blendMode: .Normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
To use:
let image = UIImage(named: "my_image")
let transparentImage = image.imageWithAlpha(0.5)
Swift 3/4/5:
Note that this implementation returns an optional UIImage. This is because in Swift 3 UIGraphicsGetImageFromCurrentImageContext
now returns an optional. This value could be nil if the context is nil or what not created with UIGraphicsBeginImageContext
.
UIImage Extension:
extension UIImage {
func image(alpha: CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: .zero, blendMode: .normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
To use:
let image = UIImage(named: "my_image")
let transparentImage = image?.image(alpha: 0.5)
background: rgba(0,0,0,.5);
you can use rgba for opacity, will only work in ie9+ and better browsers
I guess you may have already found the answer, but if not (and for other developers), you can do it like this:
btnMybutton.getBackground().setAlpha(45);
Here I have set the opacity to 45. You can basically set it from anything between 0(fully transparent) to 255 (completely opaque)
Make the background image transparent/semi-transparent. If it's a solid coloured background just create a 1px by 1px image in fireworks or whatever and adjust its opacity...
I agree with yossi's example, stretch the image to fit the div but in a slightly different way (without background-image as this is a little inflexible in css 2.1). Show full image:
<div id="yourdiv">
<img id="theimage" src="image.jpg" alt="" />
</div>
#yourdiv img {
width:100%;
/*height will be automatic to remain aspect ratio*/
}
Show part of the image using background-position:
#yourdiv
{
background-image: url(image.jpg);
background-repeat: no-repeat;
background-position: 10px 25px;
}
Same as the first part of (1) the image will scale to the div so bigger or smaller will both work
Same as yossi's.
If you can't use rgba
due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
position: absolute; z-index: 1;_x000D_
top: 0; left: 0; width: 100%; height: 100%;_x000D_
background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
<div class="box">_x000D_
<div class="back"></div>_x000D_
<div class="text">_x000D_
Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
The opacity
style affects the whole element and everything within it. The correct answer to this is to use an rgba background colour instead.
The CSS is fairly simple:
.myelement {
background: rgba(200, 54, 54, 0.5);
}
...where the first three numbers are the red, green and blue values for your background colour, and the fourth is the 'alpha' channel value, which works the same way as the opacity
value.
See this page for more info: http://css-tricks.com/rgba-browser-support/
The down-side, is that this doesn't work in IE8 or lower. The page I linked above also lists a few other browsers it doesn't work in, but they're all very old by now; all browsers in current use except IE6/7/8 will work with rgba colours.
The good news is that you can force IE to work with this as well, using a hack called CSS3Pie. CSS3Pie adds a number of modern CSS3 features to older versions of IE, including rgba background colours.
To use CSS3Pie for backgrounds, you need to add a specific -pie-background
declaration to your CSS, as well as the PIE behavior
style, so your stylesheet would end up looking like this:
.myelement {
background: rgba(200, 54, 54, 0.5);
-pie-background: rgba(200, 54, 54, 0.5);
behavior: url(PIE.htc);
}
Hope that helps.
[EDIT]
For what it's worth, as others have mentioned, you can use IE's filter
style, with the gradient
keyword. The CSS3Pie solution does actually use this same technique behind the scenes, but removes the need for you to mess around directly with IE's filters, so your stylesheets are much cleaner. (it also adds a whole bunch of other nice features too, but that's not relevant to this discussion)
It's better to use a semi-transparent .png
.
Just open Photoshop, create a 2x2
pixel image (picking 1x1
can cause an Internet Explorer bug!), fill it with a green color and set the opacity in "Layers tab" to 60%. Then save it and make it a background image:
<p style="background: url(green.png);">any text</p>
It works cool, of course, except in lovely Internet Explorer 6. There are better fixes available, but here's a quick hack:
p {
_filter: expression((runtimeStyle.backgroundImage != 'none') ? runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src='+currentStyle.backgroundImage.split('\"')[1]+', sizingMethod=scale)' : runtimeStyle.filter,runtimeStyle.backgroundImage = 'none');
}
Some things seem appeared to have changed in batch scripts on Windows 8, and the solution above by DGG now causes the Command Prompt to crash.
The following solution worked for me:
@echo off
set /a n=0
:repeat
set /a n+=1
echo 192.168.1.%n%
ping -n 1 -w 500 192.168.1.%n% | FIND /i "Reply">>ipaddresses.txt
if %n% lss 254 goto repeat
type ipaddresses.txt
For having hover effect you can simply try this code
import React from "react";
import "./styles.css";
export default function App() {
function MouseOver(event) {
event.target.style.background = 'red';
}
function MouseOut(event){
event.target.style.background="";
}
return (
<div className="App">
<button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
</div>
);
}
Or if you want to handle this situation using useState() hook then you can try this piece of code
import React from "react";
import "./styles.css";
export default function App() {
let [over,setOver]=React.useState(false);
let buttonstyle={
backgroundColor:''
}
if(over){
buttonstyle.backgroundColor="green";
}
else{
buttonstyle.backgroundColor='';
}
return (
<div className="App">
<button style={buttonstyle}
onMouseOver={()=>setOver(true)}
onMouseOut={()=>setOver(false)}
>Hover over me!</button>
</div>
);
}
Both of the above code will work for hover effect but first procedure is easier to write and understand
Callable
interface declares call()
method and you need to provide generics as type of Object call() should return -
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
Runnable
on the other hand is interface that declares run()
method that is called when you create a Thread with the runnable and call start() on it. You can also directly call run() but that just executes the run() method is same thread.
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
To summarize few notable Difference are
Runnable
object does not return a result whereas a Callable
object returns a result.Runnable
object cannot throw a checked exception wheras a Callable
object can throw an
exception.Runnable
interface has been around since Java 1.0 whereas Callable
was only introduced
in Java 1.5.Few similarities include
Methods in ExecutorService interface are
<T> Future<T> submit(Callable<T> task);
Future<?> submit(Runnable task);
<T> Future<T> submit(Runnable task, T result);
There's actually quite a bit of useful information added to debug allocations. This table is more complete:
http://www.nobugs.org/developer/win32/debug_crt_heap.html#table
Address Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments 0x00320FD8 -40 0x01090009 0x01090009 0x01090009 0x0109005A Win32 heap info 0x00320FDC -36 0x01090009 0x00180700 0x01090009 0x00180400 Win32 heap info 0x00320FE0 -32 0xBAADF00D 0x00320798 0xDDDDDDDD 0x00320448 Ptr to next CRT heap block (allocated earlier in time) 0x00320FE4 -28 0xBAADF00D 0x00000000 0xDDDDDDDD 0x00320448 Ptr to prev CRT heap block (allocated later in time) 0x00320FE8 -24 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Filename of malloc() call 0x00320FEC -20 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Line number of malloc() call 0x00320FF0 -16 0xBAADF00D 0x00000008 0xDDDDDDDD 0xFEEEFEEE Number of bytes to malloc() 0x00320FF4 -12 0xBAADF00D 0x00000001 0xDDDDDDDD 0xFEEEFEEE Type (0=Freed, 1=Normal, 2=CRT use, etc) 0x00320FF8 -8 0xBAADF00D 0x00000031 0xDDDDDDDD 0xFEEEFEEE Request #, increases from 0 0x00320FFC -4 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x00321000 +0 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321004 +4 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321008 +8 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x0032100C +12 0xBAADF00D 0xBAADF00D 0xDDDDDDDD 0xFEEEFEEE Win32 heap allocations are rounded up to 16 bytes 0x00321010 +16 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321014 +20 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321018 +24 0x00000010 0x00000010 0x00000010 0xFEEEFEEE Win32 heap bookkeeping 0x0032101C +28 0x00000000 0x00000000 0x00000000 0xFEEEFEEE Win32 heap bookkeeping 0x00321020 +32 0x00090051 0x00090051 0x00090051 0xFEEEFEEE Win32 heap bookkeeping 0x00321024 +36 0xFEEE0400 0xFEEE0400 0xFEEE0400 0xFEEEFEEE Win32 heap bookkeeping 0x00321028 +40 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping 0x0032102C +44 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping
On Chrome's latest update (38.0.2125.104 m at the moment), Google added the option to know whether the files loaded to the website were newly downloaded from the server - or read from the local cache.
When an error like yours "hits" the console - you know the files were just downloaded from the server and not read from the local cache. You can recreate this error by clicking Ctrl + F5 (refresh and erase cache).
It fits your description where Firebug (or equivalents) doesn't fire any errors to the console - whilst Chrome does.
So, the bottom line is - your're just fine and you can ignore this error - it's merely an indicator.
Use int(@array)
as it threats the argument as scalar.
Below code would work:
int a=-32768;
String a1=Integer.toHexString(a);
int parsedResult=(int)Long.parseLong(a1,16);
System.out.println("Parsed Value is " +parsedResult);
I got this bug when I renamed the class. Then I solved it just by following the below steps
Product
-> Clean
Restart
the XcodeYou can use env package to manage your environment variables per project:
.env
file under the project directory and put all of your
variables there.require('dotenv').config();
Done. Now you can access your environment variables with process.env.ENV_NAME
.
I noticed that the answers here are using: device-width
, device-height
, min-device-width
, min-device-height
, max-device-width
, max-device-height
.
Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width
, max-width
and so on. For extra assurance, you can set the min and max to the same px amount.
For example:
iPhone X
@media only screen
and (width : 375px)
and (height : 635px)
and (orientation : portrait)
and (-webkit-device-pixel-ratio : 3) { }
You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight
. Here are a few useful links on this subject:
If you insist, here is some horrible inspect-based solution.
import inspect, re
def varname(p):
for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
if m:
return m.group(1)
if __name__ == '__main__':
spam = 42
print varname(spam)
I hope it will inspire you to reevaluate the problem you have and look for another approach.
You can use set operations on the keys:
diff = set(dictb.keys()) - set(dicta.keys())
Here is a class to find all the possibilities: what was added, what was removed, which key-value pairs are the same, and which key-value pairs are changed.
class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
"""
def __init__(self, current_dict, past_dict):
self.current_dict, self.past_dict = current_dict, past_dict
self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
self.intersect = self.set_current.intersection(self.set_past)
def added(self):
return self.set_current - self.intersect
def removed(self):
return self.set_past - self.intersect
def changed(self):
return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
def unchanged(self):
return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])
Here is some sample output:
>>> a = {'a': 1, 'b': 1, 'c': 0}
>>> b = {'a': 1, 'b': 2, 'd': 0}
>>> d = DictDiffer(b, a)
>>> print "Added:", d.added()
Added: set(['d'])
>>> print "Removed:", d.removed()
Removed: set(['c'])
>>> print "Changed:", d.changed()
Changed: set(['b'])
>>> print "Unchanged:", d.unchanged()
Unchanged: set(['a'])
Available as a github repo: https://github.com/hughdbrown/dictdiffer
I had the same issue and solved it using this code.
MyFragment fragment = (MyFragment) thisActivity.getFragmentManager().findFragmentById(R.id.container);
Just replace the name MyFragment with the name of your fragment and add the id of your fragment container.
If you really just want a random value from the available key range, use random.choice
on the dictionary's values (converted to list form, if Python 3).
>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))
The future is here! The proposals are closer to completion, no more ActiveX or flash or java. Now we can use:
You could use the Drag/Drop to get the file into the browser, or a simple upload control. Once the user has selected a file, you can read it w/ Javascript: http://www.html5rocks.com/en/tutorials/file/dndfiles/
If by all permissions you mean 777
Navigate to folder and
chmod -R 777 .
Quite simple:
$input = array(
array(
'tag_name' => 'google'
),
array(
'tag_name' => 'technology'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
and new in php v5.5.0, array_column
:
echo implode(', ', array_column($input, 'tag_name'));
You can disable constraints in Oracle but not indexes. There's a command to make an index ununsable but you have to rebuild the index anyway, so I'd probably just write a script to drop and rebuild the indexes. You can use the user_indexes and user_ind_columns to get all the indexes for a schema or use dbms_metadata:
select dbms_metadata.get_ddl('INDEX', u.index_name) from user_indexes u;
If there is no error in starting the Postgres service, follow these steps
pg_lsclusters
will list all the Postgres clusters running on your deviceeg:
Ver Cluster Port Status Owner Data directory Log file
9.6 main 5432 online postgres /var/lib/postgresql/9.6/main /var/log/postgresql/postgresql-9.6-main.log
most probably the status will be down in your case. If not restart PostgreSQL service
#format is pg_ctlcluster <version> <cluster> <action>
sudo pg_ctlcluster 9.6 main start
#restart PostgreSQL service
sudo service postgresql restart
If restarting pg_lsclusters was not successful, it will throw an error.
My error was(You can see the errors in the logs /var/log/postgresql/postgresql-9.6-main.log
)
FATAL: could not access private key file "/etc/ssl/private/ssl-cert-snakeoil.key": Permission denied
Try adding `postgres` user to the group `ssl-cert`
Make sure that postgres
is the owner of /var/lib/postgresql/version_no/main
eg: sudo chown postgres -R /var/lib/postgresql/9.6/main/
It happened to me and it turned out that I removed erroneously the Postgres user from "ssl-cert" group. Run the below code to fix the user group issue and for fixing the permissions
#set user to group back with
sudo gpasswd -a postgres ssl-cert
# Fixed ownership and mode
sudo chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
sudo chmod 740 /etc/ssl/private/ssl-cert-snakeoil.key
# now postgresql starts! (and install command doesn't fail anymore)
sudo service postgresql restart
Have you looked at the EXIF data of the images? It may know the orientation of the camera when the picture was taken.
Try this:
@PropertySource("classpath:${spring.profiles.active:production}_file.properties")
A slight modification to one of the previous ip route ...
solutions, which eliminates the need for a grep:
ip route get 8.8.8.8 | sed -n 's|^.*src \(.*\)$|\1|gp'
I personally like the following solution the most:
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
... then before you do request getting the error, do the following
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
Found this after consulting Luke's Solution
I usually add to index changes I don't want to stash and then stash with --keep-index
option.
git add app/controllers/cart_controller.php
git stash --keep-index
git reset
Last step is optional, but usually you want it. It removes changes from index.
Warning
As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index
just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.
The canonical way to get the current location object is window.location
(see this MSDN page from 1996 and the W3C draft from 2006).
Compare this to document.location
, which originally only returned the current URL as a string (see this page on MSDN). Probably to avoid confusion, document.location
was replaced with document.URL
(see here on MSDN), which is also part of DOM Level 1.
As far as I know, all modern browsers map document.location
to window.location
, but I still prefer window.location
as that's what I've used since I wrote my first DHTML.
Here is My Code
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
if (gvDetail.Rows.Count > 0)
{
System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
gvDetail.RenderControl(htmlWrite1);
gvDetail.AllowPaging = false;
Search();
sh.ExportToExcel(gvDetail, "Report");
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
The problem is that you're reading nextLine()
on the while loop and THEN reading it to a variable. Not only are you getting every 2nd line printed out you're opening yourself to the exception being thrown. An example:
File:
Hello,
Blah blah blah,
Sincerely,
CapnStank
PS. Something something
On first iteration through the loop. The check on while will consume the "Hello," as not equal to null. Inside the loop body you'll see Blah blah blah,
printed to the System.
The process will repeat with Sincerely, being consumed and Capnstank printing out.
Finally the while will consume the "PS" line while the String line = fileReader.nextLine()
retreives an exception from the file because there's nothing further to read.
To resolve the issue:
String line = fileReader.nextLine();
while (line != null) {
System.out.println(line);
line = fileReader.nextLine();
}
The disabled
attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled
) and check for that attribute when you handle the click event.
In my case, it happened with a p-radioButton. The problem was that I was using the name attribute (which wasn't needed) alongside the formControlName attribute like this:
<p-radioButton formControlName="isApplicant" name="isapplicant" value="T" label="Yes"></p-radioButton>
<p-radioButton formControlName="isApplicant" name="isapplicant" value="T" label="No"></p-radioButton>
I also had the initial value "T" bound to the isApplicant form control like this:
isApplicant: ["T"]
I fixed the problem by removing the name attributes in the radio buttons. Also, because the 2 radio buttons have the same value (T) which is wrong in my case, simply changing one of then to another value (say F) also fixed the issue.
I really liked @gerard answer which is actually deserves to be the correct answer here. I made some improvements:
Here's the code:
'use strict'
const fs = require('fs'),
util = require('util'),
stream = require('stream'),
es = require('event-stream'),
parse = require("csv-parse"),
iconv = require('iconv-lite');
class CSVReader {
constructor(filename, batchSize, columns) {
this.reader = fs.createReadStream(filename).pipe(iconv.decodeStream('utf8'))
this.batchSize = batchSize || 1000
this.lineNumber = 0
this.data = []
this.parseOptions = {delimiter: '\t', columns: true, escape: '/', relax: true}
}
read(callback) {
this.reader
.pipe(es.split())
.pipe(es.mapSync(line => {
++this.lineNumber
parse(line, this.parseOptions, (err, d) => {
this.data.push(d[0])
})
if (this.lineNumber % this.batchSize === 0) {
callback(this.data)
}
})
.on('error', function(){
console.log('Error while reading file.')
})
.on('end', function(){
console.log('Read entirefile.')
}))
}
continue () {
this.data = []
this.reader.resume()
}
}
module.exports = CSVReader
So basically, here is how you will use it:
let reader = CSVReader('path_to_file.csv')
reader.read(() => reader.continue())
I tested this with a 35GB CSV file and it worked for me and that's why I chose to build it on @gerard's answer, feedbacks are welcomed.
You can close files not csv.writer object, it should be:
f = open(fileName, "wb")
writer = csv.writer(f)
String[] entries = "first*second*third".split("*");
writer.writerows(entries)
f.close()
You simply can find a matrix dimension by using Numpy:
import numpy as np
x = np.arange(24).reshape((6, 4))
x.ndim
output will be:
2
It means this matrix is a 2 dimensional matrix.
x.shape
Will show you the size of each dimension. The shape for x is equal to:
(6, 4)
You can run brew link openssl
to link it into /usr/local
, if you don't mind the potential problem highlighted in the warning message. Otherwise, you can add the openssl bin directory to your path:
export PATH=$(brew --prefix openssl)/bin:$PATH
I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:
foreach (var mc in list.Where(x => x.Name == "height"))
mc.Value = 30;
Use find
on the command line:
find /my/directory -name '*.js'
look at yt:statistics
tag.
It provides viewCount
, videoWatchCount
, favoriteCount
etc.
You can temporarily increase the cache size and do one dummy select and then reset the cache size back to 1. So for example
ALTER SEQUENCE mysequence INCREMENT BY 100;
select mysequence.nextval from dual;
ALTER SEQUENCE mysequence INCREMENT BY 1;
you don't need this code
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
?>
Instead, you can check whether the form is submitted by checking the post variables using isset
.
here goes the code
if(isset($_POST)){
echo "hello ".$_POST['studentname'];
}
click here for the php manual for isset
A bit old, but oh well...
The most up-voted solution from @houbysoft will not work as that will exclude any line with "gloom" in it, even if it has "loom". According to OP's expectations, we need to include lines with "loom", even if they also have "gloom" in them. This line needs to be in the output "Arty is slooming in a gloomy day.", but this will be excluded by a chained grep like
grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'
Instead, the egrep regex example of Bentoy13 works better
egrep '(^|[^g])loom' ~/projects/**/trunk/src/**/*.@(h|cpp)
as it will include any line with "loom" in it, regardless of whether or not it has "gloom". On the other hand, if it only has gloom, it will not include it, which is precisely the behaviour OP wants.
for entry in "/home/loc/etc/"/*
do
if [ -s /home/loc/etc/$entry ]
then
echo "$entry File is available"
else
echo "$entry File is not available"
fi
done
Hope it helps
There is an important difference that no answer has mentioned yet.
From this:
new Array(2).length // 2
new Array(2)[0] === undefined // true
new Array(2)[1] === undefined // true
You might think the new Array(2)
is equivalent to [undefined, undefined]
, but it's NOT!
Let's try with map()
:
[undefined, undefined].map(e => 1) // [1, 1]
new Array(2).map(e => 1) // "(2) [undefined × 2]" in Chrome
See? The semantics are totally different! So why is that?
According to ES6 Spec 22.1.1.2, the job of Array(len)
is just creating a new array whose property length
is set to the argument len
and that's it, meaning there isn't any real element inside this newly created array.
Function map()
, according to spec 22.1.3.15 would firstly check HasProperty
then call the callback, but it turns out that:
new Array(2).hasOwnProperty(0) // false
[undefined, undefined].hasOwnProperty(0) // true
And that's why you can not expect any iterating functions working as usual on arrays created from new Array(len)
.
BTW, Safari and Firefox have a much better "printing" to this situation:
// Safari
new Array(2) // [](2)
new Array(2).map(e => 1) // [](2)
[undefined, undefined] // [undefined, undefined] (2)
// Firefox
new Array(2) // Array [ <2 empty slots> ]
new Array(2).map(e => 1) // Array [ <2 empty slots> ]
[undefined, undefined] // Array [ undefined, undefined ]
I have already submitted an issue to Chromium and ask them to fix this confusing printing: https://bugs.chromium.org/p/chromium/issues/detail?id=732021
UPDATE: It's already fixed. Chrome now printed as:
new Array(2) // (2) [empty × 2]
A faster / alternative way to change the height and/or width of a UIView
is by setting its width/height through frame.size
:
let neededHeight = UIScreen.main.bounds.height * 0.2
yourView.frame.size.height = neededHeight
I also had same error. In my case some of the resources were in drawable-v21 only. Copy those resources to drawable folder also. This solved the issue for me.
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
This is the main problem.
There are a few options:
I'm sure there are others out there that you could use too...
What if - the Bot does not find any form
at all?
3 examples:
<noscript> <p class="error"> ERROR: The form could not be loaded. Please enable JavaScript in your browser to fully enjoy our services. </p> </noscript>
Create a form.html
and place your form
inside a <div id="formContainer">
element.
Inside the page where you need to call that form use an empty <div id="dynamicForm"></div>
and this jQuery: $("#dynamicForm").load("form.html #formContainer");
// THE FORM
var $form = $("<form/>", {
appendTo : $("#formContainer"),
class : "myForm",
submit : AJAXSubmitForm
});
// EMAIL INPUT
$("<input/>",{
name : "Email", // Needed for serialization
placeholder : "Your Email",
appendTo : $form,
on : { // Yes, the jQuery's on() Method
input : function() {
console.log( this.value );
}
}
});
// MESSAGE TEXTAREA
$("<textarea/>",{
name : "Message", // Needed for serialization
placeholder : "Your message",
appendTo : $form
});
// SUBMIT BUTTON
$("<input/>",{
type : "submit",
value : "Send",
name : "submit",
appendTo : $form
});
function AJAXSubmitForm(event) {
event.preventDefault(); // Prevent Default Form Submission
// do AJAX instead:
var serializedData = $(this).serialize();
alert( serializedData );
$.ajax({
url: '/mail.php',
type: "POST",
data: serializedData,
success: function (data) {
// log the data sent back from PHP
console.log( data );
}
});
}
_x000D_
.myForm input,
.myForm textarea{
font: 14px/1 sans-serif;
box-sizing: border-box;
display:block;
width:100%;
padding: 8px;
margin-bottom:12px;
}
.myForm textarea{
resize: vertical;
min-height: 120px;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formContainer"></div>
_x000D_
<input type="text" name="email" id="email" placeholder="Your email" autocomplete="nope" tabindex="-1"
They wll be happy to enter some value such as
`[email protected]`
input[name=email]{ /* bait input */ /* do not use display:none or visibility:hidden that will not fool the bot*/ position:absolute; left:-2000px; }
$_POST["email"]
should be empty (without any value)! Otherwise don't submit the form.<input name="sender" type="text" placeholder="Your email">
after (!) the "bot-bait" input for the actual user Email address.Acknowledgments:
Developer.Mozilla - Turning off form autocompletition
StackOverflow - Ignore Tabindex
To remove the scrollbar add the following CSS:
select[multiple] {
overflow-y: auto;
}
Here's a snippet:
select[multiple] {_x000D_
overflow-y: auto;_x000D_
}
_x000D_
<select>_x000D_
<option value="1">One</option>_x000D_
<option value="2">Two</option>_x000D_
<option value="3">Three</option>_x000D_
</select>_x000D_
_x000D_
<select multiple size="3">_x000D_
<option value="1">One</option>_x000D_
<option value="2">Two</option>_x000D_
<option value="3">Three</option>_x000D_
</select>
_x000D_
Do you have control over running the transformation? If so, you could pass in the current date to the XSL and use $current-date from inside your XSL. Below is how you declare the incoming parameter, but with knowing how you are running the transformation, I can't tell you how to pass in the value.
<xsl:param name="current-date" />
For example, from the bash script, use:
xsltproc --stringparam current-date `date +%Y-%m-%d` -o output.html path-to.xsl path-to.xml
Then, in the xsl you can use:
<xsl:value-of select="$current-date"/>
You wouldn't really want to do this given the existing Instr/InstrRev functions but there are times when it is handy to use EVALUATE to return the result of Excel worksheet functions within VBA
Option Explicit
Public Sub test()
Debug.Print ContainsSubString("bc", "abc,d")
End Sub
Public Function ContainsSubString(ByVal substring As String, ByVal testString As String) As Boolean
'substring = string to test for; testString = string to search
ContainsSubString = Evaluate("=ISNUMBER(FIND(" & Chr$(34) & substring & Chr$(34) & ", " & Chr$(34) & testString & Chr$(34) & "))")
End Function
At page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally, JSP include directive is used to include header banners and footers.
Syntax for include a jsp file:
<%@ include file="relative url">
Example
<%@include file="page_name.jsp" %>
because u have to have jquery set-up to enable the toggling functionality of the toggler button. So, all u have to do is to add bootstrap.bundle.js before bootstrap.css:
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
Assuming your project root is the current working directory, this should work:
// require built-in path module
path = require('path');
// require file relative to current working directory
config = require( path.resolve('.','config.js') );
You can use the standard HTTP_PROXY
environment var. Simply set it to the URL of your proxy. Many operating systems already set this variable for you.
Just export the variable, then you don't have to type it all the time.
export HTTP_PROXY="http://johndoeproxy.cu:8080"
Then you can do composer update
normally.
very simple
<img onload="loaded(this, 'success')" onerror="error(this,
'error')" src="someurl" alt="" />
function loaded(_this, status){
console.log(_this, status)
// do your work in load
}
function error(_this, status){
console.log(_this, status)
// do your work in error
}
Try This
final Button button = (Button) findViewById(R.id.button_id);
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
button.setBackgroundColor(Color.RED);
} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
button.setBackgroundColor(Color.BLUE);
}
return false;
}
});
This is a likely a linker error.
Add the -lm
switch to specify that you want to link against the standard C math library (libm
) which has the definition for those functions (the header just has the declaration for them - worth looking up the difference.)
Well, if you study the structure of how the application life-cycle works,here , then you'll come to know that onPause()
is called when another activity gains focus, and onStop()
is called when the activity is no longer visible.
From what I have learned yet, you can call finish()
only from the activity which is active and/or has the focus. If you're calling finish()
from the onPause()
method that means you're calling it when the activity is no longer active. thus an exception is thrown.
When you're calling finish()
from onStop()
then the activity is being sent to background, thus will no longer be visible, then this exception.
When you press the back
button, onStop()
is called.
Most probably, Android will automatically do for you what you are currently wanting to do.
If you would like to remove by a list of IDs this works great.
db.CollectionName.remove({
"_id": {
$in: [
ObjectId("0930292929292929292929"),
ObjectId("0920292929292929292929")
]
}
})
I tested the statement:
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;
It did not work out for me.
Instead
$cfg['Servers'][$i]['AllowNoPassword'] = true;
worked.
Thanks!
The Sass .sass
file is visually different from .scss
file, e.g.
$color: red
=my-border($color)
border: 1px solid $color
body
background: $color
+my-border(green)
$color: red;
@mixin my-border($color) {
border: 1px solid $color;
}
body {
background: $color;
@include my-border(green);
}
Any valid CSS document can be converted to Sassy CSS (SCSS) simply by changing the extension from .css
to .scss
.
Try:
string output = YourString.replaceAll("\\s","")
s - indicates space character (tab characters etc)
Do checks like that in a controller function. Your HTML should be easy-to-read markup without logic.
Controller:
angular.module("myApp")
.controller("myController",function(){
var self = this;
self.select = { /* ... */ };
self.showFoo = function() {
//Checks if self.select.name contains the character '?'
return self.select.name.indexOf('?') != -1;
}
});
Page example:
<div ng-app="myApp" ng-controller="myController as vm">
<p ng-show="vm.showFoo()">Bar</p>
</div>
I have the same problem....
I change my project name and i have this problem...my solution was the checking project refences and use /
in my web.xml (instead of /*
)
git stash drop
takes no parameter - which drops the top stash - or a stash reference which looks like: stash@{n}
which n
nominates which stash to drop. You can't pass a commit id to git stash drop
.
git stash drop # drop top hash, stash@{0}
git stash drop stash@{n} # drop specific stash - see git stash list
Dropping a stash will change the stash@{n}
designations of all stashes further down the stack.
I'm not sure why you think need to drop a stash because if you are using stash create
a stash entry isn't created for your "stash" so there isn't anything to drop.
Check your node version node -v and your npm version npm -v Then To update your npm, type this into your terminal : sudo npm install npm@latest -g
N.B: Debian Based OS{ubuntu or Linux mint}
You can use DataTable.Select
:
var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";
// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);
Or you can use DataView
:
ds.Tables[0].DefaultView.RowFilter = strExpr;
UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:
var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);
<div style="display:none;">CREDITS_HERE</div>
File from = new File(Environment.getExternalStorageDirectory().getAbsolutePath().getAbsolutePath()+"/kaic1/imagem.jpg");
File to = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kaic2/imagem.jpg");
from.renameTo(to);
You can use the parent selector reference &
, it will be replaced by the parent selector after compilation:
For your example:
.container {
background:red;
&.desc{
background:blue;
}
}
/* compiles to: */
.container {
background: red;
}
.container.desc {
background: blue;
}
The &
will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the &
.
This notation is most often used to write pseudo-elements and -classes:
.element{
&:hover{ ... }
&:nth-child(1){ ... }
}
However, you can place the &
at virtually any position you like*, so the following is possible too:
.container {
background:red;
#id &{
background:blue;
}
}
/* compiles to: */
.container {
background: red;
}
#id .container {
background: blue;
}
However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.
*: No other characters than whitespaces are allowed in front of the &
. So you cannot do a direct concatenation of selector
+&
- #id&
would throw an error.
OnClientClick="SomeMethod()"
event of that BUTTON, it return by default "true
" so after that function it do postback
for solution use
//use this code in BUTTON ==> OnClientClick="return SomeMethod();"
//and your function like this
<script type="text/javascript">
function SomeMethod(){
// put your code here
return false;
}
</script>
Best way in python is use this link.
A small Python 3.5+ library for decoding ASP.NET viewstate.
First install that: pip install viewstate
>>> from viewstate import ViewState
>>> base64_encoded_viewstate = '/wEPBQVhYmNkZQ9nAgE='
>>> vs = ViewState(base64_encoded_viewstate)
>>> vs.decode()
('abcde', (True, 1))
Using .NET 4.5 trying to perform form POST file upload. Tried most of the methods above but to no avail. Found the solution here https://www.c-sharpcorner.com/article/upload-any-file-using-http-post-multipart-form-data
But I am not not keen as I do not understand why we still need to deal with such low level programming in these common usages (should be handled nicely by framework)
Using query comprehension syntax you could achieve the orderby as follows:
var uniqueColors = (from dbo in database.MainTable
where dbo.Property
orderby dbo.Color.Name ascending
select dbo.Color.Name).Distinct();
Some receivers expect EOL sequence, which is typically two characters \r\n
, so try in your code replace the line
unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};
with
unsigned char cmd[] = "INIT\r\n";
BTW, the above way is probably more efficient. There is no need to quote every character.
Ran into another instance of this problem, and in searching for a solution to it came here. My issue was that I was doing the children, and lazy loading of the components as well to optimize things a bit. In short if you are lazy loading the parent module. Main thing was my using '/:id' in the route, and it's complaints about '/' being a part of it. Not the exact problem here, but it applies.
App-routing from parent
...
const routes: Routes = [
{
path: '',
children: [
{
path: 'pathOne',
loadChildren: 'app/views/$MODULE_PATH.module#PathOneModule'
},
{
path: 'pathTwo',
loadChildren: 'app/views/$MODULE_PATH.module#PathTwoModule'
},
...
Child routes lazy loaded
...
const routes: Routes = [
{
path: '',
children: [
{
path: '',
component: OverviewComponent
},
{
path: ':id',
component: DetailedComponent
},
]
}
];
...
You can substitute in HTML entitiy:
$FileName = preg_replace("/'/", "\'", $UserInput);
You can use DecimalFormat
. One way to use it:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Another one is to construct it using the #.##
format.
I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.
Also, a good reason to use a controller vs. link function (since they both have access to the scope, element, and attrs) is because you can pass in any available service or dependency into a controller (and in any order), whereas you cannot do that with the link function. Notice the different signatures:
controller: function($scope, $exceptionHandler, $attr, $element, $parse, $myOtherService, someCrazyDependency) {...
vs.
link: function(scope, element, attrs) {... //no services allowed
Although using File.separator to reference a file name is overkill (for those who imagine far off lands, I imagine their JVM implementation would replace a /
with a :
just like the windows jvm replaces it with a \
).
However, sometimes you are getting the file reference, not creating it, and you need to parse it, and to be able to do that, you need to know the separator on the platform. File.separator helps you do that.
Simply mark any method you need to fake as virtual
(and not private). Then you will be able to create a fake that can override the method.
If you use new Mock<Type>
and you don't have a parameterless constructor then you can pass the parameters as the arguments of the above call as it takes a type of param Objects
Unless the writer of the executable has specifically provided a way for you to display a list of all the command line switches that it offers, then there is no way of doing this.
As Marcin suggests, the typical switches for displaying all of the options are either /?
or /help
(some applications might prefer the Unix-style syntax, -?
and -help
, respectively). But those are just a common convention.
If those don't work, you're out of luck. You'll need to check the documentation for the application, or perhaps try decompiling the executable (if you know what you're looking for).
Another option:
$("#<%=dropDownId.ClientID%>").children("option:selected").val();
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
ticker
on itYou need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:
"temp" environment variable setting - then it would be:
%temp%\Temporary ASP.NET Files
Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:
c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files
There are also cases where the temp folder can be set via config for a machine or site specific using this:
<compilation tempDirectory="d:\MyTempPlace" />
I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.
Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.
Thank you for your help. At last I could draw a line on the map. This is how I done it:
/** Called when the activity is first created. */
private List<Overlay> mapOverlays;
private Projection projection;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linearLayout = (LinearLayout) findViewById(R.id.zoomview);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
mapOverlays.add(new MyOverlay());
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
class MyOverlay extends Overlay{
public MyOverlay(){
}
public void draw(Canvas canvas, MapView mapv, boolean shadow){
super.draw(canvas, mapv, shadow);
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(2);
GeoPoint gP1 = new GeoPoint(19240000,-99120000);
GeoPoint gP2 = new GeoPoint(37423157, -122085008);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
Projection projection=mapv.getProjection();
projection.toPixels(gP1, p1);
projection.toPixels(gP2, p2);
path.moveTo(p2.x, p2.y);
path.lineTo(p1.x,p1.y);
canvas.drawPath(path, mPaint);
}
URL url = new File("src/main/java/ua/adeptius/goit/sample.fxml").toURI().toURL();
Parent root = FXMLLoader.load(url);
That is helped for me because
getClass.getResource("path")
always returns me null;
This is a variation to the answer provided by @Metrics and edited by @Max Ghenis...
l <- sapply(iris, function(x) is.factor(x))
m <- iris[,l]
n <- sapply( m, function(x) { y <- summary(x)/length(x)
len <- length(y[y<0.005 | y>0.995])
cbind(len,t(y))} )
drop_cols_df <- data.frame(var = names(l[l]),
status = ifelse(as.vector(t(n[1,]))==0,"NODROP","DROP" ),
level1 = as.vector(t(n[2,])),
level2 = as.vector(t(n[3,])))
Here, after identifying factor variables, the second sapply
computes what percent of records belong to each level / category of the variable. Then it identifies number of levels over 99.5% or below 0.5% incidence rate (my arbitrary thresholds).
It then goes on to return the number of valid levels and the incidence rate of each level in each categorical variable.
Variables with zero levels crossing the thresholds should not be dropped, while the other should be dropped from the linear model.
The last data frame makes viewing the results easy. It's hard coded for this data set since all factor variables are binomial. This data frame can be made generic easily enough.
A combined solution from different answers is:
new Handler().postDelayed(() -> {
myViewPager.setCurrentItem(position, true);
myTabLayout.setScrollPosition(position, 0f, true);
},
100);
The recommended way is to create your own component, such as MyAppText. MyAppText would be a simple component that renders a Text component using your universal style and can pass through other props, etc.
https://facebook.github.io/react-native/docs/text.html#limited-style-inheritance
I just use tops:
find . -name '*.[c|cc|cp|cpp|m|mm|h]' -print0 | xargs -0 tops -verbose replace "verify_noerr(<b args>)" with "__Verify_noErr(<args>)" \
replace "check(<b args>)" with "__Check(<args>)"
In Python, you can use urllib2
(http://docs.python.org/2/library/urllib2.html) to do all of that work for you.
Simply enough:
import urllib2
f = urllib2.urlopen(url)
print f.read()
Will print the received HTTP response.
To pass GET/POST parameters the urllib.urlencode()
function can be used. For more information, you can refer to the Official Urllib2 Tutorial
search()
is a String method.
You are executing the attr
function on every <li>
element.
You need to invoke each
and use the this
reference within.
Example:
$('li').each(function() {
var isFound = $(this).attr('title').search(/string/i);
//do something based on isFound...
});
Even after 9 years of the original post, this helped me.
If you are receiving these types of errors without any clue, there should be a trigger, function related to the table, and obviously it should end up with an SP, or function with selecting/filtering data NOT USING Primary Unique column. If you are searching/filtering using the Primary Unique column there won't be any multiple results. Especially when you are assigning value for a declared variable. The SP never gives you en error but only an runtime error.
"System.Data.SqlClient.SqlException (0x80131904): Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated."
In my case obviously there was no clue, but only this error message. There was a trigger connected to the table and the table updating by the trigger also had another trigger likewise it ended up with two triggers and in the end with an SP. The SP was having a select clause which was resulting in multiple rows.
SET @Variable1 =(
SELECT column_gonna_asign
FROM dbo.your_db
WHERE Non_primary_non_unique_key= @Variable2
If this returns multiple rows, you are in trouble.
It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.
Or just run it in the foreground as suggested and kill it with control c
To find all files whose file status was last changed N minutes ago:
find -cmin -N
For example:
find -cmin -5
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.
I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.
If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.
With the Hub command-line wrapper you can link it to git and then you can do
git pull-request
From the man page of hub:
git pull-request [-f] [TITLE|-i ISSUE|ISSUE-URL] [-b BASE] [-h HEAD]
Opens a pull request on GitHub for the project that the "origin" remote points to. The default head of the pull request is the current branch. Both base and head of the pull request can be explicitly given in one of the following formats: "branch", "owner:branch",
"owner/repo:branch". This command will abort operation if it detects that the current topic branch has local commits that are not yet pushed to its upstream branch on the remote. To skip this check, use -f.
If TITLE is omitted, a text editor will open in which title and body of the pull request can be entered in the same manner as git commit message.
If instead of normal TITLE an issue number is given with -i, the pull request will be attached to an existing GitHub issue. Alternatively, instead of title you can paste a full URL to an issue on GitHub.
First is understanding that RFID is very generic term. NFC is subset of RFID technology. NFC is used for prox card, credit cards, tap and go payment system. Your phones can read and emulate NFC (Apple pay, Google pay, etc.), if they support NFC. NFC is very short distance and low power - which is why you see tap and go type usage.
The more common RFID are the tags you see here and there. They come in a wide ranges of styles, uses and frequency.
HF - high frequency tags are what they use for "chipping" animals - cattle, dogs, cats. Read range is about 12 inches and requires an external antenna that is powered the bigger the antenna the more power it needs and the further it can read.
UFH tags look similar to HF tags but have a read range of several feet.
Also HF tags come single read and multi read. UFH is exclusviely multi read.
Mutiread means when a reader is active, you can litterally read about 1700 tags in under 10 seconds.
But this is a function of the size of the antenna and how much power you can push through the reader.
As to the direct question about Android and RFID - the best way to go is to get an external handheld reader that connects to your mobile device via Bluetooth. Bluetooth libraries exist for all mobile devices - Android, Apple, Windows. From there its just a matter of the manufacturer documentation about how to open a socket to the reader and how to decode the serial information.
The TSL line of readers is very popular because you don't have to deal with reading bytes and all that low level serial jazz that other manufactures do. They have a nice set of commands that are easy to use to control the reader.
Other manufactures are basic in that you open a serial socket and then read the output like you would see in terminal app like PuTTY.
Changing only what's after hash - old browsers
document.location.hash = 'lookAtMeNow';
Changing full URL. Chrome, Firefox, IE10+
history.pushState('data to be passed', 'Title of the page', '/test');
The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use
history.replaceState('data to be passed', 'Title of the page', '/test');
Try running these in the console now!
If you KNOW that a function returns a promise, i suggest using the new async/await features in JavaScript. It makes the syntax look synchronous but work asynchronously. When you add the async
keyword to a function, it allows you to await
promises in that scope:
async function ace() {
var r = await new Promise((resolve, reject) => {
resolve(true)
});
console.log(r); // true
}
if a function does not return a promise, i recommend wrapping it in a new promise that you define, then resolve the data that you want:
function ajax_call(url, method) {
return new Promise((resolve, reject) => {
fetch(url, { method })
.then(resp => resp.json())
.then(json => { resolve(json); })
});
}
async function your_function() {
var json = await ajax_call('www.api-example.com/some_data', 'GET');
console.log(json); // { status: 200, data: ... }
}
Bottom line: leverage the power of Promises.
Exceptions are logged into the JavaScript console. You can use that if you want to keep Firebug disabled.
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0);
}
Usage:
log('Hello World');
log('another message');
#!/bin/bash
#file getActivity.sh
package_name=$1
#launch app by package name
adb shell monkey -p ${package_name} -c android.intent.category.LAUNCHER 1;
sleep 1;
#get Activity name
adb shell logcat -d | grep 'START u0' | tail -n 1 | sed 's/.*cmp=\(.*\)} .*/\1/g'
sample:
getActivity.sh com.tencent.mm
com.tencent.mm/.ui.LauncherUI
This error is due to more security features of gmail..
Once this error is generated...Please login to your gmail account..there you can find security alert from GOOGLE..follow the mail...check on click for less secure option..Then try again phpmailer..
SO thread 'Multiply two arrays element wise, where one of the arrays has arrays as elements' has an example of constructing an array from arrays. If the subarrays are the same size, numpy makes a 2d array. But if they differ in length, it makes an array with dtype=object
, and the subarrays retain their identity.
Following that, you could do something like this:
In [5]: result=np.array([np.zeros((1)),np.zeros((2))])
In [6]: result
Out[6]: array([array([ 0.]), array([ 0., 0.])], dtype=object)
In [7]: np.append([result[0]],[1,2])
Out[7]: array([ 0., 1., 2.])
In [8]: result[0]
Out[8]: array([ 0.])
In [9]: result[0]=np.append([result[0]],[1,2])
In [10]: result
Out[10]: array([array([ 0., 1., 2.]), array([ 0., 0.])], dtype=object)
However, I don't offhand see what advantages this has over a pure Python list or lists. It does not work like a 2d array. For example I have to use result[0][1]
, not result[0,1]
. If the subarrays are all the same length, I have to use np.array(result.tolist())
to produce a 2d array.
with the help of below commands your application will work as you aspected run each command as I mention
1.npm list -g --depth=0
2.npm i npm-check-updates
3.npm install
and finally, run the below command to open your project in browser
ng serve --open
With dplyr
it's now also possible to access a specific column of a dataframe by simply using double curly braces {{...}}
around the desired column name within the function body, e.g. for col_name
:
library(tidyverse)
fun <- function(df, col_name){
df %>%
filter({{col_name}} == "test_string")
}
In C# and VB the SqlCommand object implements the Parameter.AddWithValue method which handles this situation
we can write a stored procedure with input parameters and then use that stored procedure to get a result set from the view. see example below.
the stored procedure is
CREATE PROCEDURE [dbo].[sp_Report_LoginSuccess] -- [sp_Report_LoginSuccess] '01/01/2010','01/30/2010'
@fromDate datetime,
@toDate datetime,
@RoleName varchar(50),
@Success int
as
If @RoleName != 'All'
Begin
If @Success!=2
Begin
--fetch based on true or false
Select * from vw_Report_LoginSuccess
where logindatetime between dbo.DateFloor(@fromDate) and dbo.DateSieling(@toDate)
And RTrim(Upper(RoleName)) = RTrim(Upper(@RoleName)) and Success=@Success
End
Else
Begin
-- fetch all
Select * from vw_Report_LoginSuccess
where logindatetime between dbo.DateFloor(@fromDate) and dbo.DateSieling(@toDate)
And RTrim(Upper(RoleName)) = RTrim(Upper(@RoleName))
End
End
Else
Begin
If @Success!=2
Begin
Select * from vw_Report_LoginSuccess
where logindatetime between dbo.DateFloor(@fromDate) and dbo.DateSieling(@toDate)
and Success=@Success
End
Else
Begin
Select * from vw_Report_LoginSuccess
where logindatetime between dbo.DateFloor(@fromDate) and dbo.DateSieling(@toDate)
End
End
and the view from which we can get the result set is
CREATE VIEW [dbo].[vw_Report_LoginSuccess]
AS
SELECT '3' AS UserDetailID, dbo.tblLoginStatusDetail.Success, CONVERT(varchar, dbo.tblLoginStatusDetail.LoginDateTime, 101) AS LoginDateTime,
CONVERT(varchar, dbo.tblLoginStatusDetail.LogoutDateTime, 101) AS LogoutDateTime, dbo.tblLoginStatusDetail.TokenID,
dbo.tblUserDetail.SubscriberID, dbo.aspnet_Roles.RoleId, dbo.aspnet_Roles.RoleName
FROM dbo.tblLoginStatusDetail INNER JOIN
dbo.tblUserDetail ON dbo.tblLoginStatusDetail.UserDetailID = dbo.tblUserDetail.UserDetailID INNER JOIN
dbo.aspnet_UsersInRoles ON dbo.tblUserDetail.UserID = dbo.aspnet_UsersInRoles.UserId INNER JOIN
dbo.aspnet_Roles ON dbo.aspnet_UsersInRoles.RoleId = dbo.aspnet_Roles.RoleId
WHERE (dbo.tblLoginStatusDetail.Success = 0)
UNION all
SELECT dbo.tblLoginStatusDetail.UserDetailID, dbo.tblLoginStatusDetail.Success, CONVERT(varchar, dbo.tblLoginStatusDetail.LoginDateTime, 101)
AS LoginDateTime, CONVERT(varchar, dbo.tblLoginStatusDetail.LogoutDateTime, 101) AS LogoutDateTime, dbo.tblLoginStatusDetail.TokenID,
dbo.tblUserDetail.SubscriberID, dbo.aspnet_Roles.RoleId, dbo.aspnet_Roles.RoleName
FROM dbo.tblLoginStatusDetail INNER JOIN
dbo.tblUserDetail ON dbo.tblLoginStatusDetail.UserDetailID = dbo.tblUserDetail.UserDetailID INNER JOIN
dbo.aspnet_UsersInRoles ON dbo.tblUserDetail.UserID = dbo.aspnet_UsersInRoles.UserId INNER JOIN
dbo.aspnet_Roles ON dbo.aspnet_UsersInRoles.RoleId = dbo.aspnet_Roles.RoleId
WHERE (dbo.tblLoginStatusDetail.Success = 1) AND (dbo.tblUserDetail.SubscriberID LIKE N'P%')
To understand the difference between a scripting language and a programming language, one has to understand why scripting languages were born.
Initially, there were programming languages that was written to build programs like excel, word, browsers, games and etc. These programs were built with languages like c and java. Overtime, these programs needed a way for users to create new functionality, so they had to provide an interface to their bytecode and hence scripting languages were born.
A scripting language usually isnt compiled so can run as soon as you write something meaningful. Hence excel may be built using C++ but it exposes a scripting language called VBA for users to define functionality. Similarly browsers may be built with C++/Java but they expose a scripting language called javascript (not related to java in any way). Games, are usually built with C++ but expose a language called Lua for users to define custom functionality.
A scripting language usually sits behind some programming language. Scripting languages usually have less access to the computers native abilities since they run on a subset of the original programming language. An example here is that Javascript will not be able to access your file system. Scripting languages are usually slower than programming languages.
Although scripting languages may have less access and are slower, they can be very powerful tools. One factor attributing to a scripting languages success is the ease of updating. Do you remember the days of java applets on the web, this is an example of running a programming language (java) vs running a scripting language (javascript). At the time, computers were not as powerful and javascript wasn't as mature so Java applets dominated the scenes. But Java applets were annoying, they required the user to sort of load and compile the language. Fast forward to today, Java applets are almost extinct and Javascript dominates the scene. Javascript is extremely fast to load since most of the browser components have been installed already.
Lastly, scripting languages are also considered programming languages (although some people refuse to accept this) - the term we should be using here is scripting languages vs compiled languages.
this one worked for me:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ... other stuff
}
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
The method onSupportNavigateUp() is called when you use the back button in the SupportActionBar.
If you would like to not inflate another view just to indicate progress then do the following:
Android will take care the progress bar's visibility.
For example, in activity_main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.fcchyd.linkletandroid.MainActivity">
<ListView
android:id="@+id/list_view_xml"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@color/colorDivider"
android:dividerHeight="1dp" />
<ProgressBar
android:id="@+id/loading_progress_xml"
style="?android:attr/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
And in MainActivity.java
:
package com.fcchyd.linkletandroid;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
final String debugLogHeader = "Linklet Debug Message";
Call<Links> call;
List<Link> arraylistLink;
ListView linksListV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linksListV = (ListView) findViewById(R.id.list_view_xml);
linksListV.setEmptyView(findViewById(R.id.loading_progress_xml));
arraylistLink = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.links.linklet.ml")
.addConverterFactory(GsonConverterFactory
.create())
.build();
HttpsInterface HttpsInterface = retrofit
.create(HttpsInterface.class);
call = HttpsInterface.httpGETpageNumber(1);
call.enqueue(new Callback<Links>() {
@Override
public void onResponse(Call<Links> call, Response<Links> response) {
try {
arraylistLink = response.body().getLinks();
String[] simpletTitlesArray = new String[arraylistLink.size()];
for (int i = 0; i < simpletTitlesArray.length; i++) {
simpletTitlesArray[i] = arraylistLink.get(i).getTitle();
}
ArrayAdapter<String> simpleAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, simpletTitlesArray);
linksListV.setAdapter(simpleAdapter);
} catch (Exception e) {
Log.e("erro", "" + e);
}
}
@Override
public void onFailure(Call<Links> call, Throwable t) {
}
});
}
}
Try,
# cat test.sh
#!/bin/bash
/bin/touch file.txt
cron as:
* * * * * /bin/sh /home/myUser/scripts/test.sh
And you can confirm this by:
# tailf /var/log/cron
The whole ls -l and then cut is rather convoluted when you have stat. It is also vulnerable to the exact format of ls -l (it didn't work until I changed the column numbers for cut)
Also, fixed the useless use of cat.
<files.txt xargs stat -c %s | paste -sd+ - | bc
if ($('#element').is(':empty')){
//do something
}
for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/
EDIT:
As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).
function isEmpty( el ){
return !$.trim(el.html())
}
if (isEmpty($('#element'))) {
// do something
}
You can also make it into a jQuery plugin, but you get the idea.
Regex if you want to ensure URL starts with HTTP/HTTPS:
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
If you do not require HTTP protocol:
[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
To try this out see http://regexr.com?37i6s, or for a version which is less restrictive http://regexr.com/3e6m0.
Example JavaScript implementation:
var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;_x000D_
var regex = new RegExp(expression);_x000D_
var t = 'www.google.com';_x000D_
_x000D_
if (t.match(regex)) {_x000D_
alert("Successful match");_x000D_
} else {_x000D_
alert("No match");_x000D_
}
_x000D_
If you have seaborn
installed, an easier method that does not require you to perform pivot
:
import seaborn as sns
sns.lineplot(data=df, x='x', y='y', hue='color')
.str.get
This is the simplest to specify string methods
# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df
A B
0 xyz 123
1 abc 456
2 foobar 789
df.dtypes
A object
B int64
dtype: object
For string (read:object
) type columns, use
df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)
.str
handles NaNs by returning NaN as the output.
For non-numeric columns, an .astype
conversion is required beforehand, as shown in @Ed Chum's answer.
# Note that this won't work well if the data has NaNs.
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.
# For string columns
df['C'] = [x[0] for x in df['A']]
# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
If your data has NaNs, then you will need to handle this appropriately with an if
/else
in the list comprehension,
df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2
A B
0 xyz 123.0
1 NaN 456.0
2 foobar NaN
# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
A B C D
0 xyz 123.0 x 1
1 NaN 456.0 NaN 4
2 foobar NaN f NaN
Let's do some timeit tests on some larger data.
df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True)
%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])
%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])
12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
List comprehensions are 4x faster.
That works fine. See this fiddle: http://jsfiddle.net/kveAL/
It is possible that you need to declare your jQuery in a $(document).ready()
handler?
Also, might you have two elements that have the same ID?
When running Tomcat under jsvc, it will not respond to the shutdown signal on the specified shutdown port which is sent from the shutdown.sh script. The only way that I'm aware of is to kill the process, however you'll need to kill the ones listed as jsvc, not java.
You could use the following. It supports Bootstrap 3.x above.
<img src="..." alt="..." class="img-responsive center-block" />
Delete the .refresh.dll file if you are under source control. Then rebuild. It should work. This worked for me
I know that this question is very old but still we often get such requirements. There are many examples however many seems to be too verbose or complex for a simple implimentation.
See this https://jsfiddle.net/vibs2006/rn0fvxuk/ and improve it (if you can). It works on IE, Firefox, Chrome and Edge Browser.
Here is the working code.
_x000D_
function IsNumeric(e) {_x000D_
var IsValidationSuccessful = false;_x000D_
console.log(e.target.value);_x000D_
document.getElementById("info").innerHTML = "You just typed ''" + e.key + "''";_x000D_
//console.log("e.Key Value = "+e.key);_x000D_
switch (e.key)_x000D_
{ _x000D_
case "1":_x000D_
case "2":_x000D_
case "3":_x000D_
case "4":_x000D_
case "5":_x000D_
case "6":_x000D_
case "7":_x000D_
case "8":_x000D_
case "9":_x000D_
case "0":_x000D_
case "Backspace": _x000D_
IsValidationSuccessful = true;_x000D_
break;_x000D_
_x000D_
case "Decimal": //Numpad Decimal in Edge Browser_x000D_
case ".": //Numpad Decimal in Chrome and Firefox _x000D_
case "Del": // Internet Explorer 11 and less Numpad Decimal _x000D_
if (e.target.value.indexOf(".") >= 1) //Checking if already Decimal exists_x000D_
{_x000D_
IsValidationSuccessful = false;_x000D_
}_x000D_
else_x000D_
{_x000D_
IsValidationSuccessful = true;_x000D_
}_x000D_
break;_x000D_
_x000D_
default:_x000D_
IsValidationSuccessful = false;_x000D_
}_x000D_
//debugger;_x000D_
if(IsValidationSuccessful == false){_x000D_
_x000D_
document.getElementById("error").style = "display:Block";_x000D_
}else{_x000D_
document.getElementById("error").style = "display:none";_x000D_
}_x000D_
_x000D_
return IsValidationSuccessful;_x000D_
}
_x000D_
Numeric Value: <input type="number" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" /><br />_x000D_
<span id="error" style="color: Red; display: none">* Input digits (0 - 9) and Decimals Only</span><br />_x000D_
<div id="info"></div>
_x000D_
resize your background image in an image editor to the size you want related to your login box, which should help page loading and preserve image quality...
hard-size your DIV relative to your image
position your asp:login control where needed...
The easiest way:
1 - Enter in phpmyadmin
2 - Click on table name in left column
3 - Click in Operation (top menu)
4 - Click "Empty the table (TRUNCATE)
5 - Disable box "Enable foreign key checks"
6 - Done!
Link to image tutorial
Tutorial: http://www.imageno.com/wz6gv1wuqajrpic.html
(sorry, I don't have enough reputation to upload images here :P)
If you are using Visual Studio, there is an easy way to setup and enable SSL using IIS Express explained here
BufferedImage is a subclass of Image. You don't need to do any conversion.
They are found on either one of the below locations depending on how chrome was installed
~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions
/Library/Application\ Support/Google/Chrome/Default/Extensions
The bootstrap v4 starter template css uses:
body {
padding-top: 5rem;
}
Use pointers as your function parameters. Then use them to return multiple value.
You can use querySelectorAll:
document.querySelectorAll('[data-foo]');
Python is a language: a set of rules that can be used to write programs. There are several implementaions of this language.
No matter what implementation you take, they do pretty much the same thing: take the text of your program and interpret it, executing its instructions. None of them compile your code into C or any other language.
CPython is the original implementation, written in C. (The "C" part in "CPython" refers to the language that was used to write Python interpreter itself.)
Jython is the same language (Python), but implemented using Java.
IronPython interpreter was written in C#.
There's also PyPy - a Python interpreter written in Python. Make your pick :)
Minimal runnable example with disassembly analysis
As usual, I like to see some disassembly to get a better understanding of what is going on.
In this case, the insight we obtain is that if a variable is optimized to be stored only in a register rather than the stack, and then the register it was in gets overwritten, then it shows as <optimized out>
as mentioned by R..
Of course, this can only happen if the variable in question is not needed anymore, otherwise the program would lose its value. Therefore it tends to happen that at the start of the function you can see the variable value, but then at the end it becomes <optimized out>
.
One typical case which we often are interested in of this is that of the function arguments themselves, since these are:
This understanding actually has a concrete application: when using reverse debugging, you might be able to recover the value of variables of interest simply by stepping back to their last point of usage: How do I view the value of an <optimized out> variable in C++?
main.c
#include <stdio.h>
int __attribute__((noinline)) f3(int i) {
return i + 1;
}
int __attribute__((noinline)) f2(int i) {
return f3(i) + 1;
}
int __attribute__((noinline)) f1(int i) {
int j = 1, k = 2, l = 3;
i += 1;
j += f2(i);
k += f2(j);
l += f2(k);
return l;
}
int main(int argc, char *argv[]) {
printf("%d\n", f1(argc));
return 0;
}
Compile and run:
gcc -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
gdb -q -nh main.out
Then inside GDB, we have the following session:
Breakpoint 1, f1 (i=1) at main.c:13
13 i += 1;
(gdb) disas
Dump of assembler code for function f1:
=> 0x00005555555546c0 <+0>: add $0x1,%edi
0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
0x00005555555546cb <+11>: callq 0x5555555546b0 <f2>
0x00005555555546d0 <+16>: lea 0x2(%rax),%edi
0x00005555555546d3 <+19>: callq 0x5555555546b0 <f2>
0x00005555555546d8 <+24>: add $0x3,%eax
0x00005555555546db <+27>: retq
End of assembler dump.
(gdb) p i
$1 = 1
(gdb) p j
$2 = 1
(gdb) n
14 j += f2(i);
(gdb) disas
Dump of assembler code for function f1:
0x00005555555546c0 <+0>: add $0x1,%edi
=> 0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
0x00005555555546cb <+11>: callq 0x5555555546b0 <f2>
0x00005555555546d0 <+16>: lea 0x2(%rax),%edi
0x00005555555546d3 <+19>: callq 0x5555555546b0 <f2>
0x00005555555546d8 <+24>: add $0x3,%eax
0x00005555555546db <+27>: retq
End of assembler dump.
(gdb) p i
$3 = 2
(gdb) p j
$4 = 1
(gdb) n
15 k += f2(j);
(gdb) disas
Dump of assembler code for function f1:
0x00005555555546c0 <+0>: add $0x1,%edi
0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
=> 0x00005555555546cb <+11>: callq 0x5555555546b0 <f2>
0x00005555555546d0 <+16>: lea 0x2(%rax),%edi
0x00005555555546d3 <+19>: callq 0x5555555546b0 <f2>
0x00005555555546d8 <+24>: add $0x3,%eax
0x00005555555546db <+27>: retq
End of assembler dump.
(gdb) p i
$5 = <optimized out>
(gdb) p j
$6 = 5
(gdb) n
16 l += f2(k);
(gdb) disas
Dump of assembler code for function f1:
0x00005555555546c0 <+0>: add $0x1,%edi
0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
0x00005555555546cb <+11>: callq 0x5555555546b0 <f2>
0x00005555555546d0 <+16>: lea 0x2(%rax),%edi
=> 0x00005555555546d3 <+19>: callq 0x5555555546b0 <f2>
0x00005555555546d8 <+24>: add $0x3,%eax
0x00005555555546db <+27>: retq
End of assembler dump.
(gdb) p i
$7 = <optimized out>
(gdb) p j
$8 = <optimized out>
To understand what is going on, remember from the x86 Linux calling convention: What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 you should know that:
From this we deduce that:
add $0x1,%edi
corresponds to the:
i += 1;
since i
is the first argument of f1
, and therefore stored in RDI.
Now, while we were at both:
i += 1;
j += f2(i);
the value of RDI hadn't been modified, and therefore GDB could just query it at anytime in those lines.
However, as soon as the f2
call is made:
i
is not needed anymore in the programlea 0x1(%rax),%edi
does EDI = j + RAX + 1
, which both:
j = 1
f2
call to RDI = j
Therefore, when the following line is reached:
k += f2(j);
both of the following instructions have/may have modified RDI, which is the only place i
was being stored (f2
may use it as a scratch register, and lea
definitely set it to RAX + 1):
0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
and so RDI does not contain the value of i
anymore. In fact, the value of i
was completely lost! Therefore the only possible outcome is:
$3 = <optimized out>
A similar thing happens to the value of j
, although j
only becomes unnecessary one line later afer the call to k += f2(j);
.
Thinking about j
also gives us some insight on how smart GDB is. Notably, at i += 1;
, the value of j
had not yet materialized in any register or memory address, and GDB must have known it based solely on debug information metadata.
-O0
analysis
If we use -O0
instead of -O3
for compilation:
gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
then the disassembly would look like:
11 int __attribute__((noinline)) f1(int i) {
=> 0x0000555555554673 <+0>: 55 push %rbp
0x0000555555554674 <+1>: 48 89 e5 mov %rsp,%rbp
0x0000555555554677 <+4>: 48 83 ec 18 sub $0x18,%rsp
0x000055555555467b <+8>: 89 7d ec mov %edi,-0x14(%rbp)
12 int j = 1, k = 2, l = 3;
0x000055555555467e <+11>: c7 45 f4 01 00 00 00 movl $0x1,-0xc(%rbp)
0x0000555555554685 <+18>: c7 45 f8 02 00 00 00 movl $0x2,-0x8(%rbp)
0x000055555555468c <+25>: c7 45 fc 03 00 00 00 movl $0x3,-0x4(%rbp)
13 i += 1;
0x0000555555554693 <+32>: 83 45 ec 01 addl $0x1,-0x14(%rbp)
14 j += f2(i);
0x0000555555554697 <+36>: 8b 45 ec mov -0x14(%rbp),%eax
0x000055555555469a <+39>: 89 c7 mov %eax,%edi
0x000055555555469c <+41>: e8 b8 ff ff ff callq 0x555555554659 <f2>
0x00005555555546a1 <+46>: 01 45 f4 add %eax,-0xc(%rbp)
15 k += f2(j);
0x00005555555546a4 <+49>: 8b 45 f4 mov -0xc(%rbp),%eax
0x00005555555546a7 <+52>: 89 c7 mov %eax,%edi
0x00005555555546a9 <+54>: e8 ab ff ff ff callq 0x555555554659 <f2>
0x00005555555546ae <+59>: 01 45 f8 add %eax,-0x8(%rbp)
16 l += f2(k);
0x00005555555546b1 <+62>: 8b 45 f8 mov -0x8(%rbp),%eax
0x00005555555546b4 <+65>: 89 c7 mov %eax,%edi
0x00005555555546b6 <+67>: e8 9e ff ff ff callq 0x555555554659 <f2>
0x00005555555546bb <+72>: 01 45 fc add %eax,-0x4(%rbp)
17 return l;
0x00005555555546be <+75>: 8b 45 fc mov -0x4(%rbp),%eax
18 }
0x00005555555546c1 <+78>: c9 leaveq
0x00005555555546c2 <+79>: c3 retq
From this horrendous disassembly, we see that the value of RDI is moved to the stack at the very start of program execution at:
mov %edi,-0x14(%rbp)
and it then gets retrieved from memory into registers whenever needed, e.g. at:
14 j += f2(i);
0x0000555555554697 <+36>: 8b 45 ec mov -0x14(%rbp),%eax
0x000055555555469a <+39>: 89 c7 mov %eax,%edi
0x000055555555469c <+41>: e8 b8 ff ff ff callq 0x555555554659 <f2>
0x00005555555546a1 <+46>: 01 45 f4 add %eax,-0xc(%rbp)
The same basically happens to j
which gets immediately pushed to the stack when when it is initialized:
0x000055555555467e <+11>: c7 45 f4 01 00 00 00 movl $0x1,-0xc(%rbp)
Therefore, it is easy for GDB to find the values of those variables at any time: they are always present in memory!
This also gives us some insight on why it is not possible to avoid <optimized out>
in optimized code: since the number of registers is limited, the only way to do that would be to actually push unneeded registers to memory, which would partly defeat the benefit of -O3
.
Extend the lifetime of i
If we edited f1
to return l + i
as in:
int __attribute__((noinline)) f1(int i) {
int j = 1, k = 2, l = 3;
i += 1;
j += f2(i);
k += f2(j);
l += f2(k);
return l + i;
}
then we observe that this effectively extends the visibility of i
until the end of the function.
This is because with this we force GCC to use an extra variable to keep i
around until the end:
0x00005555555546c0 <+0>: lea 0x1(%rdi),%edx
0x00005555555546c3 <+3>: mov %edx,%edi
0x00005555555546c5 <+5>: callq 0x5555555546b0 <f2>
0x00005555555546ca <+10>: lea 0x1(%rax),%edi
0x00005555555546cd <+13>: callq 0x5555555546b0 <f2>
0x00005555555546d2 <+18>: lea 0x2(%rax),%edi
0x00005555555546d5 <+21>: callq 0x5555555546b0 <f2>
0x00005555555546da <+26>: lea 0x3(%rdx,%rax,1),%eax
0x00005555555546de <+30>: retq
which the compiler does by storing i += i
in RDX at the very first instruction.
Tested in Ubuntu 18.04, GCC 7.4.0, GDB 8.1.0.
You can just put this all on one line:
LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/path/to/library" ./sync_test
Should make things a little easier, even if it doesn't change anything fundamental
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
If you are using Create React App environment simply add @import rule to index.css as such:
@import url('https://fonts.googleapis.com/css?family=Anton');
Import index.css in your main React app:
import './index.css'
React gives you a choice of Inline styling, CSS Modules or Styled Components in order to apply CSS:
font-family: 'Anton', sans-serif;
My answer is quite easy:
Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.
As a bonus, it's very easy to work with as well.
You could use label based using .loc or index based using .iloc method to do column-slicing including column ranges:
In [50]: import pandas as pd
In [51]: import numpy as np
In [52]: df = pd.DataFrame(np.random.rand(4,4), columns = list('abcd'))
In [53]: df
Out[53]:
a b c d
0 0.806811 0.187630 0.978159 0.317261
1 0.738792 0.862661 0.580592 0.010177
2 0.224633 0.342579 0.214512 0.375147
3 0.875262 0.151867 0.071244 0.893735
In [54]: df.loc[:, ["a", "b", "d"]] ### Selective columns based slicing
Out[54]:
a b d
0 0.806811 0.187630 0.317261
1 0.738792 0.862661 0.010177
2 0.224633 0.342579 0.375147
3 0.875262 0.151867 0.893735
In [55]: df.loc[:, "a":"c"] ### Selective label based column ranges slicing
Out[55]:
a b c
0 0.806811 0.187630 0.978159
1 0.738792 0.862661 0.580592
2 0.224633 0.342579 0.214512
3 0.875262 0.151867 0.071244
In [56]: df.iloc[:, 0:3] ### Selective index based column ranges slicing
Out[56]:
a b c
0 0.806811 0.187630 0.978159
1 0.738792 0.862661 0.580592
2 0.224633 0.342579 0.214512
3 0.875262 0.151867 0.071244
<?php
$username=urldecode($_POST['log_user']);
$user="select * from tbl_registration where member_id= '".$username."' ";
$rsuser = $obj->select($user);
if(count($rsuser)>0)
{
// (Status if 2 then its expire) (1= use) ( 0 = not use)
$cheknew="select name,ldate,offer_photo from tbl_offer where status=1 ";
$rscheknew = $obj->selectjson($cheknew);
if(count($rscheknew)>0)
{
$nik=json_encode($rscheknew);
echo "{\"status\" : \"200\" ,\"responce\" : \"201\", \"message\" : \"Get Record\",\"feed\":".str_replace("<p>","",$nik). "}";
}
else
{
$row2="No Record Found";
$nik1=json_encode($row2);
echo "{\"status\" : \"202\", \"responce\" : \"604\",\"message\" : \"No Record Found \",\"feed\":".str_replace("<p>","",$nik1). "}";
}
}
else
{
$row2="Invlid User";
$nik1=json_encode($row2);
echo "{\"status\" : \"404\", \"responce\" : \"602\",\"message\" : \"Invlid User \",\"feed\":".str_replace("<p>","",$nik1). "}";
}
?>
https://www.mockable.io. It has nice feature of getting endpoints without login (24h temporary account)
As already posted in earlier answer, most common MIME types are configured in a webserver. For example in tomcat conf/ we have web.xml with following MIME configured:
<mime-mapping>
<extension>abs</extension>
<mime-type>audio/x-mpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>ai</extension>
<mime-type>application/postscript</mime-type>
</mime-mapping>
<mime-mapping>
<extension>aif</extension>
<mime-type>audio/x-aiff</mime-type>
</mime-mapping>
...
Create a startup listener that kicks in when web app is started and parses this XML file and creates the ENUMS for you and binds it to servlet context for sharing downstream.
Just use android:focusableInTouchMode="false"
on your webView.
This error in REACT. following steps
Go to Project Root Directory Package.json file
add "type":"module";
Save it and Restart Server
Use:
npm run test -- test-name
This will only work if your test specification name is unique.
The code above would reference a file with this name: test-name.component.spec.ts
I was able to fix this in Android Studio 0.2.0 by changing API from API 18: Android 4.3 to API 17: Android 4.2.2
This is under the Android icon menu in the top right of the design window.
This was a solution from http://www.hankcs.com/program/mobiledev/idea-this-version-of-the-rendering-library-is-more-recent-than-your-version-of-intellij-idea-please-update-intellij-idea.html.This required a Google translation into English since it was in another language.
Hope it helps.
Note that the names generated by the RTTI feature of C++ is not portable. For example, the class
MyNamespace::CMyContainer<int, test_MyNamespace::CMyObject>
will have the following names:
// MSVC 2003:
class MyNamespace::CMyContainer[int,class test_MyNamespace::CMyObject]
// G++ 4.2:
N8MyNamespace8CMyContainerIiN13test_MyNamespace9CMyObjectEEE
So you can't use this information for serialization. But still, the typeid(a).name() property can still be used for log/debug purposes
The @Qualifier
annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.
The @Qualifier
annotation can be used on any class annotated with @Component
or on methods annotated with @Bean
. This annotation can also be applied on constructor arguments or method parameters.
Ex:-
public interface Vehicle {
public void start();
public void stop();
}
There are two beans, Car and Bike implements Vehicle interface
@Component(value="car")
public class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void stop() {
System.out.println("Car stopped");
}
}
@Component(value="bike")
public class Bike implements Vehicle {
@Override
public void start() {
System.out.println("Bike started");
}
@Override
public void stop() {
System.out.println("Bike stopped");
}
}
Injecting Bike bean in VehicleService using @Autowired
with @Qualifier
annotation. If you didn't use @Qualifier
, it will throw NoUniqueBeanDefinitionException.
@Component
public class VehicleService {
@Autowired
@Qualifier("bike")
private Vehicle vehicle;
public void service() {
vehicle.start();
vehicle.stop();
}
}
Reference:- @Qualifier annotation example
Method or Function: toLowerCase(), toUpperCase()
Description: These methods are used to cover a string or alphabet from lower case to upper case or vice versa. e.g: "and" to "AND".
Converting to Upper Case:- Example Code:-
<script language=javascript>
var ss = " testing case conversion method ";
var result = ss.toUpperCase();
document.write(result);
</script>
Result: TESTING CASE CONVERSION METHOD
Converting to Lower Case:- Example Code:
<script language=javascript>
var ss = " TESTING LOWERCASE CONVERT FUNCTION ";
var result = ss.toLowerCase();
document.write(result);
</script>
Result: testing lowercase convert function
Explanation: In the above examples,
toUpperCase() method converts any string to "UPPER" case letters.
toLowerCase() method converts any string to "lower" case letters.
I tried most of the (upvoted) solutions here but in docker 17.09 (in 2018) there is no longer /var/lib/docker/aufs folder.
This simple docker cp
solved this task.
docker cp c:\path\to\local\file container_name:/path/to/target/dir/
How to get container_name?
docker ps
There is a NAMES
section. Don't use aIMAGE
.
Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim
EXEC xp_cmdshell 'sqlcmd -S ' + @DBServerName + ' -d ' + @DBName + ' -i ' + @FilePathName
in angular2 2.1.1 I was not able to catch the exception using the (data),(error) pattern, so I implemented it using .catch(...).
It's nice because it can be used with all other Observable chained methods like .retry .map etc.
import {Observable} from 'rxjs/Rx';
Http
.put(...)
.catch(err => {
notify('UI error handling');
return Observable.throw(err); // observable needs to be returned or exception raised
})
.subscribe(data => ...) // handle success
from documentation:
Returns
(Observable): An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
With Swift 5, you may choose one of the three examples shown below in order to solve your problem.
String
's init(format:_:)
initializerFoundation
provides Swift String
a init(format:_:)
initializer. init(format:_:)
has the following declaration:
init(format: String, _ arguments: CVarArg...)
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:_:)
:
import Foundation
let string0 = String(format: "%02d", 0) // returns "00"
let string1 = String(format: "%02d", 1) // returns "01"
let string2 = String(format: "%02d", 10) // returns "10"
let string3 = String(format: "%02d", 100) // returns "100"
String
's init(format:arguments:)
initializerFoundation
provides Swift String
a init(format:arguments:)
initializer. init(format:arguments:)
has the following declaration:
init(format: String, arguments: [CVarArg])
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:arguments:)
:
import Foundation
let string0 = String(format: "%02d", arguments: [0]) // returns "00"
let string1 = String(format: "%02d", arguments: [1]) // returns "01"
let string2 = String(format: "%02d", arguments: [10]) // returns "10"
let string3 = String(format: "%02d", arguments: [100]) // returns "100"
NumberFormatter
Foundation provides NumberFormatter
. Apple states about it:
Instances of
NSNumberFormatter
format the textual representation of cells that containNSNumber
objects and convert textual representations of numeric values intoNSNumber
objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position.
The following Playground code shows how to create a NumberFormatter
that returns String?
from a Int
with at least two integer digits:
import Foundation
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2
let optionalString0 = formatter.string(from: 0) // returns Optional("00")
let optionalString1 = formatter.string(from: 1) // returns Optional("01")
let optionalString2 = formatter.string(from: 10) // returns Optional("10")
let optionalString3 = formatter.string(from: 100) // returns Optional("100")
To open a PDF at page 100 the follow works
<path to Adobe Reader> /A "page=100" "<Path To PDF file>"
If you require more than one argument separate them with &
I use the following in a batch file to open the book I'm reading to the page I was up to.
C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe /A "page=149&pagemode=none" "D:\books\MCTS(70-562) ASP.Net 3.5 Development.pdf"
The best list of command line args for Adobe Reader I have found is here.
http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf
It's for version 7 but all the arguments I tried worked.
As for closing the file, I think you will need to use the SDK, or if you are opening the file from code you could close the file from code once you have finished with it.
The accepted answer here does not take into account the Kind of the DateTime instance. For example if your original DateTime instance was a UTC Kind then by making a new DateTime instance you will be making an Unknown Kind instance which will then be treated as local time based on server settings. Therefore the more proper way to get the first and last date of the month would be this:
var now = DateTime.UtcNow;
var first = now.Date.AddDays(-(now.Date.Day - 1));
var last = first.AddMonths(1).AddTicks(-1);
This way the original Kind of the DateTime instance is preserved.
Have a look at Managing Hierarchical Data in MySQL. It discusses two approaches for storing and managing hierarchical (tree-like) data in a relational database.
The first approach is the adjacency list model, which is what you essentially describe: having a foreign key that refers to the table itself. While this approach is simple, it can be very inefficient for certain queries, like building the whole tree.
The second approach discussed in the article is the nested set model. This approach is far more efficient and flexible. Refer to the article for detailed explanation and example queries.
When you request your JSON file, server returns JavaScript Content-Type
header (text/javascript
) instead of JSON (application/json
).
According to MooTools docs:
Responses with javascript content-type will be evaluated automatically.
In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:
{"votes":47,"totalvotes":90}
as JavaScript, parser treats {
and }
as a block scope instead of object notation. It is the same as evaluating following "code":
"votes":47,"totalvotes":90
As you can see, :
is totally unexpected there.
The solution is to set correct Content-Type
header for the JSON file. If you save it with .json
extension, your server should do it by itself.
I often want to highlight a particular word/function name, but don't want to search to the next instance of it yet:
map m* *#
When setting with JQM
, don't forget to update the UI
:
$('#selectId').val('newValue').selectmenu('refresh', true);
If the iframe was not on a different domain, you could do something like this:
document.getElementById(FrameID).contentDocument.location.reload(true);
But since the iframe is on a different domain, you will be denied access to the iframe's contentDocument
property by the same-origin policy.
But you can hackishly force the cross-domain iframe to reload if your code is running on the iframe's parent page, by setting it's src attribute to itself. Like this:
// hackishly force iframe to reload
var iframe = document.getElementById(FrameId);
iframe.src = iframe.src;
If you are trying to reload the iframe from another iframe, you are out of luck, that is not possible.
Quoting the spec
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
And here's a table for typeof
To add some background, there are two data types in JavaScript:
An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.
An array can be considered to be an object with the following properties/keys:
Hope this helped shed more light on why typeof Array returns an object. Cheers!
A solution for AngularJS:
$scope.targetObject = angular.copy($scope.sourceObject)
Taking into account that the separator can be more than one space/tab and that we want to preserve them:
public static String reverse(String string)
{
StringBuilder sb = new StringBuilder(string.length());
StringBuilder wsb = new StringBuilder(string.length());
for (int i = 0; i < string.length(); i++)
{
char c = string.charAt(i);
if (c == '\t' || c == ' ')
{
if (wsb.length() > 0)
{
sb.append(wsb.reverse().toString());
wsb = new StringBuilder(string.length() - sb.length());
}
sb.append(c);
}
else
{
wsb.append(c);
}
}
if (wsb.length() > 0)
{
sb.append(wsb.reverse().toString());
}
return sb.toString();
}
Try the following (Which does not print -1 at the end now!)
int index = word.indexOf(guess);
while(index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index+1);
}
I've had very good experience with copy-maven-plugin. It has a much more convenient and concise syntax in comparison to maven-resources-plugin.
Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers.
See:
using System.Configuration;
string conn = ConfigurationManager.ConnectionStrings["ConStringName"].ToString();
This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.
You can convert your date in many formats, the syntaxe is simple to use :
CONVERT('TheTypeYouWant', 'TheDateToConvert', 'TheCodeForFormating' * )
CONVERT(NVARCHAR(10), DATE_OF_DAY, 103) => 15/09/2016
In your case, i've just converted and restrict size by nvarchar(10) like this :
CONVERT(NVARCHAR(10), MY_DATE_TIME, 120) => 2016-09-15
See more at : http://www.w3schools.com/sql/func_convert.asp
Another solution (if your date is a Datetime) is a simple CAST :
CAST(MY_DATE_TIME as DATE) => 2016-09-15
found this very clever idea from https://gist.github.com/scottrippey/3428114 for every $.ajax calls it modifies the request and add the token.
// Setup CSRF safety for AJAX:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.type.toUpperCase() === "POST") {
// We need to add the verificationToken to all POSTs
var token = $("input[name^=__RequestVerificationToken]").first();
if (!token.length) return;
var tokenName = token.attr("name");
// If the data is JSON, then we need to put the token in the QueryString:
if (options.contentType.indexOf('application/json') === 0) {
// Add the token to the URL, because we can't add it to the JSON data:
options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
} else if (typeof options.data === 'string' && options.data.indexOf(tokenName) === -1) {
// Append to the data string:
options.data += (options.data ? "&" : "") + token.serialize();
}
}
});
If you logged into "phpmyadmin", then logged out, you might have trouble attempting to log back in on the same browser window. The logout sends the browser to a URL that looks like this:
http://localhost/phpmyadmin/index.php?db=&token=354a350abed02588e4b59f44217826fd&old_usr=tester
But for me, on Mac OS X in Safari browser, that URL just doesn't want to work. Therefore, I have to put in the clean URL:
http://localhost/phpmyadmin
Don't know why, but as of today, Oct 20, 2015, that is what I am experiencing.
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
There are three options:
Using jQuery (download from jQuery website) - jquery.com
var lines = $("#ptest").val().split("\n");
return lines.length;
Using Regex
var lines = str.split(/\r\n|\r|\n/);
return lines.length;
Or, a recreation of a for each loop
var length = 0;
for(var i = 0; i < str.length; ++i){
if(str[i] == '\n') {
length++;
}
}
return length;
The Oracle/PLSQL
CONCAT
function allows to concatenate two strings together.
CONCAT( string1, string2 )
string1
The first string to concatenate.
string2
The second string to concatenate.
E.g.
SELECT 'I like ' || type_column_name || ' cake with ' ||
icing_column_name || ' and a ' fruit_column_name || '.'
AS Cake FROM table;
There are several answers with the same recursive appending scheme as below, but none makes use of try
, which makes the solution more robust and pythonic. Other advantages of this solution are:
~
def flatten(itr):
t = tuple()
for e in itr:
try:
t += flatten(e)
except:
t += (e,)
return t
Another variant with same features:
def flatten(itr):
try:
t = sum((flatten(e) for e in itr), tuple())
except:
t = (itr,)
return t
If you need to return a list (which is slightly slower) use list()
instead of tuple()
and [ ]
instead of ( ,)
.
This work for me
from flask import Flask
from flask import Response
app = Flask(__name__)
@app.route("/")
def home():
return Response(headers={'Access-Control-Allow-Origin':'*'})
if __name__ == "__main__":
app.run()
Update: appears to have stopped working since Chrome 80
Drag & Drop the '.crx' file on to the 'Extensions' page
Settings - icon > Tools > Extensions
( the 'hamburger' icon in the top-right corner )Enable Developer Mode ( toggle button in top-right corner )
Drag and drop the '.crx' extension file onto the Extensions page from step 1
( crx file should likely be in your Downloads directory )Install
Source: Chrome YouTube Downloader - install instructions
Try this code:
EndpointImpl impl = (EndpointImpl)Endpoint.publish(address, implementor);
impl.getServer().getEndpoint().getInInterceptors().add(new LoggingInInterceptor());
impl.getServer().getEndpoint().getOutInterceptors().add(new LoggingOutInterceptor());
Inside the logback.xml
you need to put the interface name for webservice:
<appender name="FILE" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator
class="com.progressoft.ecc.integration.logging.ThreadNameDiscriminator">
<key>threadName</key>
<defaultValue>unknown</defaultValue>
</discriminator>
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator>
<expression>logger.contains("InterfaceWebServiceSoap")</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>NEUTRAL</OnMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>TRACE</level>
</filter>
<sift>
<appender name="FILE-${threadName}"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${LOGGING_PATH}/${threadName}.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${ARCHIVING_PATH}/%d{yyyy-MM-dd}.${threadName}%i.log.zip
</FileNamePattern>
<MaxHistory>30</MaxHistory>
<TimeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<MaxFileSize>50MB</MaxFileSize>
</TimeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%date{dd-MM-yyyy HH:mm:ss.SSS} | %5level | %-60([%logger{53}:%line]): %msg %ex{full} %n</Pattern>
</encoder>
</appender>
</sift>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="FILE" />
</root>
I spent hours on this, and the solution was:
Try to set response dataType property directly:
dataType: 'text'
and put
die('');
in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.
ES2015 the easiest way is to do something like
'X'.repeat(data.length)
X
being any string, data.length
being the desired length.
see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
This answer illustrates a pre-HTML5 approach. Please take a look at Psytronic's answer for a modern solution using the placeholder
attribute.
HTML:
<input type="text" name="firstname" title="First Name" style="color:#888;"
value="First Name" onfocus="inputFocus(this)" onblur="inputBlur(this)" />
JavaScript:
function inputFocus(i) {
if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; }
}
function inputBlur(i) {
if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; }
}
Background:
Actually in getComposer website it clearly states that, install the Composer by using the following curl command,
curl -sS https://getcomposer.org/installer |php
And it certainly does what it's intended to do. And then it says to move the composer.phar to the directory /usr/local/bin/composer and then composer will be available Globally, by using the following command line in terminal!
mv composer.phar /usr/local/bin/composer
Question:
So the problem which leads me to Google over it is when I executed the above line in Mac OS X Terminal, it said that, Permission denied. Like as follows:
mv: rename composer.phar to /usr/local/bin/composer: Permission denied
Answer:
Following link led me to the solution like a charm and I'm thankful to that. The thing I just missed was sudo command before the above stated "Move" command line. Now my Move command is as follows:
sudo mv composer.phar /usr/local/bin/composer
Password:
It directly prompts you to authenticate yourself and see if you are authorized. So if you enter a valid password, then the Moving will be done, and you can just check if composer is globally installed, by using the following line.
composer about
I hope this answer helped you to broaden your view and finally resolve your problem.
Cheers!
You can set the constraints on that table / column to not check temporarily, then re-enable the constraints. General form would be:
ALTER TABLE TableName NOCHECK CONSTRAINT ConstraintName
Then re-enable all constraints with
ALTER TABLE TableName CHECK CONSTRAINT ConstraintName
I assume that this would be temporary though? You obviously wouldn't want to do this consistently.
To create a simple table using terminaltables
Open the terminal or your command prompt and run pip install terminaltables
You can print and python list as the following
from terminaltables import AsciiTable
l = [
['Head', 'Head'],
['R1 C1', 'R1 C2'],
['R2 C1', 'R2 C2'],
['R3 C1', 'R3 C2']
]
table = AsciiTable(l)
print(table.table)
They have other cool tables don't forget to check them out. Just google their library.
Hope that helps :100:!
For everyone stumbling upon this post because pandas gets mentioned,
you now have the very elegant and straighforward option of directly accessing the
secondary_y axis in pandas with ax.right_ax
So paraphrasing the example initially posted, you would write:
table = sql.read_frame(query,connection)
ax = table[[0, 1]].plot(ylim=(0,100), secondary_y=table[1])
ax.set_ylabel('$')
ax.right_ax.set_ylabel('Your second Y-Axis Label goes here!')
A specification (blueprint) about how to make an OS compatible with late UNIX OS (may God bless him!). This is why macOS and GNU/Linux have very similar terminal command lines, GUI's, libraries, etc. Because they both were designed according to POSIX blueprint.
POSIX does not tell engineers and programmers how to code but what to code.
Try this so you don't need to worry about where your logs are:
dmesg -T | egrep -i 'killed process'
-T
- readable timestamps
None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!
They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.
Tip - if you right click on Applications > Netbeans and choose Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules
To check if a string is empty or contains only whitespace you could use:
shopt -s extglob # more powerful pattern matching
if [ -n "${str##+([[:space:]])}" ]; then
echo '$str is not null or space'
fi
See Shell Parameter Expansion and Pattern Matching in the Bash Manual.
This is a moment.js flavored module based on the dirty blocking approach suggested by @atlex2. Use this only for testing.
const moment = require('moment');
let sleep = (secondsToSleep = 1) => {
let sleepUntill = moment().add(secondsToSleep, 'seconds');
while(moment().isBefore(sleepUntill)) { /* block the process */ }
}
module.exports = sleep;
This is way more simpler with Maven dependency feature:
Hope this will help!
The issue seems to be with autorelease of objects. NSJSONSerialization JSONObjectWithData is obviously creating some autoreleased objects and passing it back to you. If you try to take that on to a different thread, it will not work since it cannot be deallocated on a different thread.
Trick might be to try doing a mutable copy of that dictionary or array and use it.
NSError *e = nil;
id jsonObject = [NSJSONSerialization
JSONObjectWithData: data
options: NSJSONReadingMutableContainers
error: &e] mutableCopy];
Treating a NSDictionary as NSArray will not result in Bad access exception but instead will probably crash when a method call is made.
Also, may be the options do not really matter here but it is better to give NSJSONReadingMutableContainers | NSJSONReadingMutableContainers | NSJSONReadingAllowFragments but even if they are autoreleased objects it may not solve this issue.
You could create a lookup method. Not the most efficient (depending on the enum's size) but it works.
public static String getNameByCode(int code){
for(RelationActiveEnum e : RelationActiveEnum.values()){
if(code == e.value) return e.name();
}
return null;
}
And call it like this:
RelationActiveEnum.getNameByCode(3);
I think writing PHP into an .html file is confusing and anti-natural. Why would you do that??
Anyway, if what you want is to execute PHP files and show them as .html in the address bar, an easiest solution would be using .php as normal, and write a rule in your .htaccess like this:
RewriteRule ^([^.]+)\.html$ $1.php [L]
You can do it like this...
sudo /home/script.sh -opt1 > /tmp/script.out &
The other answers did not address my need for properly showing tooltips in a recent version of Jupyter inline matplotlib figure. This one works though:
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
np.random.seed(42)
fig, ax = plt.subplots()
ax.scatter(*np.random.random((2, 26)))
ax.set_title("Mouse over a point")
crs = mplcursors.cursor(ax,hover=True)
crs.connect("add", lambda sel: sel.annotation.set_text(
'Point {},{}'.format(sel.target[0], sel.target[1])))
plt.show()
Leading to something like the following picture when going over a point with mouse: