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.)
Solution:
Add the below line in your application
tag:
android:usesCleartextTraffic="true"
As shown below:
<application
....
android:usesCleartextTraffic="true"
....>
UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"
No Need to set clear text traffic to true as shown above, instead use the below code:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
....
....
</domain-config>
<base-config cleartextTrafficPermitted="false"/>
</network-security-config>
Set the cleartextTrafficPermitted
to true
Hope it helps.
Use LayoutBuilder
and Get the output you want
Wrap the SingleChildScrollView
with LayoutBuilder
and implement the Builder function.
we can use a LayoutBuilder
to get the box contains
or the amount of space available.
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints){
return SingleChildScrollView(
child: Stack(
children: <Widget>[
Container(
height: constraints.maxHeight,
),
topTitle(context),
middleView(context),
bottomView(context),
],
),
);
}
)
We have noticed that using the MediaQuery
class can be a bit cumbersome, and it’s also missing a couple of key pieces of information.
Here We have a small Screen helper class, that we use across all our new projects:
class Screen {
static double get _ppi => (Platform.isAndroid || Platform.isIOS)? 150 : 96;
static bool isLandscape(BuildContext c) => MediaQuery.of(c).orientation == Orientation.landscape;
//PIXELS
static Size size(BuildContext c) => MediaQuery.of(c).size;
static double width(BuildContext c) => size(c).width;
static double height(BuildContext c) => size(c).height;
static double diagonal(BuildContext c) {
Size s = size(c);
return sqrt((s.width * s.width) + (s.height * s.height));
}
//INCHES
static Size inches(BuildContext c) {
Size pxSize = size(c);
return Size(pxSize.width / _ppi, pxSize.height/ _ppi);
}
static double widthInches(BuildContext c) => inches(c).width;
static double heightInches(BuildContext c) => inches(c).height;
static double diagonalInches(BuildContext c) => diagonal(c) / _ppi;
}
To use
bool isLandscape = Screen.isLandscape(context)
bool isLargePhone = Screen.diagonal(context) > 720;
bool isTablet = Screen.diagonalInches(context) >= 7;
bool isNarrow = Screen.widthInches(context) < 3.5;
To More, See: https://blog.gskinner.com/archives/2020/03/flutter-simplify-platform-detection-responsive-sizing.html
I had same issue for windows , the cause of the problem was currupted or missing dll files. I had to change them.
In android studio ,
Help Menu -> Show log in explorer.
It opens log folder, where you can find all logs . In my situation error like "Emulator terminated with exit code -1073741515"
Go to folder ~\Android\Sdk\emulator
Run this command:
emulator.exe -netdelay none -netspeed full -avd <virtual device name>
ex: emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_26.avd
You can find this command from folder ~.android\avd\xxx.avd\emu-launch-params.txt
Search and download the appropriate vcruntime140.dll file for your system from the internet (32 / 64 bit version) , and replace it with the vcruntime140.dll file in the folder ~\Android\Sdk\emulator
Try step 1
If you get error about vcruntime140_1 , change the file name as vcruntime140_1.dll ,try step 1
If it runs , you can run it from Android Studio also.
append
on an ndarray is ambiguous; to which axis do you want to append the data? Without knowing precisely what your data looks like, I can only provide an example using numpy.concatenate
that I hope will help:
import numpy as np
pixels = np.array([[3,3]])
pix = [4,4]
pixels = np.concatenate((pixels,[pix]),axis=0)
# [[3 3]
# [4 4]]
use only
base64.b64decode(a)
instead of
base64.b64decode(a).decode('utf-8')
/* ----------- iPad Pro ----------- */
/* Portrait and Landscape */
@media only screen
and (min-width: 1024px)
and (max-height: 1366px)
and (-webkit-min-device-pixel-ratio: 1.5) {
}
/* Portrait */
@media only screen
and (min-width: 1024px)
and (max-height: 1366px)
and (orientation: portrait)
and (-webkit-min-device-pixel-ratio: 1.5) {
}
/* Landscape */
@media only screen
and (min-width: 1024px)
and (max-height: 1366px)
and (orientation: landscape)
and (-webkit-min-device-pixel-ratio: 1.5) {
}
I don't have an iPad Pro but this works for me in the Chrome simulator.
It is possible to get this working in VS Code and have the Cmder terminal be integrated (not pop up).
To do so:
"terminal.integrated.shell.windows": "cmd.exe"
"terminal.integrated.shellArgs.windows": ["/k", "%CMDER_ROOT%\\vendor\\init.bat"]
This worked well in React 16.11.0
// in customData.js
export const customData = {
//json data here
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
// in index.js
import { customData } from './customData';
// example usage later in index.js
<p>{customData.name}</p>
Best explanation for X = aY + b
(in fact it f(x) = ax + b
)) is provided at https://math.stackexchange.com/a/906280/357701
A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:
import cv2
img = cv2.imread('test.jpg')
cv2.imshow('test', img)
cv2.waitKey(1000)
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]
cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))
cv2.waitKey(1000)
raw_input()
You can do the following. Add your ggplot code after the first line of code and end with dev.off()
.
tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()
res=300
specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.
Change width
and height
in the code above depending on the desired output.
Note that this also works for other R
plots including plot
, image
, and pheatmap
.
Other file formats
In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.
class PushObjects {
testMethod(): Array<number> {
//declaration and initialisation of array onject
var objs: number[] = [1,2,3,4,5,7];
//push the elements into the array object
objs.push(100);
//pop the elements from the array
objs.pop();
return objs;
}
}
let pushObj = new PushObjects();
//create the button element from the dom object
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () {
alert(pushObj.testMethod());
}
document.body.appendChild(btn);
For Python 3, try the following:
import sys
!conda install --yes --prefix {sys.prefix} scikit-image
Please add this option:
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
(Reference: Chart.js)
N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion
Note: This is not a duplicate, because the OP is aware that the image from cv2.imread
is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)
To illustrate, I've opened up this same color JPEG image:
once using the conversion
img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
and another by loading it in gray scale mode
img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom
I've summed up the diff too to see
import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image
I tried all cv2.imread()
modes
Among all the IMREAD_
modes for cv2.imread()
, only IMREAD_COLOR
and IMREAD_ANYCOLOR
can be converted using COLOR_BGR2GRAY
, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE
The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)
Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.
In brief, let's not mix the versions and types in the processing pipeline.
So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)
in my app I do it like so (typescript and nested postcss, so change the code accordingly):
const appHeight = () => {
const doc = document.documentElement
doc.style.setProperty('--app-height', `${window.innerHeight}px`)
}
window.addEventListener('resize', appHeight)
appHeight()
in your css:
:root {
--app-height: 100%;
}
html,
body {
padding: 0;
margin: 0;
overflow: hidden;
width: 100vw;
height: 100vh;
@media not all and (hover:hover) {
height: var(--app-height);
}
}
it works at least on chrome mobile and ipad. What doesn't work is when you add your app to homescreen on iOS and change the orientation a few times - somehow the zoom levels mess with the innerHeight value, I might post an update if I find a solution to it.
You can use tf.convert_to_tensor()
:
import tensorflow as tf
import numpy as np
data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)
data_tf = tf.convert_to_tensor(data_np, np.float32)
sess = tf.InteractiveSession()
print(data_tf.eval())
sess.close()
Here's a link to the documentation for this method:
https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor
You turn off pack_propagate
by setting pack_propagate(0)
Turning off pack_propagate
here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally
To turn off resizing the root window, you can set root.resizable(0, 0)
, where resizing is allowed in the x
and y
directions respectively.
To set a maxsize to window, as noted in the other answer you can set the maxsize
attribute or minsize
although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.
Whenever you set grid
or pack
on a widget it will return None
. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid
or pack
on it. You should instead set the variable to be the widget Widget(master, ....)
and then call pack
or grid
on the widget instead.
import tkinter as tk
def startgame():
pass
mw = tk.Tk()
#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()
mw.mainloop()
PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.
Alternatively, try MobaXterm. It has an X server builtin.
You have to create Different values folder for different screens . Like
values-sw720dp 10.1” tablet 1280x800 mdpi
values-sw600dp 7.0” tablet 1024x600 mdpi
values-sw480dp 5.4” 480x854 mdpi
values-sw480dp 5.1” 480x800 mdpi
values-xxhdpi 5.5" 1080x1920 xxhdpi
values-xxxhdpi 5.5" 1440x2560 xxxhdpi
values-xhdpi 4.7” 1280x720 xhdpi
values-xhdpi 4.65” 720x1280 xhdpi
values-hdpi 4.0” 480x800 hdpi
values-hdpi 3.7” 480x854 hdpi
values-mdpi 3.2” 320x480 mdpi
values-ldpi 3.4” 240x432 ldpi
values-ldpi 3.3” 240x400 ldpi
values-ldpi 2.7” 240x320 ldpi
For more information you may visit here
Different values folders in android
http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html
Edited By @humblerookie
You can make use of Android Studio plugin called Dimenify to auto generate dimension values for other pixel buckets based on custom scale factors. Its still in beta, be sure to notify any issues/suggestions you come across to the developer.
You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.
Check the John Resig's post describing how helpful this method is.
The Main Reason for the denying permission is that we don’t have permission for drawing over another apps,We have to provide the permission for the Drawing over other apps that can be done by the following code
Request code for Permission
public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 5469;
add this in your MainActivity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
askPermission();
}
private void askPermission() {
Intent intent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName()));
startActivityForResult(intent,ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
Add this also
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE){
if(!Settings.canDrawOverlays(this)){
askPermission();
}
}
}
If you need (for example) a two digit approximation for A, then
int(A*100+0.5)/100.0
will do what you are looking for.
If you need three digit approximation multiply and divide by 1000 and so on.
calling of resizeimage method
let image1 = resizeimage(image: myimage.image!, withSize: CGSize(width:200, height: 200))
method for resizeing image
func resizeimage(image:UIImage,withSize:CGSize) -> UIImage {
var actualHeight:CGFloat = image.size.height
var actualWidth:CGFloat = image.size.width
let maxHeight:CGFloat = withSize.height
let maxWidth:CGFloat = withSize.width
var imgRatio:CGFloat = actualWidth/actualHeight
let maxRatio:CGFloat = maxWidth/maxHeight
let compressionQuality = 0.5
if (actualHeight>maxHeight||actualWidth>maxWidth) {
if (imgRatio<maxRatio){
//adjust width according to maxHeight
imgRatio = maxHeight/actualHeight
actualWidth = imgRatio * actualWidth
actualHeight = maxHeight
}else if(imgRatio>maxRatio){
// adjust height according to maxWidth
imgRatio = maxWidth/actualWidth
actualHeight = imgRatio * actualHeight
actualWidth = maxWidth
}else{
actualHeight = maxHeight
actualWidth = maxWidth
}
}
let rec:CGRect = CGRect(x:0.0,y:0.0,width:actualWidth,height:actualHeight)
UIGraphicsBeginImageContext(rec.size)
image.draw(in: rec)
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
let imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality))
UIGraphicsEndImageContext()
let resizedimage = UIImage(data: imageData!)
return resizedimage!
}
Depending on your version:
Python 2.x:
for key, val in PIX0.iteritems():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
Python 3.x:
for key, val in PIX0.items():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
You should also get in the habit of using the new string formatting syntax ({}
instead of %
operator) from PEP 3101:
I needed to find the position of an element inside a ListView and used this snippet that works kind of like .offset
:
const UIManager = require('NativeModules').UIManager;
const handle = React.findNodeHandle(this.refs.myElement);
UIManager.measureLayoutRelativeToParent(
handle,
(e) => {console.error(e)},
(x, y, w, h) => {
console.log('offset', x, y, w, h);
});
This assumes I had a ref='myElement'
on my component.
To handle this use case, you can use the <ImageBackground>
component, which has the same props as <Image>
, and add whatever children to it you would like to layer on top of it.
Example:
return (
<ImageBackground source={...} style={{width: '100%', height: '100%'}}>
<Text>Inside</Text>
</ImageBackground>
);
For more: ImageBackground | React Native
Note that you must specify some width and height style attributes.
To open the Eye Dropper simply:
Its main functionality is to inspect pixel color values by clicking them though with its new features you can also see your page's existing colors palette or material design palette by clicking on the two arrows icon at the bottom. It can get quite handy when designing your page.
Require Screen sizes for splash :
LDPI: Portrait: 200 X 320px
MDPI: Portrait: 320 X 480px
HDPI: Portrait: 480 X 800px
XHDPI: Portrait: 720 X 1280px
XXHDPI: Portrait: 960 X 1600px
XXXHDPI: Portrait: 1440 x 2560px
Require icon Sizes for App :
You don't need align="center"
and float:left
. Remove both of these. margin: 0 auto
is sufficient.
Swift 5 : For evenly distributed spaces between cells with dynamic cell width to make the best of container space you may use the code snippet below by providing a minimumCellWidth value.
private func collectionViewLayout() -> UICollectionViewLayout {
let layout = UICollectionViewFlowLayout()
layout.sectionHeadersPinToVisibleBounds = true
// Important: if direction is horizontal use minimumItemSpacing instead.
layout.scrollDirection = .vertical
let itemHeight: CGFloat = 240
let minCellWidth :CGFloat = 130.0
let minItemSpacing: CGFloat = 10
let containerWidth: CGFloat = self.view.bounds.width
let maxCellCountPerRow: CGFloat = floor((containerWidth - minItemSpacing) / (minCellWidth+minItemSpacing ))
let itemWidth: CGFloat = floor( ((containerWidth - (2 * minItemSpacing) - (maxCellCountPerRow-1) * minItemSpacing) / maxCellCountPerRow ) )
// Calculate the remaining space after substracting calculating cellWidth (Divide by 2 because of left and right insets)
let inset = max(minItemSpacing, floor( (containerWidth - (maxCellCountPerRow*itemWidth) - (maxCellCountPerRow-1)*minItemSpacing) / 2 ) )
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
layout.minimumInteritemSpacing = min(minItemSpacing,inset)
layout.minimumLineSpacing = minItemSpacing
layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom: minItemSpacing, right: inset)
return layout
}
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
This is discouraged (if you want to create/distribute a clean Docker image), since the PATH
variable is set by /etc/profile
script, the value can be overridden.
head /etc/profile
:
if [ "`id -u`" -eq 0 ]; then
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH
At the end of the Dockerfile, you could add:
RUN echo "export PATH=$PATH" > /etc/environment
So PATH is set for all users.
You should not put the windowManager.addView in onCreate
Try to call the windowManager.addView
after onWindowFocusChanged
and the status of hasFoucus
is true.
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
//code here
//that you can add a flag that you can call windowManager.addView now.
}
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
I think there is a much better approach, that allows for solid type-safety and scalability.
First declare interfaces that you want to implement on your target class:
interface IBar {
doBarThings(): void;
}
interface IBazz {
doBazzThings(): void;
}
class Foo implements IBar, IBazz {}
Now we have to add the implementation to the Foo
class. We can use class mixins that also implements these interfaces:
class Base {}
type Constructor<I = Base> = new (...args: any[]) => I;
function Bar<T extends Constructor>(constructor: T = Base as any) {
return class extends constructor implements IBar {
public doBarThings() {
console.log("Do bar!");
}
};
}
function Bazz<T extends Constructor>(constructor: T = Base as any) {
return class extends constructor implements IBazz {
public doBazzThings() {
console.log("Do bazz!");
}
};
}
Extend the Foo
class with the class mixins:
class Foo extends Bar(Bazz()) implements IBar, IBazz {
public doBarThings() {
super.doBarThings();
console.log("Override mixin");
}
}
const foo = new Foo();
foo.doBazzThings(); // Do bazz!
foo.doBarThings(); // Do bar! // Override mixin
ios will always tries to take the best image, but will fall back to other options .. so if you only have normal images in the app and it needs @2x images it will use the normal images.
if you only put @2x in the project and you open the app on a normal device it will scale the images down to display.
if you target ios7 and ios8 devices and want best quality you would need @2x and @3x for phone and normal and @2x for ipad assets, since there is no non retina phone left and no @3x ipad.
maybe it is better to create the assets in the app from vector graphic... check http://mattgemmell.com/using-pdf-images-in-ios-apps/
Make it simple : DEMO
section {_x000D_
display: flex;_x000D_
flex-flow: column;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: tomato;_x000D_
/* no flex rules, it will grow */_x000D_
}_x000D_
_x000D_
div {_x000D_
flex: 1; /* 1 and it will fill whole space left if no flex value are set to other children*/_x000D_
background: gold;_x000D_
overflow: auto;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background: lightgreen;_x000D_
min-height: 60px; /* min-height has its purpose :) , unless you meant height*/_x000D_
}
_x000D_
<section>_x000D_
<header>_x000D_
header: sized to content_x000D_
<br/>(but is it really?)_x000D_
</header>_x000D_
<div>_x000D_
main content: fills remaining space<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
<!-- uncomment to see it break -->_x000D_
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
<!-- -->_x000D_
</div>_x000D_
<footer>_x000D_
footer: fixed height in px_x000D_
</footer>_x000D_
</section>
_x000D_
Full screen version
section {_x000D_
display: flex;_x000D_
flex-flow: column;_x000D_
height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: tomato;_x000D_
/* no flex rules, it will grow */_x000D_
}_x000D_
_x000D_
div {_x000D_
flex: 1;_x000D_
/* 1 and it will fill whole space left if no flex value are set to other children*/_x000D_
background: gold;_x000D_
overflow: auto;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background: lightgreen;_x000D_
min-height: 60px;_x000D_
/* min-height has its purpose :) , unless you meant height*/_x000D_
}_x000D_
_x000D_
body {_x000D_
margin: 0;_x000D_
}
_x000D_
<section>_x000D_
<header>_x000D_
header: sized to content_x000D_
<br/>(but is it really?)_x000D_
</header>_x000D_
<div>_x000D_
main content: fills remaining space<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
<!-- uncomment to see it break -->_x000D_
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
<!-- -->_x000D_
</div>_x000D_
<footer>_x000D_
footer: fixed height in px_x000D_
</footer>_x000D_
</section>
_x000D_
Works particularly great for Google Earth Studio images:
ffmpeg -framerate 24 -i Project%03d.png Project.mp4
You can't make window.open
modal and I strongly recommend you not to go that way.
Instead you can use something like jQuery UI's dialog widget.
UPDATE:
You can use load()
method:
$("#dialog").load("resource.php").dialog({options});
This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.
And you can use an IFRAME:
$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});
This is slower, but will submit independently.
Give your body
tag an overflow: scroll;
body {
overflow: scroll;
}
or if you only want a vertical scrollbar use overflow-y
body {
overflow-y: scroll;
}
So, perhaps this is a bit clunky but so far so good. Im working in angular 9.
file .ts
scroll(el: HTMLElement) {
el.scrollIntoView({ block: 'start', behavior: 'smooth' });
}
file .html
<button (click)="scroll(target)"></button>
<div #target style="margin-top:-50px;padding-top: 50px;" ></div>
I adjust the offset with margin and padding top.
Saludos!
No, not all browsers support the sizes
attribute:
Note that some platforms define specific sizes:
manifest.json
if it is present. Plus, Chrome uses the Apple Touch icon for bookmarks.And if you have this problem in slider or slideshow you must use jquery.easing.1.3
:
<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>
I would not use .at for performance reasons.
Define a struct:
//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
uchar blue;
uchar green;
uchar red; };
And then use it like this on your cv::Mat image:
RGB& rgb = image.ptr<RGB>(y)[x];
image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y
This answer similar to others, but using preferred stringr::str_detect
and dplyr rownames_to_column
.
library(tidyverse)
mtcars %>%
rownames_to_column("type") %>%
filter(stringr::str_detect(type, 'Toyota|Mazda') )
#> type mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 2 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 3 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
#> 4 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
Created on 2018-06-26 by the reprex package (v0.2.0).
Your log complains about not finding exportfs:
sudo: /usr/bin/exportfs: command not found
The exportfs makes local directories available for NFS clients to mount.
However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
@theczechsensation's solution is already half way there.
For those who like to exclude noisy log messages and keep the log to their app only this is the solution:
Add your exclusions to Log Tag like this: ^(?!(eglCodecCommon|tagToExclude))
Add your package name or prefix to Package Name: com.mycompany.
This way it is possible to filter for as many strings you like and keep the log to your package.
Displaying an Image
in WPF is much easier than that. Try this:
<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left"
Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom"
Grid.Row="8" Width="200" Grid.ColumnSpan="2" />
And the property can just be a string
:
public string DisplayedImage
{
get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}
Although you really should add your images to a folder named Images
in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
UPDATE >>>
As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.
UPDATE 2 >>>
If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image
control. Using the string
property that I suggested, try this:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
If you can't see the file path in the TextBlock
, then you probably haven't set your DataContext
to the instance of your view model. If you can see the text, then the problem is with your file path.
UPDATE 3 >>>
In .NET 4, the above Image.Source
values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack
path like this:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.
Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
Means you are not passing numbers into the google.maps.LatLng constructor. Per your comment:
/*Information from chromium debugger
trader: Object
geo: Object
lat: "49.014821"
lon: "10.985072"
*/
trader.geo.lat and trader.geo.lon are strings, not numbers. Use parseFloat to convert them to numbers:
var myLatlng = new google.maps.LatLng(parseFloat(trader.geo.lat),parseFloat(trader.geo.lon));
Tested code for getting height of navigation bar (in pixels):
public static int getNavBarHeight(Context c) {
int resourceId = c.getResources()
.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
return c.getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
Tested code for getting height of status bar (in pixels):
public static int getStatusBarHeight(Context c) {
int resourceId = c.getResources()
.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
return c.getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
Converting pixels to dp:
public static int pxToDp(int px) {
return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}
I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics
If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.
Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.
>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
[3, 0, 1, 2],
[2, 0, 1, 1],
[4, 0, 2, 3],
[0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False, True, True, True],
[False, True, True, True],
[ True, True, True, True],
[False, True, True, False],
[ True, True, True, True]], dtype=bool)
>>>
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 0],
[1, 1, 1, 1]])
You can shorten this with:
>>> c = (a < 3).astype(int)
For your information you could use grid but with side effects :)
.parent {
display: grid
}
From official documentation. Maybe you can use it in your case.
When you need equal height, add .h-100 to the cards.
<div class="row row-cols-1 row-cols-md-3 g-4">
<div class="col">
<div class="card h-100">
<div>.....</div>
</div>
<div class="col">
<div class="card h-100">
<div>.....</div>
</div>
You can consider using numpy.putmask:
np.putmask(arr, arr>=T, 255.0)
Here is a performance comparison with the Numpy's builtin indexing:
In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit np.putmask(A, A>0.5, 5)
1000 loops, best of 3: 1.34 ms per loop
In [4]: timeit A[A > 0.5] = 5
1000 loops, best of 3: 1.82 ms per loop
Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.
Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px
I start my line :
<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
<tr style="height:40px; width:450px; margin:0;">
<td style="height:40px; width:40px; margin:0;">
<img src="" style="width=40px;height40;margin:0;display:block"
</td>
<td style="height:40px; width:10px; margin:0;">
</td>
<td style="height:40px; width:400px; margin:0;">
<p style=" margin:0;"> my text </p>
</td>
</tr>
</table>
The reference to 480px has been removed. Instead it says:
/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */
There isn't a breakpoint below 768px in Bootstrap 3.
If you want to use the @screen-sm-min
and other mixins then you need to be compiling with LESS, see http://getbootstrap.com/css/#grid-less
Here's a tutorial on how to use Bootstrap 3 and LESS: http://www.helloerik.com/bootstrap-3-less-workflow-tutorial
Just to make this thread more complete i am adding my version of answer:
What i wanted to achieve: The surface view shouldn't be stretched, and it should cover the whole screen, Moreover, there was only a landscape mode in my app.
Solution:
The solution is an extremely small extension to F1sher's solution:
=> First step is to integrate F1sher's solution.
=> Now, there might arise a scenario in F1sher's solution when the surface view doesn't covers the whole screen, The solution is to make the surface view greater than the screen dimensions so that it covers the whole screen, for that:
size = getOptimalPreviewSize(mCamera.getParameters().getSupportedPreviewSizes(), screenWidth, screenHeight);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(size.width, size.height);
mCamera.setParameters(parameters);
double screenRatio = (double) screenHeight / screenWidth;
double previewRatio = (double) size.height / size.width;
if (previewRatio > screenRatio) /*if preview ratio is greater than screen ratio then we will have to recalculate the surface height while keeping the surface width equal to the screen width*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
else /*if preview ratio is smaller than screen ratio then we will have to recalculate the surface width while keeping the surface height equal to the screen height*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
flPreview.addView(mPreview);
/* The TopMost layout used is the RelativeLayout, flPreview is the FrameLayout in which Surface View is added, mPreview is an instance of a class which extends SurfaceView */
Seems like a Permissions Issue. I was facing the same error. But when I ran it from the root account, it worked. So either give the read permission to the file using chmod (in linux) or run your script after logging in as a root user.
You are specifying .fixedbutton
in your CSS (a class) and specifying the id
on the element itself.
Change your CSS to the following, which will select the id
fixedbutton
#fixedbutton {
position: fixed;
bottom: 0px;
right: 0px;
}
$(document).ready(function(){
var div=$('#header');
var start=$(div).offset().top;
$.event.add(window,'scroll',function(){
var p=$(window).scrollTop();
$(div).css('position',(p>start)?'fixed':'static');
$(div).css('top',(p>start)?'0px':'');
});
});
It works perfectly.
In this instance, your div
elements have been changed from block
level elements to inline
elements. A typical characteristic of inline
elements is that they respect the whitespace in the markup. This explains why a gap of space is generated between the elements. (example)
There are a few solutions that can be used to solve this.
Example 1 - Comment the whitespace out: (example)
<div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div>
Example 2 - Remove the line breaks: (example)
<div>text</div><div>text</div><div>text</div><div>text</div><div>text</div>
Example 3 - Close part of the tag on the next line (example)
<div>text</div
><div>text</div
><div>text</div
><div>text</div
><div>text</div>
Example 4 - Close the entire tag on the next line: (example)
<div>text
</div><div>text
</div><div>text
</div><div>text
</div><div>text
</div>
font-size
Since the whitespace between the inline
elements is determined by the font-size
, you could simply reset the font-size
to 0
, and thus remove the space between the elements.
Just set font-size: 0
on the parent elements, and then declare a new font-size
for the children elements. This works, as demonstrated here (example)
#parent {
font-size: 0;
}
#child {
font-size: 16px;
}
This method works pretty well, as it doesn't require a change in the markup; however, it doesn't work if the child element's font-size
is declared using em
units. I would therefore recommend removing the whitespace from the markup, or alternatively floating the elements and thus avoiding the space generated by inline
elements.
display: flex
In some cases, you can also set the display
of the parent element to flex
. (example)
This effectively removes the spaces between the elements in supported browsers. Don't forget to add appropriate vendor prefixes for additional support.
.parent {
display: flex;
}
.parent > div {
display: inline-block;
padding: 1em;
border: 2px solid #f00;
}
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.parent > div {_x000D_
display: inline-block;_x000D_
padding: 1em;_x000D_
border: 2px solid #f00;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
</div>
_x000D_
It is incredibly unreliable to use negative margins to remove the space between inline
elements. Please don't use negative margins if there are other, more optimal, solutions.
You should rather use ViewPropertyAnimator. This animates the view to its future position and you don't need to force any layout params on the view after the animation ends. And it's rather simple.
myView.animate().x(50f).y(100f);
myView.animate().translateX(pixelInScreen)
Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.
override func viewDidLoad() {
// your code
if let nc = self.navigationController {
yourView.frame.origin.y = nc.navigationBar.frame.origin.y + nc.navigationBar.frame.height
}
}
if I add a tableHeaderView with a really small height, it fixes the problem
let v = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.000000001))
tableViewDocuments.tableHeaderView = v
Using overflow: auto
on the <body>
tag is a cleaner solution and will work a charm.
You don't have to do it this complicated way. If you are using XCode 5 (which I am sure most of us are) then create your icons call them whatever you like i.e.
And drag and drop them on to the correct boxes under AppIcon. See screenshots. You don't have to manually edit plist file.
You can use something like this,
var element = document.getElementById("yourDivID");
window.scrollTo(0,element.offsetHeight);
Simply get the current item from pager and then ask your adapter to the fragment of that position.
int currentItem = viewPager.getCurrentItem();
Fragment item = mPagerAdapter.getItem(currentItem);
if (null != item && item.isVisible()) {
//do whatever want to do with fragment after doing type checking
return;
}
So far the best solution to accept seems to be <img class="center-block" ... />
. But no one has mentioned how center-block
works.
Take Bootstrap v3.3.6 for example:
.center-block {
display: block;
margin-right: auto;
margin-left: auto;
}
The default value of dispaly
for <img>
is inline
. Value block
will display an element as a block element (like <p>
). It starts on a new line, and takes up the whole width. In this way, the two margin settings let the image stay in the middle horizontally.
New versions of excel have made old answers obsolete. It took a long time to make this, but it does a pretty good job. Note that the maximum image size is limited and the aspect ratio is ever so slightly off, as I was not able to perfectly optimize the reshaping math. Note that I've named one of my worksheets wsTMP, you can replace it with Sheet1 or the like. Takes about 1 second to print the screenshot to target path.
Option Explicit
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Sub weGucciFam()
Dim tmp As Variant, str As String, h As Double, w As Double
Application.PrintCommunication = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
If Application.StatusBar = False Then Application.StatusBar = "EVENTS DISABLED"
keybd_event vbKeyMenu, 0, 0, 0 'these do just active window
keybd_event vbKeySnapshot, 0, 0, 0
keybd_event vbKeySnapshot, 0, 2, 0
keybd_event vbKeyMenu, 0, 2, 0 'sendkeys alt+printscreen doesn't work
wsTMP.Paste
DoEvents
Const dw As Double = 1186.56
Const dh As Double = 755.28
str = "C:\Users\YOURUSERNAMEHERE\Desktop\Screenshot.jpeg"
w = wsTMP.Shapes(1).Width
h = wsTMP.Shapes(1).Height
Application.DisplayAlerts = False
Set tmp = Charts.Add
On Error Resume Next
With tmp
.PageSetup.PaperSize = xlPaper11x17
.PageSetup.TopMargin = IIf(w > dw, dh - dw * h / w, dh - h) + 28
.PageSetup.BottomMargin = 0
.PageSetup.RightMargin = IIf(h > dh, dw - dh * w / h, dw - w) + 36
.PageSetup.LeftMargin = 0
.PageSetup.HeaderMargin = 0
.PageSetup.FooterMargin = 0
.SeriesCollection(1).Delete
DoEvents
.Paste
DoEvents
.Export Filename:=str, Filtername:="jpeg"
.Delete
End With
On Error GoTo 0
Do Until wsTMP.Shapes.Count < 1
wsTMP.Shapes(1).Delete
Loop
Application.PrintCommunication = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False
End Sub
Having the same error trying to install matplotlib for Python 3, those solutions didn't work for me. It was just a matter of dependencies, though it wasn't clear in the error message.
I used sudo apt-get build-dep python3-matplotlib
then sudo pip3 install matplotlib
and it worked.
Hope it'll help !
It can be achieved using JS. Here is a 'one-line' solution using elastic.js:
$('#note').elastic();
Updated: Seems like elastic.js is not there anymore, but if you are looking for an external library, I can recommend autosize.js by Jack Moore. This is the working example:
autosize(document.getElementById("note"));
_x000D_
textarea#note {_x000D_
width:100%;_x000D_
box-sizing:border-box;_x000D_
direction:rtl;_x000D_
display:block;_x000D_
max-width:100%;_x000D_
line-height:1.5;_x000D_
padding:15px 15px 30px;_x000D_
border-radius:3px;_x000D_
border:1px solid #F7E98D;_x000D_
font:13px Tahoma, cursive;_x000D_
transition:box-shadow 0.5s ease;_x000D_
box-shadow:0 4px 6px rgba(0,0,0,0.1);_x000D_
font-smoothing:subpixel-antialiased;_x000D_
background:linear-gradient(#F9EFAF, #F7E98D);_x000D_
background:-o-linear-gradient(#F9EFAF, #F7E98D);_x000D_
background:-ms-linear-gradient(#F9EFAF, #F7E98D);_x000D_
background:-moz-linear-gradient(#F9EFAF, #F7E98D);_x000D_
background:-webkit-linear-gradient(#F9EFAF, #F7E98D);_x000D_
}
_x000D_
<script src="https://rawgit.com/jackmoore/autosize/master/dist/autosize.min.js"></script>_x000D_
<textarea id="note">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</textarea>
_x000D_
Check this similar topics too:
Autosizing textarea using Prototype
From Chris Coyier's article on centering percentage width elements:
Instead of using negative margins, you use negative
translate()
transforms.
.center {
position: absolute;
left: 50%;
top: 50%;
/*
Nope =(
margin-left: -25%;
margin-top: -25%;
*/
/*
Yep!
*/
transform: translate(-50%, -50%);
/*
Not even necessary really.
e.g. Height could be left out!
*/
width: 40%;
height: 50%;
}
I just found an easy solution for myself. Had an margin-top of 15px
HTML
<h2 id="Anchor">Anchor</h2>
CSS
h2{margin-top:-60px; padding-top:75px;}
You should use options.addAll(allPoints);
instead of options.add(point);
For Android 3+:
In the Project window, select the Android view.
Right-click the res folder and select New > Image Asset.
If your app supports Android 8.0, create adaptive and legacy launcher icons.
If your app supports versions no higher than Android 7.1, create a legacy launcher icon only.
In the Icon Type field, select Launcher Icons (Legacy Only) .
Select an Asset Type, and then specify the asset in the field underneath.
replace your image tag with
<img src="http://localhost:6054/wp-content/themes/BLANK-Theme/images/material/images.jpg" alt="the-buzz-img3" style="width:640px;height:360px" />
use style attribute and make sure there is no css class for image which set image height and width
I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.
Just for the records you can also define your object in the controller like this:
this.styleDiv = {color: '', backgroundColor:'', backgroundImage : '' };
and then you can define a function to change the property of the object directly:
this.changeBackgroundImage = function (){
this.styleDiv.backgroundImage = 'url('+this.backgroundImage+')';
}
Doing it in that way you can modify dinamicaly your style.
Thats too easy to use javascrpt. thats not hover problem thats focus problem. set outline to none when focus using css.
.button:focus {
outline: none;
}
Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
data = np.arange(250, 260)
for ax, d in zip(axs.ravel(), data):
ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
ax.set_title(str(d))
I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:
div {
width: 100%;
height: 0;
padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
position: relative;
}
div iframe {
width: 100%;
height: 100%;
position: absolute;
display: block;
top: 0;
left: 0;
}
Just did it now for a client, and it seems to be working: http://themilkrunsa.co.za/
This works regardless of the size of its contents
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
source: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/
<div>
<h1> Ok </h1>
<button type='button'>Button</button>
<div style="clear:both;"></div>
</div>
css
div {
background: purple;
}
div h1 {
text-align: center;
}
div button {
float: right;
margin-right:10px;
}
What's wrong with actually using ng-animate
for ng-show
as you mentioned?
<script src="lib/angulr.js"></script>
<script src="lib/angulr_animate.js"></script>
<script>
var app=angular.module('ang_app', ['ngAnimate']);
app.controller('ang_control01_main', function($scope) {
});
</script>
<style>
#myDiv {
transition: .5s;
background-color: lightblue;
height: 100px;
}
#myDiv.ng-hide {
height: 0;
}
</style>
<body ng-app="ang_app" ng-controller="ang_control01_main">
<input type="checkbox" ng-model="myCheck">
<div id="myDiv" ng-show="myCheck"></div>
</body>
Try updating the line to:
ocr.Init(@"C:\", "eng", false); // the path here should be the parent folder of tessdata
This hack 100% work only for safari 5.1-6.0. I've just tested it with success.
@media only screen and (-webkit-min-device-pixel-ratio: 1) {
::i-block-chrome, .yourcssrule {
your css property
}
}
If you add text-align: center
to the declarations for .columns-container
then they align centrally:
.columns-container {
display: table-cell;
height: 100%;
width:600px;
text-align: center;
}
/*************************_x000D_
* Sticky footer hack_x000D_
* Source: http://pixelsvsbytes.com/blog/2011/09/sticky-css-footers-the-flexible-way/_x000D_
************************/_x000D_
_x000D_
/* Stretching all container's parents to full height */_x000D_
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
/* Setting the container to be a table with maximum width and height */_x000D_
_x000D_
#container {_x000D_
display: table;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
/* All sections (container's children) should be table rows with minimal height */_x000D_
_x000D_
.section {_x000D_
display: table-row;_x000D_
height: 1px;_x000D_
}_x000D_
/* The last-but-one section should be stretched to automatic height */_x000D_
_x000D_
.section.expand {_x000D_
height: auto;_x000D_
}_x000D_
/*************************_x000D_
* Full height columns_x000D_
************************/_x000D_
_x000D_
/* We need one extra container, setting it to full width */_x000D_
_x000D_
.columns-container {_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
width:600px;_x000D_
text-align: center;_x000D_
}_x000D_
/* Creating columns */_x000D_
_x000D_
.column {_x000D_
/* The float:left won't work for Chrome for some reason, so inline-block */_x000D_
display: inline-block;_x000D_
/* for this to work, the .column elements should have NO SPACE BETWEEN THEM */_x000D_
vertical-align: top;_x000D_
height: 100%;_x000D_
width: 100px;_x000D_
}_x000D_
/****************************************************************_x000D_
* Just some coloring so that we're able to see height of columns_x000D_
****************************************************************/_x000D_
_x000D_
header {_x000D_
background-color: yellow;_x000D_
}_x000D_
#a {_x000D_
background-color: pink;_x000D_
}_x000D_
#b {_x000D_
background-color: lightgreen;_x000D_
}_x000D_
#c {_x000D_
background-color: lightblue;_x000D_
}_x000D_
footer {_x000D_
background-color: purple;_x000D_
}
_x000D_
<div id="container">_x000D_
<header class="section">_x000D_
foo_x000D_
</header>_x000D_
_x000D_
<div class="section expand">_x000D_
<div class="columns-container">_x000D_
<div class="column" id="a">_x000D_
<p>Contents A</p>_x000D_
</div>_x000D_
<div class="column" id="b">_x000D_
<p>Contents B</p>_x000D_
</div>_x000D_
<div class="column" id="c">_x000D_
<p>Contents C</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<footer class="section">_x000D_
bar_x000D_
</footer>_x000D_
</div>
_x000D_
This does, though, require that you reset the .column
elements to text-align: left
(assuming you want them left-aligned, obviously (JS Fiddle demo).
You need to ensure the html and body are set to 100% and also be sure to add vendor prefixes for calc, so -moz-calc, -webkit-calc.
Following CSS works:
html,body {
background: blue;
height:100%;
padding:0;
margin:0;
}
header {
background: red;
height: 20px;
width:100%
}
h1 {
font-size:1.2em;
margin:0;
padding:0;
height: 30px;
font-weight: bold;
background:yellow
}
#theCalcDiv {
background:green;
height: -moz-calc(100% - (20px + 30px));
height: -webkit-calc(100% - (20px + 30px));
height: calc(100% - (20px + 30px));
display:block
}
I also set your margin/padding to 0 on html and body, otherwise there would be a scrollbar when this is added on.
Here's an updated fiddle
Browser support is: IE9+, Firefox 16+ and with vendor prefix Firefox 4+, Chrome 19+, Safari 6+
Do I need to double the size of the .box div to 400px by 400px to match the new high res background image
No, but you do need to set the background-size
property to match the original dimensions:
@media (-webkit-min-device-pixel-ratio: 2),
(min-resolution: 192dpi) {
.box{
background:url('images/[email protected]') no-repeat top left;
background-size: 200px 200px;
}
}
EDIT
To add a little more to this answer, here is the retina detection query I tend to use:
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and ( min--moz-device-pixel-ratio: 2),
only screen and ( -o-min-device-pixel-ratio: 2/1),
only screen and ( min-device-pixel-ratio: 2),
only screen and ( min-resolution: 192dpi),
only screen and ( min-resolution: 2dppx) {
}
NB. This min--moz-device-pixel-ratio:
is not a typo. It is a well documented bug in certain versions of Firefox and should be written like this in order to support older versions (prior to Firefox 16).
- Source
As @LiamNewmarch mentioned in the comments below, you can include the background-size
in your shorthand background
declaration like so:
.box{
background:url('images/[email protected]') no-repeat top left / 200px 200px;
}
However, I personally would not advise using the shorthand form as it is not supported in iOS <= 6 or Android making it unreliable in most situations.
Always have your element with this attribute:
JavaScript: element.style.fontSize = "100%";
or
CSS: style = "font-size: 100%;"
When you go fullscreen, you should already have a scale variable calculated (scale > 1 or scale = 1). Then, on fullscreen:
document.body.style.fontSize = (scale * 100) + "%";
It works nicely with little code.
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.
To clear a canvas, use the delete method. Give it the special parameter "all"
to delete all items on the canvas (the string "all"
" is a special tag that represents all items on the canvas):
canvas.delete("all")
If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all"
, you could supply the name of a tag.
If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.
The solution from the blog Prevent desktop lock or screensaver with PowerShell is working for me. Here is the relevant script, which simply sends a single period to the shell:
param($minutes = 60)
$myshell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
Start-Sleep -Seconds 60
$myshell.sendkeys(".")
}
and an alternative from the comments, which moves the mouse a single pixel:
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + 1) , $Pos.Y)
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) - 1) , $Pos.Y)
Try line-height
like I've done here:
http://jsfiddle.net/BqTUS/5/
Alternatively, you could use tensorflow for the cropping and openCV for making an array from the image.
import cv2
img = cv2.imread('YOURIMAGE.png')
Now img
is a (imageheight, imagewidth, 3) shape array. Crop the array with tensorflow:
import tensorflow as tf
offset_height=0
offset_width=0
target_height=500
target_width=500
x = tf.image.crop_to_bounding_box(
img, offset_height, offset_width, target_height, target_width
)
Reassemble the image with tf.keras, so we can look at it if it worked:
tf.keras.preprocessing.image.array_to_img(
x, data_format=None, scale=True, dtype=None
)
This prints out the pic in a notebook (tested in Google Colab).
The whole code together:
import cv2
img = cv2.imread('YOURIMAGE.png')
import tensorflow as tf
offset_height=0
offset_width=0
target_height=500
target_width=500
x = tf.image.crop_to_bounding_box(
img, offset_height, offset_width, target_height, target_width
)
tf.keras.preprocessing.image.array_to_img(
x, data_format=None, scale=True, dtype=None
)
It is the area of the marker. I mean if you have s1 = 1000
and then s2 = 4000
, the relation between the radius of each circle is: r_s2 = 2 * r_s1
. See the following plot:
plt.scatter(2, 1, s=4000, c='r')
plt.scatter(2, 1, s=1000 ,c='b')
plt.scatter(2, 1, s=10, c='g')
I had the same doubt when I saw the post, so I did this example then I used a ruler on the screen to measure the radii.
Try this :
width:auto;
margin-right:50px;
You want getActivity()
inside your class. It's better to use
yourclassname.this.getActivity()
Try this. It's helpful for you.
You can, using CSS variables (more precisely called CSS custom properties).
style="--my-color-var: orange;"
background-color: var(--my-color-var);
div {
width: 100px;
height: 100px;
position: relative;
border: 1px solid black;
}
div:after {
background-color: var(--my-color-var);
content: '';
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
_x000D_
<div style="--my-color-var: orange;"></div>
_x000D_
.bubble {
position: relative;
width: 30px;
height: 15px;
padding: 0;
background: #FFF;
border: 1px solid #000;
border-radius: 5px;
text-align: center;
background-color: var(--bubble-color);
}
.bubble:after {
content: "";
position: absolute;
top: 4px;
left: -4px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent var(--bubble-color);
display: block;
width: 0;
z-index: 1;
}
.bubble:before {
content: "";
position: absolute;
top: 4px;
left: -5px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent #000;
display: block;
width: 0;
z-index: 0;
}
_x000D_
<div class='bubble' style="--bubble-color: rgb(100,255,255);"> 100 </div>
_x000D_
I would suggest checking the drivers and updating them if required.
<style>
background: url(images/Untitled-2.fw.png);
background-repeat:no-repeat;
background-position:center;
background-size: cover;
</style>
For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..
function AbsoluteCoordinates($element) {
var sTop = $(window).scrollTop();
var sLeft = $(window).scrollLeft();
var w = $element.width();
var h = $element.height();
var offset = $element.offset();
var $p = $element;
while(typeof $p == 'object') {
var pOffset = $p.parent().offset();
if(typeof pOffset == 'undefined') break;
offset.left = offset.left + (pOffset.left);
offset.top = offset.top + (pOffset.top);
$p = $p.parent();
}
var pos = {
left: offset.left + sLeft,
right: offset.left + w + sLeft,
top: offset.top + sTop,
bottom: offset.top + h + sTop,
}
pos.tl = { x: pos.left, y: pos.top };
pos.tr = { x: pos.right, y: pos.top };
pos.bl = { x: pos.left, y: pos.bottom };
pos.br = { x: pos.right, y: pos.bottom };
//console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom );
return pos;
}
try giving border in % for exapmle 0.1% according to your need.
This solution works for matplotlib versions 3.0.1, 3.0.3 and 3.2.1.
def save_inp_as_output(_img, c_name, dpi=100):
h, w, _ = _img.shape
fig, axes = plt.subplots(figsize=(h/dpi, w/dpi))
fig.subplots_adjust(top=1.0, bottom=0, right=1.0, left=0, hspace=0, wspace=0)
axes.imshow(_img)
axes.axis('off')
plt.savefig(c_name, dpi=dpi, format='jpeg')
Because the subplots_adjust setting makes the axis fill the figure, you don't want to specify a bbox_inches='tight', as it actually creates whitespace padding in this case. This solution works when you have more than 1 subplot also.
Just use this website: http://ticons.fokkezb.nl :)
It makes it easier for you, and generates the correct sizes directly
From plt.imshow()
official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 10000, 0, 10], aspect = 1000)
Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.
plt.imshow(data, origin = 'lower', extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')
To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1]
and y_max - y_min = y_res * data.shape[0]
, where extent = [x_min, x_max, y_min, y_max]
. By default, aspect = 1
, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower', extent = [0, 5, 0, 5])
The aspect of color pixel is x_res / y_res
. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])
) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.5)
The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.2)
Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.
When animating height (from 0 to auto), using transform: scaleY(0);
is another useful approach to hide the element, instead of display: none;
:
.section {
overflow: hidden;
transition: transform 0.3s ease-out;
height: auto;
transform: scaleY(1);
transform-origin: top;
&.hidden {
transform: scaleY(0);
}
}
I looked around the internet for correct dimensions for these densities for square images, but couldn't find anything reliable.
If it's any consolation, referring to Veerababu Medisetti's answer I used these dimensions for SQUARES :)
xxxhdpi: 1280x1280 px
xxhdpi: 960x960 px
xhdpi: 640x640 px
hdpi: 480x480 px
mdpi: 320x320 px
ldpi: 240x240 px
Here is a Swift way to get screen status bar height:
var screenStatusBarHeight: CGFloat {
return UIApplication.sharedApplication().statusBarFrame.height
}
These are included as a standard function in a project of mine: https://github.com/goktugyil/EZSwiftExtensions
I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:
plt.title(figure_title, y=1.08)
This also works for plt.suptitle()
, but not (yet) for plt.xlabel()
, etc.
In my example i am adding an ImageView to a LinearLayout programatically. I have set top and bottom margins to ImagerView. Then adding the ImageView to the LinearLayout.
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(bitmap);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 20, 0, 40);
imageView.setLayoutParams(params);
linearLayout.addView(imageView);
As it has more pixels in height, things like GCRectMake that use coordinates won't work seamlessly between versions, as it happened when we got the Retina.
Well, they do work the same with Retina displays - it's just that 1 unit in the CoreGraphics coordinate system will correspond to 2 physical pixels, but you don't/didn't have to do anything, the logic stayed the same. (Have you actually tried to run one of your non-retina apps on a retina iPhone, ever?)
For the actual question: that's why you shouldn't use explicit CGRectMakes and co... That's why you have stuff like [[UIScreen mainScreen] applicationFrame]
.
Using xCode 5, select "Migrate to Asset Catalog" on Project>General.
Then use "Show in finder" to find your launch image, you can dummy-edit it to be 640x1136, then drag it into the asset catalog as shown in the image below.
Make sure that both iOS7 and iOS6 R4 section has an image that is 640x1136. Next time you launch the app, the black bars will disappear, and your app will use 4 inch screen
Try jQuery:
$("#banner-contenedor").width();
The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array
:
size_in_bytes = my_numpy_array.nbytes
Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.
This answer https://stackoverflow.com/a/33149413/6481542 got me 90% of the way with uploading large files to a development Django server, but I had to use setFixedLengthStreamingMode to make it worked. That requires setting the Content-Length before writing the content, thus requiring a fairly significant rewrite of the above answer. Here's my end result
public class MultipartLargeUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
private final int maxBufferSize = 4096;
private long contentLength = 0;
private URL url;
private List<FormField> fields;
private List<FilePart> files;
private class FormField {
public String name;
public String value;
public FormField(String name, String value) {
this.name = name;
this.value = value;
}
}
private class FilePart {
public String fieldName;
public File uploadFile;
public FilePart(String fieldName, File uploadFile) {
this.fieldName = fieldName;
this.uploadFile = uploadFile;
}
}
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* @param requestURL
* @param charset
* @throws IOException
*/
public MultipartLargeUtility(String requestURL, String charset, boolean requireCSRF)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
url = new URL(requestURL);
fields = new ArrayList<>();
files = new ArrayList<>();
if (requireCSRF) {
getCSRF();
}
}
/**
* Adds a form field to the request
*
* @param name field name
* @param value field value
*/
public void addFormField(String name, String value)
throws UnsupportedEncodingException {
String fieldContent = "--" + boundary + LINE_FEED;
fieldContent += "Content-Disposition: form-data; name=\"" + name + "\"" + LINE_FEED;
fieldContent += "Content-Type: text/plain; charset=" + charset + LINE_FEED;
fieldContent += LINE_FEED;
fieldContent += value + LINE_FEED;
contentLength += fieldContent.getBytes(charset).length;
fields.add(new FormField(name, value));
}
/**
* Adds a upload file section to the request
*
* @param fieldName name attribute in <input type="file" name="..." />
* @param uploadFile a File to be uploaded
* @throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
String fieldContent = "--" + boundary + LINE_FEED;
fieldContent += "Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"" + LINE_FEED;
fieldContent += "Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName) + LINE_FEED;
fieldContent += "Content-Transfer-Encoding: binary" + LINE_FEED;
fieldContent += LINE_FEED;
// file content would go here
fieldContent += LINE_FEED;
contentLength += fieldContent.getBytes(charset).length;
contentLength += uploadFile.length();
files.add(new FilePart(fieldName, uploadFile));
}
/**
* Adds a header field to the request.
*
* @param name - name of the header field
* @param value - value of the header field
*/
//public void addHeaderField(String name, String value) {
// writer.append(name + ": " + value).append(LINE_FEED);
// writer.flush();
//}
/**
* Completes the request and receives response from the server.
*
* @return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* @throws IOException
*/
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
String content = "--" + boundary + "--" + LINE_FEED;
contentLength += content.getBytes(charset).length;
if (!openConnection()) {
return response;
}
writeContent();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
private boolean getCSRF()
throws IOException {
/// First, need to get CSRF token from server
/// Use GET request to get the token
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("GET");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.getContent();
conn.disconnect();
/// parse the returned object for the CSRF token
CookieStore cookieJar = cookieManager.getCookieStore();
List<HttpCookie> cookies = cookieJar.getCookies();
String csrf = null;
for (HttpCookie cookie : cookies) {
Log.d("cookie", "" + cookie);
if (cookie.getName().equals("csrftoken")) {
csrf = cookie.getValue();
break;
}
}
if (csrf == null) {
Log.d(TAG, "Unable to get CSRF");
return false;
}
Log.d(TAG, "Received cookie: " + csrf);
addFormField("csrfmiddlewaretoken", csrf);
return true;
}
private boolean openConnection()
throws IOException {
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
//httpConn.setRequestProperty("Accept-Encoding", "identity");
httpConn.setFixedLengthStreamingMode(contentLength);
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = new BufferedOutputStream(httpConn.getOutputStream());
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
return true;
}
private void writeContent()
throws IOException {
for (FormField field : fields) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + field.name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(field.value).append(LINE_FEED);
writer.flush();
}
for (FilePart filePart : files) {
String fileName = filePart.uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + filePart.fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(filePart.uploadFile);
int bufferSize = Math.min(inputStream.available(), maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
}
}
Usage is largely the same as in the above answer, but I've included CSRF support that Django uses by default with forms
boolean useCSRF = true;
MultipartLargeUtility multipart = new MultipartLargeUtility(url, "UTF-8",useCSRF);
multipart.addFormField("param1","value");
multipart.addFilePart("filefield",new File("/path/to/file"));
List<String> response = multipart.finish();
Log.w(TAG,"SERVER REPLIED:");
for(String line : response) {
Log.w(TAG, "Upload Files Response:::" + line);
}
This will Fill images to a specific size, without stretching it or without cropping it
img{
width:150px; //your requirement size
height:100px; //your requirement size
/*Scale down will take the necessary specified space that is 150px x 100px without stretching the image*/
object-fit:scale-down;
}
I would suggest going the lxml route and using xpath.
from lxml import etree
# data is the variable containing the html
data = etree.HTML(data)
anchor = data.xpath('//a[@class="title"]/text()')
You should use white-space with display table
Example:
legend {
display:table; /* Enable line-wrapping in IE8+ */
white-space:normal; /* Enable line-wrapping in old versions of some other browsers */
}
I suppose this is a cleaner approach.
It works with inline height
and width
properties (I set random value in the fiddle to prove that) and with CSS max-width
property.
HTML:
<div class="wrapper">
<div class="h_iframe">
<iframe height="2" width="2" src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe>
</div>
<p>Please scale the "result" window to notice the effect.</p>
</div>
CSS:
html,body {height: 100%;}
.wrapper {width: 80%; max-width: 600px; height: 100%; margin: 0 auto; background: #CCC}
.h_iframe {position: relative; padding-top: 56%;}
.h_iframe iframe {position: absolute; top: 0; left: 0; width: 100%; height: 100%;}
With numpy :
im = Image.open('image.gif')
im_matrix = np.array(im)
print(im_matrix[0][0])
Give RGB vector of the pixel in position (0,0)
You can try this; create a dummy HTML anchor, and download the image from there like...
// Convert canvas to image
document.getElementById('btn-download').addEventListener("click", function(e) {
var canvas = document.querySelector('#my-canvas');
var dataURL = canvas.toDataURL("image/jpeg", 1.0);
downloadImage(dataURL, 'my-canvas.jpeg');
});
// Save | Download image
function downloadImage(data, filename = 'untitled.jpeg') {
var a = document.createElement('a');
a.href = data;
a.download = filename;
document.body.appendChild(a);
a.click();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
ImageView view = (ImageView) v;
dumpEvent(event);
// Handle touch events here...
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG, "mode=DRAG");
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
Log.d(TAG, "mode=NONE");
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
// ...
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY()
- start.y);
} else if (mode == ZOOM) {
float newDist = spacing(event);
Log.d(TAG, "newDist=" + newDist);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
view.setImageMatrix(matrix);
return true;
}
private void dumpEvent(MotionEvent event) {
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid ").append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";");
}
sb.append("]");
Log.d(TAG, sb.toString());
}
/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
and dont forget to set scaleType
property to matrix of ImageView
tag like:
<ImageView
android:id="@+id/imageEnhance"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:background="@drawable/enhanceimageframe"
android:scaleType="matrix" >
</ImageView>
and the variables used are:
// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked;
It's better to use $(window).scroll()
rather than $('#Eframe').on("mousewheel")
$('#Eframe').on("mousewheel")
will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.
$(window).scroll(function(){
var scrollPos = $(document).scrollTop();
console.log(scrollPos);
});
If #Eframe
is an element with overflow:scroll
on it and you want it's scroll position. I think this should work (I haven't tested it though).
$('#Eframe').scroll(function(){
var scrollPos = $('#Eframe').scrollTop();
console.log(scrollPos);
});
Some time ago i created an excel file with supported dimensions
Hope this will be helpful for somebody
To be honest i lost the idea, but it refers another screen feature as size (not only density)
https://developer.android.com/guide/practices/screens_support.html
Please inform me if there are some mistakes
Why write custom jQuery code for Marquee... just use a plugin for jQuery - marquee() and use it like in the example below:
First include :
<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>
and then:
//proporcional speed counter (for responsive/fluid use)
var widths = $('.marquee').width()
var duration = widths * 7;
$('.marquee').marquee({
//speed in milliseconds of the marquee
duration: duration, // for responsive/fluid use
//duration: 8000, // for fixed container
//gap in pixels between the tickers
gap: $('.marquee').width(),
//time in milliseconds before the marquee will start animating
delayBeforeStart: 0,
//'left' or 'right'
direction: 'left',
//true or false - should the marquee be duplicated to show an effect of continues flow
duplicated: true
});
If you can make it simpler and better I dare you all people :). Don't make your life more difficult than it should be. More about this plugin and its functionalities at: http://aamirafridi.com/jquery/jquery-marquee-plugin
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
///*
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK && null != data){
uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(prjection[0]);
ImagePath = cursor.getString(columnIndex);
cursor.close();
FixBitmap = BitmapFactory.decodeFile(ImagePath);
ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
// FixBitmap = new BitmapDrawable(ImagePath);
int nh = (int) ( FixBitmap.getHeight() * (512.0 / FixBitmap.getWidth()) );
FixBitmap = Bitmap.createScaledBitmap(FixBitmap, 512, nh, true);
// ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath));
ShowSelectedImage.setImageBitmap(FixBitmap);
}
}
This code is work
This one might works for you....
void List<Integer> makeSequence(int begin, int end) {
AtomicInteger ai=new AtomicInteger(begin);
List<Integer> ret = new ArrayList(end-begin+1);
while ( end-->begin) {
ret.add(ai.getAndIncrement());
}
return ret;
}
You can just add the padding to tour block element and add background-origin
style like so:
.block {
position: relative;
display: inline-block;
padding: 10px 12px;
border:1px solid #e5e5e5;
background-size: contain;
background-position: center;
background-repeat: no-repeat;
background-origin: content-box;
background-image: url(_your_image_);
height: 14rem;
width: 10rem;
}
You can check several https://www.w3schools.com/cssref/css3_pr_background-origin.asp
Maybe too many years late, but nevertheless a theory to try.
The ratio of bounding rectangle of red logo region to the overall dimension of the bottle/can is different. In the case of Can, should be 1:1, whereas will be different in that of bottle (with or without cap). This should make it easy to distinguish between the two.
Update: The horizontal curvature of the logo region will be different between the Can and Bottle due their respective size difference. This could be specifically useful if your robot needs to pick up can/bottle, and you decide the grip accordingly.
Here is an actual implementation of what you described. I rewrote your code a bit using the latest best practices to actualize is. If you resize your browser windows under 1000px
, the image's left and right side will be cropped using negative margins and it will be 300px
narrower.
<style>
.container {
position: relative;
width: 100%;
}
.bg {
position:relative;
z-index: 1;
height: 100%;
min-width: 1000px;
max-width: 1500px;
margin: 0 auto;
}
.nebula {
width: 100%;
}
@media screen and (max-width: 1000px) {
.nebula {
width: 100%;
overflow: hidden;
margin: 0 -150px 0 -150px;
}
}
</style>
<div class="container">
<div class="bg">
<img src="http://i.stack.imgur.com/tFshX.jpg" class="nebula">
</div>
</div>
This can be achieved purely with JavaScript.
I see the answer I wanted to write has been answered by lynx in comments to the question.
But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.
So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:
// Fetch the element
var el = document.getElementById("someElement");
// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top;
Thats it!
Hope this helps someone :)
This is not perfect but it does the job.
convert -density 1200 -resize 200x200 source.svg target.png
Basically it increases the DPI high enough (just use an educated/safe guess) that resizing is done with adequate quality. I was trying to find a proper solution to this but after a while decided this was good enough for my current need.
Note: Use 200x200! to force the given resolution
Beginning PowerShell 5.0 New-Item
, Remove-Item
, and Get-ChildItem
have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item
accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.
New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"
Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.
Anyway if you want to create a Run As Administrator shortcut using Powershell you can use
$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)
If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.
body
has default margins: http://www.w3.org/TR/CSS2/sample.html
body { margin:0; } /* Remove body margins */
Or you could use this useful Global reset
* { margin:0; padding:0; box-sizing:border-box; }
If you want something less *
global than:
html, body, body div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, figure, footer, header, hgroup, menu, nav, section, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
some other CSS Reset:
http://yui.yahooapis.com/3.5.0/build/cssreset/cssreset-min.css
http://meyerweb.com/eric/tools/css/reset/
https://github.com/necolas/normalize.css/
http://html5doctor.com/html-5-reset-stylesheet/
…
Java version for Sathyaraj's code above:
// Resize
public Bitmap resize(Bitmap img, int newWidth, int newHeight) {
Bitmap bmap = img.copy(img.getConfig(), true);
double nWidthFactor = (double) img.getWidth() / (double) newWidth;
double nHeightFactor = (double) img.getHeight() / (double) newHeight;
double fx, fy, nx, ny;
int cx, cy, fr_x, fr_y;
int color1;
int color2;
int color3;
int color4;
byte nRed, nGreen, nBlue;
byte bp1, bp2;
for (int x = 0; x < bmap.getWidth(); ++x) {
for (int y = 0; y < bmap.getHeight(); ++y) {
fr_x = (int) Math.floor(x * nWidthFactor);
fr_y = (int) Math.floor(y * nHeightFactor);
cx = fr_x + 1;
if (cx >= img.getWidth())
cx = fr_x;
cy = fr_y + 1;
if (cy >= img.getHeight())
cy = fr_y;
fx = x * nWidthFactor - fr_x;
fy = y * nHeightFactor - fr_y;
nx = 1.0 - fx;
ny = 1.0 - fy;
color1 = img.getPixel(fr_x, fr_y);
color2 = img.getPixel(cx, fr_y);
color3 = img.getPixel(fr_x, cy);
color4 = img.getPixel(cx, cy);
// Blue
bp1 = (byte) (nx * Color.blue(color1) + fx * Color.blue(color2));
bp2 = (byte) (nx * Color.blue(color3) + fx * Color.blue(color4));
nBlue = (byte) (ny * (double) (bp1) + fy * (double) (bp2));
// Green
bp1 = (byte) (nx * Color.green(color1) + fx * Color.green(color2));
bp2 = (byte) (nx * Color.green(color3) + fx * Color.green(color4));
nGreen = (byte) (ny * (double) (bp1) + fy * (double) (bp2));
// Red
bp1 = (byte) (nx * Color.red(color1) + fx * Color.red(color2));
bp2 = (byte) (nx * Color.red(color3) + fx * Color.red(color4));
nRed = (byte) (ny * (double) (bp1) + fy * (double) (bp2));
bmap.setPixel(x, y, Color.argb(255, nRed, nGreen, nBlue));
}
}
bmap = setGrayscale(bmap);
bmap = removeNoise(bmap);
return bmap;
}
// SetGrayscale
private Bitmap setGrayscale(Bitmap img) {
Bitmap bmap = img.copy(img.getConfig(), true);
int c;
for (int i = 0; i < bmap.getWidth(); i++) {
for (int j = 0; j < bmap.getHeight(); j++) {
c = bmap.getPixel(i, j);
byte gray = (byte) (.299 * Color.red(c) + .587 * Color.green(c)
+ .114 * Color.blue(c));
bmap.setPixel(i, j, Color.argb(255, gray, gray, gray));
}
}
return bmap;
}
// RemoveNoise
private Bitmap removeNoise(Bitmap bmap) {
for (int x = 0; x < bmap.getWidth(); x++) {
for (int y = 0; y < bmap.getHeight(); y++) {
int pixel = bmap.getPixel(x, y);
if (Color.red(pixel) < 162 && Color.green(pixel) < 162 && Color.blue(pixel) < 162) {
bmap.setPixel(x, y, Color.BLACK);
}
}
}
for (int x = 0; x < bmap.getWidth(); x++) {
for (int y = 0; y < bmap.getHeight(); y++) {
int pixel = bmap.getPixel(x, y);
if (Color.red(pixel) > 162 && Color.green(pixel) > 162 && Color.blue(pixel) > 162) {
bmap.setPixel(x, y, Color.WHITE);
}
}
}
return bmap;
}
Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG
support for sorl thumbnails.
from PIL import Image
png = Image.open(object.logo.path)
png.load() # required for png.split()
background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel
background.save('foo.jpg', 'JPEG', quality=80)
Result @80%
Result @ 50%
Change your css as below
#element1 {float:left;margin-right:10px;}
#element2 {float:left;}
Here is the JSFiddle http://jsfiddle.net/a4aME/
def rotate(image, angle, center = None, scale = 1.0):
(h, w) = image.shape[:2]
if center is None:
center = (w / 2, h / 2)
# Perform the rotation
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
return rotated
uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{
if (r > 2) r = 0;
if (r == 0) value[i] = 0;
if (r == 1)value[i] = 0;
if (r == 2)value[i] = 255;
r++;
}
I think that the best solution for drawing text in OpenGL is texture fonts, I work with them for a long time. They are flexible, fast and nice looking (with some rear exceptions). I use special program for converting font files (.ttf for example) to texture, which is saved to file of some internal "font" format (I've developed format and program based on http://content.gpwiki.org/index.php/OpenGL:Tutorials:Font_System though my version went rather far from the original supporting Unicode and so on). When starting the main app, fonts are loaded from this "internal" format. Look link above for more information.
With such approach the main app doesn't use any special libraries like FreeType, which is undesirable for me also. Text is being drawn using standard OpenGL functions.
Boris Smus's article High DPI Images for Variable Pixel Densities has a more accurate definition of device pixel ratio: the number of device pixels per CSS pixel is a good approximation, but not the whole story.
Note that you can get the DPR used by a device with window.devicePixelRatio
.
The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.
MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.
For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).
Console output:
(0,0): TRANSPARENT
(150,150): NOT_TRANSPARENT
image = new MarvinImage();_x000D_
image.load("https://i.imgur.com/eLZVbQG.png", imageLoaded);_x000D_
_x000D_
function imageLoaded(){_x000D_
console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
}
_x000D_
<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
_x000D_
Add new folder with name of Images in your project. Put some images into Images folder. Then it will work fine.
<input type="image" src="~/Images/Desert.jpg" alt="Submit" width="48" height="48">
Note: The widely used solution above is based on displayMetrics.density
. However, the docs explain that this value is a rounded value, used with the screen 'buckets'. Eg. on my Nexus 10 it returns 2, where the real value would be 298dpi (real) / 160dpi (default) = 1.8625.
Depending on your requirements, you might need the exact transformation, which can be achieved like this:
[Edit] This is not meant to be mixed with Android's internal dp unit, as this is of course still based on the screen buckets. Use this where you want a unit that should render the same real size on different devices.
Convert dp to pixel:
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
Convert pixel to dp:
public int pxToDp(int px) {
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
Note that there are xdpi and ydpi properties, you might want to distinguish, but I can't imagine a sane display where these values differ greatly.
/*working only in ipad portrait device*/
@media only screen and (width: 768px) and (height: 1024px) and (orientation:portrait) {
body{
background: red !important;
}
}
/*working only in ipad landscape device*/
@media all and (width: 1024px) and (height: 768px) and (orientation:landscape){
body{
background: green !important;
}
}
In the media query of specific devices, please use '!important' keyword to override the default CSS. Otherwise that does not change your webpage view on that particular devices.
I tried using phyatt's AspectRatioPixmapLabel
class, but experienced a few problems:
QLabel::setPixmap(...)
inside the resizeEvent method, because QLabel
actually calls updateGeometry
inside setPixmap
, which may trigger resize events...heightForWidth
seemed to be ignored by the containing widget (a QScrollArea
in my case) until I started setting a size policy for the label, explicitly calling policy.setHeightForWidth(true)
QLabel
's implementation of minimumSizeHint()
does some magic for labels containing text, but always resets the size policy to the default one, so I had to overwrite itThat said, here is my solution. I found that I could just use setScaledContents(true)
and let QLabel
handle the resizing.
Of course, this depends on the containing widget / layout honoring the heightForWidth
.
aspectratiopixmaplabel.h
#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H
#include <QLabel>
#include <QPixmap>
class AspectRatioPixmapLabel : public QLabel
{
Q_OBJECT
public:
explicit AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent = 0);
virtual int heightForWidth(int width) const;
virtual bool hasHeightForWidth() { return true; }
virtual QSize sizeHint() const { return pixmap()->size(); }
virtual QSize minimumSizeHint() const { return QSize(0, 0); }
};
#endif // ASPECTRATIOPIXMAPLABEL_H
aspectratiopixmaplabel.cpp
#include "aspectratiopixmaplabel.h"
AspectRatioPixmapLabel::AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent) :
QLabel(parent)
{
QLabel::setPixmap(pixmap);
setScaledContents(true);
QSizePolicy policy(QSizePolicy::Maximum, QSizePolicy::Maximum);
policy.setHeightForWidth(true);
this->setSizePolicy(policy);
}
int AspectRatioPixmapLabel::heightForWidth(int width) const
{
if (width > pixmap()->width()) {
return pixmap()->height();
} else {
return ((qreal)pixmap()->height()*width)/pixmap()->width();
}
}
You can do it using string.indexOf("{item}")
. If the result is greater than -1 {item}
is in the string
The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).
For this example, let's draw a RED pixel at position 100x50.
Mat foo;
int x=100, y=50;
Solution 1:
Create a macro function that obtains the pixel from the array.
#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
Solution 2:
Get's the pixel using the method ptr.
unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
Check out the image-map plugin on Github. It works both with vanilla JavaScript and as a jQuery plugin.
$('img[usemap]').imageMap(); // jQuery
ImageMap('img[usemap]') // JavaScript
Check out the demo.
This should do the job
//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");
//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
Give the height of the div .youtube-thumb
the height of the image. That should set the problem in Firefox browser.
.youtube-thumb{ height: 106px }
Another answer is:
Try checking the View dimensions at onWindowFocusChanged
.
Try this code
if ($(window).width() < 960) {
alert('width is less than 960px');
}
else {
alert('More than 960');
}
if ($(window).width() < 960) {_x000D_
alert('width is less than 960px');_x000D_
}_x000D_
else {_x000D_
alert('More than 960');_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
The following code works for me:
.half {
-moz-transform:scale(0.5);
-webkit-transform:scale(0.5);
transform:scale(0.5);
}
<img class="half" src="images/myimage.png">
You probably want the next transformation for you pixels:
pixels = map(list, image.getdata())
Specifying CV_THRESH_OTSU
causes the threshold value to be ignored. From the documentation:
Also, the special value THRESH_OTSU may be combined with one of the above values. In this case, the function determines the optimal threshold value using the Otsu’s algorithm and uses it instead of the specified thresh . The function returns the computed threshold value. Currently, the Otsu’s method is implemented only for 8-bit images.
This code reads frames from the camera and performs the binary threshold at the value 20.
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int main(int argc, const char * argv[]) {
VideoCapture cap;
if(argc > 1)
cap.open(string(argv[1]));
else
cap.open(0);
Mat frame;
namedWindow("video", 1);
for(;;) {
cap >> frame;
if(!frame.data)
break;
cvtColor(frame, frame, CV_BGR2GRAY);
threshold(frame, frame, 20, 255, THRESH_BINARY);
imshow("video", frame);
if(waitKey(30) >= 0)
break;
}
return 0;
}
You can also use pytiff of which I'm the author.
import pytiff
with pytiff.Tiff("filename.tif") as handle:
part = handle[100:200, 200:400]
# multipage tif
with pytiff.Tiff("multipage.tif") as handle:
for page in handle:
part = page[100:200, 200:400]
It's a fairly small module and may not have as many features as other modules, but it supports tiled tiffs and bigtiff, so you can read parts of large images.
I think what you want is to set the android:layout_weight,
http://developer.android.com/resources/tutorials/views/hello-linearlayout.html
something like this (I'm just putting text views above and below as placeholders):
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="68"/>
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="16"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="16"/>
</LinearLayout>
Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:
/search?searchquery=text and 'query' is provided.
In this case searchquery param value is changed.
Code:
function replaceUrlParam(url, paramName, paramValue){
var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
var newUrl=url
if(url.search(pattern)>=0){
newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
}
else{
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
public int getActionBarHeight() {
int actionBarHeight = 0;
TypedValue tv = new TypedValue();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv,
true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(
tv.data, getResources().getDisplayMetrics());
} else {
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
getResources().getDisplayMetrics());
}
return actionBarHeight;
}
$('div').css({
position: 'relative',
top: '-15px'
});
We finally found an answer of sorts. First, the problem: the table always sizes itself around the content, rather than forcing the content to fit in the table. That limits your options.
We did it by setting the content div to display:none, letting the table size itself, and then in javascript setting the height and width of the content div to the inner height and width of the enclosing td tag. Show the content div. Repeat the process when the window is resized.
You usually use padding to add distance between a border and a content.However, background are spread on padding.
You can still do it with nested element.
html :
<div id="outter">
<div id="inner">
test
</div>
</div>
outter div :
border-style: ridge;
border-color: #567498;
border-spacing:10px;
min-width: 100px;
min-height: 100px;
float:left;
inner div :
width: 100px;
min-height: 100px;
margin: 10px;
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0, rgb(39,54,73)),
color-stop(1, rgb(30,42,54))
);
background-image: -moz-linear-gradient(
center bottom,
rgb(39,54,73) 0%,
rgb(30,42,54) 100%
);}
I took my chance to provide full .htaccess
code to pass on Google PageSpeed Insight:
# Enable Compression <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE application/x-font AddOutputFilterByType DEFLATE application/x-font-opentype AddOutputFilterByType DEFLATE application/x-font-otf AddOutputFilterByType DEFLATE application/x-font-truetype AddOutputFilterByType DEFLATE application/x-font-ttf AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE font/opentype AddOutputFilterByType DEFLATE font/otf AddOutputFilterByType DEFLATE font/ttf AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE image/x-icon AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/plain </IfModule> <IfModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file .(html?|txt|css|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text/.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.* </IfModule> # Leverage Browser Caching <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType text/css "access 1 month" ExpiresByType text/html "access 1 month" ExpiresByType application/pdf "access 1 month" ExpiresByType text/x-javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 1 month" </IfModule> <IfModule mod_headers.c> <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$"> Header set Cache-Control "max-age=2678400, public" </filesmatch> <filesmatch "\.(html|htm)$"> Header set Cache-Control "max-age=7200, private, must-revalidate" </filesmatch> <filesmatch "\.(pdf)$"> Header set Cache-Control "max-age=86400, public" </filesmatch> <filesmatch "\.(js)$"> Header set Cache-Control "max-age=2678400, private" </filesmatch> </IfModule>
There is also some configurations for various web servers see here.
Hope this would help to get the 100/100 score.
LinearLayout YOUR_LinearLayout =(LinearLayout)findViewById(R.id.YOUR_LinearLayout)
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ 100,
/*weight*/ 1.0f
);
YOUR_LinearLayout.setLayoutParams(param);
Try this: parseInt(jQuery.offset().top, 10)
context.getImageData(x, y, 1, 1).data;
returns an rgba array. e.g. [50, 50, 50, 255]
Here's a version of @lwburk's rgbToHex function that takes the rgba array as an argument.
function rgbToHex(rgb){
return '#' + ((rgb[0] << 16) | (rgb[1] << 8) | rgb[2]).toString(16);
};
It's probably because size of a frame includes the size of the border.
A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method. Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of width - (insets.left + insets.right) by height - (insets.top + insets.bottom).
Source: http://download.oracle.com/javase/tutorial/uiswing/components/frame.html
This worked for me:
BufferedImage bufImgs = ImageIO.read(new File("c:\\adi.bmp"));
double[][] data = new double[][];
bufImgs.getData().getPixels(0,0,bufImgs.getWidth(),bufImgs.getHeight(),data[i]);
Here is a simple method to troubleshoot connection issues:
Get Screen Width and Height in terms of DP with some good decoration:
Step 1: Create interface
public interface ScreenInterface {
float getWidth();
float getHeight();
}
Step 2: Create implementer class
public class Screen implements ScreenInterface {
private Activity activity;
public Screen(Activity activity) {
this.activity = activity;
}
private DisplayMetrics getScreenDimension(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics;
}
private float getScreenDensity(Activity activity) {
return activity.getResources().getDisplayMetrics().density;
}
@Override
public float getWidth() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.widthPixels / getScreenDensity(activity);
}
@Override
public float getHeight() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.heightPixels / getScreenDensity(activity);
}
}
Step 3: Get width and height in activity:
Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();
This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)
char *words; // setting this to NULL would have prevented the issue
if (condition) {
words = malloc( 512 );
/* calling free sometime later works here */
free(words)
} else {
/* do not allocate words in this branch */
}
/* free(words); -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/
There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:
*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer
IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.
If you are willing to put a container element around your image, a pure CSS solution is simple. You see, 99% height has no meaning when the parent element will extend vertically to contain its children. The parent needs to have a fixed height, say... the height of the viewport.
HTML
<!-- use a tall image to illustrate the problem -->
<div class='fill-screen'>
<img class='make-it-fit'
src='https://upload.wikimedia.org/wikipedia/commons/f/f2/Leaning_Tower_of_Pisa.jpg'>
</div>
CSS
div.fill-screen {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
text-align: center;
}
img.make-it-fit {
max-width: 99%;
max-height: 99%;
}
Play with the fiddle.
You can try this:
-ms-transform: scale(width,height); /* IE 9 */
-webkit-transform: scale(width,height); /* Safari */
transform: scale(width, height);
Example: image "grows" 1.3 times
-ms-transform: scale(1.3,1.3); /* IE 9 */
-webkit-transform: scale(1.3,1.3); /* Safari */
transform: scale(1.3,1.3);
please, something went xxx*x, and that's not true at all, check that
JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]
code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )
EDIT: forget setDefaultCloseOperation()
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FrameSize {
private JFrame frm = new JFrame();
private JPanel pnl = new JPanel();
private JButton btn = new JButton("Get ScreenSize for JComponents");
public FrameSize() {
btn.setPreferredSize(new Dimension(400, 40));
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("JButton Size - " + btn.getSize());
System.out.println("JPanel Size - " + pnl.getSize());
System.out.println("JFrame Size - " + frm.getSize());
}
});
pnl.setPreferredSize(new Dimension(640, 480));
pnl.add(btn, BorderLayout.SOUTH);
frm.add(pnl, BorderLayout.CENTER);
frm.setLocation(150, 100);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
frm.setResizable(false);
frm.pack();
frm.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FrameSize fS = new FrameSize();
}
});
}
}
One can use a plain ImageView in his xml and make it clickable (android:clickable="true")? You only have to use as src an image that has been shaped like a button i.e round corners.
The solution is:
$('body').scroll(function(e){
console.log(e);
});
Currently, no, not without resorting to trickery. borders on elements are supposed to run the entire length of whatever side of the element box they apply to.
I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5
This makes me happy.
Try this: Live Demo
display: table
is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>
.
CSS:
#container {
background: #ccc;
display: table
}
#left, #right {
display: table-cell
}
#left {
width: 150px;
background: #f0f;
border: 5px dotted blue;
}
#right {
background: #aaa;
border: 3px solid #000
}
When you give up the inline blocks
.post-container {
border: 5px solid #333;
overflow:auto;
}
.post-thumb {
float: left;
display:block;
background:#ccc;
width:200px;
height:200px;
}
.post-content{
display:block;
overflow:hidden;
}
You can appendChild
to document.body
but not if the document hasn't been loaded. So you should
put everything in:
window.onload=function(){
//your code
}
This works or you can make appendChild
to be dependent on something else like another event for eg.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append
As a matter of fact you can try changing the innerHTML
of the document.body
it works...!
from PIL import Image
image = Image.open('File.jpg')
image.show()
The iFrame attribute does not support percent in HTML5. It only supports pixels. http://www.w3schools.com/tags/att_iframe_height.asp
Looking at your requirement, there is alternate solution as well. It seems you know the dimensions in dp at compile time, so you can add a dimen entry in the resources. Then you can query the dimen entry and it will be automatically converted to pixels in this call:
final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);
And your dimens.xml will have:
<dimen name="dimen_entry_in_dp">72dp</dimen>
Extending this idea, you can simply store the value of 1dp or 1sp as a dimen entry and query the value and use it as a multiplier. Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations.
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
If you have proportioned elements, you could use:
.valid {
background-position: 98% center;
}
.half .valid {
background-position: 96% center;
}
In this example, .valid
would be the class with the picture and .half
would be a row with half the size of the standard one.
Dirty, but works as a charm and it's reasonably manageable.
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
Use flexbox and do a fallback (from suggestions above) for older browsers:
ul {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
}
Yes this is safe.
The c language uses a feature called integer promotion to increase the number of bits in a value before performing calculations. Therefore your CLAMP255 macro will operate at integer (probably 32 bit) precision. The result is assigned to a jbyte, which reduces the integer precision back to 8 bits fit in to the jbyte.
checkbox that act like radio btn
$(".checkgroup").live('change',function() {
var previous=this.checked;
$(".checkgroup).attr("checked", false);
$(this).attr("checked", previous);
});
Just use toDateString() on both dates. toDateString doesn't include the time, so for 2 times on the same date, the values will be equal, as demonstrated below.
var d1 = new Date(2019,01,01,1,20)
var d2 = new Date(2019,01,01,2,20)
console.log(d1==d2) // false
console.log(d1.toDateString() == d2.toDateString()) // true
Obviously some of the timezone concerns expressed elsewhere on this question are valid, but in many scenarios, those are not relevant.
While the w32tm /resync
in theory does the job, it only does so under certain conditions. When "down to the millisecond" matters, however, I found that Windows wouldn't actually make the adjustment; as if "oh, I'm off by 2.5 seconds, close enough bro, nothing to see or do here".
In order to truly force the resync (Windows 7):
w32tm /resync
watch -n 0.1 date
on a Linux machine on the network that I had SSH'd over into)--- Rapid Method ---
net start w32time
(Time Service must be running)time 8
(where 8 may be replaced by any 'hour' value, presumably 0-23)w32tm /resync
Check out http://www.odata.org/
It defines the MERGE method, so in your case it would be something like this:
MERGE /customer/123
<customer>
<status>DISABLED</status>
</customer>
Only the status
property is updated and the other values are preserved.
I use below sql to exclude the null string and empty string lines.
select * from table where length(nvl(column1,0))>0
Because, the length of empty string is 0.
select length('');
+-----------+--+
| length() |
+-----------+--+
| 0 |
+-----------+--+
check out android:textScaleX
Depending on how much spacing you need, this might help. That's the only thing remotely related to letter-spacing in the TextView.
Edit: please see @JerabekJakub's response below for an updated, better method to do this starting with api 21 (Lollipop)
Here is a sample code with explanation.
//Create a response instance
$response = new Illuminate\Http\Response('Hello World');
//Call the withCookie() method with the response method
$response->withCookie(cookie('name', 'value', $minutes));
//return the response
return $response;
Cookie can be set forever by using the forever method as shown in the below code.
$response->withCookie(cookie()->forever('name', 'value'));
//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');
Manage mongo connection pools in a single self contained module. This approach provides two benefits. Firstly it keeps your code modular and easier to test. Secondly your not forced to mix your database connection up in your request object which is NOT the place for a database connection object. (Given the nature of JavaScript I would consider it highly dangerous to mix in anything to an object constructed by library code). So with that you only need to Consider a module that exports two methods. connect = () => Promise
and get = () => dbConnectionObject
.
With such a module you can firstly connect to the database
// runs in boot.js or what ever file your application starts with
const db = require('./myAwesomeDbModule');
db.connect()
.then(() => console.log('database connected'))
.then(() => bootMyApplication())
.catch((e) => {
console.error(e);
// Always hard exit on a database connection error
process.exit(1);
});
When in flight your app can simply call get()
when it needs a DB connection.
const db = require('./myAwesomeDbModule');
db.get().find(...)... // I have excluded code here to keep the example simple
If you set up your db module in the same way as the following not only will you have a way to ensure that your application will not boot unless you have a database connection you also have a global way of accessing your database connection pool that will error if you have not got a connection.
// myAwesomeDbModule.js
let connection = null;
module.exports.connect = () => new Promise((resolve, reject) => {
MongoClient.connect(url, option, function(err, db) {
if (err) { reject(err); return; };
resolve(db);
connection = db;
});
});
module.exports.get = () => {
if(!connection) {
throw new Error('Call connect first!');
}
return connection;
}
sup, sub {
vertical-align: baseline;
position: relative;
top: -0.4em;
}
sub {
top: 0.4em;
}
If you need to have control over the format of the date (in other words not just the yyyy-mm-dd format is acceptable), another solution could be adding a helper property that is of type string and add a date validator to that property, and bind to this property on UI.
[Display(Name = "Due date")]
[Required]
[AllowHtml]
[DateValidation]
public string DueDateString { get; set; }
public DateTime? DueDate
{
get
{
return string.IsNullOrEmpty(DueDateString) ? (DateTime?)null : DateTime.Parse(DueDateString);
}
set
{
DueDateString = value == null ? null : value.Value.ToString("d");
}
}
And here is a date validator:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class DateValidationAttribute : ValidationAttribute
{
public DateValidationAttribute()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
DateTime date;
if (value is string)
{
if (!DateTime.TryParse((string)value, out date))
{
return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
}
}
else
date = (DateTime)value;
if (date < new DateTime(1900, 1, 1) || date > new DateTime(3000, 12, 31))
{
return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
}
}
return null;
}
}
public static IEnumerable<T> ExecuteProcedure<T>(this SqlConnection connection,
string storedProcedure, object parameters = null,
int commandTimeout = 180)
{
try
{
if (connection.State != ConnectionState.Open)
{
connection.Close();
connection.Open();
}
if (parameters != null)
{
return connection.Query<T>(storedProcedure, parameters,
commandType: CommandType.StoredProcedure, commandTimeout: commandTimeout);
}
else
{
return connection.Query<T>(storedProcedure,
commandType: CommandType.StoredProcedure, commandTimeout: commandTimeout);
}
}
catch (Exception ex)
{
connection.Close();
throw ex;
}
finally
{
connection.Close();
}
}
}
var data = db.Connect.ExecuteProcedure<PictureModel>("GetPagePicturesById",
new
{
PageId = pageId,
LangId = languageId,
PictureTypeId = pictureTypeId
}).ToList();
Another possibility, is the machine has an older version of xlrd installed separately, and it's not in the "..:\Python27\Scripts.." folder.
In another word, there are 2 different versions of xlrd in the machine.
when you check the version below, it reads the one not in the "..:\Python27\Scripts.." folder, no matter how updated you done with pip.
print xlrd.__version__
Delete the whole redundant sub-folder, and it works. (in addition to xlrd, I had another library encountered the same)
Looks like the question has been long ago answered but the solution did not work for me. When I was getting that error, I was able to fix the problem by downloading PyWin32
From a comment:
I want to sort each set.
That's easy. For any set s
(or anything else iterable), sorted(s)
returns a list of the elements of s
in sorted order:
>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
Note that sorted
is giving you a list
, not a set
. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2}
and {2, 1}
are the same set.
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).
The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key
function:
>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
For more information, see the Sorting HOWTO in the official docs.
* See the comments for exceptions.
alternative way:
mail -N
d *
quit
-N
Inhibits the initial display of message headers when reading mail or editing a mail folder.
d *
delete all mails
There is one more way to achieve it:-
Private Sub UserForm_Initialize()
Dim list As Object
Set list = UserForm1.Controls.Add("Forms.ListBox.1", "hello", True)
With list
.Top = 30
.Left = 30
.Width = 200
.Height = 340
.ColumnHeads = True
.ColumnCount = 2
.ColumnWidths = "100;100"
.MultiSelect = fmMultiSelectExtended
.RowSource = "Sheet1!C4:D25"
End With End Sub
Here, I am using the range C4:D25 as source of data for the columns. It will result in both the columns populated with values.
The properties are self explanatory. You can explore other options by drawing ListBox in UserForm and using "Properties Window (F4)" to play with the option values.
If you need two variables in the XML
, you can use:
%1$d text... %2$d
or %1$s text... %2$s
for string variables.
Example :
<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>
String site = "site.tld";
String days = "11";
//Toast example
String notyet = getString(R.string.notyet, site, days);
Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();
If you are using IIS Express and VS 2017:
Go to the Web Application Properties > Web Tab > Servers Section > And change the Bitness to x64.
Five options:
Use the free jsonutils web tool without installing anything.
If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.
Use the free jsonclassgenerator.exe
The web tool app.quicktype.io does not require installing anything.
The web tool json2csharp also does not require installing anything.
Pros and Cons:
jsonclassgenerator converts to PascalCase but the others do not.
app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.
Alternatively to usleep()
, which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep()
:
nanosleep
- high resolution sleep#include <time.h> int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
The
nanosleep()
function shall cause the current thread to be suspended from execution until either the time interval specified by therqtp
argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified byrqtp
, as measured by the system clock CLOCK_REALTIME.The use of the
nanosleep()
function has no effect on the action or blockage of any signal.
A good question. Should tell you it took some time to crack this one. Here is my result.
DECLARE @TABLE TABLE
(
ID INT,
USERS VARCHAR(10),
ACTIVITY VARCHAR(10),
PAGEURL VARCHAR(10)
)
INSERT INTO @TABLE
VALUES (1, 'Me', 'act1', 'ab'),
(2, 'Me', 'act1', 'cd'),
(3, 'You', 'act2', 'xy'),
(4, 'You', 'act2', 'st')
SELECT T1.USERS, T1.ACTIVITY,
STUFF(
(
SELECT ',' + T2.PAGEURL
FROM @TABLE T2
WHERE T1.USERS = T2.USERS
FOR XML PATH ('')
),1,1,'')
FROM @TABLE T1
GROUP BY T1.USERS, T1.ACTIVITY
Tomcat can tell you in several ways. Here's the easiest:
$ /path/to/catalina.sh version
Using CATALINA_BASE: /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME: /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME: /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH: /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built: Jul 3 2012 11:31:52
Server number: 7.0.29.0
OS Name: Mac OS X
OS Version: 10.7.4
Architecture: x86_64
JVM Version: 1.6.0_33-b03-424-11M3720
JVM Vendor: Apple Inc.
If you don't know where catalina.sh
is (or it never gets called), you can usually find it via ps
:
$ ps aux | grep catalina
chris 930 0.0 3.1 2987336 258328 s000 S Wed01PM 2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start
From the ps
output, you can see both catalina.home
and catalina.base
. catalina.home
is where the Tomcat base files are installed, and catalina.base
is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.
You can also interrogate the JVM directly if you can't find it in a ps
listing:
$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29
If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home
and catalina.base
.
Here is an easy to understand solution
import numpy as np
import pandas as pd
# Creating a 2 dimensional numpy array
>>> data = np.array([[5.8, 2.8], [6.0, 2.2]])
>>> print(data)
>>> data
array([[5.8, 2.8],
[6. , 2.2]])
# Creating pandas dataframe from numpy array
>>> dataset = pd.DataFrame({'Column1': data[:, 0], 'Column2': data[:, 1]})
>>> print(dataset)
Column1 Column2
0 5.8 2.8
1 6.0 2.2
Here is a really nice example of a pythonic way to do that:
import json
import psycopg2
def db(database_name='pepe'):
return psycopg2.connect(database=database_name)
def query_db(query, args=(), one=False):
cur = db().cursor()
cur.execute(query, args)
r = [dict((cur.description[i][0], value) \
for i, value in enumerate(row)) for row in cur.fetchall()]
cur.connection.close()
return (r[0] if r else None) if one else r
my_query = query_db("select * from majorroadstiger limit %s", (3,))
json_output = json.dumps(my_query)
You get an array of JSON objects:
>>> json_output
'[{"divroad": "N", "featcat": null, "countyfp": "001",...
Or with the following:
>>> j2 = query_db("select * from majorroadstiger where fullname= %s limit %s",\
("Mission Blvd", 1), one=True)
you get a single JSON object:
>>> j2 = json.dumps(j2)
>>> j2
'{"divroad": "N", "featcat": null, "countyfp": "001",...
You will have to add -x test
e.g. ./gradlew build -x test
or
gradle build -x test
We can simulate constructor overload using guards
interface IUser {
name: string;
lastName: string;
}
interface IUserRaw {
UserName: string;
UserLastName: string;
}
function isUserRaw(user): user is IUserRaw {
return !!(user.UserName && user.UserLastName);
}
class User {
name: string;
lastName: string;
constructor(data: IUser | IUserRaw) {
if (isUserRaw(data)) {
this.name = data.UserName;
this.lastName = data.UserLastName;
} else {
this.name = data.name;
this.lastName = data.lastName;
}
}
}
const user = new User({ name: "Jhon", lastName: "Doe" })
const user2 = new User({ UserName: "Jhon", UserLastName: "Doe" })
You can create a subprocess using Windows cmd.exe
that restarts yourself:
Process process = new Process();
process.StartInfo.FileName = "cmd";
process.StartInfo.Arguments = "/c net stop \"servicename\" & net start \"servicename\"";
process.Start();
just simply use as below and it will word wrap any long text within a table . No need to anything else
<td style="word-wrap: break-word;min-width: 160px;max-width: 160px;">long long comments</td>
I also faced the same issue, now it is resolved. If you are facing issues with pure components or classes, make sure that you are using .js extension instead of .jsx.
Virtual functions are used in order to invoke functions based on the type of object pointed to by the pointer, and not the type of pointer itself. But a constructor is not "invoked". It is called only once when an object is declared. So, a constructor cannot be made virtual in C++.
In Lollipop (21), you can use Intent.EXTRA_REPLACEMENT_EXTRAS
to override the intent for Facebook specifically (and specify a link only)
https://developer.android.com/reference/android/content/Intent.html#EXTRA_REPLACEMENT_EXTRAS
private void doShareLink(String text, String link) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share_via));
// for 21+, we can use EXTRA_REPLACEMENT_EXTRAS to support the specific case of Facebook
// (only supports a link)
// >=21: facebook=link, other=text+link
// <=20: all=link
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
shareIntent.putExtra(Intent.EXTRA_TEXT, text + " " + link);
Bundle facebookBundle = new Bundle();
facebookBundle.putString(Intent.EXTRA_TEXT, link);
Bundle replacement = new Bundle();
replacement.putBundle("com.facebook.katana", facebookBundle);
chooserIntent.putExtra(Intent.EXTRA_REPLACEMENT_EXTRAS, replacement);
} else {
shareIntent.putExtra(Intent.EXTRA_TEXT, link);
}
chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(chooserIntent);
}
To prevent recopy the array every time which isn't efficient
What about using Stack
csharp> var i = new Stack<byte>();
csharp> i.Push(1);
csharp> i.Push(2);
csharp> i.Push(3);
csharp> i; { 3, 2, 1 }
csharp> foreach(var x in i) {
> Console.WriteLine(x);
> }
3 2 1
Personally I sanitize all my data with some PHP libraries before going into the database so there's no need for another XSS filter for me.
From AngularJS 1.0.8
directives.directive('ngBindHtmlUnsafe', [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
}
}]);
To use:
<div ng-bind-html-unsafe="group.description"></div>
To disable $sce
:
app.config(['$sceProvider', function($sceProvider) {
$sceProvider.enabled(false);
}]);
You can do
$('.page-address-edit').addClass('test1 test2');
More here:
More than one class may be added at a time, separated by a space, to the set of matched elements, like so:
$("p").addClass("myClass yourClass");
If testing on Windows, don't forget to open port 3306.
It's quite simple:
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/html');
// do whatever you want with htmlDoc.getElementsByTagName('a');
According to MDN, to do this in chrome you need to parse as XML like so:
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/xml');
// do whatever you want with htmlDoc.getElementsByTagName('a');
It is currently unsupported by webkit and you'd have to follow Florian's answer, and it is unknown to work in most cases on mobile browsers.
Edit: Now widely supported
To test your method validation in a test, you have to wrap it a proxy in the @Before method.
@Before
public void setUp() {
this.classAutowiredWithFindStuffMethod = MethodValidationProxyFactory.createProxy(this.classAutowiredWithFindStuffMethod);
}
With MethodValidationProxyFactory as :
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
public class MethodValidationProxyFactory {
private static final StaticApplicationContext ctx = new StaticApplicationContext();
static {
MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
processor.afterPropertiesSet(); // init advisor
ctx.getBeanFactory()
.addBeanPostProcessor(processor);
}
@SuppressWarnings("unchecked")
public static <T> T createProxy(T instance) {
return (T) ctx.getAutowireCapableBeanFactory()
.applyBeanPostProcessorsAfterInitialization(instance, instance.getClass()
.getName());
}
}
And then, add your test :
@Test
public void findingNullStuff() {
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> this.classAutowiredWithFindStuffMethod.findStuff(null));
}
This changes the focus of the EditText when the button is clicked:
public class MainActivity extends Activity {
private EditText e1,e2;
private Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1=(EditText) findViewById(R.id.editText1);
e2=(EditText) findViewById(R.id.editText2);
e1.requestFocus();
b1=(Button) findViewById(R.id.one);
b2=(Button) findViewById(R.id.two);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
e1.requestFocus();
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
e2.requestFocus();
}
});
}
}
You can set a custom toolbar item color dynamically by creating a custom toolbar class:
package view;
import android.app.Activity;
import android.content.Context;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.support.v7.internal.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomToolbar extends Toolbar{
public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public CustomToolbar(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomToolbar(Context context) {
super(context);
// TODO Auto-generated constructor stub
ctxt = context;
}
int itemColor;
Context ctxt;
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d("LL", "onLayout");
super.onLayout(changed, l, t, r, b);
colorizeToolbar(this, itemColor, (Activity) ctxt);
}
public void setItemColor(int color){
itemColor = color;
colorizeToolbar(this, itemColor, (Activity) ctxt);
}
/**
* Use this method to colorize toolbar icons to the desired target color
* @param toolbarView toolbar view being colored
* @param toolbarIconsColor the target color of toolbar icons
* @param activity reference to activity needed to register observers
*/
public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
final PorterDuffColorFilter colorFilter
= new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN);
for(int i = 0; i < toolbarView.getChildCount(); i++) {
final View v = toolbarView.getChildAt(i);
doColorizing(v, colorFilter, toolbarIconsColor);
}
//Step 3: Changing the color of title and subtitle.
toolbarView.setTitleTextColor(toolbarIconsColor);
toolbarView.setSubtitleTextColor(toolbarIconsColor);
}
public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
if(v instanceof ImageButton) {
((ImageButton)v).getDrawable().setAlpha(255);
((ImageButton)v).getDrawable().setColorFilter(colorFilter);
}
if(v instanceof ImageView) {
((ImageView)v).getDrawable().setAlpha(255);
((ImageView)v).getDrawable().setColorFilter(colorFilter);
}
if(v instanceof AutoCompleteTextView) {
((AutoCompleteTextView)v).setTextColor(toolbarIconsColor);
}
if(v instanceof TextView) {
((TextView)v).setTextColor(toolbarIconsColor);
}
if(v instanceof EditText) {
((EditText)v).setTextColor(toolbarIconsColor);
}
if (v instanceof ViewGroup){
for (int lli =0; lli< ((ViewGroup)v).getChildCount(); lli ++){
doColorizing(((ViewGroup)v).getChildAt(lli), colorFilter, toolbarIconsColor);
}
}
if(v instanceof ActionMenuView) {
for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {
//Step 2: Changing the color of any ActionMenuViews - icons that
//are not back button, nor text, nor overflow menu icon.
final View innerView = ((ActionMenuView)v).getChildAt(j);
if(innerView instanceof ActionMenuItemView) {
int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
for(int k = 0; k < drawablesCount; k++) {
if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
final int finalK = k;
//Important to set the color filter in seperate thread,
//by adding it to the message queue
//Won't work otherwise.
//Works fine for my case but needs more testing
((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
// innerView.post(new Runnable() {
// @Override
// public void run() {
// ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
// }
// });
}
}
}
}
}
}
}
then refer to it in your layout file. Now you can set a custom color using
toolbar.setItemColor(Color.Red);
Sources:
I found the information to do this here: How to dynamicaly change Android Toolbar icons color
and then I edited it, improved upon it, and posted it here: GitHub:AndroidDynamicToolbarItemColor
Simple function with try - catch
const parseJwt = (token) => {
try {
return JSON.parse(atob(token.split('.')[1]));
} catch (e) {
return null;
}
};
Thanks!
For anyone interested and using a newer rails and the Devise gem: Devise's "trackable" option includes a column for current/last_sign_in_ip in the users table.
You can provide for jar-file
element path to a folder with compiled classes. For example I added something like that when I prepared persistence.xml to some integration tests:
<jar-file>file:../target/classes</jar-file>
$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');
or
var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);
Though I'm not certain it will have an affect as it will be generated after the page is loaded
If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx
This may allow other meta tags, if you're lucky
Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx
For persistent key/value storage, you can use kv-bash
, a pure bash implementation of key/value database available at https://github.com/damphat/kv-bash
Usage
git clone https://github.com/damphat/kv-bash
source kv-bash/kv-bash
Try create some permanent variables
kvset myName xyz
kvset myEmail [email protected]
#read the varible
kvget myEmail
#you can also use in another script with $(kvget keyname)
echo $(kvget myEmail)
when you bind localhost
or 127.0.0.1
, it means you can only connect to your service from local.
you cannot bind 10.0.0.1
because it not belong to you, you can only bind ip owned by your computer
you can bind 0.0.0.0
because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip
My solution would be after converting data to numerical type:
Top15[['Citable docs per Capita','Energy Supply per Capita']].corr()
This happened to me after adding/renaming current configurations and it makes sense.
Every configuration makes use of Configurations Set generated by cocoapods so these things needs to match.
So if you add/rename configurations, these will need to use the right configuration sets, and for that running pod install
will do it.
I love 10 ways to format time and date using JavaScript and Working with Dates.
Basically, you have three methods and you have to combine the strings for yourself:
getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year
Example:
var d = new Date();_x000D_
var curr_date = d.getDate();_x000D_
var curr_month = d.getMonth() + 1; //Months are zero based_x000D_
var curr_year = d.getFullYear();_x000D_
console.log(curr_date + "-" + curr_month + "-" + curr_year);
_x000D_
This command works for me:
./mysql -u root -p
(PS: I'm working on mac through terminal)
I found that the only option that worked for me was
font-size:0;
I was also using overflow
and white-space: nowrap;
float: left;
seems to mess things up
Unfortunately no with current state of affairs in CSS.
Ellipsis rendering has prerequisite white-space:nowrap
that effectively means: ellipsis are drawn on single line text containers only.
Use the following JavaScript to get the value after hash (#) from a URL. You don't need to use jQuery for that.
var hash = location.hash.substr(1);
I have got this code and tutorial from here - How to get hash value from URL using JavaScript
In your situation, git rebase
would also do the trick. Since you have no changes that master doesn't have, git will just fast-forward. If you are working with a rebase workflow, that might be more advisable, as you wouldn't end up with a merge commit if you mess up.
username@workstation:~/work$ git status
# On branch master
# Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
# (use "git pull" to update your local branch)
#
nothing to commit, working directory clean
username@workstation:~/work$ git rebase
First, rewinding head to replay your work on top of it...
Fast-forwarded master to refs/remotes/origin/master.
# On branch master
nothing to commit, working directory clean
I landed this question in 2019. MY problem was updating table1 with table2 ignoring the variables with different name in both tables. I was getting the same error as mentioned in question: Error Code: 1364. Field 'id' doesn't have a default value in mysql. Here is how solved it:
Table 1 Schema : id ( unique & auto increment)| name | profile | Age Table 2 Schema: motherage| father| name| profile
This solved my error: INSERT IGNORE INTO table2 (name,profile) SELECT name, profile FROM table1
Unless you specify a severity of 20 or higher, raiserror
will not stop execution. See the MSDN documentation.
The normal workaround is to include a return
after every raiserror
:
if @whoops = 1
begin
raiserror('Whoops!', 18, 1)
return -1
end
You could write a script to do it in your favourite scripting language. The script would do the following:
SHOW FULL TABLES
.'BASE TABLE'
and not 'VIEW'
.'VIEW'
, issue the appropriate ALTER TABLE
command.I solved this only after removing simulators with prior iOS versions.
import data from './data.json';
export class AppComponent {
json:any = data;
}
See this article for more details.
When using more +n that Matt already mentioned, to avoid pauses in long files, try this:
more +1 myfile.txt > con
When you redirect the output from more, it doesn't pause - and here you redirect to the console. You can similarly redirect to some other file like this w/o the pauses of more if that's your desired end result. Use > to redirect to file and overwrite it if it already exists, or >> to append to an existing file. (Can use either to redirect to con.)
Inspired by writing this answer, I ended up later expanding and writing a blog post going over this in careful detail. I recommend checking that out if you want to develop a deeper understanding of how to think about this problem--I try to explain it piece by piece, and also give a JSperf comparison at the end, going over speed considerations.
That said, The tl;dr is this:
To accomplish what you're asking for (filtering and mapping within one function call), you would use Array.reduce()
.
However, the more readable and (less importantly) usually significantly faster2 approach is to just use filter and map chained together:
[1,2,3].filter(num => num > 2).map(num => num * 2)
What follows is a description of how Array.reduce()
works, and how it can be used to accomplish filter and map in one iteration. Again, if this is too condensed, I highly recommend seeing the blog post linked above, which is a much more friendly intro with clear examples and progression.
You give reduce an argument that is a (usually anonymous) function.
That anonymous function takes two parameters--one (like the anonymous functions passed in to map/filter/forEach) is the iteratee to be operated on. There is another argument for the anonymous function passed to reduce, however, that those functions do not accept, and that is the value that will be passed along between function calls, often referred to as the memo.
Note that while Array.filter() takes only one argument (a function), Array.reduce() also takes an important (though optional) second argument: an initial value for 'memo' that will be passed into that anonymous function as its first argument, and subsequently can be mutated and passed along between function calls. (If it is not supplied, then 'memo' in the first anonymous function call will by default be the first iteratee, and the 'iteratee' argument will actually be the second value in the array)
In our case, we'll pass in an empty array to start, and then choose whether to inject our iteratee into our array or not based on our function--this is the filtering process.
Finally, we'll return our 'array in progress' on each anonymous function call, and reduce will take that return value and pass it as an argument (called memo) to its next function call.
This allows filter and map to happen in one iteration, cutting down our number of required iterations in half--just doing twice as much work each iteration, though, so nothing is really saved other than function calls, which are not so expensive in javascript.
For a more complete explanation, refer to MDN docs (or to my post referenced at the beginning of this answer).
Basic example of a Reduce call:
let array = [1,2,3];
const initialMemo = [];
array = array.reduce((memo, iteratee) => {
// if condition is our filter
if (iteratee > 1) {
// what happens inside the filter is the map
memo.push(iteratee * 2);
}
// this return value will be passed in as the 'memo' argument
// to the next call of this function, and this function will have
// every element passed into it at some point.
return memo;
}, initialMemo)
console.log(array) // [4,6], equivalent to [(2 * 2), (3 * 2)]
more succinct version:
[1,2,3].reduce((memo, value) => value > 1 ? memo.concat(value * 2) : memo, [])
Notice that the first iteratee was not greater than one, and so was filtered. Also note the initialMemo, named just to make its existence clear and draw attention to it. Once again, it is passed in as 'memo' to the first anonymous function call, and then the returned value of the anonymous function is passed in as the 'memo' argument to the next function.
Another example of the classic use case for memo would be returning the smallest or largest number in an array. Example:
[7,4,1,99,57,2,1,100].reduce((memo, val) => memo > val ? memo : val)
// ^this would return the largest number in the list.
An example of how to write your own reduce function (this often helps understanding functions like these, I find):
test_arr = [];
// we accept an anonymous function, and an optional 'initial memo' value.
test_arr.my_reducer = function(reduceFunc, initialMemo) {
// if we did not pass in a second argument, then our first memo value
// will be whatever is in index zero. (Otherwise, it will
// be that second argument.)
const initialMemoIsIndexZero = arguments.length < 2;
// here we use that logic to set the memo value accordingly.
let memo = initialMemoIsIndexZero ? this[0] : initialMemo;
// here we use that same boolean to decide whether the first
// value we pass in as iteratee is either the first or second
// element
const initialIteratee = initialMemoIsIndexZero ? 1 : 0;
for (var i = initialIteratee; i < this.length; i++) {
// memo is either the argument passed in above, or the
// first item in the list. initialIteratee is either the
// first item in the list, or the second item in the list.
memo = reduceFunc(memo, this[i]);
// or, more technically complete, give access to base array
// and index to the reducer as well:
// memo = reduceFunc(memo, this[i], i, this);
}
// after we've compressed the array into a single value,
// we return it.
return memo;
}
The real implementation allows access to things like the index, for example, but I hope this helps you get an uncomplicated feel for the gist of it.
The best solution is:
Computer
-> Properties
-> Device manager
.View
-> Show hidden devices
.Non-plug and plug drivers
-> HTTP
-> Disable
.This worked for me and it does simulate a keyup for my textaera. if you want it for the entire page just put the KeySimulation()
on <body>
like this <body onmousemove="KeySimulation()">
or if not onmousemove
then onmouseover
or onload
works too.
function KeySimulation()
{
var e = document.createEvent("KeyboardEvent");
if (e.initKeyboardEvent) { // Chrome, IE
e.initKeyboardEvent("keyup", true, true, document.defaultView, "Enter", 0, "", false, "");
} else { // FireFox
e.initKeyEvent("keyup", true, true, document.defaultView, false, false, false, false, 13, 0);
}
document.getElementById("MyTextArea").dispatchEvent(e);
}
_x000D_
<input type="button" onclick="KeySimulation();" value=" Key Simulation " />
<textarea id="MyTextArea" rows="15" cols="30"></textarea>
_x000D_
Add the following css class
.dropdown-menu {
width: 300px !important;
height: 400px !important;
}
Of course you can use what matches your need.
Use the "has attribute" selector:
$('p[MyTag]')
Or to select one where that attribute has a specific value:
$('p[MyTag="Sara"]')
There are other selectors for "attribute value starts with", "attribute value contains", etc.
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt
or rs.getString
you can pass column_id
starting from 1
, but i prefer to pass column_name
as its more informative as you don't have to look at database table
for which index
is what column
.
UPDATE : rs.next
boolean next() throws SQLException
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.
Returns: true if the new current row is valid; false if there are no more rows Throws: SQLException - if a database access error occurs or this method is called on a closed result set
If you need to access this as a server-side control (e.g. you want to add data attributes to a link, as I did), then there is a way to do what you want; however, you don't use the Hyperlink or HtmlAnchor controls to do it. Create a literal control and then add in "Your Text" as the text for the literal control (or whatever else you need to do that way). It's hacky, but it works.
using Routing.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Routing.Controllers
{
public class StudentsController : ApiController
{
static List<Students> Lststudents =
new List<Students>() { new Students { id=1, name="kim" },
new Students { id=2, name="aman" },
new Students { id=3, name="shikha" },
new Students { id=4, name="ria" } };
[HttpGet]
public IEnumerable<Students> getlist()
{
return Lststudents;
}
[HttpGet]
public Students getcurrentstudent(int id)
{
return Lststudents.FirstOrDefault(e => e.id == id);
}
[HttpGet]
[Route("api/Students/{id}/course")]
public IEnumerable<string> getcurrentCourse(int id)
{
if (id == 1)
return new List<string>() { "emgili", "hindi", "pun" };
if (id == 2)
return new List<string>() { "math" };
if (id == 3)
return new List<string>() { "c#", "webapi" };
else return new List<string>() { };
}
[HttpGet]
[Route("api/students/{id}/{name}")]
public IEnumerable<Students> getlist(int id, string name)
{ return Lststudents.Where(e => e.id == id && e.name == name).ToList(); }
[HttpGet]
public IEnumerable<string> getlistcourse(int id, string name)
{
if (id == 1 && name == "kim")
return new List<string>() { "emgili", "hindi", "pun" };
if (id == 2 && name == "aman")
return new List<string>() { "math" };
else return new List<string>() { "no data" };
}
}
}
A relatively easy way of doing this is to write the entire sequence as a shell script.
out.tar:
set -e ;\
TMP=$$(mktemp -d) ;\
echo hi $$TMP/hi.txt ;\
tar -C $$TMP cf $@ . ;\
rm -rf $$TMP ;\
I have consolidated some related tips here: https://stackoverflow.com/a/29085684/86967
Regarding the beautiful code of Raghunandan above.
Many have asked how to "clear" the drawing. Here's how to do that:
public void clearDrawing()
{
Utils.Log("RaghunandanDraw, how to clear....");
setDrawingCacheEnabled(false);
// don't forget that one and the match below,
// or you just keep getting a duplicate when you save.
onSizeChanged(width, height, width, height);
invalidate();
setDrawingCacheEnabled(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
width = w; // don't forget these
height = h;
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
Many have asked how to "save" the drawing. Here's how to do that:
public DrawingView(Context c)
{
circlePaint.setStrokeJoin(Paint.Join.MITER);
circlePaint.setStrokeWidth(4f);
etc...
// in the class where you set up the view, add this:
setDrawingCacheEnabled( true );
}
public void saveDrawing()
{
Bitmap whatTheUserDrewBitmap = getDrawingCache();
// don't forget to clear it (see above) or you just get duplicates
// almost always you will want to reduce res from the very high screen res
whatTheUserDrewBitmap =
ThumbnailUtils.extractThumbnail(whatTheUserDrewBitmap, 256, 256);
// NOTE that's an incredibly useful trick for cropping/resizing squares
// while handling all memory problems etc
// http://stackoverflow.com/a/17733530/294884
// you can now save the bitmap to a file, or display it in an ImageView:
ImageView testArea = ...
testArea.setImageBitmap( whatTheUserDrewBitmap );
// these days you often need a "byte array". for example,
// to save to parse.com or other cloud services
ByteArrayOutputStream baos = new ByteArrayOutputStream();
whatTheUserDrewBitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
byte[] yourByteArray;
yourByteArray = baos.toByteArray();
}
Hope it helps someone as this has helped me.
Instead of using align-self: center
use align-items: center
.
There's no need to change flex-direction
or use text-align
.
Here's your code, with one adjustment, to make it all work:
ul {
height: 100%;
}
li {
display: flex;
justify-content: center;
/* align-self: center; <---- REMOVE */
align-items: center; /* <---- NEW */
background: silver;
width: 100%;
height: 20%;
}
The align-self
property applies to flex items. Except your li
is not a flex item because its parent – the ul
– does not have display: flex
or display: inline-flex
applied.
Therefore, the ul
is not a flex container, the li
is not a flex item, and align-self
has no effect.
The align-items
property is similar to align-self
, except it applies to flex containers.
Since the li
is a flex container, align-items
can be used to vertically center the child elements.
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
html, body {_x000D_
height: 100%;_x000D_
}_x000D_
ul {_x000D_
height: 100%;_x000D_
}_x000D_
li {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
/* align-self: center; */_x000D_
align-items: center;_x000D_
background: silver;_x000D_
width: 100%;_x000D_
height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
<li>This is the text</li>_x000D_
</ul>
_x000D_
Technically, here's how align-items
and align-self
work...
The align-items
property (on the container) sets the default value of align-self
(on the items). Therefore, align-items: center
means all flex items will be set to align-self: center
.
But you can override this default by adjusting the align-self
on individual items.
For example, you may want equal height columns, so the container is set to align-items: stretch
. However, one item must be pinned to the top, so it is set to align-self: flex-start
.
How is the text a flex item?
Some people may be wondering how a run of text...
<li>This is the text</li>
is a child element of the li
.
The reason is that text that is not explicitly wrapped by an inline-level element is algorithmically wrapped by an inline box. This makes it an anonymous inline element and child of the parent.
From the CSS spec:
9.2.2.1 Anonymous inline boxes
Any text that is directly contained inside a block container element must be treated as an anonymous inline element.
The flexbox specification provides for similar behavior.
Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item.
Hence, the text in the li
is a flex item.
The following CSS removes the yellow background color and replaces it with a background color of your choosing. It doesn't disable auto-fill and it requires no jQuery or Javascript hacks.
input:-webkit-autofill {
-webkit-box-shadow:0 0 0 50px white inset; /* Change the color to your own background color */
-webkit-text-fill-color: #333;
}
input:-webkit-autofill:focus {
-webkit-box-shadow: /*your box-shadow*/,0 0 0 50px white inset;
-webkit-text-fill-color: #333;
}
Solution copied from: Override browser form-filling and input highlighting with HTML/CSS
To remove the variable from the current environment (not permanently):
set FOOBAR=
To permanently remove the variable from the user environment (which is the default place setx
puts it):
REG delete HKCU\Environment /F /V FOOBAR
If the variable is set in the system environment (e.g. if you originally set it with setx /M
), as an administrator run:
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
Note: The REG
commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.
If you know what parameter you want to pass, take a Action<T>
for the type. Example:
void LoopMethod (Action<int> code, int count) {
for (int i = 0; i < count; i++) {
code(i);
}
}
If you want the parameter to be passed to your method, make the method generic:
void LoopMethod<T> (Action<T> code, int count, T paramater) {
for (int i = 0; i < count; i++) {
code(paramater);
}
}
And the caller code:
Action<string> s = Console.WriteLine;
LoopMethod(s, 10, "Hello World");
Update. Your code should look like:
private void Include(IList<string> includes, Action<string> action)
{
if (includes != null)
{
foreach (var include in includes)
action(include);
}
}
public void test()
{
Action<string> dg = (s) => {
_context.Cars.Include(s);
};
this.Include(includes, dg);
}
Try This below method code to get the distance in meter between two location, hope it will help for you
public static double distance(LatLng start, LatLng end){
try {
Location location1 = new Location("locationA");
location1.setLatitude(start.latitude);
location1.setLongitude(start.longitude);
Location location2 = new Location("locationB");
location2.setLatitude(end.latitude);
location2.setLongitude(end.longitude);
double distance = location1.distanceTo(location2);
return distance;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
Really, what you want to do cannot be done because the protocols do not allow for this. If static IPs were universally used then you might be able to do it. They are not, so you cannot.
If you really want to identify people, have them log in.
Since they will probably be moving around to different pages on your web site, you need a way to keep track of them as they move about.
So long as they are logged in, and you are tracking their session within your site via cookies/link-parameters/beacons/whatever, you can be pretty sure that they are using the same computer during that time.
Ultimately, it is incorrect to say this tells you which computer they are using if your users are not using your own local network and do not have static IP addresses.
If what you want to do is being done with the cooperation of the users and there is only one user per cookie and they use a single web browser, just use a cookie.
Grab the radio group and look at the children to see if any are unchecked.
RadioGroup rg = (RadioGroup) view;
int checked = savedInstanceState.getInt(wrap.getAttributeName());
if(checked != -1) {
RadioButton btn = (RadioButton) rg.getChildAt(checked);
btn.toggle();
}
I think Lukas Bach solution to use react-app-rewired in order to modify webpack config is a good way to go, however, I wouldn't exclude the whole ModuleScopePlugin but instead whitelist the specific file that can be imported outside of src:
config-overrides.js
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const path = require("path");
module.exports = function override(config) {
config.resolve.plugins.forEach(plugin => {
if (plugin instanceof ModuleScopePlugin) {
plugin.allowedFiles.add(path.resolve("./config.json"));
}
});
return config;
};
Here's one from jQuery Validate plugin's additional-methods.js
file...
jQuery.validator.addMethod("zipUS", function(value, element) {
return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(value);
}, "Please specify a valid US zip code.");
EDIT: Since the above code is part of the jQuery Validate plugin, it depends on the .addMethod()
method.
Remove dependency on plugins and make it more generic....
function checkZip(value) {
return (/(^\d{5}$)|(^\d{5}-\d{4}$)/).test(value);
};
Example Usage: http://jsfiddle.net/5PNcJ/
Late to the party, but this will give you the age (in years) accurately and easily:
b = birthday
today = datetime.datetime.today()
age = today.year - b.year + (today.month - b.month > 0 or
(today.month == b.month > 0 and
today.day - b.day > 0))
I had a similar issue and ended up with this:
For me this has the advantage that data and annotation are not overlapping.
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
x = A[ind]
y = B[ind]
xPos = x1 + .02 * (x1 - x0)
yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
ax.annotate('',#label,
xy=(x, y), xycoords='data',
xytext=(xPos, yPos), textcoords='data',
arrowprops=dict(
connectionstyle="arc3,rad=0.",
shrinkA=0, shrinkB=10,
arrowstyle= '-|>', ls= '-', linewidth=2
),
va='bottom', ha='left', zorder=19
)
ax.text(xPos + .01 * (x1 - x0), yPos,
'({:.2f}, {:.2f})'.format(x,y),
transform=ax.transData, va='center')
plt.grid()
plt.show()
Using the text argument in .annotate
ended up with unfavorable text positions.
Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.
For individual element the code below could be used:
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
for (int second = 0;; second++) {
if (second >= 60){
fail("timeout");
}
try {
if (isElementPresent(By.id("someid"))){
break;
}
}
catch (Exception e) {
}
Thread.sleep(1000);
}
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
If you want to use loops you can also do:
$array = array('lastname', 'email', 'phone');
foreach($array as &$value){
$value = "'$value'";
}
$comma_separated = implode(",", $array);
While there are some solid answers above, I am surprised by the number of confusions and misunderstandings I have read. This probably proves the idea that one should use java.util.concurrent as much as possible instead of trying to write their own broken concurrent code.
Back to the question: to summarize, the best practice today is to AVOID notify() in ALL situations due to the lost wakeup problem. Anyone who doesn't understand this should not be allowed to write mission critical concurrency code. If you are worried about the herding problem, one safe way to achieve waking one thread up at a time is to:
Or you can use Java.util.concurrent.*, which have already implemented this.
I had to do this with text fields and came across the limit of 100 bytes on the index.
I solved this by adding a column, doing a md5 hash of the fields, and the doing the alter.
ALTER TABLE table ADD `merged` VARCHAR( 40 ) NOT NULL ;
UPDATE TABLE SET merged` = MD5(CONCAT(`col1`, `col2`, `col3`))
ALTER IGNORE TABLE table ADD UNIQUE INDEX idx_name (`merged`);
Those things are Compiler- and Platform-specific. Neither the C nor the C++ standard say anything about calling conventions except for extern "C"
in C++.
how does a caller know if it should free up the stack ?
The caller knows the calling convention of the function and handles the call accordingly.
At the call site, does the caller know if the function being called is a cdecl or a stdcall function ?
Yes.
How does it work ?
It is part of the function declaration.
How does the caller know if it should free up the stack or not ?
The caller knows the calling conventions and can act accordingly.
Or is it the linkers responsibility ?
No, the calling convention is part of a function's declaration so the compiler knows everything it needs to know.
If a function which is declared as stdcall calls a function(which has a calling convention as cdecl), or the other way round, would this be inappropriate ?
No. Why should it?
In general, can we say that which call will be faster - cdecl or stdcall ?
I don't know. Test it.
You seem to have misunderstood how character classes definition works in regex.
To match any of the strings 01
, 02
, 03
, 04
, 05
, 06
, 07
, 08
, 09
, 10
, 11
, or 12
, something like this works:
0[1-9]|1[0-2]
A character class, by itself, attempts to match one and exactly one character from the input string. [01-12]
actually defines [012]
, a character class that matches one character from the input against any of the 3 characters 0
, 1
, or 2
.
The -
range definition goes from 1
to 1
, which includes just 1
. On the other hand, something like [1-9]
includes 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
.
Beginners often make the mistakes of defining things like [this|that]
. This doesn't "work". This character definition defines [this|a]
, i.e. it matches one character from the input against any of 6 characters in t
, h
, i
, s
, |
or a
. More than likely (this|that)
is what is intended.
So it's obvious now that a pattern like between [24-48] hours
doesn't "work". The character class in this case is equivalent to [248]
.
That is, -
in a character class definition doesn't define numeric range in the pattern. Regex engines doesn't really "understand" numbers in the pattern, with the exception of finite repetition syntax (e.g. a{3,5}
matches between 3 and 5 a
).
Range definition instead uses ASCII/Unicode encoding of the characters to define ranges. The character 0
is encoded in ASCII as decimal 48; 9
is 57. Thus, the character definition [0-9]
includes all character whose values are between decimal 48 and 57 in the encoding. Rather sensibly, by design these are the characters 0
, 1
, ..., 9
.
Let's take a look at another common character class definition [a-zA-Z]
In ASCII:
A
= 65, Z
= 90a
= 97, z
= 122This means that:
[a-zA-Z]
and [A-Za-z]
are equivalent[a-Z]
is likely to be an illegal character range
a
(97) is "greater than" than Z
(90)[A-z]
is legal, but also includes these six characters:
[
(91), \
(92), ]
(93), ^
(94), _
(95), `
(96)Use a real dropdown menu instead: a list (ul
, li
) and links. Never misuse form elements as links.
Readers with screen readers usually scan through a automagically generated list of links – the’ll miss these important information. Many keyboard navigation systems (e.g. JAWS, Opera) offer different keyboard shortcuts for links and form elements.
If you still cannot drop the idea of a select
don’t use the onchange
handler at least. This is a real pain for keyboard users, it makes your third item nearly inaccessible.
It may be
select timediff(current_time(),utc_time())
You won't get the timezone value directly this way.
@@global.time_zone
cannot be used as it is a variable, and it returns the value 'SYSTEM'
.
If you need to use your query in a session with a changed timezone by using session SET TIME_ZONE =
, then you will get that with @@session.time_zone
. If you query @@global.time_zone
, then you get 'SYSTEM'
.
If you try datediff
, date_sub
, or timediff
with now()
and utc_time()
, then you'll probably run into conversion issues.
But the things suggested above will probably work at least with some server versions. My version is 5.5.43-37 and is a hosted solution.
To enable the Windows Authentication on IIS7 on Windows 7 machine:
Go to Control Panel
Click Programs >> Programs and Features
Select "Turn Windows Features on or off" from left side.
Expand Internet Information Services >> World Wide Web Services >> Security
Select Windows Authentication and click OK.
Reset the IIS and Check in IIS now for windows authentication.
Enjoy
When you test using class inherits unittest.TestCase you can simply use methods like:
and similar (in python documentation you find the rest).
In your example we can simply assert if mock_method.called property is False, which means that method was not called.
import unittest
from unittest import mock
import my_module
class A(unittest.TestCase):
def setUp(self):
self.message = "Method should not be called. Called {times} times!"
@mock.patch("my_module.method_to_mock")
def test(self, mock_method):
my_module.method_to_mock()
self.assertFalse(mock_method.called,
self.message.format(times=mock_method.call_count))
You can try the FileReader API. Do something like this:
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>
_x000D_
If anyone is looking for an updated correct syntax for this as I was, try the following:
Example:
dg.Rows[0].Cells[6].Value = "test";
As the question is asked simply use @Min(1) instead of @size on integer fields and it will work.
You're calling writer.close();
after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.
public void writeToFile(){
String file_text= pedStatusText + " " + gatesStatus + " " + DrawBridgeStatusText;
try {
writer.write(file_text);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And add a method cleanUp
to close the stream.
public void cleanUp() {
writer.close();
}
This means that you have the responsibility to make sure that you're calling cleanUp
when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.
EDIT: You can create a new stream each time you want to write to the file, by moving writer
into the writeToFile()
method..
public void writeToFile() {
FileWriter writer = new FileWriter("status.txt", true);
// ... Write to the file.
writer.close();
}
The web.config approach works for InfoPath form services calls to IntApp web service enabled rules.
<system.net>
<defaultProxy />
<settings> <!-- 20130323 bchauvin -->
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
str.matches(regex)
behaves like Pattern.matches(regex, str)
which attempts to match the entire input sequence against the pattern and returns
true
if, and only if, the entire input sequence matches this matcher's pattern
Whereas matcher.find()
attempts to find the next subsequence of the input sequence that matches the pattern and returns
true
if, and only if, a subsequence of the input sequence matches this matcher's pattern
Thus the problem is with the regex. Try the following.
String test = "User Comments: This is \t a\ta \ntest\n\n message \n";
String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find()); //true
String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2)); //true
Thus in short, the (\\W)*(\\S)*
portion in your first regex matches an empty string as *
means zero or more occurrences and the real matched string is User Comments:
and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W
matches a non word character, ie [^a-zA-Z0-9_]
and the first character is T
, a word character.
Not sure why no one besides Erik mentioned this, but according to this page, the assignment operator works just fine. No need to use a constructor, .assign(), or .append().
std::string mystring;
mystring = "This is a test!"; // Assign C string to std:string directly
std::cout << mystring << '\n';
My version of user113716's answer. His removes a value if no match is found, which is not good.
var y = [1, 2, 3]
var removeItem = 2;
var i = $.inArray(removeItem,y)
if (i >= 0){
y.splice(i, 1);
}
alert(y);
This now removes 1 item if a match is found, 0 if no matches are found.
How it works:
value
in an array
count
number of values starting at index
, so we just want a count
of 1
Make the splits depend on the same list of abis as the external build. Single source of truth.
android {
// ...
defaultConfig {
// ...
externalNativeBuild {
cmake {
cppFlags "-std=c++17"
abiFilters 'x86', 'armeabi-v7a', 'x86_64'
}
}
} //defaultConfig
splits {
abi {
enable true
reset()
include defaultConfig.externalNativeBuild.getCmake().getAbiFilters().toListString()
universalApk true
}
}
} //android
You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus
See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.
am assuming that you want to know how to format numbers in SSRS
Just right click
the TextBox
on which you want to apply formatting, go to its expression
.
suppose its expression is something like below
=Fields!myField.Value
then do this
=Format(Fields!myField.Value,"##.##")
or
=Format(Fields!myFields.Value,"00.00")
difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00
this should give you an idea.
also: you might have to convert your field into a numerical one. i.e.
=Format(CDbl(Fields!myFields.Value),"00.00")
so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:
UPDATE :
if you want to apply variable formatting on the same column based on row values i.e.
you want myField
to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)
Go to the appropriate textbox and go to its expression and do this:
=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0,
Format(Fields!myField.Value, "##.##"),Fields!myField.Value)
so basically you are using IIF(condition, true,false)
operator of SSRS,
ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.
this should give you an idea, how to handle variable formatting.
Three possible solutions come to my mind:
1. Reverse the order:
//convert the arr to list first
Collections.reverse(listWithNumbers);
System.out.print("Numbers in Descending Order: " + listWithNumbers);
2. Iterate backwards and print it:
Arrays.sort(arr);
System.out.print("Numbers in Descending Order: " );
for(int i = arr.length - 1; i >= 0; i--){
System.out.print( " " +arr[i]);
}
3. Sort it with "oposite" comparator:
Arrays.sort(arr, new Comparator<Integer>(){
int compare(Integer i1, Integer i2) {
return i2 - i1;
}
});
// or Collections.reverseOrder(), could be used instead
System.out.print("Numbers in Descending Order: " );
for(int i = 0; i < arr.length; i++){
System.out.print( " " +arr[i]);
}
Just to add something I was missing from all the answers - even if it seems to be silly and obvious as soon as you know:
The file has to be named "App.config" or "app.config" and can be located in your project at the same level as e.g. Program.cs.
I do not know if other locations are possible, other names (like application.conf, as suggested in the ODP.net documentation) did not work for me.
PS. I started with Visual Studio Code and created a new project with "dotnet new". No configuration file is created in this case, I am sure there are other cases. PPS. You may need to add a nuget package to be able to read the config file, in case of .NET CORE it would be "dotnet add package System.Configuration.ConfigurationManager --version 4.5.0"
This problem also occurs when you have 2 resources with the same file name; say "configurations.properties" within 2 different jar or directory path configured within the classpath. For example:
You have your "configurations.properties" in your process or web application (jar, war or ear). But another dependency (jar) have the same file "configurations.properties" in the same path. Then I suppose that Spring have no idea (@_@?) where to get the property and just sends the property name declared within the @Value annotation.
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'ko', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
The NEW values (or NEW_BUFFER as you have renamed them) are only available when INSERTING and UPDATING. For DELETING you would need to use OLD (OLD_BUFFER). So your trigger would become:
CREATE or REPLACE TRIGGER test001
AFTER INSERT OR DELETE OR UPDATE ON tabletest001
REFERENCING OLD AS old_buffer NEW AS new_buffer
FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00')
You may need to add logic inside the trigger to cater for code that updates field1 from 'HBP000' to something else.
This helped for me:
All you need to do, is to specify a envirnoment variable called JAVA_TOOL_OPTIONS. If you set this variable to -Dfile.encoding=UTF8, everytime a JVM is started, it will pick up this information.
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
var newTH = document.createElement('th');
newTH.setAttribute("onclick", "removeColumn(#)");
newTH.setAttribute("id", "#");
function removeColumn(#){
// remove column #
}
In most contexts: a function returns a value, while a procedure doesn't. Both are pieces of code grouped together to do the same thing.
In functional programming context (where all functions return values), a function is an abstract object:
f(x)=(1+x)
g(x)=.5*(2+x/2)
Here, f is the same function as g, but is a different procedure.
$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.
See also boost::format:
#include <boost/format.hpp>
std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();
input type="hidden" name="is_main" value="0"
input type="checkbox" name="is_main" value="1"
so you can control like this as I did in the application. if it checks then send value 1 otherwise 0
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
Alternatively you can use the classmethod
decorator:
class A:
@classmethod
def get_classname(cls):
return cls.__name__
def use_classname(self):
return self.get_classname()
Usage:
>>> A.get_classname()
'A'
>>> a = A()
>>> a.get_classname()
'A'
>>> a.use_classname()
'A'
Just tried both ways and in both ways I got generated .env
file:
Composer should automatically create .env file. In the post-create-project-cmd
section of the composer.json
you can find:
"post-create-project-cmd": [
"php -r \"copy('.env.example', '.env');\"",
"php artisan key:generate"
]
Both ways use the same composer.json
file, so there shoudn't be any difference.
I suggest you to update laravel/installer
to the last version: 1.2 and try again:
composer global require "laravel/installer=~1.2"
You can always generate .env
file manually by running:
cp .env.example .env
php artisan key:generate
You can use Microsoft's WFetch tool also. This is a good tool for all HTTP operations.
You can't read the transaction log file easily because that's not properly documented. There are basically two ways to do this. Using undocumented or semi-documented database functions or using third-party tools.
Note: This only makes sense if your database is in full recovery mode.
SQL Functions:
DBCC LOG and fn_dblog - more details here and here.
Third-party tools:
Toad for SQL Server and ApexSQL Log.
You can also check out several other topics where this was discussed:
I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.
It is neither an API nor a framework. It is just an architectural concept. You can find more details here.
I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.
EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.
It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).
Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.
Another useful thing to do with numpy.histogram
is to plot the output as the x and y coordinates on a linegraph. For example:
arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()
This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.
Like this :
var id = $('div.foo').attr('id');
$('div.foo').attr('id', id + ' id_adding');
This is what worked for me:
I was using the Microsoft.IdentityModel.Clients.ActiveDirectory
version 3.19 in a class library project but only had version 2.22 installed in the actual ASP.NET Web Application project. Upgrading to 3.19 in the web app project got me past the error.
In chrome, if you hover your cursor on Download ZIP it will give you the link at the bottom of the browser
If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();
SELECT field1,
field2,
'example' AS newfield
FROM TABLE1
This will add a column called "newfield" to the output, and its value will always be "example".
There many methods to send raw data with a post
request. I personally like this one.
const url = "your url"
const data = {key: value}
const headers = {
"Content-Type": "application/json"
}
axios.post(url, data, headers)
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
Buffer is an area of memory used to temporarily store data while it's being moved from one place to another.
Cache is a temporary storage area used to store frequently accessed data for rapid access. Once the data is stored in the cache, future use can be done by accessing the cached copy rather than re-fetching the original data, so that the average access time is shorter.
Note: buffer and cache can be allocated on disk as well
To test a bit you would do the following: (assuming flags is a 32 bit number)
Test Bit:
if((flags & 0x08) == 0x08)
(If bit 4 is set then its true)
Toggle Back (1 - 0 or 0 - 1): flags = flags ^ 0x08;
Reset Bit 4 to Zero: flags = flags & 0xFFFFFF7F;
Try adding the line c = cv.WaitKey(10)
at the bottom of your repeat()
method.
This waits for 10 ms for the user to enter a key. Even if you're not using the key at all, put this in. I think there just needed to be some delay, so time.sleep(10)
may also work.
In regards to the camera index, you could do something like this:
for i in range(3):
capture = cv.CaptureFromCAM(i)
if capture: break
This will find the index of the first "working" capture device, at least for indices from 0-2. It's possible there are multiple devices in your computer recognized as a proper capture device. The only way I know of to confirm you have the right one is manually looking at your light. Maybe get an image and check its properties?
To add a user prompt to the process, you could bind a key to switching cameras in your repeat loop:
import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)
def repeat():
global capture #declare as globals since we are assigning to them now
global camera_index
frame = cv.QueryFrame(capture)
cv.ShowImage("w1", frame)
c = cv.WaitKey(10)
if(c=="n"): #in "n" key is pressed while the popup window is in focus
camera_index += 1 #try the next camera index
capture = cv.CaptureFromCAM(camera_index)
if not capture: #if the next camera index didn't work, reset to 0.
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)
while True:
repeat()
disclaimer: I haven't tested this so it may have bugs or just not work, but might give you at least an idea of a workaround.
The Symfony documentation now explicitly shows how to do this:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p
FROM AppBundle:Product p
WHERE p.price > :price
ORDER BY p.price ASC'
)->setParameter('price', '19.99');
$products = $query->getResult();
From http://symfony.com/doc/2.8/book/doctrine.html#querying-for-objects-with-dql
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
You can use an RDLC file provided in visual studio to define your report layout. You can view the rdlc using the ReportViewer control.
Both are provided out of the box with visual studio.
Use:
:wq!
The exclamation mark is used for overriding read-only mode.
ECMAScript 5 supports trim
and this has been implemented in Firefox.
The GitLens icon will show up in nav bar. Click on it.
Click on compare
Select branches to compare
Now you can see the difference. You can select any file for which you want to see the diff for.
My resolution was adding the following import:
import { of } from 'rxjs/observable/of';
So the overall code of hero.service.ts after the change is:
import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { of } from 'rxjs/observable/of';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class HeroService {
constructor() { }
getHeroes(): Observable<Hero[]> {
return of(HEROES);
}
}
The following should work with the latest version of Apache common codec
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));
and for encoding
byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));
By publishing your whole node_modules
folder you are deploying far more files than you will actually need in production.
Instead, use a task runner as part of your build process to package up those files you require, and deploy them to your wwwroot
folder. This will also allow you to concat and minify your assets at the same time, rather than having to serve each individual library separately.
You can then also completely remove the FileServer
configuration and rely on UseStaticFiles
instead.
Currently, gulp is the VS task runner of choice. Add a gulpfile.js
to the root of your project, and configure it to process your static files on publish.
For example, you can add the following scripts
section to your project.json
:
"scripts": {
"prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
},
Which would work with the following gulpfile (the default when scaffolding with yo
):
/// <binding Clean='clean'/>
"use strict";
var gulp = require("gulp"),
rimraf = require("rimraf"),
concat = require("gulp-concat"),
cssmin = require("gulp-cssmin"),
uglify = require("gulp-uglify");
var webroot = "./wwwroot/";
var paths = {
js: webroot + "js/**/*.js",
minJs: webroot + "js/**/*.min.js",
css: webroot + "css/**/*.css",
minCss: webroot + "css/**/*.min.css",
concatJsDest: webroot + "js/site.min.js",
concatCssDest: webroot + "css/site.min.css"
};
gulp.task("clean:js", function (cb) {
rimraf(paths.concatJsDest, cb);
});
gulp.task("clean:css", function (cb) {
rimraf(paths.concatCssDest, cb);
});
gulp.task("clean", ["clean:js", "clean:css"]);
gulp.task("min:js", function () {
return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
.pipe(concat(paths.concatJsDest))
.pipe(uglify())
.pipe(gulp.dest("."));
});
gulp.task("min:css", function () {
return gulp.src([paths.css, "!" + paths.minCss])
.pipe(concat(paths.concatCssDest))
.pipe(cssmin())
.pipe(gulp.dest("."));
});
gulp.task("min", ["min:js", "min:css"]);
For Mono(Droid) solutions:
decimal decimalValue = decimal.Parse(input.Text.Replace(",", ".") , CultureInfo.InvariantCulture);
To use file_get_contents()
over/through a proxy that doesn't require authentication, something like this should do :
(I'm not able to test this one : my proxy requires an authentication)
$aContext = array(
'http' => array(
'proxy' => 'tcp://192.168.0.2:3128',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);
$sFile = file_get_contents("http://www.google.com", False, $cxContext);
echo $sFile;
Of course, replacing the IP and port of my proxy by those which are OK for yours ;-)
If you're getting that kind of error :
Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 407 Proxy Authentication Required
It means your proxy requires an authentication.
If the proxy requires an authentication, you'll have to add a couple of lines, like this :
$auth = base64_encode('LOGIN:PASSWORD');
$aContext = array(
'http' => array(
'proxy' => 'tcp://192.168.0.2:3128',
'request_fulluri' => true,
'header' => "Proxy-Authorization: Basic $auth",
),
);
$cxContext = stream_context_create($aContext);
$sFile = file_get_contents("http://www.google.com", False, $cxContext);
echo $sFile;
Same thing about IP and port, and, this time, also LOGIN and PASSWORD ;-) Check out all valid http options.
Now, you are passing an Proxy-Authorization header to the proxy, containing your login and password.
And... The page should be displayed ;-)
You might also take a look at the Memoize decorator. You could probably get it to do what you want without too much modification.
you can use framelayout to achieve this.
how to use framelayout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView
android:text="Frame Demo"
android:textSize="30px"
android:textStyle="bold"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
ref: tutorialspoint
Ok, for this first of all you need to use Device Policy Manager, and need to make your device Admin device. After that you have to create one BroadCast receiver and one service. I am posting code here and its working fine.
MainActivity:
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 0;
private DevicePolicyManager mDPM;
private ComponentName mAdminName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Initiate DevicePolicyManager.
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mAdminName = new ComponentName(this, DeviceAdminDemo.class);
if (!mDPM.isAdminActive(mAdminName)) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Click on Activate button to secure your application.");
startActivityForResult(intent, REQUEST_CODE);
} else {
// mDPM.lockNow();
// Intent intent = new Intent(MainActivity.this,
// TrackDeviceService.class);
// startService(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE == requestCode) {
Intent intent = new Intent(MainActivity.this, TService.class);
startService(intent);
}
}
}
//DeviceAdminDemo class
public class DeviceAdminDemo extends DeviceAdminReceiver {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
public void onEnabled(Context context, Intent intent) {
};
public void onDisabled(Context context, Intent intent) {
};
}
//TService Class
public class TService extends Service {
MediaRecorder recorder;
File audiofile;
String name, phonenumber;
String audio_format;
public String Audio_Type;
int audioSource;
Context context;
private Handler handler;
Timer timer;
Boolean offHook = false, ringing = false;
Toast toast;
Boolean isOffHook = false;
private boolean recordstarted = false;
private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
private CallBr br_call;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// final String terminate =(String)
// intent.getExtras().get("terminate");//
// intent.getStringExtra("terminate");
// Log.d("TAG", "service started");
//
// TelephonyManager telephony = (TelephonyManager)
// getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
// // object
// CustomPhoneStateListener customPhoneListener = new
// CustomPhoneStateListener();
// telephony.listen(customPhoneListener,
// PhoneStateListener.LISTEN_CALL_STATE);
// context = getApplicationContext();
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.br_call = new CallBr();
this.registerReceiver(this.br_call, filter);
// if(terminate != null) {
// stopSelf();
// }
return START_NOT_STICKY;
}
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (wasRinging == true) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordstarted = true;
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
}
//Permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.STORAGE" />
//my_admin.xml
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
//Declare following thing in manifest:
Declare DeviceAdminDemo class to manifest:
<receiver
android:name="com.example.voicerecorder1.DeviceAdminDemo"
android:description="@string/device_description"
android:label="@string/device_admin_label"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/my_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
</intent-filter>
</receiver>
<service android:name=".TService" >
</service>
In regards to Gordon M's answer above, the 1st and 2nd parameter in mysqli_real_escape_string ()
call should be swapped for the newer php versions,
according to: http://php.net/manual/en/mysqli.real-escape-string.php
Unfortunately:
It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.
It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.
What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.
Here's the code I was hoping would complete this task:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1);
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);
for (int i = 0; i < 16; i++) {
if (prefs.getBoolean("itemKey[i]", true)) {
itemsArrayList.add(itemNames[i]);
}
}
What I did:
I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.
To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.
Here's the new code:
for (int i = 0; i < 16; i++) {
if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {
itemsArrayList.add(itemNames[i]);
}
}
It is definitely not the case the question was about, but as it is the first search result while googling the error message, I'll leave it here.
First of all, check if docker service is running using the following command:
systemctl status docker.service
If it is not running, try starting it:
sudo systemctl start docker.service
... and check the status again:
systemctl status docker.service
If it has not started, investigate the reason. Probably, you have modified a config file and made an error (like I did while modifying /etc/docker/daemon.json
)
var getMatchingGroups = function(s) {
var r=/\((.*?)\)/g, a=[], m;
while (m = r.exec(s)) {
a.push(m[1]);
}
return a;
};
getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]
It really depends on the type of HTML file you're creating.
For such tasks, I use to create an object, serialize it to XML, then transform it with XSL. The pros of this approach are:
The cons are:
<textarea/>
tags (which make the page unusable), XML declaration (which can cause problems with IE), whitespace (with <pre></pre>
tags etc.), HTML entities (
), etc.Now, if your HTML is very short or very repetitive or if the HTML has a volatile structure which changes dynamically, this approach must not be taken in account. On the other hand, if you serve HTML files which have all a similar structure and you want to reduce the amount of Java code and use templates, this approach may work.
If none of the options work, I change the port and then enable USB debugging and it works fine.
On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755
As far as I can see you have the JRE
in your PATH
, but not the JDK
.
From a command prompt try this:
set PATH=%PATH%;C:\Program Files (x86)\Java\jdk1.7.0_17\bin
Then try javac
again - if this works you'll need to permanently modify your environment variables to have PATH
include the JDK
too.
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
from keras.models import load_model
h= load_model('FILE_NAME.h5')
To add to the already selected "Best Answer" (and others that are just as good like Suragch's), String.replace()
is constrained by replacing characters that are sequential (thus taking CharSequence
). However, String.replaceAll()
is not constrained by replacing sequential characters only. You could replace non-sequential characters as well as long as your regular expression is constructed in such a way.
Also (most importantly and painfully obvious), replace()
can only replace literal values; whereas replaceAll
can replace 'like' sequences (not necessarily identical).
var newdata= //You call Ajax peticion//
$("#idGrid").clearGridData();
$("#idGrid").jqGrid('setGridParam', {data:newdata)});
$("#idGrid").trigger("reloadGrid");
in event update data table
using position:fixed
alone is just fine when you don't have a header or logo at the top of your page. This solution will take into account the how far the window has scrolled, and moves the div when you scrolled past your header. It will then lock it back into place when you get to the top again.
if($(window).scrollTop() > Height_of_Header){
//begin to scroll
$("#div").css("position","fixed");
$("#div").css("top",0);
}
else{
//lock it back into place
$("#div").css("position","relative");
}
it's much easier than you think to write your own, just use an interface for JsonElementInterface
with a method string toJson()
, and an abstract class AbstractJsonElement
implementing that interface,
then all you have to do is have a class for JSONProperty
that implements the interface, and JSONValue
(any token), JSONArray
([...]), and JSONObject
({...}) that extend the abstract class
JSONObject
has a list of JSONProperty
's
JSONArray
has a list of AbstractJsonElement
's
your add function in each should take a vararg list of that type, and return this
now if you don't like something you can just tweak it
the benifit of the inteface and the abstract class is that JSONArray
can't accept properties, but JSONProperty
can accept objects or arrays
You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).
You specify sigma
and hsize
in fspecial
.
%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)
In Python you generally have for in loops instead of general for loops like C/C++, but you can achieve the same thing with the following code.
for k in range(1, c+1, 2):
do something with k
Reference Loop in Python.
Short answer:
use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.
Long answer:
The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.
TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.
Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.
Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.
So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.
Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().
Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.
I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".
In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.
What you can do is:
For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.
I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:
The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)
Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.
In my case I got this error when trying to impersonate as another user. E.g.
EXEC AS USER = 'dbo';
And as the database was imported from another environment, some of its users did not match the SQL Server logins.
You can check if you have the same problem by running the (deprecated) sp_change_users_login (in "Report" mode), or use the following query:
select p.name,p.sid "sid in DB", (select serp.sid from sys.server_principals serp where serp.name = p.name) "sid in server"
from sys.database_principals p
where p.type in ('G','S','U')
and p.authentication_type = 1
and p.sid not in (select sid from sys.server_principals)
If in that list shows the user you are trying to impersonate, then you probably can fix it by assigning the DB user to the proper login in your server. For instance:
ALTER USER dbo WITH LOGIN = dbo;
Try this :
@Override
protected void onPause() {
super.onPause();
if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
getSupportFragmentManager().findFragmentByTag("MyFragment").setRetainInstance(true);
}
@Override
protected void onResume() {
super.onResume();
if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
getSupportFragmentManager().findFragmentByTag("MyFragment").getRetainInstance();
}
Hope this will help.
Also you can write this to activity tag in menifest file :
android:configChanges="orientation|screenSize"
Good luck !!!
Here are the results I got with ipython's timeit function:
from datetime import date
today = date.today()
timeit[Model.objects.filter(date_created__year=today.year, date_created__month=today.month, date_created__day=today.day)]
1000 loops, best of 3: 652 us per loop
timeit[Model.objects.filter(date_created__gte=today)]
1000 loops, best of 3: 631 us per loop
timeit[Model.objects.filter(date_created__startswith=today)]
1000 loops, best of 3: 541 us per loop
timeit[Model.objects.filter(date_created__contains=today)]
1000 loops, best of 3: 536 us per loop
contains seems to be faster.
You can use a plain old C array:
NSInteger myIntegers[40];
for (NSInteger i = 0; i < 40; i++)
myIntegers[i] = i;
// to get one of them
NSLog (@"The 4th integer is: %d", myIntegers[3]);
Or, you can use an NSArray
or NSMutableArray
, but here you will need to wrap up each integer inside an NSNumber
instance (because NSArray
objects are designed to hold class instances).
NSMutableArray *myIntegers = [NSMutableArray array];
for (NSInteger i = 0; i < 40; i++)
[myIntegers addObject:[NSNumber numberWithInteger:i]];
// to get one of them
NSLog (@"The 4th integer is: %@", [myIntegers objectAtIndex:3]);
// or
NSLog (@"The 4th integer is: %d", [[myIntegers objectAtIndex:3] integerValue]);
If you use rails, you can use the asset pipeline to compile and shove all your haml/erb templates into a template module which can be appended to your application.js file. Checkout http://minhajuddin.com/2013/04/28/angularjs-templates-and-rails-with-eager-loading
ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your code here
}
});
You can use contains:
string[] example = { "sample1", "sample2" };
var result = (from c in example where c.Contains("2") select c);
// returns only sample2
You need to enclose your <parent>
elements in a surrounding element as XML Documents can have only one root node:
<parents> <!-- I've added this tag -->
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</parents> <!-- I've added this tag -->
As you're receiving this markup from somewhere else, rather than generating it yourself, you may have to do this yourself by treating the response as a string and wrapping it with appropriate tags, prior to attempting to parse it as XML.
So, you've a couple of choices:
<parent>
node) and process each as a distinct XML DocumentIf you need output from Console.WriteLine, and the Redirect All Output Window Text to the Immediate Window does not function and you need to know the output of Tests from the Integrated Test Explorer, using NUnit.Framework our problem is already solved at VS 2017:
Example taken from C# In Depth by Jon Skeet: This produce this output at Text Explorer:
When we click on Blue Output, under Elapsed Time, at right, and it produces this:
Standard Output is our desired Output, produced by Console.WriteLine.
It functions for Console and for Windows Form Applications at VS 2017, but only for Output generated for Test Explorer at Debug or Run; anyway, this is my main need of Console.WriteLine output.
Use DATE_FORMAT()
SELECT
DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;
The "evil" answer did not work for me. Instead, I used what was recommended on the JSHints docs page. If you know the warning that is thrown, you can turn it off for a block of code. For example, I am using some third party code that does not use camel case functions, yet my JSHint rules require it, which led to a warning. To silence it, I wrote:
/*jshint -W106 */
save_state(id);
/*jshint +W106 */
Just like @porneL said, the C api is very handy.
NSString* fileRoot = [[NSBundle mainBundle] pathForResource:@"record" ofType:@"txt"];
FILE *file = fopen([fileRoot UTF8String], "r");
char buffer[256];
while (fgets(buffer, 256, file) != NULL){
NSString* result = [NSString stringWithUTF8String:buffer];
NSLog(@"%@",result);
}
This is an old question, and I'm not sure if it will help, but I've been able to programatically fire an event using:
if (document.createEvent && ctrl.dispatchEvent) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", true, true);
ctrl.dispatchEvent(evt); // for DOM-compliant browsers
} else if (ctrl.fireEvent) {
ctrl.fireEvent("onchange"); // for IE
}
The easy way using JavaScript:
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >
Not exactly the case of actual context of this question, but this exception can be reproduced by the next query:
update users set dismissal_reason='he can't and don't want' where userid=123
Single quotes in words can't
and don't
broke the string.
In case string have only one inside quote e.g. 'he don't want' oracle throws more relevant quoted string not properly terminated error, but in case of two SQL command not properly ended is thrown.
Summary: check your query for double single quotes.
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
Linux: who am i | awk '{print $5}' | sed 's/[()]//g'
AIX: who am i | awk '{print $6}' | sed 's/[()]//g'
x and y
returns true if both x
and y
are true
.
x or y
returns if either one is true
.
From this we can conclude that or
contains and
within itself unless you mean xOR
(or except if and
is true)
Try the following:
for i in {1..600}; do echo wget http://example.com/search/link$(($i % 5)); done
The $(( ))
syntax does an arithmetic evaluation of the contents.
You can do this using PHP:
$txt1 = "the color is";
$txt2 = " red!";
echo $txt1.$txt2;
This will combine two strings and the putput will be: "the color is red!".
There's a great look at this on the wikipedia article.
It even has a nice plot of complexity for value pairs.
It is not O(a%b)
.
It is known (see article) that it will never take more steps than five times the number of digits in the smaller number. So the max number of steps grows as the number of digits (ln b)
. The cost of each step also grows as the number of digits, so the complexity is bound by O(ln^2 b)
where b is the smaller number. That's an upper limit, and the actual time is usually less.
This code uses the event
object's .keyCode
property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.
HTML:
<form>
<input type="text" id="txt" />
</form>
JS:
(function(a) {
a.onkeypress = function(e) {
if (e.keyCode >= 49 && e.keyCode <= 57) {}
else {
if (e.keyCode >= 97 && e.keyCode <= 122) {
alert('Error');
// return false;
} else return false;
}
};
})($('txt'));
function $(id) {
return document.getElementById(id);
}
For a result: http://jsfiddle.net/uUc22/
Mind you that the .keyCode
result for .onkeypress
, .onkeydown
, and .onkeyup
differ from each other.
The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
You cannot use a variable in a create table statement. The best thing I can suggest is to write the entire query as a string and exec that.
Try something like this:
declare @query varchar(max);
set @query = 'create database TEST...';
exec (@query);
In addition to the beautiful solution given by @Jon Skeet, I also needed ThenBy and ThenByDescending, so I am adding it based on his solution:
public static IOrderedEnumerable<TSource> ThenByWithDirection<TSource, TKey>(
this IOrderedEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool descending)
{
return descending ?
source.ThenByDescending(keySelector) :
source.ThenBy(keySelector);
}
I prefer something like this, it lets you decide what NumberStyle
to test for.
public static Boolean IsNumeric(String input, NumberStyles numberStyle) {
Double temp;
Boolean result = Double.TryParse(input, numberStyle, CultureInfo.CurrentCulture, out temp);
return result;
}
As per dart 2.6
The optional onError
parameter of int.parse
is deprecated. Therefore, you should use int.tryParse
instead.
Note:
The same applies to double.parse
. Therefore, use double.tryParse
instead.
/**
* ...
*
* The [onError] parameter is deprecated and will be removed.
* Instead of `int.parse(string, onError: (string) => ...)`,
* you should use `int.tryParse(string) ?? (...)`.
*
* ...
*/
external static int parse(String source, {int radix, @deprecated int onError(String source)});
The difference is that int.tryParse
returns null
if the source string is invalid.
/**
* Parse [source] as a, possibly signed, integer literal and return its value.
*
* Like [parse] except that this function returns `null` where a
* similar call to [parse] would throw a [FormatException],
* and the [source] must still not be `null`.
*/
external static int tryParse(String source, {int radix});
So, in your case it should look like:
// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345
// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
print(parsedValue2); // null
//
// handle the error here ...
//
}
You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:
$("#change_password").click(function() {
var target = $(this).attr("rel");
if($("#" + target).attr("disabled")) {
$("#" + target).attr("disabled", false);
} else {
$("#" + target).attr("disabled", true);
}
});
The "rel" attribute stores the id of the target input field.
How to deal with Zeros when calculating percentage changes is the researcher's call and requires some domain expertise. If the researcher believes that it would not be distorting the data, s/he may simply add a very small constant to all values to get rid of all zeros. In financial series, when dealing with trading volume, for example, we may not want to do this because trading volume = 0 just means that: the asset did not trade at all. The meaning of volume = 0 may be very different from volume = 0.00000000001. This is my preferred strategy in cases whereby I can not logically add a small constant to all values. Consider the percentage change formula ((New-Old)/Old) *100. If New = 0, then percentage change would be -100%. This number indeed makes financial sense as long as it is the minimum percentage change in the series (This is indeed guaranteed to be the minimum percentage change in the series). Why? Because it shows that trading volume experiences maximum possible decrease, which is going from any number to 0, -100%. So, I'll be fine with this value being in my percentage change series. If I normalize that series, then even better since this (possibly) relatively big number in absolute value will be analyzed on the same scale as other variables are. Now, what if the Old value = 0. That's a trickier case. Percentage change due to going from 0 to 1 will be equal to that due to going from 0 to a million: infinity. The fact that we call both "infinity" percentage change is problematic. In this case, I would set the infinities equal to np.nan and interpolate them.
The following graph shows what I discussed above. Starting from series 1, we get series 4, which is ready to be analyzed, with no Inf or NaNs.
One more thing: a lot of the time, the reason for calculating percentage change is to stationarize the data. So, if your original series contains zero and you wish to convert it to percentage change to achieve stationarity, first make sure it is not already stationary. Because if it is, you don't have to calculate percentage change. The point is that series that take the value of 0 a lot (the problem OP has) are very likely to be already stationary, for example the volume series I considered above. Imagine a series oscillating above and below zero, thus hitting 0 at times. Such a series is very likely already stationary.
Don't agree with post above. I have a Hero with only English available and I want Spanish.
I installed MoreLocale 2, and it has lots of different languages (Dutch among them). I choose Spanish, Sense UI restarted and EVERYTHING in my phone changed to Spanish: menus, settings, etc. The keyboard predictive text defaulted to Spanish and started suggesting words in Spanish. This means, somewhere within the OS there is a Spanish dictionary hidden and MoreLocale made it available.
The problem is that English is still the only option available in keyboard input language so I can switch to English but can't switch back to Spanish unless I restart Sense UI, which takes a couple of minutes so not a very practical solution.
Still looking for an easier way to do it so please help.
As the signature from the error message implies, the second argument must be an IEnumerable, more specifically, an IEnumerable of SelectListItem. It is the list of choices. You can use the SelectList type, which is a IEnumerable of SelectListItem. For a list with no choices:
@Html.DropDownList("PriorityID", new List<SelectListItem>(), new {@class="textbox"} )
For a list with a few choices:
@Html.DropDownList(
"PriorityID",
new List<SelectListItem>
{
new SelectListItem { Text = "High", Value = 1 },
new SelectListItem { Text = "Low", Value = 0 },
},
new {@class="textbox"})
Maybe this tutorial can be of help: How to create a DropDownList with ASP.NET MVC
Iterate over a copy instead, such as the one returned by items()
:
for k, v in list(mydict.items()):
The main difference from other solutions here is that this one reuses logic in RequiredAttribute
on the server side, and uses required
's validation method depends
property on the client side:
public class RequiredIf : RequiredAttribute, IClientValidatable
{
public string OtherProperty { get; private set; }
public object OtherPropertyValue { get; private set; }
public RequiredIf(string otherProperty, object otherPropertyValue)
{
OtherProperty = otherProperty;
OtherPropertyValue = otherPropertyValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult($"Unknown property {OtherProperty}");
}
object otherValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (Equals(OtherPropertyValue, otherValue)) // if other property has the configured value
return base.IsValid(value, validationContext);
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "requiredif"; // data-val-requiredif
rule.ValidationParameters.Add("other", OtherProperty); // data-val-requiredif-other
rule.ValidationParameters.Add("otherval", OtherPropertyValue); // data-val-requiredif-otherval
yield return rule;
}
}
$.validator.unobtrusive.adapters.add("requiredif", ["other", "otherval"], function (options) {
var value = {
depends: function () {
var element = $(options.form).find(":input[name='" + options.params.other + "']")[0];
return element && $(element).val() == options.params.otherval;
}
}
options.rules["required"] = value;
options.messages["required"] = options.message;
});