Try line-height
like I've done here:
http://jsfiddle.net/BqTUS/5/
string strvalue="11".PadRight(4, '0');
output= 1100
string strvalue="301".PadRight(4, '0');
output= 3010
string strvalue="11".PadLeft(4, '0');
output= 0011
string strvalue="301".PadLeft(4, '0');
output= 0301
For reference, the Base64 encoder's length formula is as follows:
As you said, a Base64 encoder given n
bytes of data will produce a string of 4n/3
Base64 characters. Put another way, every 3 bytes of data will result in 4 Base64 characters. EDIT: A comment correctly points out that my previous graphic did not account for padding; the correct formula is Ceiling(4n/3)
.
The Wikipedia article shows exactly how the ASCII string Man
encoded into the Base64 string TWFu
in its example. The input string is 3 bytes, or 24 bits, in size, so the formula correctly predicts the output will be 4 bytes (or 32 bits) long: TWFu
. The process encodes every 6 bits of data into one of the 64 Base64 characters, so the 24-bit input divided by 6 results in 4 Base64 characters.
You ask in a comment what the size of encoding 123456
would be. Keeping in mind that every every character of that string is 1 byte, or 8 bits, in size (assuming ASCII/UTF8 encoding), we are encoding 6 bytes, or 48 bits, of data. According to the equation, we expect the output length to be (6 bytes / 3 bytes) * 4 characters = 8 characters
.
Putting 123456
into a Base64 encoder creates MTIzNDU2
, which is 8 characters long, just as we expected.
You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:
public class RightPadder {
private int length;
private String padding;
public RightPadder(int length, String pad) {
this.length = length;
StringBuilder sb = new StringBuilder(pad);
while (sb.length() < length) {
sb.append(sb);
}
padding = sb.toString();
}
public String pad(String s) {
return (s.length() < length ? s + padding : s).substring(0, length);
}
}
As an alternative, you can make the result length a parameter to the pad(...)
method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.
(Hint: For extra credit, make it thread-safe! ;-)
=TEXT(A1,"0000")
However the TEXT function is able to do other fancy stuff like date formating, aswell.
compatible utf-8 encoding
def _pad(self, s):
s = s.encode()
res = s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs).encode()
return res
According to the jQuery documentation, shorthand CSS properties are not supported.
Depending on what you mean by "total padding", you may be able to do something like this:
var $img = $('img');
var paddT = $img.css('padding-top') + ' ' + $img.css('padding-right') + ' ' + $img.css('padding-bottom') + ' ' + $img.css('padding-left');
Swift 3, iOS10 solution:
open class UIInsetLabel: UILabel {
open var insets : UIEdgeInsets = UIEdgeInsets() {
didSet {
super.invalidateIntrinsicContentSize()
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += insets.left + insets.right
size.height += insets.top + insets.bottom
return size
}
override open func drawText(in rect: CGRect) {
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
The padding options padx
and pady
of the grid
and pack
methods can take a 2-tuple that represent the left/right and top/bottom padding.
Here's an example:
import tkinter as tk
class MyApp():
def __init__(self):
self.root = tk.Tk()
l1 = tk.Label(self.root, text="Hello")
l2 = tk.Label(self.root, text="World")
l1.grid(row=0, column=0, padx=(100, 10))
l2.grid(row=1, column=0, padx=(10, 100))
app = MyApp()
app.root.mainloop()
Other way :
zeroos="000"
echo
for num in {99..105};do
echo ${zeroos:${#num}:${#zeroos}}${num}
done
So simple function to convert any number would be:
function leading_zero(){
local num=$1
local zeroos=00000
echo ${zeroos:${#num}:${#zeroos}}${num}
}
(The above answers explained the reason quite clearly, but seems not totally clear about the size of padding, so, I will add an answer according to what I learned from The Lost Art of Structure Packing, it has evolved to not limit to C
, but also applicable to Go
, Rust
.)
Rules:
int
should start at address divisible by 4, and long
by 8, short
by 2.char
and char[]
are special, could be any memory address, so they don't need padding before them.struct
, other than the alignment need for each individual member, the size of whole struct itself will be aligned to a size divisible by size of largest individual member, by padding at end.long
then divisible by 8, int
then by 4, short
then by 2.Order of member:
stu_c
and stu_d
from example below have the same members, but in different order, and result in different size for the 2 structs.Rules:
(n * 16)
bytes. (You can see in the example below, all printed hex addresses of structs end with 0
.)long double
).char
as member, its address could start at any address.Empty space:
test_struct_address()
below, the variable x
resides between adjacent struct g
and h
.x
is declared, h
's address won't change, x
just reused the empty space that g
wasted.y
.(for 64 bit system)
memory_align.c:
/**
* Memory align & padding - for struct.
* compile: gcc memory_align.c
* execute: ./a.out
*/
#include <stdio.h>
// size is 8, 4 + 1, then round to multiple of 4 (int's size),
struct stu_a {
int i;
char c;
};
// size is 16, 8 + 1, then round to multiple of 8 (long's size),
struct stu_b {
long l;
char c;
};
// size is 24, l need padding by 4 before it, then round to multiple of 8 (long's size),
struct stu_c {
int i;
long l;
char c;
};
// size is 16, 8 + 4 + 1, then round to multiple of 8 (long's size),
struct stu_d {
long l;
int i;
char c;
};
// size is 16, 8 + 4 + 1, then round to multiple of 8 (double's size),
struct stu_e {
double d;
int i;
char c;
};
// size is 24, d need align to 8, then round to multiple of 8 (double's size),
struct stu_f {
int i;
double d;
char c;
};
// size is 4,
struct stu_g {
int i;
};
// size is 8,
struct stu_h {
long l;
};
// test - padding within a single struct,
int test_struct_padding() {
printf("%s: %ld\n", "stu_a", sizeof(struct stu_a));
printf("%s: %ld\n", "stu_b", sizeof(struct stu_b));
printf("%s: %ld\n", "stu_c", sizeof(struct stu_c));
printf("%s: %ld\n", "stu_d", sizeof(struct stu_d));
printf("%s: %ld\n", "stu_e", sizeof(struct stu_e));
printf("%s: %ld\n", "stu_f", sizeof(struct stu_f));
printf("%s: %ld\n", "stu_g", sizeof(struct stu_g));
printf("%s: %ld\n", "stu_h", sizeof(struct stu_h));
return 0;
}
// test - address of struct,
int test_struct_address() {
printf("%s: %ld\n", "stu_g", sizeof(struct stu_g));
printf("%s: %ld\n", "stu_h", sizeof(struct stu_h));
printf("%s: %ld\n", "stu_f", sizeof(struct stu_f));
struct stu_g g;
struct stu_h h;
struct stu_f f1;
struct stu_f f2;
int x = 1;
long y = 1;
printf("address of %s: %p\n", "g", &g);
printf("address of %s: %p\n", "h", &h);
printf("address of %s: %p\n", "f1", &f1);
printf("address of %s: %p\n", "f2", &f2);
printf("address of %s: %p\n", "x", &x);
printf("address of %s: %p\n", "y", &y);
// g is only 4 bytes itself, but distance to next struct is 16 bytes(on 64 bit system) or 8 bytes(on 32 bit system),
printf("space between %s and %s: %ld\n", "g", "h", (long)(&h) - (long)(&g));
// h is only 8 bytes itself, but distance to next struct is 16 bytes(on 64 bit system) or 8 bytes(on 32 bit system),
printf("space between %s and %s: %ld\n", "h", "f1", (long)(&f1) - (long)(&h));
// f1 is only 24 bytes itself, but distance to next struct is 32 bytes(on 64 bit system) or 24 bytes(on 32 bit system),
printf("space between %s and %s: %ld\n", "f1", "f2", (long)(&f2) - (long)(&f1));
// x is not a struct, and it reuse those empty space between struts, which exists due to padding, e.g between g & h,
printf("space between %s and %s: %ld\n", "x", "f2", (long)(&x) - (long)(&f2));
printf("space between %s and %s: %ld\n", "g", "x", (long)(&x) - (long)(&g));
// y is not a struct, and it reuse those empty space between struts, which exists due to padding, e.g between h & f1,
printf("space between %s and %s: %ld\n", "x", "y", (long)(&y) - (long)(&x));
printf("space between %s and %s: %ld\n", "h", "y", (long)(&y) - (long)(&h));
return 0;
}
int main(int argc, char * argv[]) {
test_struct_padding();
// test_struct_address();
return 0;
}
Execution result - test_struct_padding()
:
stu_a: 8
stu_b: 16
stu_c: 24
stu_d: 16
stu_e: 16
stu_f: 24
stu_g: 4
stu_h: 8
Execution result - test_struct_address()
:
stu_g: 4
stu_h: 8
stu_f: 24
address of g: 0x7fffd63a95d0 // struct variable - address dividable by 16,
address of h: 0x7fffd63a95e0 // struct variable - address dividable by 16,
address of f1: 0x7fffd63a95f0 // struct variable - address dividable by 16,
address of f2: 0x7fffd63a9610 // struct variable - address dividable by 16,
address of x: 0x7fffd63a95dc // non-struct variable - resides within the empty space between struct variable g & h.
address of y: 0x7fffd63a95e8 // non-struct variable - resides within the empty space between struct variable h & f1.
space between g and h: 16
space between h and f1: 16
space between f1 and f2: 32
space between x and f2: -52
space between g and x: 12
space between x and y: 12
space between h and y: 8
Thus address start for each variable is g:d0 x:dc h:e0 y:e8
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.
There is another solution.
Implement IFormatProvider
to return a ICustomFormatter
that will be passed to string.Format :
public class StringPadder : ICustomFormatter
{
public string Format(string format, object arg,
IFormatProvider formatProvider)
{
// do padding for string arguments
// use default for others
}
}
public class StringPadderFormatProvider : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return new StringPadder();
return null;
}
public static readonly IFormatProvider Default =
new StringPadderFormatProvider();
}
Then you can use it like this :
string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");
Advanced Margin versus Padding Explained
It is inappropriate to use padding
to space content in an element; you must utilize margin
on the child element instead. Older browsers such as Internet Explorer misinterpreted the box model except when it came to using margin
which works perfectly in Internet Explorer 4.
There are two exceptions when using padding
is appropriate to use:
It is applied to an inline element which can not contain any child elements such as an input element.
You are compensating for a highly miscellaneous browser bug which a vendor *cough* Mozilla *cough* refuses to fix and are certain (to the degree that you hold regular exchanges with W3C and WHATWG editors) that you must have a working solution and this solution will not effect the styling of anything other then the bug you are compensating for.
When you have a 100% width element with padding: 50px;
you effectively get width: calc(100% + 100px);
. Since margin
is not added to the width
it will not cause unexpected layout problems when you use margin
on child elements
instead of padding
directly on the element.
So if you're not doing one of those two things do not add padding to the element but to it's direct child/children element(s) to ensure you're going to get the expected behavior in all browsers.
You need to get the size of the image that you are using in order to add your padding to this size. On the Android internals, they get the drawable you specify on src and use its size afterwards. Since it's a private variable and there are no getters you cannot access to it. Also you cannot get the com.android.internal.R.styleable.CompoundButton and get the drawable from there.
So you need to create your own styleable (i.e. custom_src) or you can add it directly in your implementation of the RadioButton:
public class CustomRadioButton extends RadioButton {
private Drawable mButtonDrawable = null;
public CustomRadioButton(Context context) {
this(context, null);
}
public CustomRadioButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomRadioButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mButtonDrawable = context.getResources().getDrawable(R.drawable.rbtn_green);
setButtonDrawable(mButtonDrawable);
}
@Override
public int getCompoundPaddingLeft() {
if (Util.getAPILevel() <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (drawable != null) {
paddingLeft += drawable.getIntrinsicWidth();
}
}
return paddingLeft;
}
}
A better solution than selected answer would be to use border-size rather than border-spacing. The main problem with using border-spacing is that even the first column would have a spacing in the front.
For example,
table {_x000D_
border-collapse: separate;_x000D_
border-spacing: 80px 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
padding: 10px 0;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>First Column</td>_x000D_
<td>Second Column</td>_x000D_
<td>Third Column</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
<td>3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
To avoid this use: border-left: 100px solid #FFF;
and set border:0px
for the first column.
For example,
td,th{_x000D_
border-left: 100px solid #FFF;_x000D_
}_x000D_
_x000D_
tr>td:first-child {_x000D_
border:0px;_x000D_
}
_x000D_
<table id="t">_x000D_
<tr>_x000D_
<td>Column1</td>_x000D_
<td>Column2</td>_x000D_
<td>Column3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>1000</td>_x000D_
<td>2000</td>_x000D_
<td>3000</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Another consideration is that, if you have more than one UITextField
where you are adding padding, is to create a separate UIView
for each textfield - because they cannot be shared.
You can't... Maybe if you posted a picture of the desired effect there's another way to achieve it.
For example, you can wrap the entire table in a DIV and set the padding to the div.
If you've to support IE7, a more compatible solution is:
/* only the cells with no cell before (aka the first one) */
td {
padding-left: 20px;
}
/* only the cells with at least one cell before (aka all except the first one) */
td + td {
padding-left: 0;
}
Also works fine with li
; general sibling selector ~
may be more suitable with mixed elements like a heading h1 followed by paragraphs AND a subheading and then again other paragraphs.
I would like to describe a very good example of why negative padding
would be useful and awesome.
As all of us CSS developers know, vertically aligning a dynamically sizing div within another is a hassle, and for the most part, viewed as being impossible only using CSS. The incorporation of negative padding
could change this.
Please review the following HTML:
<div style="height:600px; width:100%;">
<div class="vertical-align" style="width:100%;height:auto;" >
This DIV's height will change based the width of the screen.
</div>
</div>
With the following CSS, we would be able to vertically center the content of the inner div
within the outer div
:
.vertical-align {
position: absolute;
top:50%;
padding-top:-50%;
overflow: visible;
}
Allow me to explain...
Absolutely positioning the inner div's top at 50% places the top edge of the inner div at the center of the outer div. Pretty simple. This is because percentage based positioning is relative to the inner dimensions of the parent element.
Percentage based padding, on the other hand, is based on the inner dimensions of the targeted element. So, by applying the property of padding-top: -50%;
we have shifted the content of the inner div upward by a distance of 50% of the height of the inner div's content, therefore centering the inner div's content within the outer div and still allowing the height dimension of the inner div to be dynamic!
If you ask me OP, this would be the best use-case, and I think it should be implemented just so I can do this hack. lol. Or, they should just fix the functionality of vertical-align
and give us a version of vertical-align
that works on all elements.
The argument you passed "Hello" is on the constant data area. Unless you've allocated enough memory to char * string, it's overrunning to other variables.
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
strncpy(buffer, "Hello", sizeof(buffer));
StringPadRight(buffer, 10, "0");
Edit: Corrected from stack to constant data area.
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
Add property:
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
Note: This won't work in Internet Explorer below version 8.
Here's my solution:
String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);
Output: 00000101
give the td padding
Try this:
table {
border-spacing: 0;
border-collapse: collapse;
}
This trick worked for me (for min-sdk >= 18).
I used android:includeFontPadding="false"
and a negative margin like android:layout_marginTop="-11dp"
and put my TextView
inside a FrameLayout
( or any ViewGroup...)
and finally sample codes:
<LinearLayout
android:layout_width="60dp"
android:layout_height="wrap_content"
>
<TextView
style="@style/MyTextViews.Bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/yellow"
android:textSize="48sp"
android:layout_marginTop="-11dp"
android:includeFontPadding="false"
tools:text="1"/>
</LinearLayout>
I find the Django template date formatting filter to be quick and easy. It strips out leading zeros. If you don't mind importing the Django module, check it out.
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')
Unfortunately you cannot.
I tried using the CSS max
function in padding
to attempt this functionality, but I got a parse error in my css. Below is what I tried:
padding: 5px max(50vw - 350px, 10vw);
I then tried to separate the operations into variables, and that didn't work either
--padding: calc(50vw - 350px);
--max-padding: max(1vw, var(--padding));
padding: 5px var(--max-padding);
What eventually worked was just nesting what I wanted padded in a div with class "centered" and using max width and width like so
.centered {
width: 98vw;
max-width: 700px;
height: 100%;
margin: 0 auto;
}
Unfortunately, this appears to be the best way to mimic a "max-padding" and "min-padding". I imagine the technique would be similar for "min-margin" and "max-margin". Hopefully this gets added at some point!
Padding is the space inside the border between the border and the actual image or cell contents. Margins are the spaces outside the border, between the border and the other elements next to this object.
Write Following Code to set padding, it may help you.
TextView ApplyPaddingTextView = (TextView)findViewById(R.id.textView1);
final LayoutParams layoutparams = (RelativeLayout.LayoutParams) ApplyPaddingTextView.getLayoutParams();
layoutparams.setPadding(50,50,50,50);
ApplyPaddingTextView.setLayoutParams(layoutparams);
Use LinearLayout.LayoutParams
or RelativeLayout.LayoutParams
according to parent layout of the child view
I would set the child's width this way:
.child {position: absolute; width: calc(100% - padding);}
Padding, in the formula, is the sum of the left and right parent's padding. I admit it is probably not very elegant, but in my case, a div with the function of an overlay, it worked.
You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:
.col {
padding-right:7px;
padding-left:7px;
}
Demo: http://bootply.com/93473
EDIT If you only want the spacing between columns you can select all cols except first and last like this..
.col:not(:first-child,:last-child) {
padding-right:7px;
padding-left:7px;
}
For Bootstrap 4 see: Remove gutter space for a specific div only
I would like to give an example which I tried by understanding above documentation and works correctly. If you wish to apply 25% padding on left and right sides medium screen size then please use px-md-1. It works as desired and can similarly follow for other screen sizes. :)
Thought I'd add my own solution because nobody yet mentioned this. Instead of designing a UserControl based on Grid, you can target controls contained in grid with a style declaration. Takes care of adding padding/margin to all elements without having to define for each, which is cumbersome and labor-intensive.For instance, if your Grid contains nothing but TextBlocks, you can do this:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Margin" Value="10"/>
</Style>
Which is like the equivalent of "cell padding".
You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.
An example:
width: calc((100%) - (32px))
Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.
.outer {_x000D_
width: 200px;_x000D_
height: 120px;_x000D_
background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
height: 40px;_x000D_
top: 30px;_x000D_
position: relative;_x000D_
padding: 16px;_x000D_
background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
<div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
<div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
Helpful post, I found that my error was using else if
instead of elif
like so:
if [ -z "$VARIABLE1" ]; then
# do stuff
else if [ -z "$VARIABLE2" ]; then
# do other stuff
fi
Fixed it by changing to this:
if [ -z "$VARIABLE1" ]; then
# do stuff
elif [ -z "$VARIABLE2" ]; then
# do other stuff
fi
$ git log 88ee8^..88ee8 --name-only --pretty="format:"
You can use in this manner also
var rowId =$("#list").jqGrid('getGridParam','selrow');
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId']; // perticuler Column name of jqgrid that you want to access
A one liner would be :
str=str[::-1].replace(".",".-",1)[::-1]
You must define the class before creating an instance of the class. Move the invocation of Something
to the end of the script.
You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:
Management Studio->Tools->SQL Server Profiler.
If it is not installed see this link
For Visual Studio-version: 8.1.5,
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}
and if you don't want to load the entire list in memory and avoid blocking you may take a look at the following answer
.
All said in the other responses are valid but the use cases are not completely valid IMHO. If one checks out Guava and especially the collections related stuff, the same has been done with static methods. E.g. Lists.newArrayList() which allows you to write
List<String> names = Lists.newArrayList();
or with static import
import static com.google.common.collect.Lists.*;
...
List<String> names = newArrayList();
List<String> names = newArrayList("one", "two", "three");
Guava has other very powerful features like this and I actually can't think of much uses for the <>.
It would have been more useful if they went for making the diamond operator behavior the default, that is, the type is inferenced from the left side of the expression or if the type of the left side was inferenced from the right side. The latter is what happens in Scala.
Use filters to transform to any color.
I recently found this solution, and hope somebody might be able to use it. Since the solution uses filters, it can be used with any type of image. Not just svg.
If you have a single-color image that you just want to change the color of, you can do this with the help of some filters. It works on multicolor images as well of course, but you can't target a specific color. Only the whole image.
The filters came from the script proposed in How to transform black into any given color using only CSS filters If you want to change white to any color, you can adjust the invert value in each filter.
.startAsBlack{_x000D_
display: inline-block;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
background: black;_x000D_
}_x000D_
_x000D_
.black-green{_x000D_
filter: invert(43%) sepia(96%) saturate(1237%) hue-rotate(88deg) brightness(128%) contrast(119%);_x000D_
}_x000D_
_x000D_
.black-red{_x000D_
filter: invert(37%) sepia(93%) saturate(7471%) hue-rotate(356deg) brightness(91%) contrast(135%);_x000D_
}_x000D_
_x000D_
.black-blue{_x000D_
filter: invert(12%) sepia(83%) saturate(5841%) hue-rotate(244deg) brightness(87%) contrast(153%);_x000D_
}_x000D_
_x000D_
.black-purple{_x000D_
filter: invert(18%) sepia(98%) saturate(2657%) hue-rotate(289deg) brightness(121%) contrast(140%);_x000D_
}
_x000D_
Black to any color: <br/>_x000D_
<div class="startAsBlack black-green"></div>_x000D_
<div class="startAsBlack black-red"></div>_x000D_
<div class="startAsBlack black-blue"></div>_x000D_
<div class="startAsBlack black-purple"></div>
_x000D_
You can use DAYS.between
from java.time.temporal.ChronoUnit
e.g.
import java.time.temporal.ChronoUnit;
public long getDaysCountBetweenDates(LocalDate dateBefore, LocalDate dateAfter) {
return DAYS.between(dateBefore, dateAfter);
}
You were close. You can do:
var element = $("#parentDiv").find(".myClassNameOfInterest");
.find()
- http://api.jquery.com/findAlternatively, you can do:
var element = $(".myClassNameOfInterest", "#parentDiv");
...which sets the context of the jQuery object to the #parentDiv
.
EDIT:
Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest
instead of just .myClassNameOfInterest
.
# return -1 if nth substr (0-indexed) d.n.e, else return index
def find_nth(s, substr, n):
i = 0
while n >= 0:
n -= 1
i = s.find(substr, i + 1)
return i
For other people looking for this solution, just use: ~~ without parseInt, it is the cleanest mode.
var a = 'hello';
var b = ~~a;
If NaN, it will return 0 instead.
OBS. This solution apply only for integers
Use git clone
with the --depth
option set to 1
to create a shallow clone with a history truncated to the latest commit.
For example:
git clone --depth 1 https://github.com/user/repo.git
To also initialize and update any nested submodules, also pass --recurse-submodules
and to clone them shallowly, also pass --shallow-submodules
.
For example:
git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git
Using prototypes:
function Box(color) // Constructor
{
this.color = color;
}
Box.prototype.getColor = function()
{
return this.color;
};
Hiding "color" (somewhat resembles a private member variable):
function Box(col)
{
var color = col;
this.getColor = function()
{
return color;
};
}
Usage:
var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue
var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")
) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:
var regexp = /^[a-zA-Z0-9-_]+$/;
I use a combined version:
if(session_id() == '' || !isset($_SESSION)) {
// session isn't started
session_start();
}
This is common issue with floating points.
Use toFixed
in combination with parseFloat
.
Here is example in JavaScript:
function roundNumber(number, decimals) {
var newnumber = new Number(number+'').toFixed(parseInt(decimals));
return parseFloat(newnumber);
}
0.1 + 0.2; //=> 0.30000000000000004
roundNumber( 0.1 + 0.2, 12 ); //=> 0.3
I just got that problem when converting from %
formatting to .format()
.
Previous code:
"SET !TIMEOUT_STEP %{USER_TIMEOUT_STEP}d" % {'USER_TIMEOUT_STEP' = 3}
Problematic syntax:
"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format('USER_TIMEOUT_STEP' = 3)
The problem is that format
is a function that needs parameters. They cannot be strings.
That is one of worst python error messages I've ever seen.
Corrected code:
"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format(USER_TIMEOUT_STEP = 3)
By using this code we can setup MapView anywhere, inside any ViewPager or Fragment or Activity.
In the latest update of Google for Maps, only MapView is supported for fragments. MapFragment & SupportMapFragment doesn't work. I might be wrong but this is what I saw after trying to implement MapFragment & SupportMapFragment.
Setting up the layout for showing the map in the file location_fragment.xml
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Now, we code the Java class for showing the map in the file MapViewFragment.java
:
public class MapViewFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_fragment, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For showing a move to my location button
googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Finally you need to get the API Key for your app by registering your app at Google Cloud Console. Register your app as Native Android App.
library(RODBC)
file.name <- "file.xls"
sheet.name <- "Sheet Name"
## Connect to Excel File Pull and Format Data
excel.connect <- odbcConnectExcel(file.name)
dat <- sqlFetch(excel.connect, sheet.name, na.strings=c("","-"))
odbcClose(excel.connect)
Personally, I like RODBC and can recommend it.
The Algorithm for given flow chart :
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Step :01
Step :02 [Variable initialization]
Step :03[Condition Check]
Step:04
I had to sort on several criterion (date, and, if same date; other things...). What was working on Eclipse with an older version of Java, did not worked any more on Android : comparison method violates contract ...
After reading on StackOverflow, I wrote a separate function that I called from compare() if the dates are the same. This function calculates the priority, according to the criteria, and returns -1, 0, or 1 to compare(). It seems to work now.
more +2 file1.txt > type > out.txt && type file2.txt > out.txt
<?php $date= date("Y-m-d");
$time=date("H:m");
$datetime=$date."T".$time;
mysql_query(INSERT INTO table (`dateposted`) VALUES ($datetime));
?>
<form action="form.php" method="get">
<input type="datetime-local" name="date" value="<?php echo $datetime; ?>">
<input type="submit" name="submit" value="submit">
TAB=$(printf '\t')
sed "s/${TAB}//g" input_file
It works for me on Red Hat, which will remove tabs from the input file.
Another similar way:
extension String {
var trimmed:String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
Use:
let trimmedString = "myString ".trimmed
token_type
is a parameter in Access Token generate call to Authorization server, which essentially represents how an access_token will be generated and presented for resource access calls.
You provide token_type in the access token generation call to an authorization server.
If you choose Bearer
(default on most implementation), an access_token
is generated and sent back to you. Bearer can be simply understood as "give access to the bearer of this token." One valid token and no question asked. On the other hand, if you choose Mac
and sign_type
(default hmac-sha-1
on most implementation), the access token is generated and kept as secret in Key Manager as an attribute, and an encrypted secret is sent back as access_token
.
Yes, you can use your own implementation of token_type
, but that might not make much sense as developers will need to follow your process rather than standard implementations of OAuth.
I suggest
l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)
Check this demo.
You can use var_dump() function to display structured information about variables/expressions including its type and value, or you can use print_r() to display information about a variable in a way that's readable by humans.
Example: Say we have got the following array and we want to display its contents.
$arr = array ('xyz', false, true, 99, array('50'));
Array
(
[0] => xyz
[1] =>
[2] => 1
[3] => 99
[4] => Array
(
[0] => 50
)
)
array(5) {
[0]=>
string(3) "xyz"
[1]=>
bool(false)
[2]=>
bool(true)
[3]=>
int(100)
[4]=>
array(1) {
[0]=>
string(2) "50"
}
}
The functions used in this answer can be found on the PHP.net website var_dump(), print_r()
For more details:
» https://stackhowto.com/how-to-display-php-variable-values-with-echo-print_r-and-var_dump/
I had the same problem with the Arduino Due, and most of the solutions proposed did not work.
The L LED was constantly on. My problem was resolved by unistalling the IDE and picking the experimental version 1.5.8. Then in the board I chose the bottom option Arduino Due (programming port).
Of course, you need to connect the USB cable on the programming port too.
Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:
var temp1;
if ( temp1 )... // false
var temp2 = true;
if ( temp2 )... // true
var temp3 = "";
if ( temp3 ).... // false
var temp4 = "hello world";
if ( temp4 )... // true
Hopefully that helps?
Also, its worth checking out these videos from Douglas Crockford
update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now
Add Following dependency in pom.xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>oracle</artifactId>
<version>10.2.0.2.0</version>
</dependency>
Since you're using requests
, you should use the response's json
method.
import requests
response = requests.get(...)
data = response.json()
column(1)
is your friend.
$ column -t <<< '"option-y" yank-pop
> "option-z" execute-last-named-cmd
> "option-|" vi-goto-column
> "option-~" _bash_complete-word
> "option-control-?" backward-kill-word
> "control-_" undo
> "control-?" backward-delete-char
> '
"option-y" yank-pop
"option-z" execute-last-named-cmd
"option-|" vi-goto-column
"option-~" _bash_complete-word
"option-control-?" backward-kill-word
"control-_" undo
"control-?" backward-delete-char
use the following commands instead:
ALTER TABLE table_name DISABLE TRIGGER tr_name
ALTER TABLE table_name ENABLE TRIGGER tr_name
Open it in word or any file editor for edit
...
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m
...
Replace -Xmx512m to -Xmx1024m
I found this solution which automates @Alistair Collins solution.
Basically you will change the = in any formula to * then do the paste after that you will change it back
Dim cell As Range
msgResult = MsgBox("Yes to lock" & vbNewLine & "No unlock ", vbYesNoCancel + vbQuestion, "Forumula locker")
If msgResult = vbNo Then
For Each cell In Range("A1:i155")
If InStr(1, cell.Value, "*") > 0 Then
cell.Formula = Replace(cell.Formula, "*", "=")
End If
Next cell
ElseIf msgResult = vbYes Then
For Each cell In Range("A1:i155")
If cell.HasFormula = True Then
cell.Formula = Replace(cell.Formula, "=", "*")
End If
Next cell
End If
JavaScript arrays can be "empty", in a sense, even if the length of the array is non-zero. For example:
var empty = new Array(10);
var howMany = empty.reduce(function(count, e) { return count + 1; }, 0);
The variable "howMany" will be set to 0
, even though the array was initialized to have a length of 10
.
Thus because many of the Array iteration functions only pay attention to elements of the array that have actually been assigned values, you can use something like this call to .some()
to see if an array has anything actually in it:
var hasSome = empty.some(function(e) { return true; });
The callback passed to .some()
will return true
whenever it's called, so if the iteration mechanism finds an element of the array that's worthy of inspection, the result will be true
.
The proper way to set the root logging level is using the property logging.level.root
. See documentation, which has been updated since this question was originally asked.
Example:
logging.level.root=WARN
Variation of the code by Bijaya Bidari that is accepted by Java 8 without warnings in regard with overridable method calls in constructor:
public class Graph extends JFrame {
JPanel jp;
public Graph() {
super("Simple Drawing");
super.setSize(300, 300);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
jp = new GPanel();
super.add(jp);
}
public static void main(String[] args) {
Graph g1 = new Graph();
g1.setVisible(true);
}
class GPanel extends JPanel {
public GPanel() {
super.setPreferredSize(new Dimension(300, 300));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//rectangle originated at 10,10 and end at 240,240
g.drawRect(10, 10, 240, 240);
//filled Rectangle with rounded corners.
g.fillRoundRect(50, 50, 100, 100, 80, 80);
}
}
}
You have to set both layout_gravity and layout_columntWeight on your columns
<android.support.v7.widget.GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
</android.support.v7.widget.GridLayout>
use lib\Newtonsoft.Json.dll
public string serializeObj(dynamic json) {
return JsonConvert.SerializeObject(json);
}
ALTER TABLE my_table ADD COLUMN new_field TinyInt(1) DEFAULT 0;
You could add google()
to repositories block
allprojects {
repositories {
jcenter()
maven {
url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'
}
maven {
url "https://jitpack.io"
}
google()
}
}
Why would you use -z? To test if a string is non-empty, you typically use -n:
if test -n "$errorstatus"; then echo errorstatus is not empty fi
also you can check the version of symfony and versions of all other installed packages by running
composer show
or
composer show | grep sonata
to get versions of specific packages like sonata etc.
Have you tried something like:
textbox.text = "text" & system.environment.newline & "some more text"
Update:
These articles in my blog describe the differences between the methods in more detail:
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: SQL Server
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: PostgreSQL
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: Oracle
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: MySQL
There are three ways to do such a query:
LEFT JOIN / IS NULL
:
SELECT *
FROM common
LEFT JOIN
table1 t1
ON t1.common_id = common.common_id
WHERE t1.common_id IS NULL
NOT EXISTS
:
SELECT *
FROM common
WHERE NOT EXISTS
(
SELECT NULL
FROM table1 t1
WHERE t1.common_id = common.common_id
)
NOT IN
:
SELECT *
FROM common
WHERE common_id NOT IN
(
SELECT common_id
FROM table1 t1
)
When table1.common_id
is not nullable, all these queries are semantically the same.
When it is nullable, NOT IN
is different, since IN
(and, therefore, NOT IN
) return NULL
when a value does not match anything in a list containing a NULL
.
This may be confusing but may become more obvious if we recall the alternate syntax for this:
common_id = ANY
(
SELECT common_id
FROM table1 t1
)
The result of this condition is a boolean product of all comparisons within the list. Of course, a single NULL
value yields the NULL
result which renders the whole result NULL
too.
We never cannot say definitely that common_id
is not equal to anything from this list, since at least one of the values is NULL
.
Suppose we have these data:
common
--
1
3
table1
--
NULL
1
2
LEFT JOIN / IS NULL
and NOT EXISTS
will return 3
, NOT IN
will return nothing (since it will always evaluate to either FALSE
or NULL
).
In MySQL
, in case on non-nullable column, LEFT JOIN / IS NULL
and NOT IN
are a little bit (several percent) more efficient than NOT EXISTS
. If the column is nullable, NOT EXISTS
is the most efficient (again, not much).
In Oracle
, all three queries yield same plans (an ANTI JOIN
).
In SQL Server
, NOT IN
/ NOT EXISTS
are more efficient, since LEFT JOIN / IS NULL
cannot be optimized to an ANTI JOIN
by its optimizer.
In PostgreSQL
, LEFT JOIN / IS NULL
and NOT EXISTS
are more efficient than NOT IN
, sine they are optimized to an Anti Join
, while NOT IN
uses hashed subplan
(or even a plain subplan
if the subquery is too large to hash)
CLAP (command line argument parser) has a usable API and is wonderfully documented. You make a method, annotating the parameters. https://github.com/adrianaisemberg/CLAP
A better approach is to let Retrofit generate POJO for you from the json (using gson
). First thing is to add .addConverterFactory(GsonConverterFactory.create())
when creating your Retrofit
instance. For example, if you had a User
java class (such as shown below) that corresponded to your json, then your retrofit api could return Call<User>
class User {
private String id;
private String Username;
private String Level;
...
}
Java 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7 (Using NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
I think I had a better output, especially for a double datatype sorting.
Though this question has been marked answered, perhaps this will help someone else;
Arrays.sort(newTag, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
return time1.compareTo(time2);
}
});
Here is a piece of code to do so:
def(StringChallenge(str1)):
#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0
def time_dif(h1,m1,h2,m2):
if(h1 == h2):
return m2-m1
else:
return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0
if str1[1] == ':':
h1=int(str1[:1])
m1=int(str1[2:4])
else:
h1=int(str1[:2])
m1=int(str1[3:5])
if str1[-7] == '-':
h2=int(str1[-6])
m2=int(str1[-4:-2])
else:
h2=int(str1[-7:-5])
m2=int(str1[-4:-2])
if h1 == 12:
h1 = 0
if h2 == 12:
h2 = 0
if "am" in str1[:8]:
flag1 = 0
else:
flag1= 1
if "am" in str1[7:]:
flag2 = 0
else:
flag2 = 1
if flag1 == flag2:
if h2 > h1 or (h2 == h1 and m2 >= m1):
count_min += time_dif(h1,m1,h2,m2)
else:
count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
count_min += (12-h1-1)*60
count_min += (60 - m1)
count_min += (h2*60)+m2
return count_min
public static List<SelectListItem> States = new List<SelectListItem>()
{
new SelectListItem() {Text="Alabama", Value="AL"},
new SelectListItem() { Text="Alaska", Value="AK"},
new SelectListItem() { Text="Arizona", Value="AZ"},
new SelectListItem() { Text="Arkansas", Value="AR"},
new SelectListItem() { Text="California", Value="CA"},
new SelectListItem() { Text="Colorado", Value="CO"},
new SelectListItem() { Text="Connecticut", Value="CT"},
new SelectListItem() { Text="District of Columbia", Value="DC"},
new SelectListItem() { Text="Delaware", Value="DE"},
new SelectListItem() { Text="Florida", Value="FL"},
new SelectListItem() { Text="Georgia", Value="GA"},
new SelectListItem() { Text="Hawaii", Value="HI"},
new SelectListItem() { Text="Idaho", Value="ID"},
new SelectListItem() { Text="Illinois", Value="IL"},
new SelectListItem() { Text="Indiana", Value="IN"},
new SelectListItem() { Text="Iowa", Value="IA"},
new SelectListItem() { Text="Kansas", Value="KS"},
new SelectListItem() { Text="Kentucky", Value="KY"},
new SelectListItem() { Text="Louisiana", Value="LA"},
new SelectListItem() { Text="Maine", Value="ME"},
new SelectListItem() { Text="Maryland", Value="MD"},
new SelectListItem() { Text="Massachusetts", Value="MA"},
new SelectListItem() { Text="Michigan", Value="MI"},
new SelectListItem() { Text="Minnesota", Value="MN"},
new SelectListItem() { Text="Mississippi", Value="MS"},
new SelectListItem() { Text="Missouri", Value="MO"},
new SelectListItem() { Text="Montana", Value="MT"},
new SelectListItem() { Text="Nebraska", Value="NE"},
new SelectListItem() { Text="Nevada", Value="NV"},
new SelectListItem() { Text="New Hampshire", Value="NH"},
new SelectListItem() { Text="New Jersey", Value="NJ"},
new SelectListItem() { Text="New Mexico", Value="NM"},
new SelectListItem() { Text="New York", Value="NY"},
new SelectListItem() { Text="North Carolina", Value="NC"},
new SelectListItem() { Text="North Dakota", Value="ND"},
new SelectListItem() { Text="Ohio", Value="OH"},
new SelectListItem() { Text="Oklahoma", Value="OK"},
new SelectListItem() { Text="Oregon", Value="OR"},
new SelectListItem() { Text="Pennsylvania", Value="PA"},
new SelectListItem() { Text="Rhode Island", Value="RI"},
new SelectListItem() { Text="South Carolina", Value="SC"},
new SelectListItem() { Text="South Dakota", Value="SD"},
new SelectListItem() { Text="Tennessee", Value="TN"},
new SelectListItem() { Text="Texas", Value="TX"},
new SelectListItem() { Text="Utah", Value="UT"},
new SelectListItem() { Text="Vermont", Value="VT"},
new SelectListItem() { Text="Virginia", Value="VA"},
new SelectListItem() { Text="Washington", Value="WA"},
new SelectListItem() { Text="West Virginia", Value="WV"},
new SelectListItem() { Text="Wisconsin", Value="WI"},
new SelectListItem() { Text="Wyoming", Value="WY"}
};
How we do it is put this method into a class and then call the class from the view
@Html.DropDownListFor(x => x.State, Class.States)
There's no benefit to using properties with primitive types. @property
is used with heap allocated NSObjects
like NSString*
, NSNumber*
, UIButton*
, and etc, because memory managed accessors are created for free. When you create a BOOL
, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking
is simply the popular way of expressing the state of a boolean value.
In another OO language you would make a variable private bool working;
and two accessors: SetWorking
for the setter and IsWorking
for the accessor.
This is more an object initialzation question more than a jpa question, both methods work and you can have both of them at the same time , usually if the data member value is ready before the instantiation you use the constructor parameters, if this value could be updated after the instantiation you should have a setter.
if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command
adb install apklocation.apk
Your main problem is you create new figures in your loop, so each vector gets drawn on a different figure. Here's what I came up with, let me know if it's still not what you expect:
CODE:
import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])
rows,cols = M.T.shape
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
for i,l in enumerate(range(0,cols)):
xs = [0,M[i,0]]
ys = [0,M[i,1]]
plt.plot(xs,ys)
plt.plot(0,0,'ok') #<-- plot a black point at the origin
plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.legend(['V'+str(i+1) for i in range(cols)]) #<-- give a legend
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
OUTPUT:
EDIT CODE:
import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])
rows,cols = M.T.shape
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
colors = ['b','r','k']
for i,l in enumerate(range(0,cols)):
plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.05,head_length=0.1,color = colors[i])
plt.plot(0,0,'ok') #<-- plot a black point at the origin
plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
I know this post is a few years old, but what I do is add this line to the top of your class and you will still be able to user Server.MapPath
Dim Server = HttpContext.Current.Server
or u can make a function
Public Function MapPath(sPath as String)
return HttpContext.Current.Server.MapPath(sPath)
End Function
I am all about making things easier. I have also added it to my Utilities class just in case i run into this again.
You should be able to add the Java Development Tools by selecting 'Help' -> 'Install New Software', there you select the 'Juno' update site, then 'Programming Languages' -> 'Eclipse Java Development Tools'.
After that, you will be able to run your JUnit tests with 'Right Click' -> 'Run as' -> 'JUnit test'.
mode con:cols=[whatever you want] lines=[whatever you want].
The unit is the number of characters that fit in the command prompt, eg.
mode con:cols=80 lines=100
will make the command prompt 80 ASCII chars of width and 100 of height
this works with "NA"
not for NA
comments = c("no","yes","NA")
for (l in 1:length(comments)) {
#if (!is.na(comments[l])) print(comments[l])
if (comments[l] != "NA") print(comments[l])
}
A string to char array is as simple as
String str = "someString";
char[] charArray = str.toCharArray();
Can you explain a little more on what you are trying to do?
* Update *
if I am understanding your new comment, you can use a byte array and example is provided.
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
With the following output
0x65 0x10 0xf3 0x29
In case you have an object logged:
Store as a global variable
temp1
copy(temp1)
You can append to your PATH
in a minimal fashion. No need for
parentheses unless you're appending more than one element. It also
usually doesn't need quotes. So the simple, short way to append is:
path+=/some/new/bin/dir
This lower-case syntax is using path
as an array, yet also
affects its upper-case partner equivalent, PATH
(to which it is
"bound" via typeset
).
(Notice that no :
is needed/wanted as a separator.)
Then the common pattern for testing a new script/executable becomes:
path+=$PWD/.
# or
path+=$PWD/bin
You can sprinkle path settings around your .zshrc
(as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)
).
Treating path
this way (as an array) also means: no need to do a
rehash
to get the newly pathed commands to be found.
Also take a look at vared path
as a dynamic way to edit path
(and other things).
You may only be interested in path
for this question, but since
we're talking about exports and arrays, note that
arrays generally cannot be exported.
You can even prevent PATH
from taking on duplicate entries
(refer to
this
and this):
typeset -U path
You need to create a structure like this:
public class Friends
{
public List<FacebookFriend> data {get; set;}
}
public class FacebookFriend
{
public string id {get; set;}
public string name {get; set;}
}
Then you should be able to do:
Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);
The names of my classes are just an example. You should use proper names.
Adding a sample test:
string json =
@"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";
Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(json);
foreach(var item in facebookFriends.data)
{
Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
}
Produces:
id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft
The answer by Aaron is the best and is working for me :) I would vote it up but sadly I can't (missing reputation).
I've to say testing private methods is the only way to use them and have clean code on the other side.
For example:
class Something {
save(){
const data = this.getAllUserData()
if (this.validate(data))
this.sendRequest(data)
}
private getAllUserData () {...}
private validate(data) {...}
private sendRequest(data) {...}
}
It' makes a lot of sense to not test all these methods at once because we would need to mock out those private methods, which we can't mock out because we can't access them. This means we need a lot of configuration for a unit test to test this as a whole.
This said the best way to test the method above with all dependencies is an end to end test, because here an integration test is needed, but the E2E test won't help you if you are practicing TDD (Test Driven Development), but testing any method will.
Using the -I
(that's a capital i) option on the file
command seems to show the file encoding.
file -I {filename}
For me it worked after manually copying the sqljdbc4-2.jar into WEB-INF/lib folder. So please have a try on this too.
try this solution
date( 'W', strtotime( "2017-01-01 + 1 day" ) );
You may try this way. just use a function to get your object
def get_object(self, id):
try:
return UniversityDetails.objects.get(email__exact=email)
except UniversityDetails.DoesNotExist:
return False
App::cpanminus
from CPAN (use: cpan App::cpanminus
for this).cpanm --uninstall Module::Name
(note the "m
") to uninstall the module with cpanminus.This should work.
In general, I/O means Input or Output. Those methods throw the IOException
whenever an input or output operation is failed or interpreted. Note that this won't be thrown for reading or writing to memory as Java will be handling it automatically.
Here are some cases which result in IOException
.
For those using macOS mkfile might be a good alternative to fallocate or dd
mkfile 100m some100mfile.pdf
reference - https://stackoverflow.com/a/33478049/711401
Use:
git push origin :bugfix # Deletes remote branch
git branch -d bugfix # Must delete local branch manually
If you are sure you want to delete it, run
git branch -D bugfix
Now to clean up deleted remote branches run
git remote prune origin
I'm working with RecyclerView and both the remove and the update work well.
1) REMOVE: There are 4 steps to remove an item from a RecyclerView
list.remove(position);
recycler.removeViewAt(position);
mAdapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, list.size());
These line of codes work for me.
2) UPDATE THE DATA: The only things I had to do is
mAdapter.notifyDataSetChanged();
You had to do all of this in the Actvity/Fragment code not in the RecyclerView Adapter code.
I think you want \b\w{1,10}\b
. The \b
matches a word boundary.
Of course, you could also replace the \b
and do ^\w{1,10}$
. This will match a word of at most 10 characters as long as its the only contents of the string. I think this is what you were doing before.
Since it's Java, you'll actually have to escape the backslashes: "\\b\\w{1,10}\\b"
. You probably knew this already, but it's gotten me before.
Best way to do it without wasting time to order records is like this :
select 0 as tmp,Column1 from Table1 Order by tmp OFFSET 5000000 ROWS FETCH NEXT 50 ROWS ONLY
it takes less than one second!
best solution for large tables.
Late to the party. I'm on Windows 10 with JDK 1.8 and Eclipse MARS 1.
I find that
getClass().getClassLoader().getResourceAsStream("path/to/resource");
works and
getClass().getClassLoader().getResourceAsStream("path"+File.separator+"to"+File.separator+"resource");
does not work and
getClass().getClassLoader().getResourceAsStream("path\to\resource");
does not work. The last two are equivalent. So... I have good reason to NOT use File.separator.
Look at the fiddle here for a quick answer
data-ng-attr-title="{{d.age > 5 ? 'My age is greater than threshold': ''}}"
for method parameters you can use Objects.requireNonNull() like this:
test(String str) {
Objects.requireNonNull(str);
}
But this is only checked at runtime and throws an NPE if null. It is like a preconditions check. But that might be what you are looking for.
As Fredrik mentions in his answer, the simple way to achieve this is to place the JTextArea
in a JScrollPane
. This will allow scrolling of the view area of the JTextArea
.
Just for the sake of completeness, the following is how it could be achieved:
JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta); // JTextArea is placed in a JScrollPane.
Once the JTextArea
is included in the JScrollPane
, the JScrollPane
should be added to where the text area should be. In the following example, the text area with the scroll bars is added to a JFrame
:
JFrame f = new JFrame();
f.getContentPane().add(sp);
Thank you kd304 for mentioning in the comments that one should add the JScrollPane
to the container rather than the JTextArea
-- I feel it's a common error to add the text area itself to the destination container rather than the scroll pane with text area.
The following articles from The Java Tutorials has more details:
To highlight a block of code in Notepad++, please do the following steps
Style token
and select any of the five choices available ( styles from Using 1st style
to using 5th style
). Each is of different colors.If you want yellow color choose using 3rd style
.If you want to create your own style you can use Style Configurator
under Settings
menu.
This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )
This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. Change "basewidth" to any other number to change the default width of your images.
from PIL import Image
basewidth = 300
img = Image.open('somepic.jpg')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save('somepic.jpg')
Here is a complete solution to your question using Python's built-in functions:
# Create the List
numbers = input("Enter the elements of the list. Separate each value with a comma. Do not put a comma at the end.\n").split(",")
# Convert the elements in the list (treated as strings) to integers
numberL = [int(element) for element in numbers]
# Loop through the list with a for-loop
for elements in numberL:
maxEle = max(numberL)
indexMax = numberL.index(maxEle)
print(maxEle)
print(indexMax)
You are missing spring-security-web-3.1.X.RELEASE.jar
from your classpath
Using TinyMCE editor, the only way I was able to remove all borders was to use border:hidden
in the style like this:
<style>
table, tr {border:hidden;}
td, th {border:hidden;}
</style>
And in the HTML like this:
<table style="border:hidden;"</table>
Cheers
You do not need to call d.keys()
, so
if key not in d:
d[key] = value
is enough. There is no clearer, more readable method.
You could update again with dict.get()
, which would return an existing value if the key is already present:
d[key] = d.get(key, value)
but I strongly recommend against this; this is code golfing, hindering maintenance and readability.
Try this:
BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));
I tried almost all of this. but still couldn't work. Finally I found it was because of 24bitmap problems. If you tried some bitmap which less than 24bit. Most of those above methods should work.
if name in ("Jesse", "jesse"):
would be the correct way to do it.
Although, if you want to use or
, the statement would be
if name == 'Jesse' or name == 'jesse':
>>> ("Jesse" or "jesse")
'Jesse'
evaluates to 'Jesse'
, so you're essentially not testing for 'jesse'
when you do if name == ("Jesse" or "jesse")
, since it only tests for equality to 'Jesse'
and does not test for 'jesse'
, as you observed.
I believe it would be:
void setCurrent(boolean current)
boolean isCurrent()
If you need one single regex, try:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)
A short explanation:
(?=.*[a-z]) // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.*\d) // use positive look ahead to see if at least one digit exists
(?=.*\W]) // use positive look ahead to see if at least one non-word character exists
And I agree with SilentGhost, \W
might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?]
(feel free to add more of course!)
Found this question searching on Google. This will return the first child of a element with class container
, regardless as to what type the child is.
.container > *:first-child
{
}
I just come here to say that, aside from Enumerable.Concat
extension method, there seems to be another method named Enumerable.Append
in .NET Core 1.1.1. The latter allows you to concatenate a single item to an existing sequence. So Aamol's answer can also be written as
IEnumerable<T> items = new T[]{new T("msg")};
items = items.Append(new T("msg2"));
Still, please note that this function will not change the input sequence, it just return a wrapper that put the given sequence and the appended item together.
In case you face the problem using TCPServer
or SimpleHTTPServer
,
override SocketServer.TCPServer.allow_reuse_address
(python 2.7.x)
or socketserver.TCPServer.allow_reuse_address
(python 3.x) attribute
class MyServer(SocketServer.TCPServer):
allow_reuse_address = True
server = MyServer((HOST, PORT), MyHandler)
server.serve_forever()
The traditional way to specify quotes is to use Chr(34)
. This is error resistant and is not an abomination.
Chr(34) & "string" & Chr(34)
I was trying to Navigate from Page 1 to 2, and I had to pass some data as well.
In my router.js, I added params name and age :
.state('page2', {
url: '/vehicle/:source',
params: {name: null, age: null},
.................
In Page1, onClick of next button :
$state.go("page2", {name: 'Ron', age: '20'});
In Page2, I could access those params :
$stateParams.name
$stateParams.age
The solution is also given by react, they advice you use useCallback
which will return a memoize version of your function :
The 'fetchBusinesses' function makes the dependencies of useEffect Hook (at line NN) change on every render. To fix this, wrap the 'fetchBusinesses' definition into its own useCallback() Hook react-hooks/exhaustive-deps
useCallback
is simple to use as it has the same signature as useEffect
the difference is that useCallback returns a function.
It would look like this :
const fetchBusinesses = useCallback( () => {
return fetch("theURL", {method: "GET"}
)
.then(() => { /* some stuff */ })
.catch(() => { /* some error handling */ })
}, [/* deps */])
// We have a first effect thant uses fetchBusinesses
useEffect(() => {
// do things and then fetchBusinesses
fetchBusinesses();
}, [fetchBusinesses]);
// We can have many effect thant uses fetchBusinesses
useEffect(() => {
// do other things and then fetchBusinesses
fetchBusinesses();
}, [fetchBusinesses]);
Use a library to (a) read the sound file(s) and (b) play them back. (I'd recommend trying both yourself at some point in your spare time, but...)
Perhaps (*nix):
Windows: DirectX.
You should try something running Mono (its compatible with .NET).
For game development, I recommend unity: http://unity3d.com/
for general aplications: http://xamarin.com/monoforandroid
You need to have typescript library installed and then you can use
npx tsc --init
If the response is error TS5023: Unknown compiler option 'init'.
that means the library is not installed
yarn add --dev typescript
and run npx
command again
If the variable you want to check is a global, do
if (window.yourVarName) {
// Your code here
}
This way to check will not throw an error even if the yourVarName
variable doesn't exist.
if (window.history) {
history.back();
}
window
is an object which holds all global variables as its properties, and in JavaScript it is legal to try to access a non-existing object property. If history
doesn't exist then window.history
returns undefined
. undefined
is falsey, so code in an if(undefined){}
block won't run.
Another difference is that <import>
allows importing by referring to another namespace. <include>
only allows importing by referring to a URI of intended include schema. That is definitely another difference than inter-intra namespace importing.
For example, the xml schema validator may already know the locations of all schemas by namespace already. Especially considering that referring to XML namespaces by URI may be problematic on different systems where classpath:// means nothing, or where http:// isn't allowed, or where some URI doesn't point to the same thing as it does on another system.
Code sample of valid and invalid imports and includes:
Valid:
<xsd:import namespace="some/name/space"/>
<xsd:import schemaLocation="classpath://mine.xsd"/>
<xsd:include schemaLocation="classpath://mine.xsd"/>
Invalid:
<xsd:include namespace="some/name/space"/>
It turns out I was just missing DECIMAL
on the CAST()
description:
DECIMAL[(M[,D])]
Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.
Thus, the following query worked:
UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));
I expand on spectra‘s answer so people don’t have to try it for themselves.
This was done on Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production.
CREATE TABLE CUSTOMERS
(
CUSTOMER_ID NUMBER NOT NULL,
FOO FLOAT NOT NULL,
JOIN_DATE DATE NOT NULL,
CUSTOMER_STATUS VARCHAR2(8) NOT NULL,
CUSTOMER_NAME VARCHAR2(20) NOT NULL,
CREDITRATING VARCHAR2(10)
);
select column_name, data_type, nullable, data_length, data_precision, data_scale
from user_tab_columns where table_name ='CUSTOMERS';
Which yields
COLUMN_NAME DATA_TYPE NULLABLE DATA_LENGTH DATA_PRECISION DATA_SCALE
CUSTOMER_ID NUMBER N 22
FOO FLOAT N 22 126
JOIN_DATE DATE N 7
CUSTOMER_STATUS VARCHAR2 N 8
CUSTOMER_NAME VARCHAR2 N 20
CREDITRATING VARCHAR2 Y 10
ConcurrentHashMap is preferred when you can use it - though it requires at least Java 5.
It is designed to scale well when used by multiple threads. Performance may be marginally poorer when only a single thread accesses the Map at a time, but significantly better when multiple threads access the map concurrently.
I found a blog entry that reproduces a table from the excellent book Java Concurrency In Practice, which I thoroughly recommend.
Collections.synchronizedMap makes sense really only if you need to wrap up a map with some other characteristics, perhaps some sort of ordered map, like a TreeMap.
Hibernate is ignorant of time zone stuff in Dates (because there isn't any), but it's actually the JDBC layer that's causing problems. ResultSet.getTimestamp
and PreparedStatement.setTimestamp
both say in their docs that they transform dates to/from the current JVM timezone by default when reading and writing from/to the database.
I came up with a solution to this in Hibernate 3.5 by subclassing org.hibernate.type.TimestampType
that forces these JDBC methods to use UTC instead of the local time zone:
public class UtcTimestampType extends TimestampType {
private static final long serialVersionUID = 8088663383676984635L;
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
@Override
public Object get(ResultSet rs, String name) throws SQLException {
return rs.getTimestamp(name, Calendar.getInstance(UTC));
}
@Override
public void set(PreparedStatement st, Object value, int index) throws SQLException {
Timestamp ts;
if(value instanceof Timestamp) {
ts = (Timestamp) value;
} else {
ts = new Timestamp(((java.util.Date) value).getTime());
}
st.setTimestamp(index, ts, Calendar.getInstance(UTC));
}
}
The same thing should be done to fix TimeType and DateType if you use those types. The downside is you'll have to manually specify that these types are to be used instead of the defaults on every Date field in your POJOs (and also breaks pure JPA compatibility), unless someone knows of a more general override method.
UPDATE: Hibernate 3.6 has changed the types API. In 3.6, I wrote a class UtcTimestampTypeDescriptor to implement this.
public class UtcTimestampTypeDescriptor extends TimestampTypeDescriptor {
public static final UtcTimestampTypeDescriptor INSTANCE = new UtcTimestampTypeDescriptor();
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>( javaTypeDescriptor, this ) {
@Override
protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
st.setTimestamp( index, javaTypeDescriptor.unwrap( value, Timestamp.class, options ), Calendar.getInstance(UTC) );
}
};
}
public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( rs.getTimestamp( name, Calendar.getInstance(UTC) ), options );
}
};
}
}
Now when the app starts, if you set TimestampTypeDescriptor.INSTANCE to an instance of UtcTimestampTypeDescriptor, all timestamps will be stored and treated as being in UTC without having to change the annotations on POJOs. [I haven't tested this yet]
There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request): http://jsfiddle.net/9N7Z2/188/
There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...
You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery
to get defined.
// Immediately-invoked function expression
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
script.onload = function() {
var $ = window.jQuery;
// Use $ here...
};
document.getElementsByTagName("head")[0].appendChild(script);
})();
Just remember that if you need to support really old browsers, like IE8, load
event handlers do not execute. In that case, you would need to poll for the existance of window.jQuery
using repeated window.setTimeout
. There is a working JSFiddle with that method here: http://jsfiddle.net/9N7Z2/3/
There are lots of people who have already done what you need to do. Check out some of the existing JavaScript Loader frameworks, like:
These are the steps I used to fix the issue:
To add nuget packages to your solution:
Case 1: If you run only this command to generate scaffold -
rails generate scaffold MODEL_NAME FIELD_NAME:DATATYPE
Ex - rails generate scaffold User name:string address:text
but till now you did not run any command for migration like
rake db:migrate
then you should need to run only this command like -
rails destroy scaffold User name:string address:text
Case 2: If you already run(Scaffold and Migration) by below commands like -
rails generate scaffold User name:string address:text
rake db:migrate
Then you should need to run first rollback migration command then destroy scaffold like below -
rake db:rollback
rails destroy scaffold User name:string address:text
So In this manner, we can undo scaffolding. Also we can use d for destroy and g for generate as a shortcut.
You can try this to get infos like:
git config --get user.name
git config --get user.email
There's nothing like "first name" and "last name" for the user.
Hope this will help.
The above claim that "If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing" seems to be quite wrong - at least with Chrome 31.0.1650.57 m or depending on your definition of "lot of pixel". I would have preferred to comment directly to the respective post - but unfortunately I don't have enough stackoverflow points yet:
I think that I am drawing "a lot of pixels" and therefore I first followed the respective advice for good measure I later changed my implementation to a simple ctx.fillRect(..) for each drawn point, see http://www.wothke.ch/webgl_orbittrap/Orbittrap.htm
Interestingly it turns out the silly ctx.fillRect() implementation in my example is actually at least twice as fast as the ImageData based double buffering approach.
At least for my scenario it seems that the built-in ctx.getImageData/ctx.putImageData is in fact unbelievably SLOW. (It would be interesting to know the percentage of pixels that need to be touched before an ImageData based approach might take the lead..)
Conclusion: If you need to optimize performance you have to profile YOUR code and act on YOUR findings..
If you created ImageView
from Java Class
ImageView img = new ImageView(this);
//Here we are setting the image in image view
img.setImageResource(R.drawable.my_image);
This is what worked for me: it redirects a visitor if javascript is disabled
<noscript><meta http-equiv="refresh" content="0; url=whatyouwant.html" /></noscript>
In order to avoid ORDER BY items must appear in the select list if SELECT DISTINCT
error, the best should be
var results = (
from ta in DBContext.TestAddresses
select ta.Name
)
.Distinct()
.OrderBy( x => 1);
Another short way:
int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();
I think it's important to note here that onBlur() fires regardless.
This is a helpful thread but the only thing it doesn't clarify is that onBlur() will fire every single time.
onChange() will only fire when the value is changed.
Store it in the database in a field with a data type of uniqueidentifier.
The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)
-Dlogging.config={file_location}\log4j2.xml
or this:
-Dlog4j.configurationFile={file_location}\log4j2.xml
<input style="border:none" >
Worked well for me. Wished to have it fixed in html itself ... :)
As David Aldridge explained, your parentheses should start right after the sqlplus command, so it should be:
sqlplus 'test/test@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname.com )(PORT=1521)))(CONNECT_DATA=(SID=mysid))'
How about using classes?
# config.py
class MYSQL:
PORT = 3306
DATABASE = 'mydb'
DATABASE_TABLES = ['tb_users', 'tb_groups']
# main.py
from config import MYSQL
print(MYSQL.PORT) # 3306
Note: this solution works only if the slaves have the same directory structure as the master. pwd()
will return the workspace directory on the master due to JENKINS-33511.
I used to do it using pwd()
functionality of pipeline plugin. So, if you need to get a workspace on slave, you may do smth like this:
node('label'){
//now you are on slave labeled with 'label'
def workspace = pwd()
//${workspace} will now contain an absolute path to job workspace on slave
}
VMDK is a virtual disk file, what you need is a VMX file. Cruise on over to EasyVMX and have it create one for you, then just replace the VMDK file it gives you with the Cnrome OS one.
EasyVMX is good since VMWare Player has no VM creation stuff in it (at least in version 2, not sure about 3). You had to use one of VMWare's other products to do that.
Visual Studio 2017 version 15.8 made it possible to use the PackageReferencesyntax to reference NuGet packages in Visual Studio Extensibility (VSIX) projects. This makes it much simpler to reason about NuGet packages and opens the door for having a complete meta package containing the entire VSSDK.
Installing below NuGet package will solve the EmbedInteropTypes Issue.
Install-Package Microsoft.VisualStudio.SDK.EmbedInteropTypes
I found that this error occurred when I extracted the .rpm file.
I then removed that folder and downloaded jdk-7u79-linux-x64.tar.gz for Linux 64 and extracted the contents of this file instead. Also: export JAVA_HOME=/opt/java/jdk1.7.0_79 export JDK_HOME=/opt/java/jdk1.7.0_79 export PATH=${JAVA_HOME}/bin
You should use Adaptive hashing like http://en.wikipedia.org/wiki/Bcrypt for securing passwords
No, it's not. instanceof
would return false
if its first operand is null
.
All solutions based on array_keys don't work for mixed arrays. Solution is simple:
echo array_search($needle,array_keys($haystack), true);
From php.net: If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.
I'm going to assume you do not want to count hidden or system files.
There are many ways to do this. All of the methods that I will show involve some form of the FOR command. There are many variations of the FOR command that look almost the same, but they behave very differently. It can be confusing for a beginner.
You can get help by typing HELP FOR
or FOR /?
from the command line. But that help is a bit cryptic if you are not used to reading it.
1) The DIR command lists the number of files in the directory. You can pipe the results of DIR to FIND to get the relevant line and then use FOR /F to parse the desired value from the line. The problem with this technique is the string you search for has to change depending on the language used by the operating system.
@echo off
for /f %%A in ('dir ^| find "File(s)"') do set cnt=%%A
echo File count = %cnt%
2) You can use DIR /B /A-D-H-S
to list the non-hidden/non-system files without other info, pipe the result to FIND to count the number of files, and use FOR /F to read the result.
@echo off
for /f %%A in ('dir /a-d-s-h /b ^| find /v /c ""') do set cnt=%%A
echo File count = %cnt%
3) You can use a simple FOR to enumerate all the files and SET /A to increment a counter for each file found.
@echo off
set cnt=0
for %%A in (*) do set /a cnt+=1
echo File count = %cnt%
The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.
Quote from Spring Data JPA reference docs.
Also, see this section on how to do it with a named native query.
SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.
< original link no longer active >
http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:
https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"
http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"
Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.
Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML
I believe. I use the jQuery html
function instead and that seemed to resolve the issue.
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
</table>
<div id="output"></div>?
the javascript:
$('#thisTable tr').on('click', function(event) {
var tds = $(this).addClass('row-highlight').find('td');
var values = '';
tds.each(function(index, item) {
values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
});
$("#output").html(values);
});
You can also try
$(document).ready(function(){
$(window).scrollTop(0);
});
If you want to scroll at x position than you can change the value of 0 to x.
No, you can not.
You can call a function
from a stored procedure
and debug a stored procedure
(this will step into the function
)
The example 1 will not compile. This version of it compiles and runs. It uses lambda features to abbreviate it.
/*
* [RollYourOwnTimeouts.java]
*
* Summary: How to roll your own timeouts.
*
* Copyright: (c) 2016 Roedy Green, Canadian Mind Products, http://mindprod.com
*
* Licence: This software may be copied and used freely for any purpose but military.
* http://mindprod.com/contact/nonmil.html
*
* Requires: JDK 1.8+
*
* Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
*
* Version History:
* 1.0 2016-06-28 initial version
*/
package com.mindprod.example;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static java.lang.System.*;
/**
* How to roll your own timeouts.
* Based on code at http://stackoverflow.com/questions/19456313/simple-timeout-in-java
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2016-06-28 initial version
* @since 2016-06-28
*/
public class RollYourOwnTimeout
{
private static final long MILLIS_TO_WAIT = 10 * 1000L;
public static void main( final String[] args )
{
final ExecutorService executor = Executors.newSingleThreadExecutor();
// schedule the work
final Future<String> future = executor.submit( RollYourOwnTimeout::requestDataFromWebsite );
try
{
// where we wait for task to complete
final String result = future.get( MILLIS_TO_WAIT, TimeUnit.MILLISECONDS );
out.println( "result: " + result );
}
catch ( TimeoutException e )
{
err.println( "task timed out" );
future.cancel( true /* mayInterruptIfRunning */ );
}
catch ( InterruptedException e )
{
err.println( "task interrupted" );
}
catch ( ExecutionException e )
{
err.println( "task aborted" );
}
executor.shutdownNow();
}
/**
* dummy method to read some data from a website
*/
private static String requestDataFromWebsite()
{
try
{
// force timeout to expire
Thread.sleep( 14_000L );
}
catch ( InterruptedException e )
{
}
return "dummy";
}
}
I just thought I'd link this here as the article has most of the answer you're looking for and it's also very interesting
The print()
function returns None
. You are trying to index None. You can not, because 'NoneType' object is not subscriptable
.
Put the [0]
inside the brackets. Now you're printing everything, and not just the first term.
Steps to Remove app from App Store
With ASP.NET Core 2.0, the ideal way to return object from Web API
(which is unified with MVC and uses same base class Controller
) is
public IActionResult Get()
{
return new OkObjectResult(new Item { Id = 123, Name = "Hero" });
}
Notice that
200 OK
status code (it's an Ok
type of ObjectResult
)Accept
header in request. If Accept: application/xml
is sent in request, it'll return as XML
. If nothing is sent, JSON
is default.If it needs to send with specific status code, use ObjectResult
or StatusCode
instead. Both does the same thing, and supports content negotiation.
return new ObjectResult(new Item { Id = 123, Name = "Hero" }) { StatusCode = 200 };
return StatusCode( 200, new Item { Id = 123, Name = "Hero" });
or even more fine grained with ObjectResult:
Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection myContentTypes = new Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection { System.Net.Mime.MediaTypeNames.Application.Json };
String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
return new ObjectResult(hardCodedJson) { StatusCode = 200, ContentTypes = myContentTypes };
If you specifically want to return as JSON, there are couple of ways
//GET http://example.com/api/test/asjson
[HttpGet("AsJson")]
public JsonResult GetAsJson()
{
return Json(new Item { Id = 123, Name = "Hero" });
}
//GET http://example.com/api/test/withproduces
[HttpGet("WithProduces")]
[Produces("application/json")]
public Item GetWithProduces()
{
return new Item { Id = 123, Name = "Hero" };
}
Notice that
JSON
in two different ways.Json(object)
.Produces()
attribute (which is a ResultFilter
) with contentType = application/json
Read more about them in the official docs. Learn about filters here.
The simple model class that is used in the samples
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
You could default the parameter to null
or false
.
This way, it would be shorter to test if a value has been passed as parameter.
@mixin clearfix($width: null) {
@if not ($width) {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
Assuming that your href attribute is linking to a div with the tag id with the same name (as usual), you can use this code:
HTML
<a href="#goto" class="sliding-link">Link to div</a>
<div id="goto">I'm the div</div>
JAVASCRIPT - (Jquery)
$(".sliding-link").click(function(e) {
e.preventDefault();
var aid = $(this).attr("href");
$('html,body').animate({scrollTop: $(aid).offset().top},'slow');
});
This is an old Question but recently Android has a support for Bubbles. Bubbles are soon going to be launched but currently developers can start using them.They are designed to be an alternative to using SYSTEM_ALERT_WINDOW
. Apps like (Facebook Messenger and MusiXMatch use the same concept).
Bubbles are created via the Notification API, you send your notification as normal. If you want it to bubble you need to attach some extra data to it. For more information about Bubbles you can go to the official Android Developer Guide on Bubbles.
This is the best way to get a simple date string :
@DateTime.Parse(Html.DisplayFor(Model => Model.AuditDate).ToString()).ToShortDateString()
Here is a complete solution to get in and out of full screen mode (aka cancel, exit, escape)
function cancelFullScreen() {
var el = document;
var requestMethod = el.cancelFullScreen||el.webkitCancelFullScreen||el.mozCancelFullScreen||el.exitFullscreen||el.webkitExitFullscreen;
if (requestMethod) { // cancel full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
function requestFullScreen(el) {
// Supports most browsers and their versions.
var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen;
if (requestMethod) { // Native full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
return false
}
function toggleFullScreen(el) {
if (!el) {
el = document.body; // Make the body go full screen.
}
var isInFullScreen = (document.fullScreenElement && document.fullScreenElement !== null) || (document.mozFullScreen || document.webkitIsFullScreen);
if (isInFullScreen) {
cancelFullScreen();
} else {
requestFullScreen(el);
}
return false;
}
You need to do a LEFT JOIN
.
SELECT Computer.ComputerName, Application.Name, Software.Version
FROM Computer
JOIN dbo.Software_Computer
ON Computer.ID = Software_Computer.ComputerID
LEFT JOIN dbo.Software
ON Software_Computer.SoftwareID = Software.ID
RIGHT JOIN dbo.Application
ON Application.ID = Software.ApplicationID
WHERE Computer.ID = 1
Here is the explanation:
The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate). If the right table returns one row and the left table returns more than one matching row for it, the values in the right table will be repeated for each distinct row on the left table. From Oracle 9i onwards the LEFT OUTER JOIN statement can be used as well as (+).
Your solution makes use of an extension to GROUP BY clause that permits to group by some fields (in this case, just post_author
):
GROUP BY wp_posts.post_author
and select nonaggregated columns:
SELECT wp_posts.*
that are not listed in the group by clause, or that are not used in an aggregate function (MIN, MAX, COUNT, etc.).
Correct use of extension to GROUP BY clause
This is useful when all values of non-aggregated columns are equal for every row.
For example, suppose you have a table GardensFlowers
(name
of the garden, flower
that grows in the garden):
INSERT INTO GardensFlowers VALUES
('Central Park', 'Magnolia'),
('Hyde Park', 'Tulip'),
('Gardens By The Bay', 'Peony'),
('Gardens By The Bay', 'Cherry Blossom');
and you want to extract all the flowers that grows in a garden, where multiple flowers grow. Then you have to use a subquery, for example you could use this:
SELECT GardensFlowers.*
FROM GardensFlowers
WHERE name IN (SELECT name
FROM GardensFlowers
GROUP BY name
HAVING COUNT(DISTINCT flower)>1);
If you need to extract all the flowers that are the only flowers in the garder instead, you could just change the HAVING condition to HAVING COUNT(DISTINCT flower)=1
, but MySql also allows you to use this:
SELECT GardensFlowers.*
FROM GardensFlowers
GROUP BY name
HAVING COUNT(DISTINCT flower)=1;
no subquery, not standard SQL, but simpler.
Incorrect use of extension to GROUP BY clause
But what happens if you SELECT non-aggregated columns that are non equal for every row? Which is the value that MySql chooses for that column?
It looks like MySql always chooses the FIRST value it encounters.
To make sure that the first value it encounters is exactly the value you want, you need to apply a GROUP BY
to an ordered query, hence the need to use a subquery. You can't do it otherwise.
Given the assumption that MySql always chooses the first row it encounters, you are correcly sorting the rows before the GROUP BY. But unfortunately, if you read the documentation carefully, you'll notice that this assumption is not true.
When selecting non-aggregated columns that are not always the same, MySql is free to choose any value, so the resulting value that it actually shows is indeterminate.
I see that this trick to get the first value of a non-aggregated column is used a lot, and it usually/almost always works, I use it as well sometimes (at my own risk). But since it's not documented, you can't rely on this behaviour.
This link (thanks ypercube!) GROUP BY trick has been optimized away shows a situation in which the same query returns different results between MySql and MariaDB, probably because of a different optimization engine.
So, if this trick works, it's just a matter of luck.
The accepted answer on the other question looks wrong to me:
HAVING wp_posts.post_date = MAX(wp_posts.post_date)
wp_posts.post_date
is a non-aggregated column, and its value will be officially undetermined, but it will likely be the first post_date
encountered. But since the GROUP BY trick is applied to an unordered table, it is not sure which is the first post_date
encountered.
It will probably returns posts that are the only posts of a single author, but even this is not always certain.
A possible solution
I think that this could be a possible solution:
SELECT wp_posts.*
FROM wp_posts
WHERE id IN (
SELECT max(id)
FROM wp_posts
WHERE (post_author, post_date) = (
SELECT post_author, max(post_date)
FROM wp_posts
WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY post_author
) AND wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY post_author
)
On the inner query I'm returning the maximum post date for every author. I'm then taking into consideration the fact that the same author could theorically have two posts at the same time, so I'm getting only the maximum ID. And then I'm returning all rows that have those maximum IDs. It could be made faster using joins instead of IN clause.
(If you're sure that ID
is only increasing, and if ID1 > ID2
also means that post_date1 > post_date2
, then the query could be made much more simple, but I'm not sure if this is the case).
Here is an updated version of Dan Grossman's answer which will cater for multidimensional arrays (what I was after):
function find_key_value($array, $key, $val)
{
foreach ($array as $item)
{
if (is_array($item) && find_key_value($item, $key, $val)) return true;
if (isset($item[$key]) && $item[$key] == $val) return true;
}
return false;
}
I would simply recommend:
/* In your CSS code: */
pre
{
display:inline;
}
<!-- And then, in your HTML code: -->
<pre> This text comes after four spaces.</pre>
<span> Continue the line with other element without braking </span>
If the above solution does not work for you, try this:
#1.1 Do NOT ignore file pattern in any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php
##########################
# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php
git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705
But may have unexpected side-effects. See --mainline parent-number
option in git-scm.com/docs/git-revert
Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD
again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.
It would look something like this:
function updatePostID(val, comment)
{
var args = {};
args.PostID = val;
args.Comment = comment;
$.ajax({
type: "POST",
url: controllerActionMethodUrlHere,
contentType: "application/json; charset=utf-8",
data: args,
dataType: "json",
success: function(msg)
{
// Something afterwards here
}
});
}
So there is two ways to pass values from fragment/activity to dialog fragment:-
Create dialog fragment object with make setter method and pass value/argument.
Pass value/argument through bundle.
// Fragment or Activity
@Override
public void onClick(View v) {
DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
dialog.setValue(header, body);
dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");
}
// your dialog fragment
public class MyDialogFragment extends DialogFragment {
String header;
String body;
public void setValue(String header, String body) {
this.header = header;
this.body = body;
}
// use above variable into your dialog fragment
}
Note:- This is not best way to do
// Fragment or Activity
@Override
public void onClick(View v) {
DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
Bundle bundle = new Bundle();
bundle.putString("header", "Header");
bundle.putString("body", "Body");
dialog.setArguments(bundle);
dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");
}
// your dialog fragment
public class MyDialogFragment extends DialogFragment {
String header;
String body;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
header = getArguments().getString("header","");
body = getArguments().getString("body","");
}
}
// use above variable into your dialog fragment
}
Note:- This is the best way to do.
This will also work:
<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
Path=DataContext.AllowItemCommand}" />
ListView
will inherit its DataContext
from Window
, so it's available at this point, too.
And since ListView
, just like similar controls (e. g. Gridview
, ListBox
, etc.), is a subclass of ItemsControl
, the Binding
for such controls will work perfectly.
For R code I use
\usepackage{listings}
\lstset{
language=R,
basicstyle=\scriptsize\ttfamily,
commentstyle=\ttfamily\color{gray},
numbers=left,
numberstyle=\ttfamily\color{gray}\footnotesize,
stepnumber=1,
numbersep=5pt,
backgroundcolor=\color{white},
showspaces=false,
showstringspaces=false,
showtabs=false,
frame=single,
tabsize=2,
captionpos=b,
breaklines=true,
breakatwhitespace=false,
title=\lstname,
escapeinside={},
keywordstyle={},
morekeywords={}
}
And it looks exactly like this
You can try this:
<div ng-app="app">
<div ng-controller="AppCtrl">
<a my-dir ng-repeat="user in users" ng-click="fxn()">{{user.name}}</a>
</div>
</div>
<script>
var app = angular.module('app', []);
function AppCtrl($scope) {
$scope.users = [{ name: 'John', id: 1 }, { name: 'anonymous' }];
$scope.fxn = function () {
alert('It works');
};
}
app.directive("myDir", function ($compile) {
return {
scope: {ngClick: '='}
};
});
</script>
Came here from google looking for same issue and wasted 4 hours to figure out what could be wrong. And now I feel really stupid while posting this answer. In my case SDK, JDK, JRE, Ant and everything else was installed and working a day before.
But just one particular project was giving me this issue. This one was under "C:\Users\Name\Documents" location
Soon I realized that I was running cmd as normal user, as soon as I choose "Run as Administrator" everything started working.
Tip: Always consider project location carefully!
Using a form in a view pretty much explains it.
The standard pattern for processing a form in a view looks like this:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
print form.cleaned_data['my_form_field_name']
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
Most of the previous answers are a bit(Very) complicated,
from google.colab import drive
drive.mount("/content/drive", force_remount=True)
I figured out this to be the easiest and fastest way to mount google drive into CO Lab, You can change the mount directory location
to what ever you want by just changing the parameter for drive.mount
. It will give you a link to accept the permissions with your account and then you have to copy paste the key generated and then drive will be mounted in the selected path.
force_remount
is used only when you have to mount the drive irrespective of whether its loaded previously.You can neglect this when parameter if you don't want to force mount
Edit: Check this out to find more ways of doing the IO
operations in colab https://colab.research.google.com/notebooks/io.ipynb
Adding a class to Html.EditorFor
doesn't make sense as inside its template you could have many different tags. So you need to assign the class inside the editor template:
@Html.EditorFor(x => x.Created)
and in the custom template:
<div>
@Html.TextBoxForModel(x => x.Created, new { @class = "date" })
</div>
To complement the Perl one-liner, here's its awk
equivalent:
awk 'NR==FNR{arr[$0];next} $0 in arr' file1 file2
This will read all lines from file1
into the array arr[]
, and then check for each line in file2
if it already exists within the array (i.e. file1
). The lines that are found will be printed in the order in which they appear in file2
.
Note that the comparison in arr
uses the entire line from file2
as index to the array, so it will only report exact matches on entire lines.
I think the xpath query you want goes something like this:
/xml/box[@stepId="$stepId"]/components/component[@id="$componentId"]/variables/variable[@nom="Enabled" and @valeur="Yes"]
This should get you the variables that are named "Enabled" with a value of "Yes" for the specified $stepId and $componentId. This is assuming that your xml starts with an tag like you show, and not
If the SQL Server 2005 XPath stuff is pretty straightforward (I've never used it), then the above query should work. Otherwise, someone else may have to help you with that.
Provide the directory on the command line:
svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html
Run gpresult
at a Windows command prompt. You'll get an abundance of information about the current domain, current user, user & computer security groups, group policy names, Active Directory Distinguished Name, and so on.
You are using Object, and you don't have an associative array to begin with. With an associative array, adding and removing items goes like this:
Array.prototype.contains = function(obj)
{
var i = this.length;
while (i--)
{
if (this[i] === obj)
{
return true;
}
}
return false;
}
Array.prototype.add = function(key, value)
{
if(this.contains(key))
this[key] = value;
else
{
this.push(key);
this[key] = value;
}
}
Array.prototype.remove = function(key)
{
for(var i = 0; i < this.length; ++i)
{
if(this[i] == key)
{
this.splice(i, 1);
return;
}
}
}
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function ForwardAndHideVariables() {
var dictParameters = getUrlVars();
dictParameters.add("mno", "pqr");
dictParameters.add("mno", "stfu");
dictParameters.remove("mno");
for(var i = 0; i < dictParameters.length; i++)
{
var key = dictParameters[i];
var value = dictParameters[key];
alert(key + "=" + value);
}
// And now forward with HTTP-POST
aa_post_to_url("Default.aspx", dictParameters);
}
function aa_post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
// Move the submit function to another variable
// so that it doesn't get written over if a parameter name is 'submit'
form._submit_function_ = form.submit;
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var i = 0; i < params.length; i++)
{
var key = params[i];
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form._submit_function_(); // Call the renamed function
}
Okay i might have some even different approach.
I am aware that it won't suit everybody but nontheless someone might find it useful.
For those who do not want to pupup a new window, and like me, are concerned about css styles this is what i came up with:
I wrapped view of my app into additional container, which is being hidden when printing and there is additional container for what needs to be printed which is shown when is printing.
Below working example:
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function($scope) {_x000D_
_x000D_
$scope.people = [{_x000D_
"id" : "000",_x000D_
"name" : "alfred"_x000D_
},_x000D_
{_x000D_
"id" : "020",_x000D_
"name" : "robert"_x000D_
},_x000D_
{_x000D_
"id" : "200",_x000D_
"name" : "me"_x000D_
}];_x000D_
_x000D_
$scope.isPrinting = false;_x000D_
$scope.printElement = {};_x000D_
_x000D_
$scope.printDiv = function(e)_x000D_
{_x000D_
console.log(e);_x000D_
$scope.printElement = e;_x000D_
_x000D_
$scope.isPrinting = true;_x000D_
_x000D_
//does not seem to work without toimeouts_x000D_
setTimeout(function(){_x000D_
window.print();_x000D_
},50);_x000D_
_x000D_
setTimeout(function(){_x000D_
$scope.isPrinting = false;_x000D_
},50);_x000D_
_x000D_
_x000D_
};_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
_x000D_
<div ng-show="isPrinting">_x000D_
<p>Print me id: {{printElement.id}}</p>_x000D_
<p>Print me name: {{printElement.name}}</p>_x000D_
</div>_x000D_
_x000D_
<div ng-hide="isPrinting">_x000D_
<!-- your actual application code -->_x000D_
<div ng-repeat="person in people">_x000D_
<div ng-click="printDiv(person)">Print {{person.name}}</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</div>_x000D_
_x000D_
Note that i am aware that this is not an elegant solution, and it has several drawbacks, but it has some ups as well:
Well, whoever you are reading this, have a nice day and keep coding :)
EDIT:
If it suits your situation you can actually use:
@media print { .noprint { display: none; } }
@media screen { .noscreen { visibility: hidden; position: absolute; } }
instead of angular booleans to select your printing and non printing content
EDIT:
Changed the screen css because it appears that display:none breaks printiing when printing first time after a page load/refresh.
visibility:hidden approach seem to be working so far.
Should it be LIBRARY_PATH
instead of LD_LIBRARY_PATH
.
gcc checks for LIBRARY_PATH
which can be seen with -v
option
You could try writing the XDocument to an XmlWriter piped to an XmlReader for an XmlDocument.
If I understand the concepts properly, a direct conversion is not possible (the internal structure is different / simplified with XDocument). But then, I might be wrong...
Yes.
This is so that you can control how the class is instantiated. If you make the constructor private, and then create a visible constructor method that returns instances of the class, you can do things like limit the number of creations (typically, guarantee there is exactly one instance) or recycle instances or other construction-related tasks.
Doing new x()
never returns null
, but using the factory pattern, you can return null
, or even return different subtypes.
You might use it also for a class which has no instance members or properties, just static ones - as in a utility function class.
Run package declaration and body separately.
I know It is an old message , but i want to add my case.
If you use more than one profile(dev,test,prod...), check your execute profile.
The code you have is correct. JSX code needs to be compiled to JS:
If there are no typos in the question, you got the conditions wrong:
You said this:
IF cells (i,"A") contains the text 'Miami'
...but your code says:
If Cells(i, "A") <> "Miami"
--> <>
means that the value of the cell is not equal to "Miami", so you're not checking what you think you are checking.
I guess you want this instead:
If Cells(i, "A") like "*Miami*"
EDIT:
Sorry, but I can't really help you more. As I already said in a comment, I'm no Excel VBA expert.
Normally I would open Excel now and try your code myself, but I don't even have Excel on any of my machines at home (I use OpenOffice).
Just one general thing: can you identify the row that does not work?
Maybe this helps someone else to answer the question.
Does it ever execute (or at least try to execute) the Cells(i, "C").Value = "BA"
line?
Or is the If Cells(i, "A") like "*Miami*"
stuff already False
?
If yes, try checking just one cell and see if that works.
cd ,
it will give the current directory
D:\Folder\subFolder>cd ,
D:\Folder\subFolder
If someone says you can't because only Windows can control the non-client area, they're wrong!
That's just a half-truth because Windows lets you specify the dimensions of the non-client area. The fact is, this is possible only throughout the Windows' kernel methods, and you're in .NET, not C/C++. Anyway, don't worry! P/Invoke was meant just for such things! Indeed, the whole of the Windows Form UI and Console application Std-I/O methods are offered using system calls. Hence, you'd have only to perform the right system calls to set the non-client area up, as documented in MSDN.
However, this is a really hard solution I came up with a lot of time ago. Luckily, as of .NET 4.5, you can use the WindowChrome
class to adjust the non-client area like you want. Here you can get to start with.
In order to make things simpler and cleaner, I'll redirect you here, a guide to change the window border dimensions to whatever you want. By setting it to 0, you'll be able to implement your custom window border in place of the system's one.
I'm sorry for not posting a clear example, but later I will for sure.
In (ANSI) C99, you can use a designated initializer to initialize a structure:
MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };
Edit: Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)
If any one is interested here is what query is executed by psql
on postgres 9.1:
SELECT n.nspname as "Schema",
p.proname as "Name",
pg_catalog.pg_get_function_result(p.oid) as "Result data type",
pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
CASE
WHEN p.proisagg THEN 'agg'
WHEN p.proiswindow THEN 'window'
WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
ELSE 'normal'
END as "Type"
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;
You can get what psql
runs for a backslash command by running psql
with the -E
flag.
PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.
<script>
in the <head>
, as that is dictated by the formats. However, some put javascript <script>
s at the bottom of the body, so that the page content will load without waiting for the <script>
, but this is a tradeoff since script execution will be delayed until other resources have loaded.Please look at this document
http://www.socialsecurity.gov/employer/randomization.html
The SSA is instituting a new policy the where all previously unused sequences are will be available for use.
Goes into affect June 25, 2011.
Taken from the new FAQ:
What changes will result from randomization?
The SSA will eliminate the geographical significance of the first three digits of the SSN, currently referred to as the area number, by no longer allocating the area numbers for assignment to individuals in specific states. The significance of the highest group number (the fourth and fifth digits of the SSN) for validation purposes will be eliminated. Randomization will also introduce previously unassigned area numbers for assignment excluding area numbers 000, 666 and 900-999. Top
Will SSN randomization assign group number (the fourth and fifth digits of the SSN) 00 or serial number (the last four digits of the SSN) 0000?
SSN randomization will not assign group number 00 or serial number 0000. SSNs containing group number 00 or serial number 0000 will continue to be invalid.
Here is my answer for the Swift 3 answers above. This is current as of Nov 2016, Xcode release was 8.2 Beta (8C23). Used some of both Sagar and Emin suggestions above and sometimes had to let Xcode autocomplete to suggest the syntax. It seemed like the syntax really changed to this beta version. buyDate
I got from a DatePicker:
let calendar = NSCalendar.current as NSCalendar
let currentDate = Date()
let date1 = calendar.startOfDay(for: buyDate!)
let date2 = calendar.startOfDay(for: currentDate)
let flags = NSCalendar.Unit.day
let components = calendar.components(flags, from: date1, to: date2)
NSLog(" day= \(components.day)")
For a python -c
oriented solution, and provided you use Bash shell, yes you can have a simple one-line syntax like in this example:
Suppose you would like to do something like this (very similar to your sample, including except: pass
instruction):
python -c "from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n" OUTPUT_VARIABLE __numpy_path
This will NOT work and produce this Error:
File "<string>", line 1
from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n
^
SyntaxError: unexpected character after line continuation character `
This is because the competition between Bash and Python Interpretation of \n
escape sequences. To solve the problem one can use the $'string'
Bash syntax to force \n
Bash interpretation BEFORE the Python one. To make the example more challenging I added a typical Python end=..\n..
specification in the Python print call: at the end you will be able to get BOTH \n
interpretations from bash and Python working together, each on its piece of text of concern. So that finally the proper solution is like this :
python -c $'from __future__ import print_function\ntry:\n import numpy;\n print( numpy.get_include(), end="\\n" )\n print( "Hello" )\nexcept:pass\n' OUTPUT_VARIABLE __numpy_path
That leads to the proper clean output with no error:
/Softs/anaconda/lib/python3.7/site-packages/numpy/core/include
Hello
Note: this should work as well with exec
oriented solutions, because the problem is still the same (Bash and Python interpreters competition).
Note2: one could workaround the problem by replacing some \n
by some ;
but it will not work anytime (depending on Python constructs), while my solution allows to always "one-line" any piece of classic multi-line Python program.
Note3: of course, when one-lining, one has always to take care of Python spaces and indentation, because in fact we are not strictly "one-lining" here, BUT doing a proper mixed-management of \n
escape sequence between bash and Python. This is how we can deal with any piece of classic multi-line Python program. The solution sample illustrates this as well.
To expand on @Agis's answer, you can also install the Redis CLI by running
$ git clone -b v2.8.7 [email protected]:antirez/redis.git
$ make -C redis install redis-cli /usr/bin
This will build the Redis CLI and toss the binary into /usr/bin. To anyone who uses Docker, I've also built a Dockerfile that does this for you: https://github.com/bacongobbler/dockerfiles/blob/master/redis-cli/Dockerfile
In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:
#include <stdio.h> #include <stdlib.h> void outchar(char ch); int main() { outchar('A'); outchar('B'); outchar('C'); return 0; } void outchar(char ch) { printf("%c", ch); }
Also, you should be specifying the return type of every function. I added that for you.
This works :
browsername <filename>
Example: google-chrome index.html
Also you can add <br> instead of \n.
And then you can add text to TexView:
articleTextView.setText(Html.fromHtml(textForTextView));
This is an embed example of video played in HD 1080.
<iframe width="560" height="315" src="http://youtube.com/v/IplDUxTQxsE&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>
Let's break apart the code:http://youtube.com/v/
video_id
&vq=hd1080
Video id for that video: IplDUxTQxsE you will see this type of random code in the link of every YouTube video.
So far so good, this trick works for playing full HD videos directly on webpages!
You can change the quality to 720 too. &vq=hd720
The simplest way to put a Toolbar transparent is to define a opacity in @colors section, define a TransparentTheme in @styles section and then put these defines in your toolbar.
@colors.xml
<color name="actionbar_opacity">#33000000</color>
@styles.xml
<style name="TransparentToolbar" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:windowActionBarOverlay">true</item>
<item name="windowActionBarOverlay">true</item>
</style>
@activity_main.xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:background="@color/actionbar_opacity"
app:theme="@style/TransparentToolbar"
android:layout_height="?attr/actionBarSize"/>
That's the result: