My question is when should a use a double and when should I use a decimal type?
decimal
for when you work with values in the range of 10^(+/-28) and where you have expectations about the behaviour based on base 10 representations - basically money.
double
for when you need relative accuracy (i.e. losing precision in the trailing digits on large values is not a problem) across wildly different magnitudes - double
covers more than 10^(+/-300). Scientific calculations are the best example here.
which type is suitable for money computations?
decimal, decimal, decimal
Accept no substitutes.
The most important factor is that double
, being implemented as a binary fraction, cannot accurately represent many decimal
fractions (like 0.1) at all and its overall number of digits is smaller since it is 64-bit wide vs. 128-bit for decimal
. Finally, financial applications often have to follow specific rounding modes (sometimes mandated by law). decimal
supports these; double
does not.
Numeric precision refers to the maximum number of digits that are present in the number.
ie 1234567.89 has a precision of 9
Numeric scale refers to the maximum number of decimal places
ie 123456.789 has a scale of 3
Thus the maximum allowed value for decimal(5,2) is 999.99
Okay, the basic difference at the machine is that double precision uses twice as many bits as single. In the usual implementation,that's 32 bits for single, 64 bits for double.
But what does that mean? If we assume the IEEE standard, then a single precision number has about 23 bits of the mantissa, and a maximum exponent of about 38; a double precision has 52 bits for the mantissa, and a maximum exponent of about 308.
The details are at Wikipedia, as usual.
By setting the scale, you decrease the precision. Try NUMBER(16,2).
Why don't you simply try
System.out.println(1500/1000.0);
System.out.println(500/1000.0);
Cast the operands to floats:
float ans = (float)a / (float)b;
Use combination of Decimal object and round() method.
Python 3.7.3
>>> from decimal import Decimal
>>> d1 = Decimal (13.949999999999999) # define a Decimal
>>> d1
Decimal('13.949999999999999289457264239899814128875732421875')
>>> d2 = round(d1, 2) # round to 2 decimals
>>> d2
Decimal('13.95')
Floating point numbers differ from real numbers in that for any given floating point number there is a next higher floating point number. Same as integers. There's no integer between 1 and 2.
There's no way to represent 1/3 as a float. There's a float below it and there's a float above it, and there's a certain distance between them. And 1/3 is in that space.
Apfloat for Java claims to work with arbitrary precision floating point numbers, but I've never used it. Probably worth a look. http://www.apfloat.org/apfloat_java/
A similar question was asked here before Java floating point high precision library
The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options
value as a default.
As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.
Mathematica or Maple will allow you to give as many decimal places as your heart desires.
EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.
On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin
(usually 2e-308).
Compare these two analyses.
x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1) #Should throw an error
x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2) #ok
In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.
As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr
package.
mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")
These are slower and more memory intensive to use than regular (double precision) numeric
vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.
In most contexts where double
values are used, calculations will have a certain amount of uncertainty. The difference between 1.33333333333333300 and 1.33333333333333399 may be less than the amount of uncertainty that exists in the calculations. Displaying the value of "2/3 + 2/3" as "1.33333333333333" is apt to be more meaningful than displaying it as "1.33333333333333319", since the latter display implies a level of precision that doesn't really exist.
In the debugger, however, it is important to uniquely indicate the value held by a variable, including essentially-meaningless bits of precision. It would be very confusing if a debugger displayed two variables as holding the value "1.333333333333333" when one of them actually held 1.33333333333333319 and the other held 1.33333333333333294 (meaning that, while they looked the same, they weren't equal). The extra precision shown by the debugger isn't apt to represent a numerically-correct calculation result, but indicates how the code will interpret the values held by the variables.
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
This will be possible with setiosflags(ios::showpoint).
printf("%.12f", M_PI);
%.12f means floating point, with precision of 12 digits.
Use DateTime Structure with milliseconds and format like this:
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
timestamp = timestamp.Replace("-", ".");
Python's built-in float
type has double precision (it's a C double
in CPython, a Java double
in Jython). If you need more precision, get NumPy and use its numpy.float128
.
Floats have less precision than doubles. Although you already know, read What WE Should Know About Floating-Point Arithmetic for better understanding.
You can use toStringAsFixed
in order to display the limited digits after decimal points. toStringAsFixed
returns a decimal-point string-representation. toStringAsFixed
accepts an argument called fraction Digits
which is how many digits after decimal we want to display. Here is how to use it.
double pi = 3.1415926;
const val = pi.toStringAsFixed(2); // 3.14
If you want to write fast to file streams then you could make stream the read buffer larger:
wfstream f;
const size_t nBufferSize = 16184;
wchar_t buffer[nBufferSize];
f.rdbuf()->pubsetbuf(buffer, nBufferSize);
Also, when writing lots of data to files it is sometimes faster to logically extend the file size instead of physically, this is because when logically extending a file the file system does not zero the new space out before writing to it. It is also smart to logically extend the file more than you actually need to prevent lots of file extentions. Logical file extention is supported on Windows by calling SetFileValidData
or xfsctl
with XFS_IOC_RESVSP64
on XFS systems.
To make Python not return to me "Attempted relative import in non-package". package/
init.py subpackage1/ init.py moduleX.py moduleY.py subpackage2/ init.py moduleZ.py moduleA.py
This error occurs only if you are applying relative import to the parent file. For example parent file already returns main after you code "print(name)" in moduleA.py .so THIS file is already main it cannot return any parent package further on. relative imports are required in files of packages subpackage1 and subpackage2 you can use ".." to refer to the parent directory or module .But parent is if already top level package it cannot go further above that parent directory(package). Such files where you are applying relative importing to parents can only work with the application of absolute import. If you will use ABSOLUTE IMPORT IN PARENT PACKAGE NO ERROR will come as python knows who is at the top level of package even if your file is in subpackages because of the concept of PYTHON PATH which defines the top level of the project
You can try this to avoid indicating custom date and if there is need to display start and end dates of current month:
LocalDate start = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()-1);
LocalDate end = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()).plusMonths(1);
System.out.println("Start of month: " + start);
System.out.println("End of month: " + end);
Result:
> Start of month: 2019-12-01
> End of month: 2019-12-30
In node, the Mongo driver will give you an ISO string, not the object. (ex: Mon Nov 24 2014 01:30:34 GMT-0800 (PST)
) So, simply convert it to a js Date by: new Date(ISOString);
Here is my solution in Enterprise 1.11 (should work in CE 1.6):
$collection->addFieldToFilter('max_item_count',
array(
array('gteq' => 10),
array('null' => true),
)
)
->addFieldToFilter('max_item_price',
array(
array('gteq' => 9.99),
array('null' => true),
)
)
->addFieldToFilter('max_item_weight',
array(
array('gteq' => 1.5),
array('null' => true),
)
);
Which results in this SQL:
SELECT `main_table`.*
FROM `shipping_method_entity` AS `main_table`
WHERE (((max_item_count >= 10) OR (max_item_count IS NULL)))
AND (((max_item_price >= 9.99) OR (max_item_price IS NULL)))
AND (((max_item_weight >= 1.5) OR (max_item_weight IS NULL)))
You could use a separate CSS style which disables every other content except the one with the id "printarea".
See CSS Design: Going to Print for further explanation and examples.
Reading it columnwise is harder?
Anyway this reads the line and stores the values in a list:
for line in open("csvfile.csv"):
csv_row = line.split() #returns a list ["1","50","60"]
Modern solution:
# pip install pandas
import pandas as pd
df = pd.read_table("csvfile.csv", sep=" ")
Cleanly read in a couple prompted values:
// Create a single reader which can be called multiple times
reader := bufio.NewReader(os.Stdin)
// Prompt and read
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Print("Enter More text: ")
text2, _ := reader.ReadString('\n')
// Trim whitespace and print
fmt.Printf("Text1: \"%s\", Text2: \"%s\"\n",
strings.TrimSpace(text), strings.TrimSpace(text2))
Here's a run:
Enter text: Jim
Enter More text: Susie
Text1: "Jim", Text2: "Susie"
I'm using apache-tomcat-7.0.70 with jdk1.7.0_45 and none of the solutions here and elsewhere on stackoverflow worked for me. Just sharing this solution as it hopefully might help someone as this is very high on Google's search
What worked is doing BOTH of these steps:
Starting my tomcat with "export JAVA_OPTS="$JAVA_OPTS -Dhttps.protocols=TLSv1.2" by adding it to tomcat/bin/setenv.sh (Syntax slightly different on Windows)
Manually building/forcing HttpClients or anything else you need with the TLS1.2 protocol:
Context ctx = SSLContexts.custom().useProtocol("TLSv1.2").build();
HttpClient httpClient = HttpClientBuilder.create().setSslcontext(ctx).build();
HttpPost httppost = new HttpPost(scsTokenVerificationUrl);
List<NameValuePair> paramsAccessToken = new ArrayList<NameValuePair>(2);
paramsAccessToken.add(new BasicNameValuePair("token", token));
paramsAccessToken.add(new BasicNameValuePair("client_id", scsClientId));
paramsAccessToken.add(new BasicNameValuePair("secret", scsClientSecret));
httppost.setEntity(new UrlEncodedFormEntity(paramsAccessToken, "utf-8"));
//Execute and get the response.
HttpResponse httpResponseAccessToken = httpClientAccessToken.execute(httppost);
String responseJsonAccessToken = EntityUtils.toString(httpResponseAccessToken.getEntity());
The action occurs when you attempt to call an object which is not a function, as with ()
. For instance, this will produce the error:
>>> a = 5
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Class instances can also be called if they define a method __call__
One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0)
instead of [0]
Yes, the new limit is approximately 1 million rows.
Did you verify that the control causing the post back has CausesValidation set to tru and that it does not have a validation group assigned to it?
I'm not sure what else might cause this behavior.
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
Or if you want to check for existence first:
if [[ ! -e /path/to/newdir ]]; then
mkdir /path/to/newdir
fi
-e is the exist test for KornShell.
You can also try googling a KornShell manual.
In most cases, you should use the instanceof
operator to test whether an object is an array.
Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a Integer[]
or an int[]
. You'd want to guard your casts with instanceof
:
if (obj instanceof Integer[]) {
Integer[] array = (Integer[]) obj;
/* Use the boxed array */
} else if (obj instanceof int[]) {
int[] array = (int[]) obj;
/* Use the primitive array */
} else ...
At the JVM level, the instanceof
operator translates to a specific "instanceof" byte code, which is optimized in most JVM implementations.
In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the isArray()
method can be helpful because you don't know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.
There are two special cases: null references and references to primitive arrays.
A null reference will cause instanceof
to result false
, while the isArray
throws a NullPointerException
.
Applied to a primitive array, the instanceof
yields false
unless the component type on the right-hand operand exactly matches the component type. In contrast, isArray()
will return true
for any component type.
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
document.getElementById('loginSubmit').submit();
or, use the same code as the onclick
handler:
changeAction('submitInput','loginForm');
document.forms['loginForm'].submit();
(Though that onclick
handler is kind of stupidly-written: document.forms['loginForm']
could be replaced with this
.)
declare
strTime1 varchar2(50) := '02/08/2013 01:09:42 PM';
strTime2 varchar2(50) := '02/08/2013 11:09:00 PM';
v_date1 date := to_date(strTime1,'DD/MM/YYYY HH:MI:SS PM');
v_date2 date := to_date(strTime2,'DD/MM/YYYY HH:MI:SS PM');
difrence_In_Hours number;
difrence_In_minutes number;
difrence_In_seconds number;
begin
difrence_In_Hours := (v_date2 - v_date1) * 24;
difrence_In_minutes := difrence_In_Hours * 60;
difrence_In_seconds := difrence_In_minutes * 60;
dbms_output.put_line(strTime1);
dbms_output.put_line(strTime2);
dbms_output.put_line('*******');
dbms_output.put_line('difrence_In_Hours : ' || difrence_In_Hours);
dbms_output.put_line('difrence_In_minutes: ' || difrence_In_minutes);
dbms_output.put_line('difrence_In_seconds: ' || difrence_In_seconds);
end ;
Hope this helps.
Without CSS: Use the STYLE property of text input
STYLE="text-align: right;"
For people who have narrowed down the issue to the COMMENT ON
statements (as per various answers below) and who have superuser access to the source database from which the dump file is created, the simplest solution might be to prevent the comments from being included to the dump file in the first place, by removing them from the source database being dumped...
COMMENT ON EXTENSION postgis IS NULL;
COMMENT ON EXTENSION plpgsql IS NULL;
COMMENT ON SCHEMA public IS NULL;
Future dumps then won't include the COMMENT ON
statements.
Exchanges will usually publish an up-to-date list of securities on their web pages. For example, these pages offer CSV downloads:
NASDAQ Updated their site, so you will have to modify the URLS:
NASDAQ
AMEX
NYSE
Depending on your requirement, you could create the map of these URLs by exchange in your own code.
On client:
axios.get('/api', {
params: {
foo: 'bar'
}
});
On server:
function get(req, res, next) {
let param = req.query.foo
.....
}
I wasn't happy with Python one-liners for HTML XPath queries, so I wrote my own. Assumes that you installed python-lxml
package or ran pip install --user lxml
:
function htmlxpath() { python -c 'for x in __import__("lxml.html").html.fromstring(__import__("sys").stdin.read()).xpath(__import__("sys").argv[1]): print(x)' $1 }
Once you have it, you can use it like in this example:
> curl -s https://slashdot.org | htmlxpath '//title/text()'
Slashdot: News for nerds, stuff that matters
If you use the "select()" statement, you can do this:
$category = $catrep->createQueryBuilder('cc')
->select('DISTINCT cc.contenttype')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->getQuery();
$categories = $category->getResult();
The Python with
statement is built-in language support of the Resource Acquisition Is Initialization
idiom commonly used in C++. It is intended to allow safe acquisition and release of operating system resources.
The with
statement creates resources within a scope/block. You write your code using the resources within the block. When the block exits the resources are cleanly released regardless of the outcome of the code in the block (that is whether the block exits normally or because of an exception).
Many resources in the Python library that obey the protocol required by the with
statement and so can used with it out-of-the-box. However anyone can make resources that can be used in a with statement by implementing the well documented protocol: PEP 0343
Use it whenever you acquire resources in your application that must be explicitly relinquished such as files, network connections, locks and the like.
ListView is actually already capable of measuring itself to be tall enough to display all items, but it doesn't do this when you simply specify wrap_content (MeasureSpec.UNSPECIFIED). It will do this when given a height with MeasureSpec.AT_MOST. With this knowledge, you can create a very simple subclass to solve this problem which works far better than any of the solutions posted above. You should still use wrap_content with this subclass.
public class ListViewForEmbeddingInScrollView extends ListView {
public ListViewForEmbeddingInScrollView(Context context) {
super(context);
}
public ListViewForEmbeddingInScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListViewForEmbeddingInScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 4, MeasureSpec.AT_MOST));
}
}
Manipulating the heightMeasureSpec to be AT_MOST with a very large size (Integer.MAX_VALUE >> 4) causes the ListView to measure all of its children up to the given (very large) height and set its height accordingly.
This works better than the other solutions for a few reasons:
On the downside, you could argue that doing this is relying on undocumented behavior in the SDK which could change. On the other hand, you could argue that this is how wrap_content should really work with ListView and that the current wrap_content behavior is just broken.
If you're worried that the behavior could change in the future, you should simply copy the onMeasure function and related functions out of ListView.java and into your own subclass, then make the AT_MOST path through onMeasure run for UNSPECIFIED as well.
By the way, I believe that this is a perfectly valid approach when you are working with small numbers of list items. It may be inefficient when compared to LinearLayout, but when the number of items is small, using LinearLayout is unnecessary optimization and therefore unnecessary complexity.
A boundary across which two systems communicate.
Interfaces are how some OO languages achieve ad hoc polymorphism. Ad hoc polymorphism is simply functions with the same names operating on different types.
Quick work around
Simply enclose the list within a new list, as done for col2 in the data frame below. The reason it works is that python takes the outer list (of lists) and converts it into a column as if it were containing normal scalar items, which is lists in our case and not normal scalars.
mydict={'col1':[1,2,3],'col2':[[1, 4], [2, 5], [3, 6]]}
data=pd.DataFrame(mydict)
data
col1 col2
0 1 [1, 4]
1 2 [2, 5]
2 3 [3, 6]
You can find those maven properties in the super pom.
You find the jar here:
${M2_HOME}/lib/maven-model-builder-3.0.3.jar
Open the jar with 7-zip or some other archiver (or use the jar tool).
Navigate to
org/apache/maven/model
There you'll find the pom-4.0.0.xml
.
It contains all those "short cuts":
<project>
...
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
...
</build>
...
</project>
After some lobbying I am adding a link to the pom-4.0.0.xml
. This allows you to see the properties without opening up the local jar file.
You can use:
EQU - equal
NEQ - not equal
LSS - less than
LEQ - less than or equal
GTR - greater than
GEQ - greater than or equal
AVOID USING:
() ! ~ - * / % + - << >> & | = *= /= %= += -= &= ^= |= <<= >>=
From tuple to list to tuple :
a = ('2',)
b = 'b'
l = list(a)
l.append(b)
tuple(l)
Or with a longer list of items to append
a = ('2',)
items = ['o', 'k', 'd', 'o']
l = list(a)
for x in items:
l.append(x)
print tuple(l)
gives you
>>>
('2', 'o', 'k', 'd', 'o')
The point here is: List is a mutable sequence type. So you can change a given list by adding or removing elements. Tuple is an immutable sequence type. You can't change a tuple. So you have to create a new one.
It depends on the amount of data you are looking to store. In reality there's no difference between flat files and XML. XML would probably be preferable since it provides a structure to the document. In practice,
The last option, and a lot of applications use now is the Windows Registry. I don't personally recommend it (Registry Bloat, Corruption, other potential issues), but it is an option.
Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.
Build - Clean project. Basically, this is a problem with studio 3.0. https://developer.android.com/studio/build/gradle-plugin-3-0-0.html (authorized link).
There is already a string handling function Series.str.startswith()
.
You should try foo[foo.b.str.startswith('f')]
.
Result:
a b
1 2 foo
2 3 fat
I think what you expect.
Alternatively you can use contains with regex option. For example:
foo[foo.b.str.contains('oo', regex= True, na=False)]
Result:
a b
1 2 foo
na=False
is to prevent Errors in case there is nan, null etc. values
You can use the out
contextual keyword in two contexts (each is a link to detailed information), as a parameter modifier or in generic type parameter declarations in interfaces and delegates. This topic discusses the parameter modifier, but you can see this other topic for information on the generic type parameter declarations.
The out
keyword causes arguments to be passed by reference. This is like the ref
keyword, except that ref
requires that the variable be initialized before it is passed. To use an out
parameter, both the method definition and the calling method must explicitly use the out
keyword. For example:
C#
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}
Although variables passed as out
arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.
Although the ref
and out
keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref
argument and the other takes an out
argument. The following code, for example, will not compile:
C#
class CS0663_Example
{
// Compiler error CS0663: "Cannot define overloaded
// methods that differ only on ref and out".
public void SampleMethod(out int i) { }
public void SampleMethod(ref int i) { }
}
Overloading can be done, however, if one method takes a ref
or out
argument and the other uses neither, like this:
C#
class OutOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(out int i) { i = 5; }
}
Properties are not variables and therefore cannot be passed as out
parameters.
For information about passing arrays, see Passing Arrays Using ref
and out
(C# Programming Guide).
You can't use the ref
and out
keywords for the following kinds of methods:
Async methods, which you define by using the async modifier.
Iterator methods, which include a yield return or yield break statement.
Example
Declaring an out
method is useful when you want a method to return multiple values. The following example uses out
to return three variables with a single method call. Note that the third argument is assigned to null. This enables methods to return values optionally.
C#
class OutReturnExample
{
static void Method(out int i, out string s1, out string s2)
{
i = 44;
s1 = "I've been returned";
s2 = null;
}
static void Main()
{
int value;
string str1, str2;
Method(out value, out str1, out str2);
// value is now 44
// str1 is now "I've been returned"
// str2 is (still) null;
}
}
You could use closure compiler to generate a small, cross-browser flash detection:
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @formatting pretty_print
// @use_closure_library true
// ==/ClosureCompiler==
// ADD YOUR CODE HERE
goog.require('goog.userAgent.flash');
if (goog.userAgent.flash.HAS_FLASH) {
alert('flash version: '+goog.userAgent.flash.VERSION);
}else{
alert('no flash found');
}
which results in the following "compiled" code:
var a = !1,
b = "";
function c(d) {
d = d.match(/[\d]+/g);
d.length = 3;
return d.join(".")
}
if (navigator.plugins && navigator.plugins.length) {
var e = navigator.plugins["Shockwave Flash"];
e && (a = !0, e.description && (b = c(e.description)));
navigator.plugins["Shockwave Flash 2.0"] && (a = !0, b = "2.0.0.11")
} else {
if (navigator.mimeTypes && navigator.mimeTypes.length) {
var f = navigator.mimeTypes["application/x-shockwave-flash"];
(a = f && f.enabledPlugin) && (b = c(f.enabledPlugin.description))
} else {
try {
var g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"),
a = !0,
b = c(g.GetVariable("$version"))
} catch (h) {
try {
g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"), a = !0, b = "6.0.21"
} catch (i) {
try {
g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"), a = !0, b = c(g.GetVariable("$version"))
} catch (j) {}
}
}
}
}
var k = b;
a ? alert("flash version: " + k) : alert("no flash found");
This message can also occur when you specify the incorrect decryption password (yeah, lame, but not quite obvious to realize this from the error message, huh?).
I was using the command line to decrypt the recent DataBase backup for my auxiliary tool and suddenly faced this issue.
Finally, after 10 mins of grief and plus reading through this question/answers I have remembered that the password is different and everything worked just fine with the correct password.
I found that most of the answers work but with a warning. So I have a tricky way to achieve this without any warning.
ArrayList<Question> questionList = new ArrayList<>();
...
Intent intent = new Intent(CurrentActivity.this, ToOpenActivity.class);
for (int i = 0; i < questionList.size(); i++) {
Question question = questionList.get(i);
intent.putExtra("question" + i, question);
}
startActivity(intent);
And now in Second Activity
ArrayList<Question> questionList = new ArrayList<>();
Intent intent = getIntent();
int i = 0;
while (intent.hasExtra("question" + i)){
Question model = (Question) intent.getSerializableExtra("question" + i);
questionList.add(model);
i++;
}
Note: implements Serializable in your Question class.
cd
to the repository then
find . -name ".git*" -exec rm -R {} \;
Make sure not to accidentally pipe a single dot, slash, asterisk, or other regex wildcard into find, or else rm
will happily delete it.
public class UrlContent{
public static void main(String[] args) {
URL url;
try {
// get URL content
String a="http://localhost:8080/TestWeb/index.jsp";
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Some cases just worked when I used Math.log10:
public static double log2(int n)
{
return (Math.log10(n) / Math.log10(2));
}
reading through this 6yrs later and thought I'd also take a hack at it, also in the TIMTOWTDI vein...:D, hoping it isn't incorrect 'JS etiquette'.
I usually set up a var with the condition and then refer to it later on..i.e;
// var set up globally OR locally depending on your requirements
var hC;
function(el) {
var $this = el;
hC = $this.hasClass("test");
// use the variable in the conditional statement
if (!hC) {
//
}
}
Although I should mention that I do this because I mainly use the conditional ternary operator and want clean code. So in this case, all i'd have is this:
hC ? '' : foo(x, n) ;
// OR -----------
!hC ? foo(x, n) : '' ;
...instead of this:
$this.hasClass("test") ? '' : foo(x, n) ;
// OR -----------
(!$this.hasClass("test")) ? foo(x, n) : '' ;
I had this problem on Windows.
My problem was that my %GOPATH%
environment variable was set to
C:\Users\john\src\goworkspace
instead of
C:\Users\john\src\goworkspace\
Adding the missing trailing slash at the end fixed it for me.
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Try making the field names legal by removing spaces. It's a long shot but it has actually helped me before.
It seems the problem is you send the form request to welcome/do_upload
, and call the Welcome::do_upload()
method in another one by $this->do_upload()
.
Hence when you call the $this->do_upload();
within your second method, the $_FILES
array would be empty.
And that's why var_dump($data['upload_data']);
returns NULL
.
If you want to upload the file from welcome/second_method
, send the form request to the welcome/second_method where you call $this->do_upload();
.
Then change the form helper function (within the View) as follows1:
// Change the 'second_method' to your method name
echo form_open_multipart('welcome/second_method');
CodeIgniter has documented the Uploading process very well, by using the File Uploading library.
You could take a look at the sample code in the user guide; And also, in order to get a better understanding of the uploading configs, Check the Config items Explanation section at the end of the manual page.
Also there are couple of articles/samples about the file uploading in CodeIgniter, you might want to consider:
Just as a side-note: Make sure that you've loaded the url
and form
helper functions before using the CodeIgniter sample code:
// Load the helper files within the Controller
$this->load->helper('form');
$this->load->helper('url');
1. The form must be "multipart" type for file uploading. Hence you should use form_open_multipart()
helper function which returns:
<form method="post" action="controller/method" enctype="multipart/form-data" />
I tend to version my framework then apply the version number to script and style paths
<cfset fw.version = '001' />
<script src="/scripts/#fw.version#/foo.js"/>
Documentation says it's just a shortcut for creating readonly properties. So
@property
def x(self):
return self._x
is equivalent to
def getx(self):
return self._x
x = property(getx)
You can do that with bool query and combination of must and must_not like this:
GET index/_search
{
"query": {
"bool": {
"must": [
{"exists": {"field": "field1"}}
],
"must_not": [
{"term": {"field1": ""}}
]
}
}
}
I tested this with Elasticsearch 5.6.5 in Kibana.
I had issues getting through a form because of this error.
I used Ctrl+Click to click the submit button and navigate through the form as usual.
It's the best way to generate .gitignore
via here
This is what worked nicely for me since all I wanted to do was set the height of the textbox. The property is Read-Only and the property is in the Unit class so you can't just set it. So I just created a new Unit and the constructor lets me set the height, then set the textbox to that unit instead.
Unit height = txtTextBox.Height;
double oldHeight = height.Value;
double newHeight = height.Value + 20; //Added 20 pixels
Unit newHeightUnit = new Unit(newHeight);
txtTextBox.Height = newHeightUnit;
Just an update:
You should use ::ng-deep
instead of /deep/
which seems to be deprecated.
Per documentation:
The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
You can find it here
Basically, the way the Selenium detection works, is that they test for predefined JavaScript variables which appear when running with Selenium. The bot detection scripts usually look anything containing word "selenium" / "webdriver" in any of the variables (on window object), and also document variables called $cdc_
and $wdc_
. Of course, all of this depends on which browser you are on. All the different browsers expose different things.
For me, I used Chrome, so, all that I had to do was to ensure that $cdc_
didn't exist anymore as a document variable, and voilà (download chromedriver source code, modify chromedriver and re-compile $cdc_
under different name.)
This is the function I modified in chromedriver:
function getPageCache(opt_doc) {
var doc = opt_doc || document;
//var key = '$cdc_asdjflasutopfhvcZLmcfl_';
var key = 'randomblabla_';
if (!(key in doc))
doc[key] = new Cache();
return doc[key];
}
(Note the comment. All I did I turned $cdc_
to randomblabla_
.)
Here is pseudocode which demonstrates some of the techniques that bot networks might use:
runBotDetection = function () {
var documentDetectionKeys = [
"__webdriver_evaluate",
"__selenium_evaluate",
"__webdriver_script_function",
"__webdriver_script_func",
"__webdriver_script_fn",
"__fxdriver_evaluate",
"__driver_unwrapped",
"__webdriver_unwrapped",
"__driver_evaluate",
"__selenium_unwrapped",
"__fxdriver_unwrapped",
];
var windowDetectionKeys = [
"_phantom",
"__nightmare",
"_selenium",
"callPhantom",
"callSelenium",
"_Selenium_IDE_Recorder",
];
for (const windowDetectionKey in windowDetectionKeys) {
const windowDetectionKeyValue = windowDetectionKeys[windowDetectionKey];
if (window[windowDetectionKeyValue]) {
return true;
}
};
for (const documentDetectionKey in documentDetectionKeys) {
const documentDetectionKeyValue = documentDetectionKeys[documentDetectionKey];
if (window['document'][documentDetectionKeyValue]) {
return true;
}
};
for (const documentKey in window['document']) {
if (documentKey.match(/\$[a-z]dc_/) && window['document'][documentKey]['cache_']) {
return true;
}
}
if (window['external'] && window['external'].toString() && (window['external'].toString()['indexOf']('Sequentum') != -1)) return true;
if (window['document']['documentElement']['getAttribute']('selenium')) return true;
if (window['document']['documentElement']['getAttribute']('webdriver')) return true;
if (window['document']['documentElement']['getAttribute']('driver')) return true;
return false;
};
According to user szx, it is also possible to simply open chromedriver.exe in a hex editor, and just do the replacement manually, without actually doing any compiling.
i think that is what you want.
SELECT
A.SalesOrderID,
A.OrderDate,
FooFromB.*
FROM A,
(SELECT TOP 1 B.Foo
FROM B
WHERE A.SalesOrderID = B.SalesOrderID
) AS FooFromB
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
TCPDF is PHP class for generating pdf documents.Here we will learn TCPDF integration with CodeIgniter.we will use following step for TCPDF integration with CodeIgniter.
Step 1
To Download TCPDF Click Here.
Step 2
Unzip the above download inside application/libraries/tcpdf.
Step 3
Create a new file inside application/libraries/Pdf.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__) . '/tcpdf/tcpdf.php';
class Pdf extends TCPDF
{ function __construct() { parent::__construct(); }
}
/*Author:Tutsway.com */
/* End of file Pdf.php */
/* Location: ./application/libraries/Pdf.php */
Step 4
Create Controller file inside application/controllers/pdfexample.php.
<?php
class pdfexample extends CI_Controller{
function __construct()
{ parent::__construct(); } function index() {
$this->load->library('Pdf');
$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Pdf Example');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(20);
$pdf->setFooterMargin(20);
$pdf->SetAutoPageBreak(true);
$pdf->SetAuthor('Author');
$pdf->SetDisplayMode('real', 'default');
$pdf->Write(5, 'CodeIgniter TCPDF Integration');
$pdf->Output('pdfexample.pdf', 'I'); }
}
?>
It is working for me. I have taken reference from http://www.tutsway.com/codeignitertcpdf.php
You can use regex:
/[a-z]/i.test(str);
The i
makes the regex case-insensitive. You could also do:
/[a-z]/.test(str.toLowerCase());
First of all, there is no difference between View.OnClickListener
and OnClickListener
. If you just use View.OnClickListener
directly, then you don't need to write-
import android.view.View.OnClickListener
You set an OnClickListener instance (e.g. myListener
named object)as the listener to a view via setOnclickListener()
. When a click
event is fired, that myListener
gets notified and it's onClick(View view)
method is called. Thats where we do our own task.
Hope this helps you.
I tried a slightly different approach to prevent UIWebView objects from scrolling and bouncing: adding a gesture recognizer to override other gestures.
It seems, UIWebView or its scroller subview uses its own pan gesture recognizer to detect user scrolling. But according to Apple's documentation there is a legitimate way of overriding one gesture recognizer with another. UIGestureRecognizerDelegate protocol has a method gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: - which allows to control the behavior of any colliding gesture recognizers.
So, what I did was
in the view controller's viewDidLoad method:
// Install a pan gesture recognizer // We ignore all the touches except the first and try to prevent other pan gestures
// by registering this object as the recognizer's delegate
UIPanGestureRecognizer *recognizer;
recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];
recognizer.delegate = self;
recognizer.maximumNumberOfTouches = 1;
[self.view addGestureRecognizer:recognizer];
self.panGestureFixer = recognizer;
[recognizer release];
then, the gesture override method:
// Control gestures precedence
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
// Prevent all panning gestures (which do nothing but scroll webViews, something we want to disable in
// the most painless way)
if ([otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
{
// Just disable every other pan gesture recognizer right away
otherGestureRecognizer.enabled = FALSE;
}
return NO;
}
Of course, this delegate method can me more complex in a real application - we may disable other recognizers selectively, analyzing otherGestureRecognizer.view and making decision based on what view it is.
And, finally, for the sake of completeness, the method we registered as a pan handler:
- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer
{
// do nothing as of yet
}
it can be empty if all we want is to cancel web views' scrolling and bouncing, or it can contain our own code to implement the kind of pan motions and animations we really want...
So far I'm just experimenting with all this stuff, and it seems to be working more or less as I want it. I haven't tried to submit any apps to iStore yet, though. But I believe I haven't used anything undocumented so far... If anyone finds it otherwise, please inform me.
The other answers don't work. The only way to see the captured output is using the following flag:
pytest --show-capture all
just use this:
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["1","2","3","4","5","6","7","8","9","10","11",],
datasets: [{
label: 'YOUR LABEL',
backgroundColor: [
"#566573",
"#99a3a4",
"#dc7633",
"#f5b041",
"#f7dc6f",
"#82e0aa",
"#73c6b6",
"#5dade2",
"#a569bd",
"#ec7063",
"#a5754a"
],
data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],
},]
},
//HERE COMES THE AXIS Y LABEL
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
});
</script>
myList.GroupBy(test => test.id)
.Select(grp => grp.First());
Edit: as getting this IEnumerable<>
into a List<>
seems to be a mystery to many people, you can simply write:
var result = myList.GroupBy(test => test.id)
.Select(grp => grp.First())
.ToList();
But one is often better off working with the IEnumerable
rather than IList
as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList
it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)
The flipside to this advice is that each time you enumerate such an IEnumerable
the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable
or to realize it into a List
, Set
, Dictionary
or whatnot.
It may be useful package list-to-tree Install:
bower install list-to-tree --save
or
npm install list-to-tree --save
For example, have list:
var list = [
{
id: 1,
parent: 0
}, {
id: 2,
parent: 1
}, {
id: 3,
parent: 1
}, {
id: 4,
parent: 2
}, {
id: 5,
parent: 2
}, {
id: 6,
parent: 0
}, {
id: 7,
parent: 0
}, {
id: 8,
parent: 7
}, {
id: 9,
parent: 8
}, {
id: 10,
parent: 0
}
];
Use package list-to-tree:
var ltt = new LTT(list, {
key_id: 'id',
key_parent: 'parent'
});
var tree = ltt.GetTree();
Result:
[{
"id": 1,
"parent": 0,
"child": [
{
"id": 2,
"parent": 1,
"child": [
{
"id": 4,
"parent": 2
}, {
"id": 5, "parent": 2
}
]
},
{
"id": 3,
"parent": 1
}
]
}, {
"id": 6,
"parent": 0
}, {
"id": 7,
"parent": 0,
"child": [
{
"id": 8,
"parent": 7,
"child": [
{
"id": 9,
"parent": 8
}
]
}
]
}, {
"id": 10,
"parent": 0
}];
Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.
check this fiddle
Simply remove the line that rotates it one degree at a time and calls the script forever.
// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);
Then pass the desired value into the function... in this example 45
for 45 degrees.
$(function() {
var $elie = $("#bkgimg");
rotate(45);
function rotate(degree) {
// For webkit browsers: e.g. Chrome
$elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
// For Mozilla browser: e.g. Firefox
$elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
}
});
Change .css()
to .animate()
in order to animate the rotation with jQuery. We also need to add a duration for the animation, 5000 for 5 seconds. And updating your original function to remove some redundancy and support more browsers...
$(function() {
var $elie = $("#bkgimg");
rotate(45);
function rotate(degree) {
$elie.animate({
'-webkit-transform': 'rotate(' + degree + 'deg)',
'-moz-transform': 'rotate(' + degree + 'deg)',
'-ms-transform': 'rotate(' + degree + 'deg)',
'-o-transform': 'rotate(' + degree + 'deg)',
'transform': 'rotate(' + degree + 'deg)',
'zoom': 1
}, 5000);
}
});
EDIT: The standard jQuery CSS animation code above is not working because apparently, jQuery .animate()
does not yet support the CSS3 transforms
.
This jQuery plugin is supposed to animate the rotation:
You can set Default attribute in Model also>
protected $attributes = [
'status' => self::STATUS_UNCONFIRMED,
'role_id' => self::ROLE_PUBLISHER,
];
You can find the details in these links
1.) How to set a default attribute value for a Laravel / Eloquent model?
You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators
2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators
Write a spider which reads in every html from disk and outputs every "href" attribute of an "a" element (can be done with a parser). Keep in mind which links belong to a certain page (this is common task for a MultiMap datastructre). After this you can produce a mapping file which acts as the input for the 404 handler.
Try this...
function nationList($limit=null, $start=null) {
if ($this->session->userdata('language') == "it") {
$this->db->select('nation.id, nation.name_it as name');
}
if ($this->session->userdata('language') == "en") {
$this->db->select('nation.id, nation.name_en as name');
}
$this->db->from('nation');
$this->db->order_by("name", "asc");
if ($limit != '' && $start != '') {
$this->db->limit($limit, $start);
}
$query = $this->db->get();
$nation = array();
foreach ($query->result() as $row) {
array_push($nation, $row);
}
return $nation;
}
HTML:
<div id="parent">
<div class="right"></div>
<div class="left"></div>
</div>
(div.right needs to be before div.left in the HTML markup)
CSS:
.right {
float:right;
width:200px;
}
Is date_field
of type datetime
? Also you need to put the eariler date first.
It should be:
SELECT * FROM `objects`
WHERE (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')
Using jQuery
Create a second column and move over the elements you need into it.
<script type="text/javascript">
$(document).ready(function() {
var size = $("#data > p").size();
$(".Column1 > p").each(function(index){
if (index >= size/2){
$(this).appendTo("#Column2");
}
});
});
</script>
<div id="data" class="Column1" style="float:left;width:300px;">
<!-- data Start -->
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
<!-- data Emd-->
</div>
<div id="Column2" style="float:left;width:300px;"></div>
Update:
Or Since the requirement now is to have them equally sized. I would suggest using the prebuilt jQuery plugins: Columnizer jQuery Plugin
use the runas command. But, I don't think you can email a .bat file easily.
In java8+ this can be written in single line as follows:
collectionObjec.sort(comparator_lamda)
or comparator.comparing(CollectionType::getterOfProperty)
code:
ListOfActiveAlarmObj.sort((a,b->a.getTimeStarted().compareTo(b.getTimeStarted())))
or
ListOfActiveAlarmObj.sort(Comparator.comparing(ActiveAlarm::getTimeStarted))
The documentation is not very clear about AngularJS routing. It talks about Hashbang and HTML5 mode. In fact, AngularJS routing operates in three modes:
For each mode there is a a respective LocationUrl class (LocationHashbangUrl, LocationUrl and LocationHashbangInHTML5Url).
In order to simulate URL rewriting you must actually set html5mode to true and decorate the $sniffer class as follows:
$provide.decorator('$sniffer', function($delegate) {
$delegate.history = false;
return $delegate;
});
I will now explain this in more detail:
Configuration:
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(false)
.hashPrefix('!');
This is the case when you need to use URLs with hashes in your HTML files such as in
<a href="index.html#!/path">link</a>
In the Browser you must use the following Link: http://www.example.com/base/index.html#!/base/path
As you can see in pure Hashbang mode all links in the HTML files must begin with the base such as "index.html#!".
Configuration:
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true);
You should set the base in HTML-file
<html>
<head>
<base href="/">
</head>
</html>
In this mode you can use links without the # in HTML files
<a href="/path">link</a>
Link in Browser:
http://www.example.com/base/path
This mode is activated when we actually use HTML5 mode but in an incompatible browser. We can simulate this mode in a compatible browser by decorating the $sniffer service and setting history to false.
Configuration:
$provide.decorator('$sniffer', function($delegate) {
$delegate.history = false;
return $delegate;
});
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true)
.hashPrefix('!');
Set the base in HTML-file:
<html>
<head>
<base href="/">
</head>
</html>
In this case the links can also be written without the hash in the HTML file
<a href="/path">link</a>
Link in Browser:
http://www.example.com/index.html#!/base/path
@media queries serve this purpose. Here's an example:
@media only screen and (max-width: 991px) and (min-width: 769px){
/* CSS that should be displayed if width is equal to or less than 991px and larger
than 768px goes here */
}
@media only screen and (max-width: 991px){
/* CSS that should be displayed if width is equal to or less than 991px goes here */
}
It's not as simple as just omitting the return
keyword. In Scala, if there is no return
then the last expression is taken to be the return value. So, if the last expression is what you want to return, then you can omit the return
keyword. But if what you want to return is not the last expression, then Scala will not know that you wanted to return it.
An example:
def f() = {
if (something)
"A"
else
"B"
}
Here the last expression of the function f
is an if/else expression that evaluates to a String. Since there is no explicit return
marked, Scala will infer that you wanted to return the result of this if/else expression: a String.
Now, if we add something after the if/else expression:
def f() = {
if (something)
"A"
else
"B"
if (somethingElse)
1
else
2
}
Now the last expression is an if/else expression that evaluates to an Int. So the return type of f
will be Int. If we really wanted it to return the String, then we're in trouble because Scala has no idea that that's what we intended. Thus, we have to fix it by either storing the String to a variable and returning it after the second if/else expression, or by changing the order so that the String part happens last.
Finally, we can avoid the return
keyword even with a nested if-else expression like yours:
def f() = {
if(somethingFirst) {
if (something) // Last expression of `if` returns a String
"A"
else
"B"
}
else {
if (somethingElse)
1
else
2
"C" // Last expression of `else` returns a String
}
}
I'd Use the following:
SHOW VARIABLES LIKE 'query_cache_type';
SET SESSION query_cache_type = OFF;
SHOW VARIABLES LIKE 'query_cache_type';
I ran into this issue as well. I don't know the technical details of what was actually happening. However, in my situation, the root cause was that there was cascading deletes setup in the Oracle database and my JPA/Hibernate code was also trying to do the cascading delete calls. So my advice is to make sure that you know exactly what is happening.
All the answers here are determining if the element is fully contained within the viewport, not just visible in some way. For example, if only half of an image is visible at the bottom of the view, the solutions here will fail, considering that "outside".
I had a use case where I'm doing lazy loading via IntersectionObserver
, but due to animations that occur during pop-in, I didn't want to observe any images that were already intersected on page load. To do that, I used the following code:
const bounding = el.getBoundingClientRect();
const isVisible = (0 < bounding.top && bounding.top < (window.innerHeight || document.documentElement.clientHeight)) ||
(0 < bounding.bottom && bounding.bottom < (window.innerHeight || document.documentElement.clientHeight));
This is basically checking to see if either the top or bottom bound is independently in the viewport. The opposite end may be outside, but as long as one end is in, it's "visible" at least partially.
I had that issue and here is much simpler solution:
Replace default petstore url in dist/index.html with your localhost/api-docs or to make it more generalized, replace with this:
location.protocol+'//' + location.hostname+(location.port ? ':' + location.port: '') + "/api-docs";
Hit again localhost/swagger-ui
Voila! You local swagger implementation is ready
Here's a reasonably terse way to do it using a Prototype:
Date.prototype.getFormattedTime = function () { var hours = this.getHours() == 0 ? "12" : this.getHours() > 12 ? this.getHours() - 12 : this.getHours(); var minutes = (this.getMinutes() < 10 ? "0" : "") + this.getMinutes(); var ampm = this.getHours() < 12 ? "AM" : "PM"; var formattedTime = hours + ":" + minutes + " " + ampm; return formattedTime; }
Then all you have to do is convert your string value to a date and use the new method:
var stringValue = "February 04, 2011 19:00:00; var dateValue = new Date(stringValue); var formattedTime = dateValue.getFormattedTime();
Or in a single line:
var formattedTime = new Date("February 04, 2011 19:00:00").getFormattedTime();
To work with observable, this is what I usually do to display if the observable array consists of data.
<div *ngIf="(observable$ | async) as listOfObject else emptyList">
<div >
....
</div>
</div>
<ng-template #emptyList>
<div >
...
</div>
</ng-template>
According to the documentation of the PropertyFile
task, you can append the generated properties to an existing file. You could have a properties file with just the comment line, and have the Ant task append the generated properties.
I agree with rpd, this is the answer and can be done on a regular basis to clean up your id column that is getting bigger with only a few hundred rows of data, but maybe an id of 34444543!, as the data is deleted out regularly but id is incremented automatically.
ALTER TABLE users DROP id
The above sql can be run via sql query or as php. This will delete the id column.
Then re add it again, via the code below:
ALTER TABLE `users` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
Place this in a piece of code that may get run maybe in an admin panel, so when anyone enters that page it will run this script that auto cleans your database, and tidys it.
Turns out it is possible to enter a host name directly into the playbook, so running the playbook with hosts: imac-2.local
will work fine. But it's kind of clunky.
A better solution might be defining the playbook's hosts using a variable, then passing in a specific host address via --extra-vars
:
# file: user.yml (playbook)
---
- hosts: '{{ target }}'
user: ...
Running the playbook:
ansible-playbook user.yml --extra-vars "target=imac-2.local"
If {{ target }}
isn't defined, the playbook does nothing. A group from the hosts file can also be passed through if need be. Overall, this seems like a much safer way to construct a potentially destructive playbook.
Playbook targeting a single host:
$ ansible-playbook user.yml --extra-vars "target=imac-2.local" --list-hosts
playbook: user.yml
play #1 (imac-2.local): host count=1
imac-2.local
Playbook with a group of hosts:
$ ansible-playbook user.yml --extra-vars "target=office" --list-hosts
playbook: user.yml
play #1 (office): host count=3
imac-1.local
imac-2.local
imac-3.local
Forgetting to define hosts is safe!
$ ansible-playbook user.yml --list-hosts
playbook: user.yml
play #1 ({{target}}): host count=0
The easier way is just to call app.get('url')
, which gives you the protocol, sub domain, domain, and port.
Redirection of program output is performed by the shell.
grep ... > output.txt
grep
has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1)
man page for details, specifically the -C
and --color
options.
I ran into this issue due to a silly mistake. Make sure the date actually exists!
For example:
September 31, 2015 does not exist.
EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150931'
So this fails with the message:
Error converting data type varchar to datetime.
To fix it, input a valid date:
EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150930'
And it executes just fine.
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
You have a multiple options:
First, you can use kill. But you need the pid of your process, which you can get by using ps, pidof or pgrep.
ps -A // to get the pid, can be combined with grep
-or-
pidof <name>
-or-
pgrep <name>
kill <pid>
It is possible to kill a process by just knowing the name. Use pkill or killall.
pkill <name>
-or-
killall <name>
All commands send a signal to the process. If the process hung up, it might be neccessary to send a sigkill to the process (this is signal number 9, so the following examples do the same):
pkill -9 <name>
pkill -SIGKILL <name>
You can use this option with kill
and killall
, too.
Read this article about controlling processes to get more informations about processes in general.
Use Jquery instead. Add a decimal class to your textbox:
<input type="text" class="decimal" value="" />
Use this code in your JS. It checks for multiple decimals and also restrict users to type only numbers.
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});?
Check this fiddle: http://jsfiddle.net/2YW8g/
Hope it helps.
You can use text-align: center; line-height: 65px;
CSS
.loginBtn {
background:url(images/loginBtn-center.jpg) repeat-x;
width:175px;
height:65px;
margin:20px auto;
border-radius:10px;
-webkit-border-radius:10px;
box-shadow:0 1px 2px #5e5d5b;
text-align: center; <--------- Here
line-height: 65px; <--------- Here
}
From the MDN docs on Function.prototype.apply() :
The apply() method calls a function with a given
this
value and arguments provided as an array (or an array-like object).Syntax
fun.apply(thisArg, [argsArray])
From the MDN docs on Function.prototype.call() :
The call() method calls a function with a given
this
value and arguments provided individually.Syntax
fun.call(thisArg[, arg1[, arg2[, ...]]])
From Function.apply and Function.call in JavaScript :
The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method.
var doSomething = function() {_x000D_
var arr = [];_x000D_
for(i in arguments) {_x000D_
if(typeof this[arguments[i]] !== 'undefined') {_x000D_
arr.push(this[arguments[i]]);_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}_x000D_
_x000D_
var output = function(position, obj) {_x000D_
document.body.innerHTML += '<h3>output ' + position + '</h3>' + JSON.stringify(obj) + '\n<br>\n<br><hr>';_x000D_
}_x000D_
_x000D_
output(1, doSomething(_x000D_
'one',_x000D_
'two',_x000D_
'two',_x000D_
'one'_x000D_
));_x000D_
_x000D_
output(2, doSomething.apply({one : 'Steven', two : 'Jane'}, [_x000D_
'one',_x000D_
'two',_x000D_
'two',_x000D_
'one'_x000D_
]));_x000D_
_x000D_
output(3, doSomething.call({one : 'Steven', two : 'Jane'},_x000D_
'one',_x000D_
'two',_x000D_
'two',_x000D_
'one'_x000D_
));
_x000D_
See also this Fiddle.
HTML
<div id="div1">
<div></div><div></div><div></div><br/><div></div><div></div><div></div>
</div>
CSS
#div1 {
width:150px;height:100px;white-space:nowrap;
line-height: 0px;
border:blue 1px solid;padding:5px;
}
#div1 div {
width:30px;height:30px;
border:blue 1px solid;
display:inline-block;
*display:inline;zoom:1;
margin:0px;outline:none;
}
You can add comments in Vim's configuration file by either:
" brief descriptiion of command
or:
"" commended command
Taken from here
This seems to be a little buggy in Pandas 0.23.4?
If there are np.nan values then this will throw an error as expected:
df['col'] = df['col'].astype(np.int64)
But doesn't change any values from float to int as I would expect if "ignore" is used:
df['col'] = df['col'].astype(np.int64,errors='ignore')
It worked if I first converted np.nan:
df['col'] = df['col'].fillna(0).astype(np.int64)
df['col'] = df['col'].astype(np.int64)
Now I can't figure out how to get null values back in place of the zeroes since this will convert everything back to float again:
df['col'] = df['col'].replace(0,np.nan)
if you want to pass an entire model go like so in the layout:
@model ViewAsModelBase
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8"/>
<link href="/img/phytech_icon.ico" rel="shortcut icon" type="image/x-icon" />
<title>@ViewBag.Title</title>
@RenderSection("styles", required: false)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
@RenderSection("scripts", required: false)
@RenderSection("head", required: false)
</head>
<body>
@Html.Action("_Header","Controller", new {model = Model})
<section id="content">
@RenderBody()
</section>
@RenderSection("footer", required: false)
</body>
</html>
and add this in the controller:
public ActionResult _Header(ViewAsModelBase model)
Try out following example of using SELECT INTO OUTFILE query for creating table backup. This will only backup a particular table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employee";
$backup_file = "/tmp/employee.sql";
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not take data backup: ' . mysql_error());
}
echo "Backedup data successfully\n";
mysql_close($conn);
?>
From the Heroku Web
Dashboard => Your App Name => Resources => Pencil icon=> Flip the switch => Confirm
Here is a simple way to do it
var lastPlayerControlCommand = this.ObjectContext.PlayerControlCommands
.Where(c => c.PlayerID == player.ID)
.OrderByDescending(t=>t.CreationTime)
.FirstOrDefault();
Also have a look this great LINQ place - LINQ to SQL Samples
Expanding on Mitch Wheat's code, the following script will generate the command to drop the constraint and dynamically execute it.
declare @schema_name nvarchar(256)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
declare @Command nvarchar(1000)
set @schema_name = N'MySchema'
set @table_name = N'Department'
set @col_name = N'ModifiedDate'
select @Command = 'ALTER TABLE ' + @schema_name + '.[' + @table_name + '] DROP CONSTRAINT ' + d.name
from sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
where t.name = @table_name
and t.schema_id = schema_id(@schema_name)
and c.name = @col_name
--print @Command
execute (@Command)
On Mac OS X, for anyone having:
-bash: /usr/local/bin/composer: Permission denied
problem, while trying to move downloaded composer.phar
using:
mv composer.phar /usr/local/bin/composer
this is the cause:
System Integrity Protection
and this is the solution:
csrutil disable
and hit enter. You should see a msg returned saying that:
the System Integrity Protection is off.
/usr/bin
and NOT /usr/local/bin
because for some reason it just didn't work there.csrutil enable
The above 6 steps are copied from here, so all the credit belongs to the user Vasheer there.
It can be installed with one command for N++ installer version:
choco install notepadplusplus-nppPluginManager
creating logo
in folders "drawable-...
" create in all of them logo.png
.
The location of the folders: [YOUR APP]\app\src\main\res
In AndroidManifest.xml add line: android:logo="@drawable/logo"
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:logo="@drawable/logo"
...
that's it.
Assuming that your Sheet1
is not necessary active you would need to use this improved code of yours:
i = ActiveWorkbook.Worksheets("Sheet1").Range("A2" , Worksheets("Sheet1").Range("A2").End(xlDown)).Rows.Count
Look into full worksheet reference for second argument for Range(arg1, arg2)
which important in this situation.
This is technique I have used on a number of occasions. It is originally based on this fiddle with a number of modifications. It is also fluid and column widths can be fixed by adding a width style to the <th>
.
/* this is for the main container of the table, also sets the height of the fixed header row */_x000D_
.headercontainer {_x000D_
position: relative;_x000D_
border: 1px solid #222;_x000D_
padding-top: 37px;_x000D_
background: #000;_x000D_
}_x000D_
/* this is for the data area that is scrollable */_x000D_
.tablecontainer {_x000D_
overflow-y: auto;_x000D_
height: 200px;_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
/* remove default cell borders and ensures table width 100% of its container*/_x000D_
.tablecontainer table {_x000D_
border-spacing: 0;_x000D_
width:100%;_x000D_
}_x000D_
_x000D_
/* add a thin border to the left of cells, but not the first */_x000D_
.tablecontainer td + td {_x000D_
border-left:1px solid #eee; _x000D_
}_x000D_
_x000D_
/* cell padding and bottom border */_x000D_
.tablecontainer td, th {_x000D_
border-bottom:1px solid #eee;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
/* make the default header height 0 and make text invisible */_x000D_
.tablecontainer th {_x000D_
height: 0px;_x000D_
padding-top: 0;_x000D_
padding-bottom: 0;_x000D_
line-height: 0;_x000D_
visibility: hidden;_x000D_
white-space: nowrap;_x000D_
}_x000D_
_x000D_
/* reposition the divs in the header cells and place in the blank area of the headercontainer */_x000D_
.tablecontainer th div{_x000D_
visibility: visible;_x000D_
position: absolute;_x000D_
background: #000;_x000D_
color: #fff;_x000D_
padding: 9px 10px;_x000D_
top: 0;_x000D_
margin-left: -10px;_x000D_
line-height: normal;_x000D_
border-left: 1px solid #222;_x000D_
}_x000D_
/* prevent the left border from above appearing in first div header */_x000D_
th:first-child div{_x000D_
border: none;_x000D_
}_x000D_
_x000D_
/* alternate colors for rows */_x000D_
.tablecontainer tbody tr:nth-child(even){_x000D_
background-color: #ddd;_x000D_
}
_x000D_
<div class="headercontainer">_x000D_
<div class="tablecontainer">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
Table attribute name_x000D_
<div>Table attribute name</div>_x000D_
</th>_x000D_
<th>_x000D_
Value_x000D_
<div>Value</div>_x000D_
</th>_x000D_
<th>_x000D_
Description_x000D_
<div>Description</div>_x000D_
</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>align</td>_x000D_
<td>left, center, right</td>_x000D_
<td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the alignment of a table according to surrounding text</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>bgcolor</td>_x000D_
<td>rgb(x,x,x), #xxxxxx, colorname</td>_x000D_
<td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the background color for a table</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>border</td>_x000D_
<td>1,""</td>_x000D_
<td>Specifies whether the table cells should have borders or not</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cellpadding</td>_x000D_
<td>pixels</td>_x000D_
<td>Not supported in HTML5. Specifies the space between the cell wall and the cell content</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cellspacing</td>_x000D_
<td>pixels</td>_x000D_
<td>Not supported in HTML5. Specifies the space between cells</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>frame</td>_x000D_
<td>void, above, below, hsides, lhs, rhs, vsides, box, border</td>_x000D_
<td>Not supported in HTML5. Specifies which parts of the outside borders that should be visible</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>rules</td>_x000D_
<td>none, groups, rows, cols, all</td>_x000D_
<td>Not supported in HTML5. Specifies which parts of the inside borders that should be visible</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>summary</td>_x000D_
<td>text</td>_x000D_
<td>Not supported in HTML5. Specifies a summary of the content of a table</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>width</td>_x000D_
<td>pixels, %</td>_x000D_
<td>Not supported in HTML5. Specifies the width of a table</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
Also as a JSFiddle
This will create glowing input fields and textareas:
textarea,textarea:focus,input,input:focus{
transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
border: 1px solid #c4c4c4;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
box-shadow: 0px 0px 8px #d9d9d9;
-moz-box-shadow: 0px 0px 8px #d9d9d9;
-webkit-box-shadow: 0px 0px 8px #d9d9d9;
}
input:focus,textarea:focus {
outline: none;
border: 1px solid #7bc1f7;
box-shadow: 0px 0px 8px #7bc1f7;
-moz-box-shadow: 0px 0px 8px #7bc1f7;
-webkit-box-shadow: 0px 0px 8px #7bc1f7;
}
The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).
Let me provide complete code for execution protected methods via reflection. It supports any types of params including generics, autoboxed params and null values
@SuppressWarnings("unchecked")
public static <T> T executeSuperMethod(Object instance, String methodName, Object... params) throws Exception {
return executeMethod(instance.getClass().getSuperclass(), instance, methodName, params);
}
public static <T> T executeMethod(Object instance, String methodName, Object... params) throws Exception {
return executeMethod(instance.getClass(), instance, methodName, params);
}
@SuppressWarnings("unchecked")
public static <T> T executeMethod(Class clazz, Object instance, String methodName, Object... params) throws Exception {
Method[] allMethods = clazz.getDeclaredMethods();
if (allMethods != null && allMethods.length > 0) {
Class[] paramClasses = Arrays.stream(params).map(p -> p != null ? p.getClass() : null).toArray(Class[]::new);
for (Method method : allMethods) {
String currentMethodName = method.getName();
if (!currentMethodName.equals(methodName)) {
continue;
}
Type[] pTypes = method.getParameterTypes();
if (pTypes.length == paramClasses.length) {
boolean goodMethod = true;
int i = 0;
for (Type pType : pTypes) {
if (!ClassUtils.isAssignable(paramClasses[i++], (Class<?>) pType)) {
goodMethod = false;
break;
}
}
if (goodMethod) {
method.setAccessible(true);
return (T) method.invoke(instance, params);
}
}
}
throw new MethodNotFoundException("There are no methods found with name " + methodName + " and params " +
Arrays.toString(paramClasses));
}
throw new MethodNotFoundException("There are no methods found with name " + methodName);
}
Method uses apache ClassUtils for checking compatibility of autoboxed params
best way to get key/value of object.
let obj = {_x000D_
'key1': 'value1',_x000D_
'key2': 'value2',_x000D_
'key3': 'value3',_x000D_
'key4': 'value4'_x000D_
}_x000D_
Object.keys(obj).map(function(k){ _x000D_
console.log("key with value: "+k +" = "+obj[k]) _x000D_
_x000D_
})_x000D_
_x000D_
import re
fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )
I use uploaded images on my website and I would definitely say option a).
One other thing I'd highly recommend is immediately changing the file name from what the user has named the photo, to something more manageable. For example something with the date and time to uniquely identify each picture.
It also helps to strip the user's file name of any strange characters to avoid future complications.
If you could use something other than 'awk' , then try this instead
echo '1540 "A B"' | cut -d' ' -f2-
-d is a delimiter, -f is the field to cut and with -f2- we intend to cut the 2nd field until end.
Just had this issue deploying a new app to an old IIS box. The investigation led to the v4.5.1 run-time being installed but the app requiring v4.5.2
Nothing apart from installing the correct version of ASP .Net run-time was required.
One alternative would be a KeyedCollection if the key is embedded in the value.
Just create a basic implementation in a sealed class to use.
So to replace Dictionary<string, int>
(which isn't a very good example as there isn't a clear key for a int).
private sealed class IntDictionary : KeyedCollection<string, int>
{
protected override string GetKeyForItem(int item)
{
// The example works better when the value contains the key. It falls down a bit for a dictionary of ints.
return item.ToString();
}
}
KeyedCollection<string, int> intCollection = new ClassThatContainsSealedImplementation.IntDictionary();
intCollection.Add(7);
int valueByIndex = intCollection[0];
You can for example do this in this way (full code with exceptions handlig):
BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("myfile.txt"));
String str;
while ((str = in.readLine()) != null) {
myList.add(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
It is important to define an id in the model
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Model(model => model.Id(p => p.id))
)
Try this:
string command = "...";
var process = Process.Start(command);
process.WaitForExit();
You can use ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
ObjectClass object = objectMapper.readValue(data, ObjectClass.class);
For muting library("name_of_library")
codes, meanly just showing the codes, {r loadlib, echo=T, results='hide', message=F, warning=F}
is great. And imho a better way than library(package, warn.conflicts=F, quietly=T)
Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:
private DataTable LoadExcelData(string fileName)
{
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);
myCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
return dt;
}
You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.
The easy way, try uname()
If that does not work, use gethostname() then gethostbyname() and finally gethostbyaddr()
The h_name of hostent{} should be your FQDN
You can use usort
with anonymous function, e.g.
usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
For something with 2 parameters, you could use BiFunction
. If you need more, you can define your own function interface, like so:
@FunctionalInterface
public interface FourParameterFunction<T, U, V, W, R> {
public R apply(T t, U u, V v, W w);
}
If there is more than one parameter, you need to put parentheses around the argument list, like so:
FourParameterFunction<String, Integer, Double, Person, String> myLambda = (a, b, c, d) -> {
// do something
return "done something";
};
I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.
Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
Brighams answer uses literal regexp
.
Solution with a Regex object.
var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');
TRY IT HERE : JSFiddle Working Example
Just read the docs:
This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.
This exception can be thrown during any interaction with the InitialContext, not only when the InitialContext is constructed. For example, the implementation of the initial context might lazily retrieve the context only when actual methods are invoked on it. The application should not have any dependency on when the existence of an initial context is determined.
But this is explained much better in the docs for InitialContext
when nothing else works, open a new terminal then:
$ ps aux | grep attach
username <pid_here> .............. 0:00 docker attach <CONTAINER_HASH_HERE>
username <another_pid> .............. 0:00 grep --color=auto attach
$ kill -9 <pid_here>
More based on the feeling, but this is the error you would get if you missed to declare a bean in the context configuration, so try adding
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
Perhaps create a shared Fruit
interface that provides isDecayed. fruits
is now of type Fruit[]
so the type can be explicit. Like this:
interface Fruit {
isDecayed: boolean;
}
interface Apple extends Fruit {
color: string;
}
interface Pear extends Fruit {
weight: number;
}
interface FruitBasket {
apples: Apple[];
pears: Pear[];
}
const fruitBasket: FruitBasket = { apples: [], pears: [] };
const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears';
const fruits: Fruit[] = fruitBasket[key];
const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);
Working with just one selector:
select {
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 5px;
height: 34px;
background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
-webkit-appearance: none;
background-position-x: 244px;
}
My situation was settings text color in the options menu (main app menu showed on menu button press).
Tested in API 16 with appcompat-v7-27.0.2 library, AppCompatActivity
for MainActivity
and AppCompat
theme for the application in AndroidManifest.xml.
styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="actionBarPopupTheme">@style/PopupTheme</item>
</style>
<style name="PopupTheme" parent="@style/ThemeOverlay.AppCompat.Light">
<item name="android:textColorSecondary">#f00</item>
</style>
Don't know if that textColorSecondary
affects other elements but it controls the menu text color.
I searched some examples on the topic but all ready-to-use snippets didn't work.
So I wanted to investigate it with the source code for the appcompat-v7 library (specifically with the res folder of the .aar package).
Though in my case I used Eclipse with exploded .aar dependencies. So I could change the default styles and check the results. Don't know how to explode the libraries to use with Gradle or Android Studio directly. It deserves another thread of investigation.
So my purpose was so find which color in the res/values/values.xml file is used for the menu text (I was almost sure the color was there).
#f00
value to all of them.secondary_text_default_material_light
color item.@color/abc_secondary_text_material_light
.Base.ThemeOverlay.AppCompat.Light
and Platform.AppCompat.Light
.android:textColorSecondary
and android:textColorTertiary
in the Base.ThemeOverlay.AppCompat.Light
.android:textColorSecondary
.Theme.AppCompat.Light
and not the ThemeOverlay.AppCompat.Light
).Base.ThemeOverlay.AppCompat.Light
. It had a child ThemeOverlay.AppCompat.Light
.ThemeOverlay.AppCompat.Light
I found its usage in the Base.Theme.AppCompat.Light.DarkActionBar
theme as the actionBarPopupTheme
attribute value.Theme.AppCompat.Light.DarkActionBar
was a child of the found Base.Theme.AppCompat.Light.DarkActionBar
so I could use that attribute in my styles.xml without problems.ThemeOverlay.AppCompat.Light
and changed the android:textColorSecondary
attribute.Try this
void Function()
{
while (condition)
{
await Task.Delay(1);
}
}
This will make the program wait until the condition is not true. You can just invert it by adding a "!" infront of the condition so that it will wait until the condition is true.
well this might be late but it will help. You can access the database without rooting your device through adb
start the adb using cmd and type the following commands
-run-as com.your.package
-shell@android:/data/data/com.your.package $ ls
cache
databases
lib
shared_prefs
Now you can open from here on.
No amount of reset and cleaning seemed to have any effect on untracked and modified files in my local git repo (I tried all the options above). My only solution to this was to rm the local repo and re-clone it from the remote.
Fortunately I didn't have any other branches I cared about.
I was able to resolve this by using my calling my high order component before exporting the class component. My problem was specifically using react-i18next
and its withTranslation method, but here was the solution:
export default withTranslation()(Header);
And then I was able to call the class Component as originally I had hoped:
<Header someProp={someValue} />
I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries: select
, group_by
, etc. You'll add a plus select: SQL_CALC_FOUND_ROWS user_id
. After this query run a query: SELECT FOUND_ROWS()
. This will return the desired number.
count of the contained lists in the outmost list
int count = data.size();
lambda to get the count of the contained inner lists
int count = data.stream().collect( summingInt(l -> l.size()) );
An update to @Aliostads answer using the more moden IHttpActionResult
introduced in Web API 2.
public class TryController : ApiController
{
public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return StatusCode(HttpStatusCode.NotModified);
// If you would like to return a Http Status code with any object instead:
// return Content(HttpStatusCode.InternalServerError, "My Message");
}
return Ok(user);
}
}
Try out below code snippet:
var list = [];
var text;
function update() {
console.log(list);
for (var i = 0; i < list.length; i++) {
console.log( i );
var letters;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(list[i]));
ul.appendChild(li);
letters += "<li>" + list[i] + "</li>";
}
document.getElementById("list").innerHTML = letters;
}
function myFunction() {
text = prompt("enter TODO");
list.push(text);
update();
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}
Since JavaScript FileList is readonly and cannot be manipulated directly,
BEST METHOD
You will have to loop through the input.files
while comparing it with the index
of the file you want to remove. At the same time, you will use new DataTransfer()
to set a new list of files excluding the file you want to remove from the file list.
With this approach, the value of the input.files
itself is changed.
removeFileFromFileList(index) {
const dt = new DataTransfer()
const input = document.getElementById('files')
const { files } = input
for (let i = 0; i < files.length; i++) {
const file = files[i]
if (index !== i) dt.items.add(file) // here you exclude the file. thus removing it.
input.files = dt.files
}
}
ALTERNATIVE METHOD
Another simple method is to convert the FileList into an array and then splice it.
But this approach will not change the input.files
const input = document.getElementById('files')
// as an array, u have more freedom to transform the file list using array functions.
const fileListArr = Array.from(input.files)
fileListArr.splice(index, 1) // here u remove the file
console.log(fileListArr)
try:
parent.childNodes[1].style.color = "rgb(155, 102, 102)";
Or
parent.childNodes[1].style.color = "#"+(155).toString(16)+(102).toString(16)+(102).toString(16);
Not sure about Win but n *nix (OS X, Linux, etc.) its in ~/.subversion
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
System32 is where Windows historically placed all 32bit DLLs, and System was for the 16bit DLLs. When microsoft created the 64 bit OS, everyone I know of expected the files to reside under System64, but Microsoft decided it made more sense to put 64bit files under System32. The only reasoning I have been able to find, is that they wanted everything that was 32bit to work in a 64bit Windows w/o having to change anything in the programs -- just recompile, and it's done. The way they solved this, so that 32bit applications could still run, was to create a 32bit windows subsystem called Windows32 On Windows64. As such, the acronym SysWOW64 was created for the System directory of the 32bit subsystem. The Sys is short for System, and WOW64 is short for Windows32OnWindows64.
Since windows 16 is already segregated from Windows 32, there was no need for a Windows 16 On Windows 64 equivalence. Within the 32bit subsystem, when a program goes to use files from the system32 directory, they actually get the files from the SysWOW64 directory. But the process is flawed.
It's a horrible design. And in my experience, I had to do a lot more changes for writing 64bit applications, that simply changing the System32 directory to read System64 would have been a very small change, and one that pre-compiler directives are intended to handle.
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
I faced the same issue(404 on a newly set up GitHub pages website) yesterday. I tried many methods such as switching a new theme etc. But it seems that it still did not work on my case. I finally figured it out by switching the branch of GitHub pages website to another branch, click save. Wait for a while and switch it back again. Then the problem was suddenly solved.
http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css
Line 11:
.postItem img {
height: auto;
width: 450px;
}
You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:
<img src="theSource" style="width:30px;" />
Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.
Add this to your main CSS:
table td {
border-top: none !important;
}
Use this for newer versions of bootstrap:
.table th, .table td {
border-top: none !important;
}
An even simpler solution would be this (IF you are targeting ALL number inputs in a particular form):
//limit number input decimal places to two
$(':input[type="number"]').change(function(){
this.value = parseFloat(this.value).toFixed(2);
});
To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.
Here's a practical example (build a dataset from your current location):
$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])
dir | foreach {
$dr = $ds.Tables["tblTest"].NewRow()
$dr["Name"] = $_.name
$dr["Path"] = $_.fullname
$ds.Tables["tblTest"].Rows.Add($dr)
}
$ds.Tables["tblTest"]
$ds.Tables["tblTest"]
is an object that you can manipulate just like any other Powershell object:
$ds.Tables["tblTest"] | foreach {
write-host 'Name value is : $_.name
write-host 'Path value is : $_.path
}
Add semi-colons ;
to the end of the function calls in order for them both to work.
<input id="btn" type="button" value="click" onclick="pay(); cls();"/>
I don't believe the last one is required but hey, might as well add it in for good measure.
Here is a good reference from SitePoint http://reference.sitepoint.com/html/event-attributes/onclick
Try this
select count(*) from table where cast(col as double) is null;
public static JSONObject updateJson(JSONObject obj, String keyString, String newValue) throws Exception {
JSONObject json = new JSONObject();
// get the keys of json object
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if the key is a string, then update the value
if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
if ((key.equals(keyString))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
updateJson(obj.getJSONObject(key), keyString, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
updateJson(jArray.getJSONObject(i), keyString, newValue);
}
}
}
return obj;
}
In python 3.6 I got the value of last key from the following code
list(dict.keys())[-1]
CMP
subtracts the operands and sets the flags. Namely, it sets the zero flag if the difference is zero (operands are equal).
TEST
sets the zero flag, ZF
, when the result of the AND operation is zero. If two operands are equal, their bitwise AND is zero when both are zero. TEST
also sets the sign flag, SF
, when the most significant bit is set in the result, and the parity flag, PF
, when the number of set bits is even.
JE
[Jump if Equals] tests the zero flag and jumps if the flag is set. JE
is an alias of JZ
[Jump if Zero] so the disassembler cannot select one based on the opcode. JE
is named such because the zero flag is set if the arguments to CMP
are equal.
So,
TEST %eax, %eax
JE 400e77 <phase_1+0x23>
jumps if the %eax
is zero.
public String hashString(String s) throws NoSuchAlgorithmException {
byte[] hash = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
hash = md.digest(s.getBytes());
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.length; ++i) {
String hex = Integer.toHexString(hash[i]);
if (hex.length() == 1) {
sb.append(0);
sb.append(hex.charAt(hex.length() - 1));
} else {
sb.append(hex.substring(hex.length() - 2));
}
}
return sb.toString();
}
If website on small devices behavior like desktop screen then you have to put this meta tag into header before
<meta name="viewport" content="width=device-width, initial-scale=1">
For media queries you can set this as
this will cover your all mobile/cellphone widths
@media only screen and (min-width: 200px) and (max-width: 767px) {
//Put your CSS here for 200px to 767px width devices (cover all width between 200px to 767px //
}
For iPad and iPad pro you have to use
@media only screen and (min-width: 768px) and (max-width: 1024px) {
//Put your CSS here for 768px to 1024px width devices(covers all width between 768px to 1024px //
}
If you want to add css for Landscape mode you can add this
and (orientation : landscape)
@media only screen and (min-width: 200px) and (max-width: 767px) and (orientation : portrait) {
//Put your CSS here for 200px to 767px width devices (cover all mobile portrait width //
}
You can remove the first character of a string using substring
:
var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"
To remove all 0's at the start of the string:
var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}
I note you suggested this formula
=IF(ISNUMBER(FIND("RuhrP";F9));LOOKUP(A9;Ruhrpumpen!A$5:A$100;Ruhrpumpen!I$5:I$100);"")
.....but LOOKUP
isn't appropriate here because I assume you want an exact match (LOOKUP won't guarantee that and also data in lookup range has to be sorted), so VLOOKUP
or INDEX/MATCH
would be better....and you can also use IFERROR to avoid the IF function, i.e
=IFERROR(VLOOKUP(A9;Ruhrpumpen!A$5:Z$100;9;0);"")
Note: VLOOKUP always looks up the lookup value (A9) in the first column of the "table array" and returns a value from the nth column of the "table array" where n is defined by col_index_num, in this case 9
INDEX/MATCH is sometimes more flexible because you can explicitly define the lookup column and the return column (and return column can be to the left of the lookup column which can't be the case in VLOOKUP), so that would look like this:
=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH(A9;Ruhrpumpen!A$5:A$100;0));"")
INDEX/MATCH also allows you to more easily return multiple values from different columns, e.g. by using $ signs in front of A9 and the lookup range Ruhrpumpen!A$5:A$100, i.e.
=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH($A9;Ruhrpumpen!$A$5:$A$100;0));"")
this version can be dragged across to get successive values from column I, column J, column K etc.....
As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.
public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
{
return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
}
Add class numOnly for the textbox,
$(document).on("input", ".numOnly", function(e) {
this.value = this.value.replace(/[^0-9\$]/g,'');
if(this.value!=""){
alert('Integer Number.');
}else{
alert('Not an Integer Number.');
}
});
It works for me.. Try this one
You can use keypres,keyup,keydown etc., instead input.
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
A key can be a function that returns a tuple:
s = sorted(s, key = lambda x: (x[1], x[2]))
Or you can achieve the same using itemgetter
(which is faster and avoids a Python function call):
import operator
s = sorted(s, key = operator.itemgetter(1, 2))
And notice that here you can use sort
instead of using sorted
and then reassigning:
s.sort(key = operator.itemgetter(1, 2))
This is the code which can help u but dont forget to include message ui framewark and include delegates method MFMailComposeViewControllerDelegate
-(void)EmailButtonACtion{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigation_bg_iPhone.png"] forBarMetrics:UIBarMetricsDefault];
controller.navigationBar.tintColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];
[controller setSubject:@""];
[controller setMessageBody:@" " isHTML:YES];
[controller setToRecipients:[NSArray arrayWithObjects:@"",nil]];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
UIImage *ui = resultimg.image;
pasteboard.image = ui;
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(ui)];
[controller addAttachmentData:imageData mimeType:@"image/png" fileName:@" "];
[self presentViewController:controller animated:YES completion:NULL];
}
else{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"alrt" message:nil delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil] ;
[alert show];
}
}
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[MailAlert show];
switch (result)
{
case MFMailComposeResultCancelled:
MailAlert.message = @"Email Cancelled";
break;
case MFMailComposeResultSaved:
MailAlert.message = @"Email Saved";
break;
case MFMailComposeResultSent:
MailAlert.message = @"Email Sent";
break;
case MFMailComposeResultFailed:
MailAlert.message = @"Email Failed";
break;
default:
MailAlert.message = @"Email Not Sent";
break;
}
[self dismissViewControllerAnimated:YES completion:NULL];
[MailAlert show];
}
select *
from tbl1
where
datetime_column >=
DATEADD(m, -6, convert(date, convert(varchar(6), getdate(),112) + '01'))
You can use plain javascript - Array.prototype.filter()
$scope.items = $scope.items.filter(function(item) {
return item.name !== 'ted';
});
I had the same problem and then figured out the cause. I was trying to type in a span tag instead of an input tag. My XPath was written with a span tag, which was a wrong thing to do. I reviewed the Html for the element and found the problem. All I then did was to find the input tag which happens to be a child element. You can only type in an input field if your XPath is created with an input tagname
I developed a maven plugin that can both, be run from CLI as a plugin goal, or import as dependency and programmatically use the parser, @see Main#main()
to get the idea on how.
It renders PlantUML src code of desired packages recursively that you can edit manually if needed (hopefully you won't). Then, by pasting the code in the plantUML page, or by downloading plant's jar you can render the UML diagram as a png image.
Check it out here https://github.com/juanmf/Java2PlantUML
Any contribution is more than welcome. It has a set of filters that customize output but I didn't expose these yet in the plugin CLI params.
It's important to note that it's not limited to your *.java files, it can render UML diagrams src from you maven dependencies as well. This is very handy to understand libraries you depend on. It actually inspects compiled classes with reflection so no source needed
Be the 1st to star it at GitHub :P
It looks like you're trying to scale the background image? There's a great article in the reference bellow where you can use css3 to achieve this.
And if I miss-read the question then I humbly accept the votes down. (Still good to know though)
Please consider the following code:
#some_div_or_body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
This will work on all major browsers, of course it doesn't come easy on IE. There are some workarounds however such as using Microsoft's filters:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
There are some alternatives that can be used with a little bit peace of mind by using jQuery:
HTML
<img src="images/bg.jpg" id="bg" alt="">
CSS
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
jQuery:
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
I hope this helps!
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
To answer your immutable question:
Collections.singletonList
will create an immutable List.
An immutable List (also referred to as an unmodifiable List) cannot have it's contents changed. The methods to add or remove items will throw exceptions if you try to alter the contents.
A singleton List contains only that item and cannot be altered.
This answer assumes you are concerned with having a system that works correctly, over and above having a system that is minimum cost or fast; most people playing with radioactive things value correctness / safety over speed / cost
Several people have suggested hardware changes you can make (fine - there's lots of good stuff here in answers already and I don't intend repeating all of it), and others have suggested redundancy (great in principle), but I don't think anyone has suggested how that redundancy might work in practice. How do you fail over? How do you know when something has 'gone wrong'? Many technologies work on the basis everything will work, and failure is thus a tricky thing to deal with. However, some distributed computing technologies designed for scale expect failure (after all with enough scale, failure of one node of many is inevitable with any MTBF for a single node); you can harness this for your environment.
Here are some ideas:
Ensure that your entire hardware is replicated n
times (where n
is greater than 2, and preferably odd), and that each hardware element can communicate with each other hardware element. Ethernet is one obvious way to do that, but there are many other far simpler routes that would give better protection (e.g. CAN). Minimise common components (even power supplies). This may mean sampling ADC inputs in multiple places for instance.
Ensure your application state is in a single place, e.g. in a finite state machine. This can be entirely RAM based, though does not preclude stable storage. It will thus be stored in several place.
Adopt a quorum protocol for changes of state. See RAFT for example. As you are working in C++, there are well known libraries for this. Changes to the FSM would only get made when a majority of nodes agree. Use a known good library for the protocol stack and the quorum protocol rather than rolling one yourself, or all your good work on redundancy will be wasted when the quorum protocol hangs up.
Ensure you checksum (e.g. CRC/SHA) your FSM, and store the CRC/SHA in the FSM itself (as well as transmitting in the message, and checksumming the messages themselves). Get the nodes to check their FSM regularly against these checksum, checksum incoming messages, and check their checksum matches the checksum of the quorum.
Build as many other internal checks into your system as possible, making nodes that detect their own failure reboot (this is better than carrying on half working provided you have enough nodes). Attempt to let them cleanly remove themselves from the quorum during rebooting in case they don't come up again. On reboot have them checksum the software image (and anything else they load) and do a full RAM test before reintroducing themselves to the quorum.
Use hardware to support you, but do so carefully. You can get ECC RAM, for instance, and regularly read/write through it to correct ECC errors (and panic if the error is uncorrectable). However (from memory) static RAM is far more tolerant of ionizing radiation than DRAM is in the first place, so it may be better to use static DRAM instead. See the first point under 'things I would not do' as well.
Let's say you have an 1% chance of failure of any given node within one day, and let's pretend you can make failures entirely independent. With 5 nodes, you'll need three to fail within one day, which is a .00001% chance. With more, well, you get the idea.
Things I would not do:
Underestimate the value of not having the problem to start off with. Unless weight is a concern, a large block of metal around your device is going to be a far cheaper and more reliable solution than a team of programmers can come up with. Ditto optical coupling of inputs of EMI is an issue, etc. Whatever, attempt when sourcing your components to source those rated best against ionizing radiation.
Roll your own algorithms. People have done this stuff before. Use their work. Fault tolerance and distributed algorithms are hard. Use other people's work where possible.
Use complicated compiler settings in the naive hope you detect more failures. If you are lucky, you may detect more failures. More likely, you will use a code-path within the compiler which has been less tested, particularly if you rolled it yourself.
Use techniques which are untested in your environment. Most people writing high availability software have to simulate failure modes to check their HA works correctly, and miss many failure modes as a result. You are in the 'fortunate' position of having frequent failures on demand. So test each technique, and ensure its application actual improves MTBF by an amount that exceeds the complexity to introduce it (with complexity comes bugs). Especially apply this to my advice re quorum algorithms etc.
Setting CommandTimeout to 120 is not recommended. Try using pagination as mentioned above. Setting CommandTimeout to 30 is considered as normal. Anything more than that is consider bad approach and that usually concludes something wrong with the Implementation. Now the world is running on MiliSeconds Approach.
You can't use brew install to upgrade an installed formula. If you want upgrade all of outdated formulas, you can use the command below.
brew outdated | xargs brew upgrade
char a[2]
defines an array of char
's. a
is a pointer to the memory at the beginning of the array and using ==
won't actually compare the contents of a
with 'ab'
because they aren't actually the same types, 'ab'
is integer type. Also 'ab'
should be "ab"
otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.
Something that might be illustrative is looking at the typeid
of 'ab'
:
#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
int some_int =5;
std::cout << typeid('ab').name() << std::endl;
std::cout << typeid(some_int).name() << std::endl;
return 0;
}
on my system this returns:
i
i
showing that 'ab'
is actually evaluated as an int.
If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator ==
overloaded and will do a comparison check when called this way.
If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:
#include <iostream>
#include <string>
using namespace std;
int main(){
string a;
cout<<"enter ab ";
cin>>a;
if(a=="ab"){
cout<<"correct";
}
return 0;
}
This one is due to:
if(a=='ab')
, here, a
is const char*
type (ie : array of char)
'ab'
is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.
Since char
is a primitive type inherited from C, no operator ==
is defined.
the good code should be:
if(strcmp(a,"ab")==0)
, then you'll compare a const char*
to another const char*
using strcmp
.
You need to be running a mail server locally. If this is Unix, enable sendmail If this is Windows install the Simple Mail Transfer Server (not sure if the name is correct) component of IIs. E.g. for windows 2003 follow this: http://msdn.microsoft.com/en-us/library/8b83ac7t.aspx
Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores
In the second version, you're passing the String returned from this.id
. Not the element itself.
So id.value
won't give you what you want.
You would need to pass the element with this
.
doSomething(this)
then:
function(el){
var value = el.value;
...
}
Note: In some browsers, the second one would work if you did:
window[id].value
because element IDs are a global property, but this is not safe.
It makes the most sense to just pass the element with this
instead of fetching it again with its ID.
NOTE: Community Edition doesn't support JEE.
First, you will need to install a local Tomcat server. It sounds like you may have already done this.
Next, on the toolbar at the top of IntelliJ, click the down arrow just to the left of the Run and Debug icons. There will be an option to Edit Configurations. In the resulting popup, click the Add icon, then click Tomcat and Local.
From that dialog, you will need to click the Configure... button next to Application Server to tell IntelliJ where Tomcat is installed.
I'd suggest doing something similar to:
function show_sub(cat) {
if (!cat) {
return false;
}
else if (document.getElementById(cat)) {
var parent = document.getElementById(cat),
sub = parent.getElementsByClassName('sub');
if (sub[0].style.display == 'inline'){
sub[0].style.display = 'none';
}
else {
sub[0].style.display = 'inline';
}
}
}
document.getElementById('cat').onclick = function(){
show_sub(this.id);
};????
Though the above relies on the use of a class
rather than a name
attribute equal to sub
.
As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:
Uncaught TypeError: Object # has no method 'getElementsByName'.
One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName()
, albeit crudely:
function eBCN(elem,classN){
if (!elem || !classN){
return false;
}
else {
var children = elem.childNodes;
for (var i=0,len=children.length;i<len;i++){
if (children[i].nodeType == 1
&&
children[i].className == classN){
var sub = children[i];
}
}
return sub;
}
}
function show_sub(cat) {
if (!cat) {
return false;
}
else if (document.getElementById(cat)) {
var parent = document.getElementById(cat),
sub = eBCN(parent,'sub');
if (sub.style.display == 'inline'){
sub.style.display = 'none';
}
else {
sub.style.display = 'inline';
}
}
}
var D = document,
listElems = D.getElementsByTagName('li');
for (var i=0,len=listElems.length;i<len;i++){
listElems[i].onclick = function(){
show_sub(this.id);
};
}?
This webpage have an explanation and a solution.
The solution is:
To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
function IsMobileNumber(txtMobId) {
var mob = /^[1-9]{1}[0-9]{9}$/;
var txtMobile = document.getElementById(txtMobId);
if (mob.test(txtMobile.value) == false) {
alert("Please enter valid mobile number.");
txtMobile.focus();
return false;
}
return true;
}
Calling Validation Mobile Number Function HTML Code -
I had the same issue while using Microsoft Visual Code with Python 3.7.3 64-bit('base':conda)as my python interpreter. Before running any code type the following three commands:
C:/ProgramData/Anaconda3/Scripts/activate #activate conda Scripts directory
conda activate base #activate conda
& C:/ProgramData/Anaconda3/python.exe #to run python
I just had a similar problem, the DISTINCT keyword works magic:
INSERT INTO Table2(Id, Name) SELECT DISTINCT Id, Name FROM Table1
Here is a full example comparing 2 fields in an object, one String and one int, also using Collator to sort.
public class Test {
public static void main(String[] args) {
Collator myCollator;
myCollator = Collator.getInstance(Locale.US);
List<Item> items = new ArrayList<Item>();
items.add(new Item("costrels", 1039737, ""));
items.add(new Item("Costs", 1570019, ""));
items.add(new Item("costs", 310831, ""));
items.add(new Item("costs", 310832, ""));
Collections.sort(items, new Comparator<Item>() {
@Override
public int compare(final Item record1, final Item record2) {
int c;
//c = record1.item1.compareTo(record2.item1); //optional comparison without Collator
c = myCollator.compare(record1.item1, record2.item1);
if (c == 0)
{
return record1.item2 < record2.item2 ? -1
: record1.item2 > record2.item2 ? 1
: 0;
}
return c;
}
});
for (Item item : items)
{
System.out.println(item.item1);
System.out.println(item.item2);
}
}
public static class Item
{
public String item1;
public int item2;
public String item3;
public Item(String item1, int item2, String item3)
{
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
}
}
}
Output:
costrels 1039737
costs 310831
costs 310832
Costs 1570019
If you want to keep using sendSynchronousRequest i work in this solution:
FailCertificateDelegate *fcd=[[FailCertificateDelegate alloc] init];
NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] init]];
[c start];
NSData *d=[fcd getData];
you can see it here: Objective-C SSL Synchronous Connection
This works for Python 2.6.6
a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result
prints
{'a': 2, 'b': 1}
Not every jar file is executable.
Now, you need to import the classes, which are there under the jar, in your java file. For example,
import org.xml.sax.SAXException;
If you are working on an IDE, then you should refer its documentation. Or at least specify which one you are using here in this thread. It would definitely enable us to help you further.
And if you are not using any IDE, then please look at javac -cp option. However, it's much better idea to package your program in a jar
file, and include all the required jar
s within that. Then, in order to execute your jar
, like,
java -jar my_program.jar
you should have a META-INF/MANIFEST.MF
file in your jar
. See here, for how-to.
How about this method:
Set a field in the first object to a new value. If the same field in the second object has the same value, it's probably the same instance. Otherwise, exit as different.
Now set the field in the first object to a different new value. If the same field in the second object has changed to the different value, it's definitely the same instance.
Don't forget to set field in the first object back to it's original value on exit.
Problems?
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
I would recommend identifying the functionality you need from any subclasses, and make a generic method to cast into the right subclass.
I had this same problem, but really didn't feel like creating some mapping class or importing a library.
Let's say you need the 'Authenticate' method to take behavior from the right subclass. In your NetworkClient:
protected bool Authenticate(string username, string password) {
//...
}
protected bool DoAuthenticate<T>(NetworkClient nc, string username, string password) where T : NetworkClient {
//Do a cast into the sub class.
T subInst = (T) nc;
return nc.Authenticate(username, password);
}
You declare the variable as extern
in a common header:
//globals.h
extern int x;
And define it in an implementation file.
//globals.cpp
int x = 1337;
You can then include the header everywhere you need access to it.
I suggest you also wrap the variable inside a namespace
.