.equals(false)
will be slower because you are calling a virtual method on an object rather than using faster syntax and rather unexpected by most of the programmers because code standards that are generally used don't really assume you should be doing that check via .equals(false)
method.
Well pandas use bitwise &
|
and each condition should be wrapped in a ()
For example following works
data_query = data[(data['year'] >= 2005) & (data['year'] <= 2010)]
But the same query without proper brackets does not
data_query = data[(data['year'] >= 2005 & data['year'] <= 2010)]
Just toggle each time it is called
this.boolValue = !this.boolValue;
Try this:-
private String getWhoozitYs(){
StringBuffer sb = new StringBuffer();
boolean stop = generator.nextBoolean();
if(stop)
{
sb.append("y");
getWhoozitYs();
}
return sb.toString();
}
class BooleanTester
{
boolean primitive;
Boolean object;
public static void main(String[] args) {
BooleanTester booleanTester = new BooleanTester();
System.out.println("primitive: " + booleanTester.getPrimitive());
System.out.println("object: " + booleanTester.getObject());
}
public boolean getPrimitive() {
return primitive;
}
public Boolean getObject() {
return object;
}
}
output:
primitive: false
object: null
This seems obvious but I had a situation where Jackson, while serializing an object to JSON, was throwing an NPE after calling a getter, just like this one, that returns a primitive boolean which was not assigned. This led me to believe that Jackson was receiving a null and trying to call a method on it, hence the NPE. I was wrong.
Moral of the story is that when Java allocates memory for a primitive, that memory has a value even if not initialized, which Java equates to false for a boolean. By contrast, when allocating memory for an uninitialized complex object like a Boolean, it allocates only space for a reference to that object, not the object itself - there is no object in memory to refer to - so resolving that reference results in null.
I think that strictly speaking, "defaults to false" is a little off the mark. I think Java does not allocate the memory and assign it a value of false until it is explicitly set; I think Java allocates the memory and whatever value that memory happens to have is the same as the value of 'false'. But for practical purpose they are the same thing.
Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:
def rps():
# Code to determine if player wins
if player_wins:
return True
return False
Then, just assign a value to the variable outside this function like so:
player_wins = rps()
It will be assigned the return value (either True or False) of the function you just called.
After the comments, I decided to add that idiomatically, this would be better expressed thus:
def rps():
# Code to determine if player wins, assigning a boolean value (True or False)
# to the variable player_wins.
return player_wins
pw = rps()
This assigns the boolean value of player_wins
(inside the function) to the pw
variable outside the function.
In python, not
is a boolean operator which gets the opposite of a value:
>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False
And True == 1
and False == 0
(if you need to convert it to an integer, you can use int()
)
If I can throw my hat into the ring, I think there is a cleaner way than the existing answers to reuse the radio button functionality.
Let's say you have the following property in your ViewModel:
Public Class ViewModel
<Display(Name:="Do you like Cats?")>
Public Property LikesCats As Boolean
End Class
You can expose that property through a reusable editor template:
First, create the file Views/Shared/EditorTemplates/YesNoRadio.vbhtml
Then add the following code to YesNoRadio.vbhtml:
@ModelType Boolean?
<fieldset>
<legend>
@Html.LabelFor(Function(model) model)
</legend>
<label>
@Html.RadioButtonFor(Function(model) model, True) Yes
</label>
<label>
@Html.RadioButtonFor(Function(model) model, False) No
</label>
</fieldset>
You can call the editor for the property by manually specifying the template name in your View:
@Html.EditorFor(Function(model) model.LikesCats, "YesNoRadio")
Pros:
Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."
Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...
Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as int
s that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h>
only require zero or non-zero, not necessarily zero or one.
If you cast that to bool
, zero will convert to false, and non-zero to true (as you'd expect).
You could use _Bool, but the return value must be an integer (1 for true, 0 for false). However, It's recommended to include and use bool as in C++, as said in this reply from daniweb forum, as well as this answer, from this other stackoverflow question:
_Bool: C99's boolean type. Using _Bool directly is only recommended if you're maintaining legacy code that already defines macros for bool, true, or false. Otherwise, those macros are standardized in the header. Include that header and you can use bool just like you would in C++.
Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.
int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
case 0: yourBool = false; break;
case 1: yourBool = true; break;
default:
throw new InvalidOperationException("Integer value is not valid");
}
The out-of-the-box Convert
won't check this; nor will yourInteger (==|!=) (0|1)
.
We can use enum type for this.We don't require a library. For example
enum {false,true};
the value for false
will be 0 and the value for true
will be 1.
I know you asked for non-looping solutions, but the only solutions I can come up with probably loop internally anyway:
map(int,y)
or:
[i*1 for i in y]
or:
import numpy
y=numpy.array(y)
y*1
You can use Bit
DataType in SQL Server to store boolean data.
You can cast this value to a Boolean in a very simple manner: by comparing it with integer value 1, like this:
boolean multipleContacts = new Integer(1).equals(jsonObject.get("MultipleContacts"))
If it is a String, you could do this:
boolean multipleContacts = "1".equals(jsonObject.get("MultipleContacts"))
you could get your clock() value and check if it is odd or even. I dont know if it is %50 of true
And you can custom-create your random function:
static double s=System.nanoTime();//in the instantiating of main applet
public static double randoom()
{
s=(double)(((555555555* s+ 444444)%100000)/(double)100000);
return s;
}
numbers 55555.. and 444.. are the big numbers to get a wide range function please ignore that skype icon :D
If you don't mind the boolean being converted to a number (that is either 0 or 1), you can use the Bitwise XOR Assignment Operator. Like so:
bool ^= true; //- toggle value.
This is especially good if you use long, descriptive boolean names, EG:
var inDynamicEditMode = true; // Value is: true (boolean)
inDynamicEditMode ^= true; // Value is: 0 (number)
inDynamicEditMode ^= true; // Value is: 1 (number)
inDynamicEditMode ^= true; // Value is: 0 (number)
This is easier for me to scan than repeating the variable in each line.
This method works in all (major) browsers (and most programming languages).
No, there is no bool
in ISO C90.
Here's a list of keywords in standard C (not C99):
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
static
struct
switch
typedef
union
unsigned
void
volatile
while
Here's an article discussing some other differences with C as used in the kernel and the standard: http://www.ibm.com/developerworks/linux/library/l-gcc-hacks/index.html
bool
is just a macro that expands to _Bool
. You can use _Bool
with no #include
very much like you can use int
or double
; it is a C99 keyword.
The macro is defined in <stdbool.h>
along with 3 other macros.
The macros defined are
bool
: macro expands to _Bool
false
: macro expands to 0
true
: macro expands to 1
__bool_true_false_are_defined
: macro expands to 1
You can use shFlags.
It gives you the option to define: DEFINE_bool
Example:
DEFINE_bool(big_menu, true, "Include 'advanced' options in the menu listing");
From the command line you can define:
sh script.sh --bigmenu
sh script.sh --nobigmenu # False
Working in Rails 5
ActiveModel::Type::Boolean.new.cast('t') # => true
ActiveModel::Type::Boolean.new.cast('true') # => true
ActiveModel::Type::Boolean.new.cast(true) # => true
ActiveModel::Type::Boolean.new.cast('1') # => true
ActiveModel::Type::Boolean.new.cast('f') # => false
ActiveModel::Type::Boolean.new.cast('0') # => false
ActiveModel::Type::Boolean.new.cast('false') # => false
ActiveModel::Type::Boolean.new.cast(false) # => false
ActiveModel::Type::Boolean.new.cast(nil) # => nil
Yes, there is a bool
data type (which inherits from int
and has only two values: True
and False
).
But also Python has the boolean-able
concept for every object, which is used when function bool([x])
is called.
See more: object.nonzero and boolean-value-of-objects-in-python.
T
and TRUE
are True, F
and FALSE
are False. T
and F
can be redefined, however, so you should only rely upon TRUE
and FALSE
. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.
There is no format specifier for bool. You can print it using some of the existing specifiers for printing integral types or do something more fancy:
printf("%s", x?"true":"false");
You can use Boolean / boolean. Simplicity is the way to go. If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).
With primitives you guarantee that you will not pass null values.
You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):
public static void main(String[] args) throws Exception {
Boolean b = true ? returnsNull() : false; // NPE on this line.
System.out.println(b);
}
public static Boolean returnsNull() {
return null;
}
Use Boolean when you need an object, eg:
The best option is 0 and 1 (as numbers - another answer suggests 0 and 1 as CHAR for space-efficiency but that's a bit too twisted for me), using NOT NULL and a check constraint to limit contents to those values. (If you need the column to be nullable, then it's not a boolean you're dealing with but an enumeration with three values...)
Advantages of 0/1:
select sum(is_ripe) from bananas
instead of select count(*) from bananas where is_ripe = 'Y'
or even (yuk) select sum(case is_ripe when 'Y' then 1 else 0) from bananas
Advantages of 'Y'/'N':
Another poster suggested 'Y'/null for performance gains. If you've proven that you need the performance, then fair enough, but otherwise avoid since it makes querying less natural (some_column is null
instead of some_column = 0
) and in a left join you'll conflate falseness with nonexistent records.
You need a mechanism which avoids busy-waiting. The old wait/notify
mechanism is fraught with pitfalls so prefer something from the java.util.concurrent
library, for example the CountDownLatch
:
public final CountDownLatch latch = new CountDownLatch(1);
public void run () {
latch.await();
...
}
And at the other side call
yourRunnableObj.latch.countDown();
However, starting a thread to do nothing but wait until it is needed is still not the best way to go. You could also employ an ExecutorService
to which you submit as a task the work which must be done when the condition is met.
Apart from "readability", no. They're functionally equivalent.
("Readability" is in quotes because I hate == false
and find !
much more readable. But others don't.)
They are the same. Boolean helps simplify conversion back and forth between C# and VB.Net. Most C# programmers tend to prefer 'bool', but if you are in a shop where there's a lot of both VB.Net and C# then you may prefer Boolean because it works in both places.
This question has been answered but I figured I'd throw in my $0.02.
I often use a CHAR(0)
, where '' == true and NULL == false
.
From mysql docs:
CHAR(0)
is also quite nice when you need a column that can take only two values: A column that is defined asCHAR(0)
NULL
occupies only one bit and can take only the valuesNULL
and''
(the empty string).
Use:
bool(distutils.util.strtobool(some_string))
True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.
Be aware that distutils.util.strtobool()
returns integer representations and thus it needs to be wrapped with bool()
to get Boolean values.
The standard streams have a boolalpha
flag that determines what gets displayed -- when it's false, they'll display as 0
and 1
. When it's true, they'll display as false
and true
.
There's also an std::boolalpha
manipulator to set the flag, so this:
#include <iostream>
#include <iomanip>
int main() {
std::cout<<false<<"\n";
std::cout << std::boolalpha;
std::cout<<false<<"\n";
return 0;
}
...produces output like:
0
false
For what it's worth, the actual word produced when boolalpha
is set to true is localized--that is, <locale>
has a num_put
category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true
and false
as they're represented in that locale. For example,
#include <iostream>
#include <iomanip>
#include <locale>
int main() {
std::cout.imbue(std::locale("fr"));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux
instead of false
. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false
for every language I've checked.
The names that get used are defined in a numpunct
facet though, so if you really want them to print out correctly for particular language, you can create a numpunct
facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:
#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>
class my_fr : public std::numpunct< char > {
protected:
char do_decimal_point() const { return ','; }
char do_thousands_sep() const { return '.'; }
std::string do_grouping() const { return "\3"; }
std::string do_truename() const { return "vrai"; }
std::string do_falsename() const { return "faux"; }
};
int main() {
std::cout.imbue(std::locale(std::locale(), new my_fr));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
And the result is (as you'd probably expect):
0
faux
The most complete, concise definition of false I've come across is:
Anything that stringifies to the empty string or the string
0
is false. Everything else is true.
Therefore, the following values are false:
Keep in mind that an empty list literal evaluates to an undefined value in scalar context, so it evaluates to something false.
A note on "true zeroes"
While numbers that stringify to 0
are false, strings that numify to zero aren't necessarily. The only false strings are 0
and the empty string. Any other string, even if it numifies to zero, is true.
The following are strings that are true as a boolean and zero as a number:
"0.0"
"0E0"
"00"
"+0"
"-0"
" 0"
"0\n"
".0"
"0."
"0 but true"
"\t00"
"\n0e1"
"+0.e-9"
Scalar::Util::looks_like_number
returns false. (e.g. "abc"
)the easiest thing to do is this:
$str = 'TRUE';
$boolean = strtolower($str) == 'true' ? true : false;
var_dump($boolean);
Doing it this way, you can loop through a series of 'true', 'TRUE', 'false' or 'FALSE' and get the string value to a boolean.
See oracle docs
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
If you want to obfuscate, use this:
System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0
0 values of basic types (1)(2)map to false
.
Other values map to true
.
This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.
It's a common error to assume that as function return values, false
indicates failure. But in particular from main
it's false
that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.
There's no need to cast to bool
for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x
, works nicely. One can read !!
as a “convert to bool
” operator, much as -->
can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)
1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false
; any other value is converted to true
. For direct-initialization (8.5), a prvalue of type std::nullptr_t
can be converted to a prvalue of type bool
; the resulting value is false
.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”
I almost never use Boolean
because its semantics are vague and obscure. Basically you have 3-state logic: true, false or unknown. Sometimes it is useful to use it when e.g. you gave user a choice between two values and the user didn't answer at all and you really want to know that information (think: NULLable database column).
I see no reason to convert from boolean
to Boolean
as it introduces extra memory overhead, NPE possibility and less typing. Typically I use awkward BooleanUtils.isTrue()
to make my life a little bit easier with Boolean
.
The only reason for the existence of Boolean
is the ability to have collections of Boolean
type (generics do not allow boolean
, as well as all other primitives).
Please explain why same ng-model
is used? And what value is passed through ng- model
and how it is passed? To be more specific, if I use console.log(color)
what would be the output?
Try (depending on what result type you want):
Boolean boolean1 = Boolean.valueOf("true");
boolean boolean2 = Boolean.parseBoolean("true");
Advantage:
Boolean.TRUE
or Boolean.FALSE
.The official documentation is in the Javadoc.
UPDATED:
Autoboxing could also be used, but it has a performance cost.
I suggest to use it only when you would have to cast yourself, not when the cast is avoidable.
theBoolean ^= true;
Fewer keystrokes if your variable is longer than four letters
Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.
First to answer your question, you set a variable to true or false by assigning True
or False
to it:
myFirstVar = True
myOtherVar = False
If you have a condition that is basically like this though:
if <condition>:
var = True
else:
var = False
then it is much easier to simply assign the result of the condition directly:
var = <condition>
In your case:
match_var = a == b
That line should be sufficient:
BooleanUtils.and(boolean... array)
but to calm the link-only purists:
Performs an and on a set of booleans.
You can use 'True' or 'False' strings for simulate bolean type data.
Select *
From <table>
Where <columna> = 'True'
I think this way maybe slow than just put 1 because it's resolved with Convert_implicit function.
Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values
You can use dict to convert string to boolean. Change this line flag = bool(reader[0])
to:
flag = {'True': True, 'False': False}.get(reader[0], False) # default is False
It's simple code to convert that to all lower case.
Not so simple to convert "true" back to "True", however.
true.ToString().ToLower()
is what I use for xml output.
You neglected to say which version of C you are concerned about. Let's assume it's this one:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
As you can see by reading the specification, the standard definitions of true
and false
are 1 and 0, yes.
If your question is about a different version of C, or about non-standard definitions for true
and false
, then ask a more specific question.
There are several problems.
One is of style; always capitalize class names. This is a universally observed Java convention. Failing to do so confuses other programmers.
Secondly, the line
System.out.println(boolean isLeapYear);
is a syntax error. Delete it.
Thirdly.
You never call the function from your main routine. That is why you never see any reply to the input.
If you're on Linux, or have cygwin available on Windows, you can run the input XML through a simple sed script that will replace <Active>True</Active>
with <Active>true</Active>
, like so:
cat <your XML file> | sed 'sX<Active>True</Active>X<Active>true</Active>X' | xmllint --schema -
If you're not, you can still use a non-validating xslt pocessor (xalan, saxon etc.) to run a simple xslt transformation on the input, and only then pipe it to xmllint.
What the xsl should contain something like below, for the example you listed above (the xslt processor should be 2.0 capable):
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="XML">
<xsl:for-each select="Active">
<xsl:value-of select=" replace(current(), 'True','true')"/>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Even though there is a bool (short for boolean) data type in C++. But in C++, any nonzero value is a true value including negative numbers. A 0 (zero) is treated as false. Where as in JAVA there is a separate data type boolean for true and false.
We're talking about C++ right? Why on earth are we still using macros!?
C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned.
inline const char * const BoolToString(bool b)
{
return b ? "true" : "false";
}
Aside from that I have a few other gripes, particularly with the accepted answer :)
// this is used in C, not C++. if you want to use printf, instead include <cstdio>
//#include <stdio.h>
// instead you should use the iostream libs
#include <iostream>
// not only is this a C include, it's totally unnecessary!
//#include <stdarg.h>
// Macros - not type-safe, has side-effects. Use inline functions instead
//#define BOOL_STR(b) (b?"true":"false")
inline const char * const BoolToString(bool b)
{
return b ? "true" : "false";
}
int main (int argc, char const *argv[]) {
bool alpha = true;
// printf? that's C, not C++
//printf( BOOL_STR(alpha) );
// use the iostream functionality
std::cout << BoolToString(alpha);
return 0;
}
Cheers :)
@DrPizza: Include a whole boost lib for the sake of a function this simple? You've got to be kidding?
I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands
OP, you can convert a string to type Boolean
by using any of the methods stated below:
string sample = "True";
bool myBool = bool.Parse(sample);
///or
bool myBool = Convert.ToBoolean(sample);
bool.Parse
expects one parameter which in this case is sample
, .ToBoolean
also expects one parameter.
You can use TryParse
which is the same as Parse
but it doesn't throw any exception :)
string sample = "false";
Boolean myBool;
if (Boolean.TryParse(sample , out myBool))
{
}
Please note that you cannot convert any type of string to type Boolean
because the value of a Boolean
can only be True
or False
Hope you understand :)
boolarr.sum(axis=1 or axis=0)
axis = 1 will output number of trues in a row and axis = 0 will count number of trues in columns so
boolarr[[true,true,true],[false,false,true]]
print(boolarr.sum(axis=1))
will be (3,1)
If you are sure that your value is not null
you can use third option which is
String str3 = b.toString();
and its code looks like
public String toString() {
return value ? "true" : "false";
}
If you want to be null-safe use String.valueOf(b)
which code looks like
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
so as you see it will first test for null
and later invoke toString()
method on your object.
Calling Boolean.toString(b)
will invoke
public static String toString(boolean b) {
return b ? "true" : "false";
}
which is little slower than b.toString()
since JVM needs to first unbox Boolean
to boolean
which will be passed as argument to Boolean.toString(...)
, while b.toString()
reuses private boolean value
field in Boolean
object which holds its state.
As mentioned above, BOOL is a signed char. bool - type from C99 standard (int).
BOOL - YES/NO. bool - true/false.
See examples:
bool b1 = 2;
if (b1) printf("REAL b1 \n");
if (b1 != true) printf("NOT REAL b1 \n");
BOOL b2 = 2;
if (b2) printf("REAL b2 \n");
if (b2 != YES) printf("NOT REAL b2 \n");
And result is
REAL b1
REAL b2
NOT REAL b2
Note that bool != BOOL. Result below is only ONCE AGAIN - REAL b2
b2 = b1;
if (b2) printf("ONCE AGAIN - REAL b2 \n");
if (b2 != true) printf("ONCE AGAIN - NOT REAL b2 \n");
If you want to convert bool to BOOL you should use next code
BOOL b22 = b1 ? YES : NO; //and back - bool b11 = b2 ? true : false;
So, in our case:
BOOL b22 = b1 ? 2 : NO;
if (b22) printf("ONCE AGAIN MORE - REAL b22 \n");
if (b22 != YES) printf("ONCE AGAIN MORE- NOT REAL b22 \n");
And so.. what we get now? :-)
MySQL does not have internal boolean data type. It uses the smallest integer data type - TINYINT.
The BOOLEAN and BOOL are equivalents of TINYINT(1), because they are synonyms.
Try to create this table -
CREATE TABLE table1 (
column1 BOOLEAN DEFAULT NULL
);
Then run SHOW CREATE TABLE, you will get this output -
CREATE TABLE `table1` (
`column1` tinyint(1) DEFAULT NULL
)
--feature
and --no-feature
at the same time (last one wins)This allows users to make a shell alias with --feature
, and overriding it with --no-feature
.
parser.add_argument('--feature', default=True, action=argparse.BooleanOptionalAction)
I recommend mgilson's answer:
parser.add_argument('--feature', dest='feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
--feature
and --no-feature
at the same timeYou can use a mutually exclusive group:
feature_parser = parser.add_mutually_exclusive_group(required=False)
feature_parser.add_argument('--feature', dest='feature', action='store_true')
feature_parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
You can use this helper if you are going to set many of them:
def add_bool_arg(parser, name, default=False):
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--' + name, dest=name, action='store_true')
group.add_argument('--no-' + name, dest=name, action='store_false')
parser.set_defaults(**{name:default})
add_bool_arg(parser, 'useful-feature')
add_bool_arg(parser, 'even-more-useful-feature')
Imho the best solution is:
fooBar | 0
This is used in asm.js to force integer type.
Using true/false removes some bracket clutter...
#! /bin/bash
# true_or_false.bash
[ "$(basename $0)" == "bash" ] && sourced=true || sourced=false
$sourced && echo "SOURCED"
$sourced || echo "CALLED"
# Just an alternate way:
! $sourced && echo "CALLED " || echo "SOURCED"
$sourced && return || exit
That query is failing and returning false
.
Put this after mysqli_query()
to see what's going on.
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
For more information:
answer = True
myvar = "the answer is " + str(answer)
or
myvar = "the answer is %s" % answer
&
, |
and ~
, and parentheses (...)
is important!Python's and
, or
and not
logical operators are designed to work with scalars. So Pandas had to do one better and override the bitwise operators to achieve vectorized (element-wise) version of this functionality.
So the following in python (exp1
and exp2
are expressions which evaluate to a boolean result)...
exp1 and exp2 # Logical AND
exp1 or exp2 # Logical OR
not exp1 # Logical NOT
...will translate to...
exp1 & exp2 # Element-wise logical AND
exp1 | exp2 # Element-wise logical OR
~exp1 # Element-wise logical NOT
for pandas.
If in the process of performing logical operation you get a ValueError
, then you need to use parentheses for grouping:
(exp1) op (exp2)
For example,
(df['col1'] == x) & (df['col2'] == y)
And so on.
Boolean Indexing: A common operation is to compute boolean masks through logical conditions to filter the data. Pandas provides three operators: &
for logical AND, |
for logical OR, and ~
for logical NOT.
Consider the following setup:
np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (5, 3)), columns=list('ABC'))
df
A B C
0 5 0 3
1 3 7 9
2 3 5 2
3 4 7 6
4 8 8 1
For df
above, say you'd like to return all rows where A < 5 and B > 5. This is done by computing masks for each condition separately, and ANDing them.
Overloaded Bitwise &
Operator
Before continuing, please take note of this particular excerpt of the docs, which state
Another common operation is the use of boolean vectors to filter the data. The operators are:
|
foror
,&
forand
, and~
fornot
. These must be grouped by using parentheses, since by default Python will evaluate an expression such asdf.A > 2 & df.B < 3
asdf.A > (2 & df.B) < 3
, while the desired evaluation order is(df.A > 2) & (df.B < 3)
.
So, with this in mind, element wise logical AND can be implemented with the bitwise operator &
:
df['A'] < 5
0 False
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df['B'] > 5
0 False
1 True
2 False
3 True
4 True
Name: B, dtype: bool
(df['A'] < 5) & (df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
And the subsequent filtering step is simply,
df[(df['A'] < 5) & (df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
The parentheses are used to override the default precedence order of bitwise operators, which have higher precedence over the conditional operators <
and >
. See the section of Operator Precedence in the python docs.
If you do not use parentheses, the expression is evaluated incorrectly. For example, if you accidentally attempt something such as
df['A'] < 5 & df['B'] > 5
It is parsed as
df['A'] < (5 & df['B']) > 5
Which becomes,
df['A'] < something_you_dont_want > 5
Which becomes (see the python docs on chained operator comparison),
(df['A'] < something_you_dont_want) and (something_you_dont_want > 5)
Which becomes,
# Both operands are Series...
something_else_you_dont_want1 and something_else_you_dont_want2
Which throws
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
So, don't make that mistake!1
Avoiding Parentheses Grouping
The fix is actually quite simple. Most operators have a corresponding bound method for DataFrames. If the individual masks are built up using functions instead of conditional operators, you will no longer need to group by parens to specify evaluation order:
df['A'].lt(5)
0 True
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df['B'].gt(5)
0 False
1 True
2 False
3 True
4 True
Name: B, dtype: bool
df['A'].lt(5) & df['B'].gt(5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
See the section on Flexible Comparisons.. To summarise, we have
+------------------------------+
¦ ¦ Operator ¦ Function ¦
¦----+------------+------------¦
¦ 0 ¦ > ¦ gt ¦
+----+------------+------------¦
¦ 1 ¦ >= ¦ ge ¦
+----+------------+------------¦
¦ 2 ¦ < ¦ lt ¦
+----+------------+------------¦
¦ 3 ¦ <= ¦ le ¦
+----+------------+------------¦
¦ 4 ¦ == ¦ eq ¦
+----+------------+------------¦
¦ 5 ¦ != ¦ ne ¦
+------------------------------+
Another option for avoiding parentheses is to use DataFrame.query
(or eval
):
df.query('A < 5 and B > 5')
A B C
1 3 7 9
3 4 7 6
I have extensively documented query
and eval
in Dynamic Expression Evaluation in pandas using pd.eval().
operator.and_
Allows you to perform this operation in a functional manner. Internally calls Series.__and__
which corresponds to the bitwise operator.
import operator
operator.and_(df['A'] < 5, df['B'] > 5)
# Same as,
# (df['A'] < 5).__and__(df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
df[operator.and_(df['A'] < 5, df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
You won't usually need this, but it is useful to know.
Generalizing: np.logical_and
(and logical_and.reduce
)
Another alternative is using np.logical_and
, which also does not need parentheses grouping:
np.logical_and(df['A'] < 5, df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
Name: A, dtype: bool
df[np.logical_and(df['A'] < 5, df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
np.logical_and
is a ufunc (Universal Functions), and most ufuncs have a reduce
method. This means it is easier to generalise with logical_and
if you have multiple masks to AND. For example, to AND masks m1
and m2
and m3
with &
, you would have to do
m1 & m2 & m3
However, an easier option is
np.logical_and.reduce([m1, m2, m3])
This is powerful, because it lets you build on top of this with more complex logic (for example, dynamically generating masks in a list comprehension and adding all of them):
import operator
cols = ['A', 'B']
ops = [np.less, np.greater]
values = [5, 5]
m = np.logical_and.reduce([op(df[c], v) for op, c, v in zip(ops, cols, values)])
m
# array([False, True, False, True, False])
df[m]
A B C
1 3 7 9
3 4 7 6
1 - I know I'm harping on this point, but please bear with me. This is a very, very common beginner's mistake, and must be explained very thoroughly.
For the df
above, say you'd like to return all rows where A == 3 or B == 7.
Overloaded Bitwise |
df['A'] == 3
0 False
1 True
2 True
3 False
4 False
Name: A, dtype: bool
df['B'] == 7
0 False
1 True
2 False
3 True
4 False
Name: B, dtype: bool
(df['A'] == 3) | (df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
dtype: bool
df[(df['A'] == 3) | (df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
If you haven't yet, please also read the section on Logical AND above, all caveats apply here.
Alternatively, this operation can be specified with
df[df['A'].eq(3) | df['B'].eq(7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
operator.or_
Calls Series.__or__
under the hood.
operator.or_(df['A'] == 3, df['B'] == 7)
# Same as,
# (df['A'] == 3).__or__(df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
dtype: bool
df[operator.or_(df['A'] == 3, df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
np.logical_or
For two conditions, use logical_or
:
np.logical_or(df['A'] == 3, df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df[np.logical_or(df['A'] == 3, df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
For multiple masks, use logical_or.reduce
:
np.logical_or.reduce([df['A'] == 3, df['B'] == 7])
# array([False, True, True, True, False])
df[np.logical_or.reduce([df['A'] == 3, df['B'] == 7])]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
Given a mask, such as
mask = pd.Series([True, True, False])
If you need to invert every boolean value (so that the end result is [False, False, True]
), then you can use any of the methods below.
Bitwise ~
~mask
0 False
1 False
2 True
dtype: bool
Again, expressions need to be parenthesised.
~(df['A'] == 3)
0 True
1 False
2 False
3 True
4 True
Name: A, dtype: bool
This internally calls
mask.__invert__()
0 False
1 False
2 True
dtype: bool
But don't use it directly.
operator.inv
Internally calls __invert__
on the Series.
operator.inv(mask)
0 False
1 False
2 True
dtype: bool
np.logical_not
This is the numpy variant.
np.logical_not(mask)
0 False
1 False
2 True
dtype: bool
Note, np.logical_and
can be substituted for np.bitwise_and
, logical_or
with bitwise_or
, and logical_not
with invert
.
In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}
, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.
This is helpful when your equals method call throws some exception e.g. NullPointerException
;
boolean isMatch = false;
try{
isMatch = email1.equals (email2);
}catch(NullPointerException npe){
.....
}
System.out.print("Match=="+isMatch);
if(isMatch){
......
}
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
From 6.11. Boolean operations:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.
The expression '/bla/bla/bla'
will be treated as true where a Boolean expression is expected (like in an if
statement), but the expressions '/bla/bla/bla' is True
and '/bla/bla/bla' == True
will evaluate to False for the reasons in Ignacio's answer.
list
has a count
method:
>>> [True,True,False].count(True)
2
This is actually more efficient than sum
, as well as being more explicit about the intent, so there's no reason to use sum
:
In [1]: import random
In [2]: x = [random.choice([True, False]) for i in range(100)]
In [3]: %timeit x.count(True)
970 ns ± 41.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [4]: %timeit sum(x)
1.72 µs ± 161 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Given that commonly 1 = true
and 0 = false
, all you need to do is count the number of rows, and cast to a boolean
.
Hence, your posted code only needs a COUNT()
function added:
SELECT CAST(COUNT(1) AS BIT) AS Expr1
FROM [User]
WHERE (UserID = 20070022)
How about something like this:
var MyNamespace = {
convertToBoolean: function (value) {
//VALIDATE INPUT
if (typeof value === 'undefined' || value === null) return false;
//DETERMINE BOOLEAN VALUE FROM STRING
if (typeof value === 'string') {
switch (value.toLowerCase()) {
case 'true':
case 'yes':
case '1':
return true;
case 'false':
case 'no':
case '0':
return false;
}
}
//RETURN DEFAULT HANDLER
return Boolean(value);
}
};
Then you can use it like this:
MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false
I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!
Given your updated question, these are the simplest forms:
If ProductID
is unique you want
SELECT COUNT(*) FROM Products WHERE ProductID IN (1, 10, 100)
and then check that result against 3
, the number of products you're querying (this last part can be done in SQL, but it may be easier to do it in C# unless you're doing even more in SQL).
If ProductID
is not unique it is
SELECT COUNT(DISTINCT ProductID) FROM Products WHERE ProductID IN (1, 10, 100)
When the question was thought to require returning rows when all ProductIds
are present and none otherwise:
SELECT ProductId FROM Products WHERE ProductID IN (1, 10, 100) AND ((SELECT COUNT(*) FROM Products WHERE ProductID IN (1, 10, 100))=3)
or
SELECT ProductId FROM Products WHERE ProductID IN (1, 10, 100) AND ((SELECT COUNT(DISTINCT ProductID) FROM Products WHERE ProductID IN (1, 10, 100))=3)
if you actually intend to do something with the results. Otherwise the simple SELECT 1 WHERE (SELECT ...)=3
will do as other answers have stated or implied.
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
On a side note...
If you are thinking about using an array of Boolean objects, don't. Use a BitSet instead - it has some performance optimisations (and some nice extra methods, allowing you to get the next set/unset bit).
A boolean
cannot be null
in java.
A Boolean
, however, can be null
.
If a boolean
is not assigned a value (say a member of a class) then it will be false
by default.
If you're using the variable result:
result = result == "true";
Generally speaking, for boolean
or bit
data types, you would use 0
or 1
like so:
UPDATE tbl SET bitCol = 1 WHERE bitCol = 0
See also:
Not at the SQL level and that's a pity There is one in PLSQL though
In Python 2.x this is not guaranteed as it is possible for True
and False
to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.
In Python 3.x True
and False
are keywords and will always be equal to 1
and 0
.
Under normal circumstances in Python 2, and always in Python 3:
False
object is of type bool
which is a subclass of int
:
object
|
int
|
bool
It is the only reason why in your example, ['zero', 'one'][False]
does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__
method (thanks mark-dickinson).
Edit:
It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:
There are two types of integers: [...] Integers (int) [...] Booleans (bool)
and in the boolean subsection:
Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.
There is also, for Python 2:
In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.
So booleans are explicitly considered as integers in Python 2 and 3.
So you're safe until Python 4 comes along. ;-)
This is the reason why you should whenever possible use strict equality ===
or strict inequality !==
"100" == 100
true
because this only checks value, not the data type
"100" === 100
false
this checks value and data type
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
If you want True False
use:
"%s %s" % (True, False)
because str(True)
is 'True'
and str(False)
is 'False'
.
or if you want 1 0
use:
"%i %i" % (True, False)
because int(True)
is 1
and int(False)
is 0
.
Some "front ends", with the "Use Booleans" option enabled, will treat all TINYINT(1) columns as Boolean, and vice versa.
This allows you to, in the application, use TRUE and FALSE rather than 1 and 0.
This doesn't affect the database at all, since it's implemented in the application.
There is not really a BOOLEAN
type in MySQL. BOOLEAN is just a synonym for TINYINT(1), and TRUE and FALSE are synonyms for 1 and 0.
If the conversion is done in the compiler, there will be no difference in performance in the application. Otherwise, the difference still won't be noticeable.
You should use whichever method allows you to code more efficiently, though not using the feature may reduce dependency on that particular "front end" vendor.
If you have only one thread modifying your boolean, you can use a volatile boolean (usually you do this to define a stop
variable checked in the thread's main loop).
However, if you have multiple threads modifying the boolean, you should use an AtomicBoolean
. Else, the following code is not safe:
boolean r = !myVolatileBoolean;
This operation is done in two steps:
If an other thread modify the value between #1
and 2#
, you might got a wrong result. AtomicBoolean
methods avoid this problem by doing steps #1
and #2
atomically.
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
addNewUser();
return true;
}
}
>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True, True, True, True],
[ True, True, True, True]], dtype=bool)
numpy.full(Size, Scalar Value, Type). There is other arguments as well that can be passed, for documentation on that, check https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html
Sample usage while creating a table:
[ColumnName] BIT NULL DEFAULT 0
myfun(){
[ -d "$1" ]
}
if myfun "path"; then
echo yes
fi
# or
myfun "path" && echo yes
Its Very simple
variable.GetType().Name
it will return your datatype of your variable
If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.
Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.
In your case it could be :
objContentLine = (from q in db.qryContents
where q.LineID == Value
orderby q.RowID descending
select q).FirstOrDefault();
Errors:
Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type
Error 242 Delegate 'System.Func<..>' does not take 1 arguments
Error 243 The name 'Value' does not exist in the current context
Fix the "Value" variable error and the other errors will also disappear.
Boolean
wrapper is useful when you want to whether value was assigned or not apart from true
and false
. It has the following three states:
null
Whereas boolean
has only two states:
The above difference will make it helpful in Lists of Boolean
values, which can have True
, False
or Null
.
Jelly Bean adds support for this with the ActivityOptions.makeCustomAnimation() method. Of course, since it's only on Jelly Bean, it's pretty much worthless for practical purposes.
u can do i hereString = hereString.replace(hereString.chatAt(hereString.length() - 1) ,' whitespeace');
I searched for help on this topic as I came across the same issue.
Although the following may not be the Answer to the question asked originally in 2012 it may be a solution for those who come across this thread.
A way to solve this is to check where your project is within the solution. It turns out for my instance (I was trying to install a NuGet package but it wouldn't and the listed error came up) that my project file was not included within the solution directory although showing in the solution explorer. I deleted the project from the directory out of scope and re-added the project but this time within the correct location.
Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.
Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).
In my case, the App Pool associated with the domain did not match the App Pool associated with the individual sites/applications. I'm not sure how this happened but once the domain App Pool was corrected, the issue was resolved.
Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.
I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :
LAST UPDATE :
In v10.12.0, NodeJS impletement recursive options :
// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });
UPDATE :
// Get modules node
const fs = require('fs');
const path = require('path');
// Create
function mkdirpath(dirPath)
{
if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
{
try
{
fs.mkdirSync(dirPath);
}
catch(e)
{
mkdirpath(path.dirname(dirPath));
mkdirpath(dirPath);
}
}
}
// Create folder path
mkdirpath('my/new/folder/create');
If you are using Swift:
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("controllerID")
self.navigationController!.pushViewController(controller, animated: true)
Other answers seem a bit complex, you can just add a parameter 'label' in scatter function and that will be the legend for your plot.
import matplotlib.pyplot as plt
from numpy.random import random
colors = ['b', 'c', 'y', 'm', 'r']
lo = plt.scatter(random(10), random(10), marker='x', color=colors[0],label='Low Outlier')
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0],label='LoLo')
l = plt.scatter(random(10), random(10), marker='o', color=colors[1],label='Lo')
a = plt.scatter(random(10), random(10), marker='o', color=colors[2],label='Average')
h = plt.scatter(random(10), random(10), marker='o', color=colors[3],label='Hi')
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4],label='HiHi')
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4],label='High Outlier')
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=True, shadow=True, ncol=4)
plt.show()
This is your output:
Your issue is in PHPMyAdmin itself. Some versions do not display the value of bit columns, even though you did set it correctly.
From MySQL documentation:
The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. For example, utf8 characters can require up to three bytes per character, so a VARCHAR column that uses the utf8 character set can be declared to be a maximum of 21,844 characters.
Limits for the VARCHAR varies depending on charset used. Using ASCII would use 1 byte per character. Meaning you could store 65,535 characters. Using utf8 will use 3 bytes per character resulting in character limit of 21,844. BUT if you are using the modern multibyte charset utf8mb4 which you should use! It supports emojis and other special characters. It will be using 4 bytes per character. This will limit the number of characters per table to 16,383. Note that other fields such as INT will also be counted to these limits.
Conclusion:
utf8 maximum of 21,844 characters
utf8mb4 maximum of 16,383 characters
You can try this
click Help>Install New Software on the menu bar
You can use Class#getDeclaredFields()
to get all declared fields of the class. You can use Field#get()
to get the value.
In short:
Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
field.setAccessible(true); // You might want to set modifier to public first.
Object value = field.get(someObject);
if (value != null) {
System.out.println(field.getName() + "=" + value);
}
}
To learn more about reflection, check the Sun tutorial on the subject.
That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get
or is
and then invoke it to grab the real property values.
for (Method method : someObject.getClass().getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() != void.class
&& (method.getName().startsWith("get") || method.getName().startsWith("is"))
) {
Object value = method.invoke(someObject);
if (value != null) {
System.out.println(method.getName() + "=" + value);
}
}
}
That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.
If you have only files there (no subdirectories) a quick solution is to select all the files (click
on the first, Shift+click
on the last) and hit Enter
or right click
and select Open
. For most of the data files this will download them straight to your computer.
I have solved it by importing FormModule in a shared.module and importing the shared.module in all other modules. My case is the FormModule is used in multiple modules.
This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.
The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.
Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:
The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null
. In other words, leaving the anchor null ensures the tip points where it is supposed to point.
However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.
By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.
var pinShadow = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
null,
null,
/* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
new google.maps.Point(40, 110),
new google.maps.Size(120, 110));
to give this:
Best way to replace linebreaks safely is
yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n") //handling mac linebreaks
that should produce a string with only \n (eg linefeed) as linebreaks. this code is usefull to fix mixed linebreaks too.
I got the same error when I added the applicationinitialization module with lots of initializationpages and deployed it on Azure app. The issue turned out to be duplicate entries in my applicationinitialization module. I din't see any errors in the logs so it was hard to troubleshoot. Below is an example of the error code:
<configuration>
<system.webServer>
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="true">
<add initializationPage="/init1.aspx?call=2"/>
<add initializationPage="/init1.aspx?call=2" />
</applicationInitialization>
</system.webServer>
Make sure there are no duplicate entries because those will be treated as duplicate keys which are not allowed and will result in "Cannot add duplicate collection entry" error for web.config.
Extra Superfluous const are bad from an API stand-point:
Putting extra superfluous const's in your code for intrinsic type parameters passed by value clutters your API while making no meaningful promise to the caller or API user (it only hampers the implementation).
Too many 'const' in an API when not needed is like "crying wolf", eventually people will start ignoring 'const' because it's all over the place and means nothing most of the time.
The "reductio ad absurdum" argument to extra consts in API are good for these first two points would be is if more const parameters are good, then every argument that can have a const on it, SHOULD have a const on it. In fact, if it were truly that good, you'd want const to be the default for parameters and have a keyword like "mutable" only when you want to change the parameter.
So lets try putting in const whereever we can:
void mungerum(char * buffer, const char * mask, int count);
void mungerum(char * const buffer, const char * const mask, const int count);
Consider the line of code above. Not only is the declaration more cluttered and longer and harder to read but three of the four 'const' keywords can be safely ignored by the API user. However, the extra use of 'const' has made the second line potentially DANGEROUS!
Why?
A quick misread of the first parameter char * const buffer
might make you think that it will not modify the memory in data buffer that is passed in -- however, this is not true! Superfluous 'const' can lead to dangerous and incorrect assumptions about your API when scanned or misread quickly.
Superfluous const are bad from a Code Implementation stand-point as well:
#if FLEXIBLE_IMPLEMENTATION
#define SUPERFLUOUS_CONST
#else
#define SUPERFLUOUS_CONST const
#endif
void bytecopy(char * SUPERFLUOUS_CONST dest,
const char *source, SUPERFLUOUS_CONST int count);
If FLEXIBLE_IMPLEMENTATION is not true, then the API is “promising” not to implement the function the first way below.
void bytecopy(char * SUPERFLUOUS_CONST dest,
const char *source, SUPERFLUOUS_CONST int count)
{
// Will break if !FLEXIBLE_IMPLEMENTATION
while(count--)
{
*dest++=*source++;
}
}
void bytecopy(char * SUPERFLUOUS_CONST dest,
const char *source, SUPERFLUOUS_CONST int count)
{
for(int i=0;i<count;i++)
{
dest[i]=source[i];
}
}
That’s a very silly promise to make. Why should you make a promise that gives no benefit at all to your caller and only limits your implementation?
Both of these are perfectly valid implementations of the same function though so all you’ve done is tied one hand behind your back unnecessarily.
Furthermore, it’s a very shallow promise that is easily (and legally circumvented).
inline void bytecopyWrapped(char * dest,
const char *source, int count)
{
while(count--)
{
*dest++=*source++;
}
}
void bytecopy(char * SUPERFLUOUS_CONST dest,
const char *source,SUPERFLUOUS_CONST int count)
{
bytecopyWrapped(dest, source, count);
}
Look, I implemented it that way anyhow even though I promised not to – just using a wrapper function. It’s like when the bad guy promises not to kill someone in a movie and orders his henchman to kill them instead.
Those superfluous const’s are worth no more than a promise from a movie bad-guy.
But the ability to lie gets even worse:
I have been enlightened that you can mismatch const in header (declaration) and code (definition) by using spurious const. The const-happy advocates claim this is a good thing since it lets you put const only in the definition.
// Example of const only in definition, not declaration
struct foo { void test(int *pi); };
void foo::test(int * const pi) { }
However, the converse is true... you can put a spurious const only in the declaration and ignore it in the definition. This only makes superfluous const in an API more of a terrible thing and a horrible lie - see this example:
struct foo
{
void test(int * const pi);
};
void foo::test(int *pi) // Look, the const in the definition is so superfluous I can ignore it here
{
pi++; // I promised in my definition I wouldn't modify this
}
All the superfluous const actually does is make the implementer's code less readable by forcing him to use another local copy or a wrapper function when he wants to change the variable or pass the variable by non-const reference.
Look at this example. Which is more readable ? Is it obvious that the only reason for the extra variable in the second function is because some API designer threw in a superfluous const ?
struct llist
{
llist * next;
};
void walkllist(llist *plist)
{
llist *pnext;
while(plist)
{
pnext=plist->next;
walk(plist);
plist=pnext; // This line wouldn't compile if plist was const
}
}
void walkllist(llist * SUPERFLUOUS_CONST plist)
{
llist * pnotconst=plist;
llist *pnext;
while(pnotconst)
{
pnext=pnotconst->next;
walk(pnotconst);
pnotconst=pnext;
}
}
Hopefully we've learned something here. Superfluous const is an API-cluttering eyesore, an annoying nag, a shallow and meaningless promise, an unnecessary hindrance, and occasionally leads to very dangerous mistakes.
In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So background-color
becomes backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
maybe it help:
<see additional>
pip install gprof2dot
sudo apt-get install graphviz
gprof2dot -f pstats profile_for_func1_001 | dot -Tpng -o profile.png
def profileit(name):
"""
@profileit("profile_for_func1_001")
"""
def inner(func):
def wrapper(*args, **kwargs):
prof = cProfile.Profile()
retval = prof.runcall(func, *args, **kwargs)
# Note use of name from outer scope
prof.dump_stats(name)
return retval
return wrapper
return inner
@profileit("profile_for_func1_001")
def func1(...)
You can now use Cache.delete()
Example:
let id = "your-cache-id";
// you can find the id by going to
// application>storage>cache storage
// (minus the page url at the end)
// in your chrome developer console
caches.open(id)
.then(cache => cache.keys()
.then(keys => {
for (let key of keys) {
cache.delete(key)
}
}));
Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.
Just to clarify a bit the difference between is
and runtimeType
. As someone said already (and this was tested with Dart V2+) the following code:
class Foo {
Type get runtimeType => String;
}
main() {
var foo = new Foo();
if (foo is Foo) {
print("it's a foo!");
}
print("type is ${foo.runtimeType}");
}
will output:
it's a foo!
type is String
Which is wrong. Now, I can't see the reason why one should do such a thing...
Use the where
command. The first result in the list is the one that will execute.
C:\> where notepad C:\Windows\System32\notepad.exe C:\Windows\notepad.exe
According to this blog post, where.exe
is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.
On Linux, the equivalent is the which
command, e.g. which ssh
.
You have a few options other than using public key authentication:
If you decide to give sshpass a chance here is a working script snippet to do so:
export SSHPASS=your-password-here
sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
cd incoming
put your-log-file.log
bye
!
Use date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);
function printCrossword(printContainer) {
var DocumentContainer = getElement(printContainer);
var WindowObject = window.open('', "PrintWindow", "width=5,height=5,top=200,left=200,toolbars=no,scrollbars=no,status=no,resizable=no");
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
If you do not mind using powershell within batch script:
@echo off
set start_date=%date% %time%
:: Simulate some type of processing using ping
ping 127.0.0.1
set end_date=%date% %time%
powershell -command "&{$start_date1 = [datetime]::parse('%start_date%'); $end_date1 = [datetime]::parse('%date% %time%'); echo (-join('Duration in seconds: ', ($end_date1 - $start_date1).TotalSeconds)); }"
I finally managed to get it working. Here the code :
private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex != color.Index)
return;
e.CellStyle.BackColor = Color.FromArgb(int.Parse(((DataRowView)dgvStatus.Rows[e.RowIndex].DataBoundItem).Row[4].ToString()));
}
if anyone know a better to do this please don't hesitate to post it. I'm open to suggestion
If the function is not defined when using that function in html, such as onclick = ‘function () ', it means function is in a callback, in my case is 'DOMContentLoaded'.
THE new @RestController annotation in Spring4+, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
The binary operators =
(assignment), []
(array subscription), ->
(member access), as well as the n-ary ()
(function call) operator, must always be implemented as member functions, because the syntax of the language requires them to.
Other operators can be implemented either as members or as non-members. Some of them, however, usually have to be implemented as non-member functions, because their left operand cannot be modified by you. The most prominent of these are the input and output operators <<
and >>
, whose left operands are stream classes from the standard library which you cannot change.
For all operators where you have to choose to either implement them as a member function or a non-member function, use the following rules of thumb to decide:
Of course, as with all rules of thumb, there are exceptions. If you have a type
enum Month {Jan, Feb, ..., Nov, Dec}
and you want to overload the increment and decrement operators for it, you cannot do this as a member functions, since in C++, enum types cannot have member functions. So you have to overload it as a free function. And operator<()
for a class template nested within a class template is much easier to write and read when done as a member function inline in the class definition. But these are indeed rare exceptions.
(However, if you make an exception, do not forget the issue of const
-ness for the operand that, for member functions, becomes the implicit this
argument. If the operator as a non-member function would take its left-most argument as a const
reference, the same operator as a member function needs to have a const
at the end to make *this
a const
reference.)
Continue to Common operators to overload.
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
Answer: From php 5.3 and >
, the var
keyword is equivalent to public
when declaring variables inside a class.
class myClass {
var $x;
}
is the same as (for php 5.3 and >
):
class myClass {
public $x;
}
History: It was previously the norm for declaring variables in classes, though later became depreciated, but later (PHP 5.3) it became un-depreciated.
Command to remove Cordova and ionic
For Window system
For Mac system
For install cordova and ionic
eg.
sudo npm install -g [email protected]
sudo npm install -g [email protected]
If you label the if statement you can use break.
breakme: if (condition) {
// Do stuff
if (condition2){
// do stuff
} else {
break breakme;
}
// Do more stuff
}
You can even label and break plain blocks.
breakme: {
// Do stuff
if (condition){
// do stuff
} else {
break breakme;
}
// Do more stuff
}
It's not a commonly used pattern though, so might confuse people and possibly won't be optimised by compliers. It might be better to use a function and return, or better arrange the conditions.
( function() {
// Do stuff
if ( condition1 ) {
// Do stuff
} else {
return;
}
// Do other stuff
}() );
Vladimir's answer is perfect, but anyone like me who is looking for swift solution
This Solution is Worked for swift version 4.2
var i = 0
func animation(){
let name = (i % 2 == 0) ? "1.png" : "2.png"
myImageView.image = UIImage.init(named: name)
let transition: CATransition = CATransition.init()
transition.duration = 1.0
transition.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut)
transition.type = .fade
myImageView.layer.add(transition, forKey: nil)
i += 1
}
You can call this method from anywhere. It will change the image to next one(image) with animation.
For Swift Version 4.0 Use bellow solution
var i = 0
func animationVersion4(){
let name = (i % 2 == 0) ? "1.png" : "2.png"
uiImage.image = UIImage.init(named: name)
let transition: CATransition = CATransition.init()
transition.duration = 1.0
transition.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
uiImage.layer.add(transition, forKey: nil)
i += 1
}
specifically I want to overload
Boolean.Parse
to allow an int argument.
Would an extension for int work?
public static bool ToBoolean(this int source){
// do it
// return it
}
Then you can call it like this:
int x = 1;
bool y = x.ToBoolean();
round(..)
function returning a floatThat float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)
See the discussion here for details.
Jason's answer will do the trick. However, instead of setting svn:ignore to "." on the cache directory, you may want to include "cache" in the parent directory's svn:ignore property, in case the cache directory is not always present. I do this on a number of "throwaway" folders.
Worth to note, you will probably use those lots more than in similar concepts in relational world (composite keys).
Example - suppose you have to find last N users who recently joined user group X. How would you do this efficiently given reads are predominant in this case? Like that (from offical Cassandra guide):
CREATE TABLE group_join_dates (
groupname text,
joined timeuuid,
join_date text,
username text,
email text,
age int,
PRIMARY KEY ((groupname, join_date), joined)
) WITH CLUSTERING ORDER BY (joined DESC)
Here, partitioning key is compound itself and the clustering key is a joined date. The reason why a clustering key is a join date is that results are already sorted (and stored, which makes lookups fast). But why do we use a compound key for partitioning key? Because we always want to read as few partitions as possible. How putting join_date in there helps? Now users from the same group and the same join date will reside in a single partition! This means we will always read as few partitions as possible (first start with the newest, then move to older and so on, rather than jumping between them).
In fact, in extreme cases you would also need to use the hash of a join_date rather than a join_date alone - so that if you query for last 3 days often those share the same hash and therefore are available from same partition!
You could target all text boxes with input[type=text]
and then explicitly define the class for the textboxes who need it.
You can code like below :
input[type=text] {_x000D_
padding: 0;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
left: 0;_x000D_
outline: none;_x000D_
border: 1px solid #cdcdcd;_x000D_
border-color: rgba(0, 0, 0, .15);_x000D_
background-color: white;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
width: 526px;_x000D_
margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
You can access elements of parent window from within an iframe by using window.parent
like this:
// using jquery
window.parent.$("#element_id");
Which is the same as:
// pure javascript
window.parent.document.getElementById("element_id");
And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top
like this:
// using jquery
window.top.$("#element_id");
Which is the same as:
// pure javascript
window.top.document.getElementById("element_id");
Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.
Here's some sample code:
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController () {
MPMoviePlayerController *moviePlayerController;
}
@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Instantiate a movie player controller and add it to your view
NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[moviePlayerController.view setFrame:self.movieView.bounds]; // player's frame must match parent's
[self.movieView addSubview:moviePlayerController.view];
// Configure the movie player controller
moviePlayerController.controlStyle = MPMovieControlStyleNone;
[moviePlayerController prepareToPlay];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Start the movie
[moviePlayerController play];
}
@end
Python has several XML modules built in. The simplest one for the case that you already have a string with the full HTML is xml.etree
, which works (somewhat) similarly to the lxml example you mention:
def remove_tags(text):
return ''.join(xml.etree.ElementTree.fromstring(text).itertext())
There's surprisingly simple way of reading resource by string:
ResourceNamespace.ResxFileName.ResourceManager.GetString("ResourceKey")
It's clean and elegant solution for reading resources by keys where "dot notation" cannot be used (for instance when resource key is persisted in the database).
Please see if you are setting client_max_body_size directive inside http {} block and not inside location {} block. I have set it inside http{} block and it works
Check out Apache Commons FileUtils (listFiles, iterateFiles, etc.). Nice convenience methods for doing what you want and also applying filters.
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html
My version using variables in a bash script:
Find any backslashes and replace with forward slashes:
input="This has a backslash \\"
output=$(echo "$input" | sed 's,\\,/,g')
echo "$output"
I could solve the problem using enctype="application/x-www-form-urlencoded" as the default is "text/plain". When you check in $DATA the seperator is a space for "text/plain" and a special character for the "urlencoded".
Kind regards Frank
Create the ArrayList like ArrayList action
.
In JDK 1.5 or higher use ArrayList <string[]>
reference name.
In JDK 1.4 or lower use ArrayList
reference name.
Specify the access specifiers:
Then specify the reference it will be assigned in
action = new ArrayList<String[]>();
In JVM new
keyword will allocate memory in runtime for the object.
You should not assigned the value where declared, because you are asking without fixed size.
Finally you can be use the add()
method in ArrayList. Use like
action.add(new string[how much you need])
It will allocate the specific memory area in heap.
You should use something ([ngClass]
instead of *ngClass
) like that:
<ol class="breadcrumb">
<li [ngClass]="{active: step==='step1'}" (click)="step='step1; '">Step1</li>
(...)
Since I wrote the MSDN article you are referring to, I guess I have to answer this one.
First, I anticipated this question and that's why I wrote a blog post that shows a more or less real use case for ExpandoObject: Dynamic in C# 4.0: Introducing the ExpandoObject.
Shortly, ExpandoObject can help you create complex hierarchical objects. For example, imagine that you have a dictionary within a dictionary:
Dictionary<String, object> dict = new Dictionary<string, object>();
Dictionary<String, object> address = new Dictionary<string,object>();
dict["Address"] = address;
address["State"] = "WA";
Console.WriteLine(((Dictionary<string,object>)dict["Address"])["State"]);
The deeper is the hierarchy, the uglier is the code. With ExpandoObject it stays elegant and readable.
dynamic expando = new ExpandoObject();
expando.Address = new ExpandoObject();
expando.Address.State = "WA";
Console.WriteLine(expando.Address.State);
Second, as it was already pointed out, ExpandoObject implements INotifyPropertyChanged interface which gives you more control over properties than a dictionary.
Finally, you can add events to ExpandoObject like here:
class Program
{
static void Main(string[] args)
{
dynamic d = new ExpandoObject();
// Initialize the event to null (meaning no handlers)
d.MyEvent = null;
// Add some handlers
d.MyEvent += new EventHandler(OnMyEvent);
d.MyEvent += new EventHandler(OnMyEvent2);
// Fire the event
EventHandler e = d.MyEvent;
e?.Invoke(d, new EventArgs());
}
static void OnMyEvent(object sender, EventArgs e)
{
Console.WriteLine("OnMyEvent fired by: {0}", sender);
}
static void OnMyEvent2(object sender, EventArgs e)
{
Console.WriteLine("OnMyEvent2 fired by: {0}", sender);
}
}
Also, keep in mind that nothing is preventing you from accepting event arguments in a dynamic way. In other words, instead of using EventHandler
, you can use EventHandler<dynamic>
which would cause the second argument of the handler to be dynamic
.
atoi can do that for you
Example:
char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234
Converting my old comment for better visibility: For a "better way to do this" without map
entirely, if your inputs are known to be ASCII ordinals, it's generally much faster to convert to bytes
and decode, a la bytes(list_of_ordinals).decode('ascii')
. That gets you a str
of the values, but if you need a list
for mutability or the like, you can just convert it (and it's still faster). For example, in ipython
microbenchmarks converting 45 inputs:
>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)
>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)
>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)
>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)
If you leave it as a str
, it takes ~20% of the time of the fastest map
solutions; even converting back to list it's still less than 40% of the fastest map
solution. Bulk convert via bytes
and bytes.decode
then bulk converting back to list
saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g. latin-1
).
Depends on what it's doing. If it has parameters, pass in mocks that you could ask later on if they have been called with the right set of parameters.
foreach (DataRow dr in dtSpecificOrders.rows)
{
dtSpecificOrders.Rows.Add(dr.ItemArray);
}
I know this is a late reply but maybe it can help someone.
Removing whitespace can be done by using the trim() function. After that if you want to sort the array with case sensitive manner you can just use:
Arrays.sort(yourArray);
and for case insensitive manner:
Arrays.sort(yourArray,String.CASE_INSENSITIVE_ORDER);
Hope this helps!
Try the method rstrip()
(see doc Python 2 and Python 3)
>>> 'test string\n'.rstrip()
'test string'
Python's rstrip()
method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp
.
>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'
To strip only newlines:
>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '
There are also the methods strip()
, lstrip()
and strip()
:
>>> s = " \n\r\n \n abc def \n\r\n \n "
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def \n\r\n \n '
>>> s.rstrip()
' \n\r\n \n abc def'
It lets you handle Many to Many relationship. Example:
Table 1: post
post has following columns
____________________
| ID | DATE |
|_________|_________|
| | |
|_________|_________|
Table 2: user
user has the following columns:
____________________
| ID |NAME |
|_________|_________|
| | |
|_________|_________|
Join Table lets you create a mapping using:
@JoinTable(
name="USER_POST",
joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
inverseJoinColumns=@JoinColumn(name="POST_ID", referencedColumnName="ID"))
will create a table:
____________________
| USER_ID| POST_ID |
|_________|_________|
| | |
|_________|_________|
As vartec says above, the HTTP spec does not define a limit, however many servers do by default. This means, practically speaking, the lower limit is 8K. For most servers, this limit applies to the sum of the request line and ALL header fields (so keep your cookies short).
It's worth noting that nginx uses the system page size by default, which is 4K on most systems. You can check with this tiny program:
pagesize.c:
#include <unistd.h>
#include <stdio.h>
int main() {
int pageSize = getpagesize();
printf("Page size on your system = %i bytes\n", pageSize);
return 0;
}
Compile with gcc -o pagesize pagesize.c
then run ./pagesize
. My ubuntu server from Linode dutifully informs me the answer is 4k.
Because this is related to something I was doing, I'll share here.
What if we're not sure if there's a header and you also don't feel like importing sniffer and other things?
If your task is basic, such as printing or appending to a list or array, you could just use an if statement:
# Let's say there's 4 columns
with open('file.csv') as csvfile:
csvreader = csv.reader(csvfile)
# read first line
first_line = next(csvreader)
# My headers were just text. You can use any suitable conditional here
if len(first_line) == 4:
array.append(first_line)
# Now we'll just iterate over everything else as usual:
for row in csvreader:
array.append(row)
I know this is an old thread but the TOP 1 WITH TIES
solutions is quite nice and might be helpful to some reading through the solutions.
select top 1 with ties
DocumentID
,Status
,DateCreated
from DocumentStatusLogs
order by row_number() over (partition by DocumentID order by DateCreated desc)
More about the TOP clause can be found here.
1.redirect return the request to the browser from server,then resend the request to the server from browser.
2.forward send the request to another servlet (servlet to servlet).
The important thing about JSON is to keep data transfer encrypted for security reasons. No doubt that JSON is much much faster then XML. I have seen XML take 100ms where as JSON only took 60ms. JSON data is easy to manipulate.
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
int count = 0;
foreach (ListViewItem lvi in listView.Items)
{
if(++count > 50) break;
}
On windows 10
If you wanna close it open command prompt with work with admin. Write NET STOP MySQL80
. Its done. If you wanna open again so you must write NET START MySQL80
If you do not want it to be turned on automatically when not in use, it automatically runs when the computer is turned on and consumes some ram.
Open services.msc find Mysql80 , look at properties and turn start type manuel or otomaticly again as you wish.
GridLayout is often not the best choice for buttons, although it might be for your application. A good reference is the tutorial on using Layout Managers. If you look at the GridLayout example, you'll see the buttons look a little silly -- way too big.
A better idea might be to use a FlowLayout for your buttons, or if you know exactly what you want, perhaps a GroupLayout. (Sun/Oracle recommend that GroupLayout or GridBag layout are better than GridLayout when hand-coding.)
Following this doc you can do this that way:
{{ p.User['first_name']|default('NONE') }}
This took me a while to figure out.
If you are using a distribution / ad hoc/ profile you cannot test it through xcode. You will get the error: The program being debugged is not being run.
You can build the app, go to the products folder in your app in xcode, click on the file with your project name and choose reveal in finder. You can drag this app into into iTunes and sync and that point you can test your app on your device.
Case sensitive: document.getElementById
(notice the capital B
).
Perhaps you could try ([^ ]+) .*
, which should give you everything to the first blank in your first group.
I tried this and it is working fine!
var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);
Index is the position where you want to insert or delete the element. 0 i.e. the second parameters defines the number of element from the index to be removed item are the new entries which you want to make in array. It can be one or more than one.
initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");
Since this question is fairly, uh, random, this may work for you:
>>> import uuid
>>> print uuid.uuid4()
58fe9784-f60a-42bc-aa94-eb8f1a7e5c17
Instead of opening a folder, try adding a folder by going to "Project" -> "Add Folder to Project..." which opens a Folder choosing dialog. This way the folder won't open in a new window and will be added to your current workspace.
If you then go to "Project" -> "Save Project As..." you can even save your current setup (cells setup, opened files, unsaved changes, etc...), this makes it easy to hotswitch between multiple projects without loosing control and unsaved changes which could be unsafe to be saved right now, but would be a loss if you just ditched them.
(Just be sure to have the "hot_exit"
setting set to true
.)
And Ctrl + Alt + P (Linux and Windows) / Super + Ctrl + P (Mac) lets you switch between the saved projects.
This way you don't have to setup your editor every time you want to work on one of your projects.
Hint: Try http://sublime-text-unofficial-documentation.readthedocs.org/en/sublime-text-2/ which is a wonderful resource for beginners, it teaches you the ropes and shows you the power of your "new" editor, just start with the "Editing" chapter.
The default credentials are:
login: admin
password: admin
But if you use EAP these credentials are turned off by default and there is no active user (security reasons :)). If you want to turn on these users, you have to edit the following file in your current profile: ./deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-users.properties
. It should be enough to remove the #
sign from the line with the user.
If you want to create a new user, don't forget to set up the correct groups in web-console-roles.properties
file.
You can easily find information where these information are stored: just open the ./conf/login-config.xml
file and find the proper security domain definition. In the case of the Web Console application, it will be web-console
policy.
Also if you want to have access to JMX, you have unlock JMX Console. Just check the following files in the conf/props/
directory (in your profile): jmx-console-users.properties
and jmx-console-roles.properties
.
unsigned is used when ur value must be positive, no negative value here, if signed for int range -32768 to +32767 if unsigned for int range 0 to 65535
You are trying to run a Python 2 codebase with Python 3. xrange()
was renamed to range()
in Python 3.
Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond xrange()
vs. range()
.
For the record, what you are seeing is not a syntax error but a runtime exception instead.
If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range
. (Take into account that you may have to update any existing range()
use in the Python 2 codebase with list(range(...))
to ensure you still get a list object in Python 3):
try:
# Python 2
xrange
except NameError:
# Python 3, xrange is now named range
xrange = range
# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))
or replace all uses of xrange(...)
with range(...)
in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:
try:
# Python 2 forward compatibility
range = xrange
except NameError:
pass
# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).
The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.
They are not lists, they are a list and a tuple. You can read about tuples in the Python tutorial. While you can mutate lists, this is not possible with tuples.
In [1]: x = (1, 2)
In [2]: x[0] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython console> in <module>()
TypeError: 'tuple' object does not support item assignment
Just wanted to say that this answer is brilliant and I'm using it for a long time without problems. But some time ago I've stumbled upon a problem that DownloadsProvider returns URIs in format content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Fdoc.pdf
and hence app is crashed with NumberFormatException
as it's impossible to parse its uri segments as long. But raw:
segment contains direct uri which can be used to retrieve a referenced file. So I've fixed it by replacing isDownloadsDocument(uri)
if
content with following:
final String id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
Log.e("FileUtils", "Downloads provider returned unexpected uri " + uri.toString(), e);
return null;
}
}
Recently, I have faced this issue. And fixed it by changing CPU/ABI from Intel Atom (x86) to ARM(armeabi-v7a).
Job done.
On Unix you can use valgrind
to find issues. It's free and powerful. If you'd rather do it yourself you can overload the new
and delete
operators to set up a configuration where you have 1 byte with 0xDEADBEEF
before and after each new object. Then track what happens at each iteration. This can fail to catch everything (you aren't guaranteed to even touch those bytes) but it has worked for me in the past on a Windows platform.
If you have only these regular shapes, there is a simple procedure as follows :
approxPolyDP
function.Below is my example in Python:
import numpy as np
import cv2
img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,1,2)
for cnt in contours:
approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
print len(approx)
if len(approx)==5:
print "pentagon"
cv2.drawContours(img,[cnt],0,255,-1)
elif len(approx)==3:
print "triangle"
cv2.drawContours(img,[cnt],0,(0,255,0),-1)
elif len(approx)==4:
print "square"
cv2.drawContours(img,[cnt],0,(0,0,255),-1)
elif len(approx) == 9:
print "half-circle"
cv2.drawContours(img,[cnt],0,(255,255,0),-1)
elif len(approx) > 15:
print "circle"
cv2.drawContours(img,[cnt],0,(0,255,255),-1)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Below is the output:
Remember, it works only for regular shapes.
Alternatively to find circles, you can use houghcircles
. You can find a tutorial here.
Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.
You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf
I had the same problem, and somehow found that I had a hidden .svn file at the c:\ level. Once I deleted this hidden folder (.svn), everything worked okay. I must have unintentionally created a working directory at the root drive.
In my case, this occurred because the password in the server config file was commented out.
Open the server config file: # sudo vim /etc/zabbix/zabbix-server.conf
Scroll down to db user and below there will be the password with a # commenting out. Remove the hash and insert your DB password.
C++20 introduced a guarantee that time_since_epoch
is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours:
#include <iostream>
#include <chrono>
int main()
{
const auto p1 = std::chrono::system_clock::now();
std::cout << "seconds since epoch: "
<< std::chrono::duration_cast<std::chrono::seconds>(
p1.time_since_epoch()).count() << '\n';
}
Using C++17 or earlier, time()
is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.
The cppreference page linked above gives this example:
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result))
<< result << " seconds since the Epoch\n";
}
A 32-bit unsigned int has a range from 0 to 4,294,967,295. 0 to 65535 would be a 16-bit unsigned.
An unsigned long long (and, on a 64-bit implementation, possibly also ulong and possibly uint as well) have a range (at least) from 0 to 18,446,744,073,709,551,615 (264-1). In theory it could be greater than that, but at least for now that's rare to nonexistent.
Not sure if this helps but in my app I had to check if a dictionary has changed.
Doing this will not work since basically it's still the same object:
val={'A':1,'B':2}
old_val=val
val['A']=10
if old_val != val:
print('changed')
Using copy/deepcopy works:
import copy
val={'A':1,'B':2}
old_val=copy.deepcopy(val)
val['A']=10
if old_val != val:
print('changed')
use
window.location.origin
and for: "http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah"
you will get: http://aaa.bbb.ccc.ddd.com/
All previous links no more direct to "Reviews" tab,
This link would direct to "Reviews Tab" directly: ?
https://itunes.apple.com/app/viewContentsUserReviews?id=AppID
or ?
itms-apps://itunes.apple.com/app/viewContentsUserReviews?id=AppID
You can also mark with a wildcard symbol * to facilitate group files to count.
Z:\SQLData>find /c /v "" FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_*.txt
Result
---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIFRS01_V1.TXT: 2041
---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIOST00_V1.TXT: 315938
---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIFRS00_V1.TXT: 0
---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_CNTPTF00_V1.TXT: 277
Or, if you are a fan of functional programming:
>>> a = [133, 53, 234, 241]
>>> "".join(map(lambda b: format(b, "02x"), a))
8535eaf1
>>>
after several days searching I figured out a possible fix for this issue.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Documento sin título</title>
</head>
<body style="height:100%">
<!-- for Firefox and Chrome compatibility set height:100% in the containing TABLE, the TR parent and the TD itself. -->
<table width="400" border="1" cellspacing="0" cellpadding="0" style="height:100%;">
<tr>
<td>whatever</td>
<td>whatever</td>
<td>whatever</td>
</tr>
<tr style="height:100%;">
<td>whatever dynamic height<br /><br /><br />more content
</td>
<td>whatever</td>
<!-- display,background-color and radius properties in TD BELOW could be placed in an <!--[if IE]> commentary If desired.
This way TD would remain as display:table-cell; in FF and Chrome and would keep working correctly.
If you don't place the properties in IE commentary it will still work in FF and Chorme with a TD display:block;
The Trick for IE is setting the cell to display:block; Setting radius is only an example of whay you may want a DIV 100%height inside a Cell.
-->
<td style="height:100%; width:100%; display:block; background-color:#3C3;border-radius: 0px 0px 1em 0px;">
<div style="width:100%;height:100%;background-color:#3C3;-webkit-border-radius: 0px 0px 0.6em 0px;border-radius: 0px 0px 0.6em 0px;">
Content inside DIV TAG
</div>
</td>
</tr>
</table>
</body>
</html>
Spanish language: El truco es establecer la Tabla, el TR y el TD a height:100%. Esto lo hace compatible con FireFox y Chrome. Internet Explorer ignora eso, por lo que ponemos la etiqueta TD como block. De esta forma Explorer sí toma la altura máxima.
English explanation: within the code commentaries
To round up an integer division you can use
import static java.lang.Math.abs;
public static long roundUp(long num, long divisor) {
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}
or if both numbers are positive
public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}
I have ran into that same problem. I actually developed my using server side programming, but I did a quick search to try and help you out and found this.
Seems alright, didn't look at the source too much, but seems to be purely JavaScript.
Take look:
http://www.rainforestnet.com/datetimepicker/datetimepicker.htm
Here is the demo page link:
http://www.rainforestnet.com/datetimepicker/datetimepicker-demo.htm
good luck
The statement is called MERGE. Look it up, I'm too lazy.
Beware, though, that MERGE is not atomic, which could cause the following effect (thanks, Marius):
SESS1:
create table t1 (pk int primary key, i int);
create table t11 (pk int primary key, i int);
insert into t1 values(1, 1);
insert into t11 values(2, 21);
insert into t11 values(3, 31);
commit;
SESS2: insert into t1 values(2, 2);
SESS1:
MERGE INTO t1 d
USING t11 s ON (d.pk = s.pk)
WHEN NOT MATCHED THEN INSERT (d.pk, d.i) VALUES (s.pk, s.i);
SESS2: commit;
SESS1: ORA-00001
g _ goes to the last non-whitespace character.
g $ goes to the end of the screen line (when a buffer line is wrapped across multiple screen lines)
When you don't care about removing the Html Dom-Element, use *ngIf.
Otherwise, use this:
<div [style.visibility]="(numberOfUnreadAlerts == 0) ? 'hidden' : 'visible' ">
COUNTER: {{numberOfUnreadAlerts}}
</div>
Pillow is released with installation wheels on Windows:
We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included
https://pillow.readthedocs.io/en/3.3.x/installation.html#basic-installation
Update: Python 3.6 is now supported by Pillow. Install with pip install pillow
and check https://pillow.readthedocs.io/en/latest/installation.html for more information.
However, Python 3.6 is still in alpha and not officially supported yet, although the tests do all pass for the nightly Python builds (currently 3.6a4).
https://travis-ci.org/python-pillow/Pillow/jobs/155605577
If it's somehow possible to install the 3.5 wheel for 3.6, that's your best bet. Otherwise, zlib notwithstanding, you'll need to build from source, requiring an MS Visual C++ compiler, and which isn't straightforward. For tips see:
https://pillow.readthedocs.io/en/3.3.x/installation.html#building-from-source
And also see how it's built for Windows on AppVeyor CI (but not yet 3.5 or 3.6):
https://github.com/python-pillow/Pillow/tree/master/winbuild
Failing that, downgrade to Python 3.5 or wait until 3.6 is supported by Pillow, probably closer to the 3.6's official release.
I would suggest the following for Java8+.
/**
* Creates a File if the file does not exist, or returns a
* reference to the File if it already exists.
*/
private File createOrRetrieve(final String target) throws IOException{
final Path path = Paths.get(target);
if(Files.notExists(path)){
LOG.info("Target file \"" + target + "\" will be created.");
return Files.createFile(Files.createDirectories(path)).toFile();
}
LOG.info("Target file \"" + target + "\" will be retrieved.");
return path.toFile();
}
/**
* Deletes the target if it exists then creates a new empty file.
*/
private File createOrReplaceFileAndDirectories(final String target) throws IOException{
final Path path = Paths.get(target);
// Create only if it does not exist already
Files.walk(path)
.filter(p -> Files.exists(p))
.sorted(Comparator.reverseOrder())
.peek(p -> LOG.info("Deleted existing file or directory \"" + p + "\"."))
.forEach(p -> {
try{
Files.createFile(Files.createDirectories(p));
}
catch(IOException e){
throw new IllegalStateException(e);
}
});
LOG.info("Target file \"" + target + "\" will be created.");
return Files.createFile(
Files.createDirectories(path)
).toFile();
}
After struggling with all available options, I ended up writing a JWT token based SessionStore provider (the session travels inside a cookie, and no backend storage is needed).
http://www.drupalonwindows.com/en/content/token-sessionstate
Advantages:
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
this is an example of a stored procedure that returns a value and it's execution in c#
CREATE PROCEDURE [dbo].[InsertPerson]
-- Add the parameters for the stored procedure here
@FirstName nvarchar(50),@LastName nvarchar(50),
@PersonID int output
AS
BEGIN
insert [dbo].[Person](LastName,FirstName) Values(@LastName,@FirstName)
set @PersonID=SCOPE_IDENTITY()
END
Go
--------------
// Using stored procedure in adapter to insert new rows and update the identity value.
static void InsertPersonInAdapter(String connectionString, String firstName, String lastName) {
String commandText = "dbo.InsertPerson";
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlDataAdapter mySchool = new SqlDataAdapter("Select PersonID,FirstName,LastName from [dbo].[Person]", conn);
mySchool.InsertCommand = new SqlCommand(commandText, conn);
mySchool.InsertCommand.CommandType = CommandType.StoredProcedure;
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("@FirstName", SqlDbType.NVarChar, 50, "FirstName"));
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("@LastName", SqlDbType.NVarChar, 50, "LastName"));
SqlParameter personId = mySchool.InsertCommand.Parameters.Add(new SqlParameter("@PersonID", SqlDbType.Int, 0, "PersonID"));
personId.Direction = ParameterDirection.Output;
DataTable persons = new DataTable();
mySchool.Fill(persons);
DataRow newPerson = persons.NewRow();
newPerson["FirstName"] = firstName;
newPerson["LastName"] = lastName;
persons.Rows.Add(newPerson);
mySchool.Update(persons);
Console.WriteLine("Show all persons:");
ShowDataTable(persons, 14);
For just in case people are looking for solution for this:
<If "req('Host') = 'www.example.com'">
Authtype Basic
AuthName "user and password"
AuthUserFile /var/www/www.example.com/.htpasswd
Require valid-user
</If>
Apart from sp_who
, you can also use the "undocumented" sp_who2
system stored procedure which gives you more detailed information. See Difference between sp_who and sp_who2.
with open('writing_file.json', 'w') as w:
with open('reading_file.json', 'r') as r:
for line in r:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
w.write(json.dumps(element))
this is the method i use..
Simplest is when you want to make a integer a string do
var a,b, c;
a = 1;
b = a.toString(); // This will give you string
Now, from the variable b which is of type string we can get the integer
c = b *1; //This will give you integer value of number :-)
If you want to check above is a number. If you are not sure if b contains integer then you can use
if(isNaN(c*1)) {
//NOt a number
}
else //number
How about Application.EnableCancelKey - Use the Esc button
On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox "This may take a long time: press ESC to cancel"
For x = 1 To 1000000 ' Do something 1,000,000 times (long!)
' do something here
Next x
handleCancel:
If Err = 18 Then
MsgBox "You cancelled"
End If
Snippet from http://msdn.microsoft.com/en-us/library/aa214566(office.11).aspx
If you are using Bootstrap 4, and you don't want to change your markup:
var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
$myGroup.find('.collapse.show').collapse('hide');
});
If you reinstalled the server it means that that the new installation most likely overwrote your username and passwords. (You might want to try loggin without a password see if it works).
If it is a clean install you need to set the root password .
Otherwise, you will need to reset root permissions.
Separate the increments with a comma too.
for(int a = 0, b = 1; a<cards.length-1; b=a+1, a++)
You can use:
public function indexAction()
{
dump( $this->getParameter('api_user'));
}
For more information I recommend you read the doc :
http://symfony.com/doc/2.8/service_container/parameters.html
AppDomain.CurrentDomain.BaseDirectory
is probably the most useful for accessing files whose location is relative to the application install directory.
In an ASP.NET application, this will be the application root directory, not the bin subfolder - which is probably what you usually want. In a client application, it will be the directory containing the main executable.
In a VSTO 2005 application, it will be the directory containing the VSTO managed assemblies for your application, not, say, the path to the Excel executable.
The others may return different directories depending on your environment - for example see @Vimvq1987's answer.
CodeBase
is the place where a file was found and can be a URL beginning with http://. In which case Location
will probably be the assembly download cache. CodeBase is not guaranteed to be set for assemblies in the GAC.
UPDATE
These days (.NET Core, .NET Standard 1.3+ or .NET Framework 4.6+) it's better to use AppContext.BaseDirectory
rather than AppDomain.CurrentDomain.BaseDirectory
. Both are equivalent, but multiple AppDomains are no longer supported.
This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx
An example of this is to make a collection of items of a specific type.
class MyArray<T>
{
T[] array = new T[10];
public T GetItem(int index)
{
return array[index];
}
}
In your code, you could then do something like this:
MyArray<int> = new MyArray<int>();
In this case, T[] array
would work like int[] array
, and public T GetItem
would work like public int GetItem
.
Even array2.extend(array1)
will work.
Use GSON library for that. Here is the sample code
List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");
String json = new Gson().toJson(foo );
Here is the maven dependency for Gson
<dependencies>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
Or you can directly download jar from here and put it in your class path
http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=
To send Json to client you can use spring or in simple servlet add this code
response.getWriter().write(json);
@Victor's answer worked for me and reposting it here in Kotlin in case useful to someone else doing Android.
if (list!!.isNotEmpty()) {
Collections.sort(
list,
Comparator { c1, c2 -> //You should ensure that list doesn't contain null values!
c1.name!!.compareTo(c2.name!!)
})
}
I tried this code, it may work for you also:
DateFormat dateFormat2 = new SimpleDateFormat("dd");
Date date2 = new Date();
String today = dateFormat2.format(date2);
//find the calendar
WebElement dateWidget = driver.findElement(By.id("dp-calendar"));
List<WebElement> columns=dateWidget.findElements(By.tagName("td"));
//comparing the text of cell with today's date and clicking it.
for (WebElement cell : columns)
{
if (cell.getText().equals(today))
{
cell.click();
break;
}
}
Sounds like myversioncontrol.com have added a pre-commit hook, or have one that is now failing. If it's a free account, it might be you've exceeded some sort of monthly commit or bandwidth limit. Check their terms of service and/or contact them to see what's up.
UPDATE:
I've just checked their website, and it looks like the free account is only valid for 30 days, so you might've exceeded that. You may need to pony up the £3.50pcm or find somewhere else (Google Code is one suggestion, though there are others).
Simon Groenewolt makes a good point that you may have changed something in the control panel on their website that has turned on a pre-commit hook but where it's configured incorrectly.
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
document.querySelectorAll
(and its document.querySelector()
variant that returns the first found element) is much, much more powerful. You can easily:
document.querySelectorAll("*")
, effectively emulating non-standard document.all
property;document.querySelector("#your-id")
, effectively emulating document.getElementById()
function;document.querySelectorAll(".your-class")
, effectively emulating document.getElementsByClassName()
function;document.querySelectorAll("form")
instead of document.forms
, and document.querySelectorAll("a")
instead of document.links
;Unified querying API is the way to go. Even if document.all
would be in the standard, it's just inconvenient.
For the case of returning an array of complex JSON objects from configuration, I've adapted @djangojazz's answer to use anonymous types and dynamic rather than tuples.
Given a settings section of:
"TestUsers": [
{
"UserName": "TestUser",
"Email": "[email protected]",
"Password": "P@ssw0rd!"
},
{
"UserName": "TestUser2",
"Email": "[email protected]",
"Password": "P@ssw0rd!"
}],
You can return the object array this way:
public dynamic GetTestUsers()
{
var testUsers = Configuration.GetSection("TestUsers")
.GetChildren()
.ToList()
.Select(x => new {
UserName = x.GetValue<string>("UserName"),
Email = x.GetValue<string>("Email"),
Password = x.GetValue<string>("Password")
});
return new { Data = testUsers };
}
These answers helped me a lot to make this function:
function xml2json(xml) {
try {
var obj = {};
if (xml.children.length > 0) {
for (var i = 0; i < xml.children.length; i++) {
var item = xml.children.item(i);
var nodeName = item.nodeName;
if (typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xml2json(item);
} else {
if (typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xml2json(item));
}
}
} else {
obj = xml.textContent;
}
return obj;
} catch (e) {
console.log(e.message);
}
}
As long as you pass in a jquery dom/xml object: for me it was:
Jquery(this).find('content').eq(0)[0]
where content was the field I was storing my xml in.
In Chrome Browser go to setting , clear browsing history and then reload the page
First of all its not the Notepad++ problem for sure. Its your "String Matching problem"
The common string throughout all IE version is MSIE Check out the various userAgent strings at http://www.useragentstring.com/pages/Internet%20Explorer/
if(navigator.userAgent.indexOf("MSIE") != -1){
alert('I am Internet Explorer!!');
}
I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
If you need a recursive search, you have a variety of options. You should consider ack
.
Failing that, if you have GNU find
and xargs
:
find . -name '*.cc' -print0 -o -name '*.h' -print0 | xargs -0 grep hello /dev/null
The use of /dev/null
ensures you get file names printed; the -print0
and -0
deals with file names containing spaces (newlines, etc).
If you don't have obstreperous names (with spaces etc), you can use:
find . -name '*.*[ch]' -print | xargs grep hello /dev/null
This might pick up a few names you didn't intend, because the pattern match is fuzzier (but simpler), but otherwise works. And it works with non-GNU versions of find
and xargs
.
This examples shows calling a method
class ParentPage extends StatefulWidget {
@override
_ParentPageState createState() => _ParentPageState();
}
class _ParentPageState extends State<ParentPage> {
final GlobalKey<ChildPageState> _key = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Parent")),
body: Center(
child: Column(
children: <Widget>[
Expanded(
child: Container(
color: Colors.grey,
width: double.infinity,
alignment: Alignment.center,
child: RaisedButton(
child: Text("Call method in child"),
onPressed: () => _key.currentState.methodInChild(), // calls method in child
),
),
),
Text("Above = Parent\nBelow = Child"),
Expanded(
child: ChildPage(
key: _key,
function: methodInParent,
),
),
],
),
),
);
}
methodInParent() => Fluttertoast.showToast(msg: "Method called in parent", gravity: ToastGravity.CENTER);
}
class ChildPage extends StatefulWidget {
final Function function;
ChildPage({Key key, this.function}) : super(key: key);
@override
ChildPageState createState() => ChildPageState();
}
class ChildPageState extends State<ChildPage> {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.teal,
width: double.infinity,
alignment: Alignment.center,
child: RaisedButton(
child: Text("Call method in parent"),
onPressed: () => widget.function(), // calls method in parent
),
);
}
methodInChild() => Fluttertoast.showToast(msg: "Method called in child");
}
You might want to take a look at Joda Time which is a really good API for dealing with date/time. Even though if you don't really need it for the solution to your current question it is bound to save you pain in the future.
xs:boolean
is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:
<xs:simpleType name="my:boolean">
<xs:restriction base="xs:string">
<xs:enumeration value="True"/>
<xs:enumeration value="False"/>
</xs:restriction>
</xs:simpleType>
Hey guys here is a simple test program that shows how to allocate and pass an array using new or malloc. Just cut, paste and run it. Have fun!
struct Coordinate
{
int x,y;
};
void resize( int **p, int size )
{
free( *p );
*p = (int*) malloc( size * sizeof(int) );
}
void resizeCoord( struct Coordinate **p, int size )
{
free( *p );
*p = (Coordinate*) malloc( size * sizeof(Coordinate) );
}
void resizeCoordWithNew( struct Coordinate **p, int size )
{
delete [] *p;
*p = (struct Coordinate*) new struct Coordinate[size];
}
void SomeMethod(Coordinate Coordinates[])
{
Coordinates[0].x++;
Coordinates[0].y = 6;
}
void SomeOtherMethod(Coordinate Coordinates[], int size)
{
for (int i=0; i<size; i++)
{
Coordinates[i].x = i;
Coordinates[i].y = i*2;
}
}
int main()
{
//static array
Coordinate tenCoordinates[10];
tenCoordinates[0].x=0;
SomeMethod(tenCoordinates);
SomeMethod(&(tenCoordinates[0]));
if(tenCoordinates[0].x - 2 == 0)
{
printf("test1 coord change successful\n");
}
else
{
printf("test1 coord change unsuccessful\n");
}
//dynamic int
int *p = (int*) malloc( 10 * sizeof(int) );
resize( &p, 20 );
//dynamic struct with malloc
int myresize = 20;
int initSize = 10;
struct Coordinate *pcoord = (struct Coordinate*) malloc (initSize * sizeof(struct Coordinate));
resizeCoord(&pcoord, myresize);
SomeOtherMethod(pcoord, myresize);
bool pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord[i].x == i) && (pcoord[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord[i].x,pcoord[i].y);
pass = false;
}
}
if (pass)
{
printf("test2 coords for dynamic struct allocated with malloc worked correctly\n");
}
//dynamic struct with new
myresize = 20;
initSize = 10;
struct Coordinate *pcoord2 = (struct Coordinate*) new struct Coordinate[initSize];
resizeCoordWithNew(&pcoord2, myresize);
SomeOtherMethod(pcoord2, myresize);
pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord2[i].x == i) && (pcoord2[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord2[i].x,pcoord2[i].y);
pass = false;
}
}
if (pass)
{
printf("test3 coords for dynamic struct with new worked correctly\n");
}
return 0;
}
If you only wanted to GROUP BY the SalesOrderID then you wouldn't be able to include the ProductID and OrderQty columns in the SELECT clause.
The PARTITION BY clause let's you break up your aggregate functions. One obvious and useful example would be if you wanted to generate line numbers for order lines on an order:
SELECT
O.order_id,
O.order_date,
ROW_NUMBER() OVER(PARTITION BY O.order_id) AS line_item_no,
OL.product_id
FROM
Orders O
INNER JOIN Order_Lines OL ON OL.order_id = O.order_id
(My syntax might be off slightly)
You would then get back something like:
order_id order_date line_item_no product_id
-------- ---------- ------------ ----------
1 2011-05-02 1 5
1 2011-05-02 2 4
1 2011-05-02 3 7
2 2011-05-12 1 8
2 2011-05-12 2 1
<script type="text/javascript">
$(function(){
$('#areaCode,#firstNum,#secNum').keyup(function(e){
if($(this).val().length==$(this).attr('maxlength'))
$(this).next(':input').focus()
})
})
</script>
<body>
<input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />-
<input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />-
<input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />
</body>
This might be useful to someone also ..
i.e. For a data analyst and data profiling type of purposes ..(i.e. not grouped by) ..
Prior to the SQL*Server 2017 String_agg function existence ..
(i.e. returns just one row ..)
select distinct
SUBSTRING (
stuff(( select distinct ',' + [FieldB] from tablename order by 1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
,1,0,'' )
,2,9999)
from
tablename
e.g. returns comma separated values A,B
EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'
; worked for me.
closing the varchar
/string
with two pairs of single quotes did the trick. Other option could be to use using
keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'
; Remember using
keyword will not work, if you are using EXECUTE IMMEDIATE
to execute DDL's with parameters, however, using quotes will work for DDL's.
I think that is the exact opposite of the solution chosen.
var decoded = $("<div/>").text(encodedStr).html();
Try it :)
Using Data::Dumper
:
use strict;
use Data::Dumper;
my $GRANTstr = 'SELECT, INSERT, UPDATE, DELETE, LOCK TABLES, EXECUTE, TRIGGER';
$GRANTstr =~ s/, /,/g;
my @GRANTs = split /,/ , $GRANTstr;
print Dumper(@GRANTs) . "===\n\n";
print Dumper(\@GRANTs) . "===\n\n";
print Data::Dumper->Dump([\@GRANTs], [qw(GRANTs)]);
Generates three different output styles:
$VAR1 = 'SELECT';
$VAR2 = 'INSERT';
$VAR3 = 'UPDATE';
$VAR4 = 'DELETE';
$VAR5 = 'LOCK TABLES';
$VAR6 = 'EXECUTE';
$VAR7 = 'TRIGGER';
===
$VAR1 = [
'SELECT',
'INSERT',
'UPDATE',
'DELETE',
'LOCK TABLES',
'EXECUTE',
'TRIGGER'
];
===
$GRANTs = [
'SELECT',
'INSERT',
'UPDATE',
'DELETE',
'LOCK TABLES',
'EXECUTE',
'TRIGGER'
];
@Mahmoud Ali Kaseem
I have just changed some CSS to make it look different and added focus();
https://jsfiddle.net/xn9eogmx/81/
$('#clear').click(function() {_x000D_
$('#input-outer input').val('');_x000D_
$('#input-outer input').focus();_x000D_
});
_x000D_
body {_x000D_
font-family: "Arial";_x000D_
font-size: 14px;_x000D_
}_x000D_
#input-outer {_x000D_
height: 2em;_x000D_
width: 15em;_x000D_
border: 1px #777 solid;_x000D_
position: relative;_x000D_
padding: 0px;_x000D_
border-radius: 4px;_x000D_
}_x000D_
#input-outer input {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
border: 0px;_x000D_
outline: none;_x000D_
margin: 0 0 0 0px;_x000D_
color: #666;_x000D_
box-sizing: border-box;_x000D_
padding: 5px;_x000D_
padding-right: 35px;_x000D_
border-radius: 4px;_x000D_
}_x000D_
#clear {_x000D_
position: absolute;_x000D_
float: right;_x000D_
height: 2em;_x000D_
width: 2em;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
background: #aaa;_x000D_
color: white;_x000D_
text-align: center;_x000D_
cursor: pointer;_x000D_
border-radius: 0px 4px 4px 0px;_x000D_
}_x000D_
#clear:after {_x000D_
content: "\274c";_x000D_
position: absolute;_x000D_
top: 4px;_x000D_
right: 7px;_x000D_
}_x000D_
#clear:hover,_x000D_
#clear:focus {_x000D_
background: #888;_x000D_
}_x000D_
#clear:active {_x000D_
background: #666;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="input-outer">_x000D_
<input type="text">_x000D_
<div id="clear"></div>_x000D_
</div>
_x000D_
String send =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <soap:Body>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
private static String getResponse(String send) throws Exception {
String url = "https://api.comscore.com/KeyMeasures.asmx"; //endpoint
String result = "";
String username="user_name";
String password="pass_word";
String[] command = {"curl", "-u", username+":"+password ,"-X", "POST", "-H", "Content-Type: text/xml", "-d", send, url};
ProcessBuilder process = new ProcessBuilder(command);
Process p;
try {
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
result = builder.toString();
}
catch (IOException e)
{ System.out.print("error");
e.printStackTrace();
}
return result;
}
This should work:
System.currentTimeMillis();
If you give generally give a span
the property display:block
, it'll then behave like a div
, i.e you can set width and height.
You can also skip the div
or span
and just set the a
the to display: block
and apply the backgound style to it.
<a href="" class="myImage"><!----></a>
<style>
.myImage {display: block; width: 160px; height: 20px; margin:0 0 10px 0; background: url(image.png) center top no-repeat;}
.myImage:hover{background-image(image_hover.png);}
</style>
@echo off
color 0f
MODE CON COLS=132 LINES=50
:start
cls
choice /C ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!?.# /N /CS /M Please enter your password to continue. (Valid characters include all letters, numbers, and ! ? .) Press # to submit:
SET ecode=%ERRORLEVEL%
IF %ecode% EQU 66 goto submit
IF %ecode% EQU 1 SET out=A
IF %ecode% EQU 2 SET out=B
IF %ecode% EQU 3 SET out=C
IF %ecode% EQU 4 SET out=D
IF %ecode% EQU 5 SET out=E
IF %ecode% EQU 6 SET out=F
IF %ecode% EQU 7 SET out=G
IF %ecode% EQU 8 SET out=H
IF %ecode% EQU 9 SET out=I
IF %ecode% EQU 10 SET out=J
IF %ecode% EQU 11 SET out=K
IF %ecode% EQU 12 SET out=L
IF %ecode% EQU 13 SET out=M
IF %ecode% EQU 14 SET out=N
IF %ecode% EQU 15 SET out=O
IF %ecode% EQU 16 SET out=P
IF %ecode% EQU 17 SET out=Q
IF %ecode% EQU 18 SET out=R
IF %ecode% EQU 19 SET out=S
IF %ecode% EQU 20 SET out=T
IF %ecode% EQU 21 SET out=U
IF %ecode% EQU 22 SET out=V
IF %ecode% EQU 23 SET out=W
IF %ecode% EQU 24 SET out=X
IF %ecode% EQU 25 SET out=Y
IF %ecode% EQU 26 SET out=Z
IF %ecode% EQU 27 SET out=a
IF %ecode% EQU 28 SET out=b
IF %ecode% EQU 29 SET out=c
IF %ecode% EQU 30 SET out=d
IF %ecode% EQU 31 SET out=e
IF %ecode% EQU 32 SET out=f
IF %ecode% EQU 33 SET out=g
IF %ecode% EQU 34 SET out=h
IF %ecode% EQU 35 SET out=i
IF %ecode% EQU 36 SET out=j
IF %ecode% EQU 37 SET out=k
IF %ecode% EQU 38 SET out=l
IF %ecode% EQU 39 SET out=m
IF %ecode% EQU 40 SET out=n
IF %ecode% EQU 41 SET out=o
IF %ecode% EQU 42 SET out=p
IF %ecode% EQU 43 SET out=q
IF %ecode% EQU 44 SET out=r
IF %ecode% EQU 45 SET out=s
IF %ecode% EQU 46 SET out=t
IF %ecode% EQU 47 SET out=u
IF %ecode% EQU 48 SET out=v
IF %ecode% EQU 49 SET out=w
IF %ecode% EQU 50 SET out=x
IF %ecode% EQU 51 SET out=y
IF %ecode% EQU 52 SET out=z
IF %ecode% EQU 53 SET out=0
IF %ecode% EQU 54 SET out=1
IF %ecode% EQU 55 SET out=2
IF %ecode% EQU 56 SET out=3
IF %ecode% EQU 57 SET out=4
IF %ecode% EQU 58 SET out=5
IF %ecode% EQU 59 SET out=6
IF %ecode% EQU 60 SET out=7
IF %ecode% EQU 61 SET out=8
IF %ecode% EQU 62 SET out=9
IF %ecode% EQU 63 SET out=!
IF %ecode% EQU 64 SET out=?
IF %ecode% EQU 65 SET out=.
SET code=%out%
SET show=*
:loop
cls
choice /C ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!?.# /N /CS /M Please enter your password to continue. (Valid characters include all letters, numbers, and ! ? .) Press # to submit: %code%
SET ecode=%ERRORLEVEL%
IF %ecode% EQU 66 goto submit
IF %ecode% EQU 1 SET out=A
IF %ecode% EQU 2 SET out=B
IF %ecode% EQU 3 SET out=C
IF %ecode% EQU 4 SET out=D
IF %ecode% EQU 5 SET out=E
IF %ecode% EQU 6 SET out=F
IF %ecode% EQU 7 SET out=G
IF %ecode% EQU 8 SET out=H
IF %ecode% EQU 9 SET out=I
IF %ecode% EQU 10 SET out=J
IF %ecode% EQU 11 SET out=K
IF %ecode% EQU 12 SET out=L
IF %ecode% EQU 13 SET out=M
IF %ecode% EQU 14 SET out=N
IF %ecode% EQU 15 SET out=O
IF %ecode% EQU 16 SET out=P
IF %ecode% EQU 17 SET out=Q
IF %ecode% EQU 18 SET out=R
IF %ecode% EQU 19 SET out=S
IF %ecode% EQU 20 SET out=T
IF %ecode% EQU 21 SET out=U
IF %ecode% EQU 22 SET out=V
IF %ecode% EQU 23 SET out=W
IF %ecode% EQU 24 SET out=X
IF %ecode% EQU 25 SET out=Y
IF %ecode% EQU 26 SET out=Z
IF %ecode% EQU 27 SET out=a
IF %ecode% EQU 28 SET out=b
IF %ecode% EQU 29 SET out=c
IF %ecode% EQU 30 SET out=d
IF %ecode% EQU 31 SET out=e
IF %ecode% EQU 32 SET out=f
IF %ecode% EQU 33 SET out=g
IF %ecode% EQU 34 SET out=h
IF %ecode% EQU 35 SET out=i
IF %ecode% EQU 36 SET out=j
IF %ecode% EQU 37 SET out=k
IF %ecode% EQU 38 SET out=l
IF %ecode% EQU 39 SET out=m
IF %ecode% EQU 40 SET out=n
IF %ecode% EQU 41 SET out=o
IF %ecode% EQU 42 SET out=p
IF %ecode% EQU 43 SET out=q
IF %ecode% EQU 44 SET out=r
IF %ecode% EQU 45 SET out=s
IF %ecode% EQU 46 SET out=t
IF %ecode% EQU 47 SET out=u
IF %ecode% EQU 48 SET out=v
IF %ecode% EQU 49 SET out=w
IF %ecode% EQU 50 SET out=x
IF %ecode% EQU 51 SET out=y
IF %ecode% EQU 52 SET out=z
IF %ecode% EQU 53 SET out=0
IF %ecode% EQU 54 SET out=1
IF %ecode% EQU 55 SET out=2
IF %ecode% EQU 56 SET out=3
IF %ecode% EQU 57 SET out=4
IF %ecode% EQU 58 SET out=5
IF %ecode% EQU 59 SET out=6
IF %ecode% EQU 60 SET out=7
IF %ecode% EQU 61 SET out=8
IF %ecode% EQU 62 SET out=9
IF %ecode% EQU 63 SET out=!
IF %ecode% EQU 64 SET out=?
IF %ecode% EQU 65 SET out=.
SET code=%code%%out%
SET show=%show%*
goto loop
:submit
cls
SET password=%code%
IF %password% EQU 0cZrocks! SET result=1
IF ELSE SET result=2
IF %result% EQU 1 echo password correct
IF %result% EQU 2 echo password incorrect
timeout /T 2 /NOBREAK >nul
cls
IF %result% EQU 1 goto end
IF ELSE goto start
:end
I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:
public class MyViewModel
{
[Required]
public string CategoryId { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
and in your controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Categories = Repository.GetCategories()
}
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// there was a validation error =>
// rebind categories and redisplay view
model.Categories = Repository.GetCategories();
return View(model);
}
// At this stage the model is OK => do something with the selected category
return RedirectToAction("Success");
}
}
and then in your strongly typed view:
@Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"),
"-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)
Also if you want client side validation don't forget to reference the necessary scripts:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:
{
"env": {},
"extends": [],
"parser": "",
"plugins": [],
"rules": {},
"overrides": [
{
"files": ["test/*.spec.js"], // Or *.test.js
"rules": {
"require-jsdoc": "off"
}
}
],
"settings": {}
}
I just fixed this issue by adding data-toggle="tab" element in anchor tag
<div class="container">
<!-------->
<div id="content">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#red">Red</a></li>
<li><a data-toggle="tab" href="#orange">Orange</a></li>
<li><a data-toggle="tab" href="#yellow">Yellow</a></li>
<li><a data-toggle="tab" href="#green">Green</a></li>
<li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="red">
<h1>Red</h1>
<p>red red red red red red</p>
</div>
<div class="tab-pane" id="orange">
<h1>Orange</h1>
<p>orange orange orange orange orange</p>
</div>
<div class="tab-pane" id="yellow">
<h1>Yellow</h1>
<p>yellow yellow yellow yellow yellow</p>
</div>
<div class="tab-pane" id="green">
<h1>Green</h1>
<p>green green green green green</p>
</div>
<div class="tab-pane" id="blue">
<h1>Blue</h1>
<p>blue blue blue blue blue</p>
and added the following in head section http://code.jquery.com/jquery-1.7.1.js'>
Import the view controller class which you want to show and use the following code
KartViewController *viewKart = [[KartViewController alloc]initWithNibName:@"KartViewController" bundle:nil];
[self presentViewController:viewKart animated:YES completion:nil];
I wanted to add my own answer as I needed a robust toTitleCase
function that takes into account grammar rules listed here (Google recommended article). There are various rules that depend on the length of the input string. Below is the function + unit tests.
The function also consolidates whitespace and removes special characters (modify regex for your needs)
toTitleCase Function
const toTitleCase = (str) => {
const articles = ['a', 'an', 'the'];
const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
const prepositions = [
'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',
'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'
];
// The list of spacial characters can be tweaked here
const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\]/gi, ' ').replace(/(\s\s+)/gi, ' ');
const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);
const normalizeStr = (str) => str.toLowerCase().trim();
const shouldCapitalize = (word, fullWordList, posWithinStr) => {
if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {
return true;
}
return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));
}
str = replaceCharsWithSpace(str);
str = normalizeStr(str);
let words = str.split(' ');
if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized
words = words.map(w => capitalizeFirstLetter(w));
}
else {
for (let i = 0; i < words.length; i++) {
words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);
}
}
return words.join(' ');
}
Unit Tests to Ensure Correctness
import { expect } from 'chai';
import { toTitleCase } from '../../src/lib/stringHelper';
describe('toTitleCase', () => {
it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){
expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long
expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long
expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long
});
it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){
expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');
expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');
expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');
});
it('Replace special characters with space', function(){
expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');
expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');
});
it('Trim whitespace at beginning and end', function(){
expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');
});
it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){
expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');
expect(toTitleCase('the three Musketeers And plus ')).to.equal('The Three Musketeers and Plus');
});
});
Please note that I am removing quite a bit of special characters from the strings provided. You will need to tweak the regex to address the requirements of your project.
You need to use delegates and protocols. Here is a site with an example http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
Try maybe this way
try{
double d= Double.valueOf(someString);
if (d==(int)d){
System.out.println("integer"+(int)d);
}else{
System.out.println("double"+d);
}
}catch(Exception e){
System.out.println("not number");
}
But all numbers outside Integers range (like "-1231231231231231238") will be treated as doubles. If you want to get rid of that problem you can try it this way
try {
double d = Double.valueOf(someString);
if (someString.matches("\\-?\\d+")){//optional minus and at least one digit
System.out.println("integer" + d);
} else {
System.out.println("double" + d);
}
} catch (Exception e) {
System.out.println("not number");
}
There are various management views built into the product. On SQL 2000 you'd use sysprocesses. On SQL 2K5 there are more views like sys.dm_exec_connections, sys.dm_exec_sessions and sys.dm_exec_requests.
There are also procedures like sp_who that leverage these views. In 2K5 Management Studio you also get Activity Monitor.
And last but not least there are community contributed scripts like the Who Is Active by Adam Machanic.
You can use this JavaScript function. Here you can display Redirection message to the user and redirected to the given URL.
<script type="text/javascript">
function Redirect()
{
window.location="http://www.newpage.com";
}
document.write("You will be redirected to a new page in 5 seconds");
setTimeout('Redirect()', 5000);
</script>
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
On Windows 7 I solved this by going into my environment settings (try this link for how) and adding user variables http_proxy
and https_proxy
with my proxy details.
Quick answer on OSX, set your environment variables.
>export PGHOST=localhost
>export PGPORT=5432
Or whatever you need.
If you go to chrome://extensions/, you can just toggle each extension one at a time and see which one is actually triggering the issue.
Once you toggle the extension off, refresh the page where you are seeing the error and wiggle the mouse around, or click. Mouse actions are the things that are throwing errors.
So I was able to pinpoint which extension was actually causing the issue and disable it.
Just use window.open()
function? The third parameter lets you specify window size.
var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
var URL = "https://www.linkedin.com/cws/share?mini=true&url=" + location.href;
var win = window.open(URL, "_blank", strWindowFeatures);
You can pass as many arguments as you want, separating them by commas:
{{ path('_files_manage', {project: project.id, user: user.id}) }}
Answer is adding this 2 lines of code to Global.asax.cs Application_Start method
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;
Reference: Handling Circular Object References
I'll share a code which has Basic Auth Header form data request body,
let username = 'test-name';
let password = 'EbQZB37gbS2yEsfs';
let formdata = new FormData();
let headers = new Headers();
formdata.append('grant_type','password');
formdata.append('username','testname');
formdata.append('password','qawsedrf');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch('https://www.example.com/token.php', {
method: 'POST',
headers: headers,
body: formdata
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
I know it's an old question, but I needed this solution too, and I acme with another solution.
I used an entrypoint.sh to execute the following line, and define a variable with the actual hostname for that instance:
HOST=`hostname --fqdn`
Then, I used it across my entrypoint script:
echo "Value: $HOST"
Hope this helps
THIS IS FOR BEGINNERS,
Python automatically compiles your script to compiled code, so called byte code, before running it.
Running a script is not considered an import and no .pyc will be created.
For example, if you have a script file abc.py that imports another module xyz.py, when you run abc.py, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported.
If you need to create a .pyc file for a module that is not imported, you can use the py_compile
and compileall
modules.
The py_compile
module can manually compile any module. One way is to use the py_compile.compile
function in that module interactively:
>>> import py_compile
>>> py_compile.compile('abc.py')
This will write the .pyc to the same location as abc.py (you can override that with the optional parameter cfile
).
You can also automatically compile all files in a directory or directories using the compileall module.
python -m compileall
If the directory name (the current directory in this example) is omitted, the module compiles everything found on sys.path
Your call to text()
doesn't output anything because you inverted your x and your y:
plot(abs_losses, percent_losses,
main= "Absolute Losses vs. Relative Losses(in%)",
xlab= "Losses (absolute, in miles of millions)",
ylab= "Losses relative (in % of January´2007 value)",
col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)
text(abs_losses, percent_losses, labels=namebank, cex= 0.7)
Now if you want to move your labels down, left, up or right you can add argument pos=
with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)
You can of course gives a vector of value to pos
if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):
pos_vector <- rep(3, length(namebank))
pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)
I tried the above and adding the registry keys to the LOCALMACHINE was not getting the job done. So in case you are still stuck , try this.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SOFTWARE\Python]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help\Main Python Documentation] @="C:\Python27\Doc\python272.chm"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath] @="C:\Python27\"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath\InstallGroup] @="Python 2.7"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Modules]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\PythonPath] @="C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk"
Copy paste the above in notepad and save it as Python27.reg . Now run/merge the file as mentioned in the answers above. (Make sure the paths of Python installation are corrected as per your installation.
It simply does ,what the above answers suggest for a local machine ,to the current user.
For android studio users:
The gradle will rebuild the project automatically.
As of jQuery 1.7 you should use jQuery.fn.on
with the selector parameter filled:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Explanation:
This is called event delegation and works as followed. The event is attached to a static parent (staticAncestors
) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild
). When there is a match then your custom handler function is executed.
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8
into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.
Use find
with a wildcard:
find . -name 'mystring*'
Your URL probably has ampersands in it. I had this problem, too, and I realized that my URL was full of ampersands (from CGI variables being passed) and so everything was getting sent to background in a weird way and thus not redirecting properly. If you put quotes around the URL it will fix it.
the discussion and answer here was massively helpful to me:
//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>
It the case of HashSet, it does NOT replace it.
From the docs:
http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add(E)
"Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false."
There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.
Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.
Another useful thing to do with numpy.histogram
is to plot the output as the x and y coordinates on a linegraph. For example:
arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()
This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.
Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do
select dbo.fun_functional_score('01091400003') as [er]
Aside from the Documents
folder, iOS also lets you save files to the temp
and Library
folders.
For more information on which one to use, see this link from the documentation:
In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm
isn't working when you put it in CFLAGS
(CFLAGS
is used in the compilation stage).
The convention for libraries to be linked is to place them in either LOADLIBES
or LDLIBS
(GNU make includes both, but your mileage may vary):
LDLIBS=-lm
This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p
). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l
directives), you'll need to write your own:
client.o: client.c
$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<
client: client.o
$(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@
You can delete rows from a table using a workaround, in which you overwrite the table by the dataset you want left into the table as a result of your operation.
insert overwrite table your_table
select * from your_table
where id <> 1
;
The workaround is useful mostly for bulk deletions of easily identifiable rows. Also, obviously doing this can muck up your data, so a backup of the table is adviced and care when planning the "deletion" rule also adviced.
It is used in transaction management to ensure that any errors result in the transaction being rolled back.
For anybody still interested:
http://wiki.phonegap.com/w/page/16494815/Preventing-Scrolling-on-iPhone-Phonegap-Applications
From the page:
<meta name="viewport" content="user-scalable=no,width=device-width" />
This instructs Safari to prevent the user from zooming into the page with the "pinch" gesture and fixes the width of the view port to the width of the screen, which ever orientation the iPhone is in.
Button endDataSendButton = (Button)findViewById(R.id.end_data_send_button);
Similarly you can get the text view by adding a id to it.
To expand upon Mr. Eels comment, you can do it like this:
File file = new File("C:\\A.txt");
FileWriter writer;
try {
writer = new FileWriter(file, true);
PrintWriter printer = new PrintWriter(writer);
printer.append("Sue");
printer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't say we ain't good to ya!
Here is the modified javascript function, it outputs Hue in set 0-360 degrees.
function rgbToHsl(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - b) / d ; break;
case g: h = 2 + ( (b - r) / d); break;
case b: h = 4 + ( (r - g) / d); break;
}
h*=60;
if (h < 0) h +=360;
}
return([h, s, l]);
}
alert(rgbToHsl(125,115,145));
%
(any host) (see manual for details)The current problem is the first one, but right after you resolve it you will likely get the second one.
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
patchFor(answer @gary) :
$ git diff JSONObject.java
diff --git a/JSONObject.java b/JSONObject.java
index e28c9cd..e12b7a0 100755
--- a/JSONObject.java
+++ b/JSONObject.java
@@ -32,7 +32,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Enumeration;
-import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
@@ -152,7 +152,9 @@ public class JSONObject {
* Construct an empty JSONObject.
*/
public JSONObject() {
- this.map = new HashMap<String, Object>();
+// this.map = new HashMap<String, Object>();
+ // I want to keep order of the given data:
+ this.map = new LinkedHashMap<String, Object>();
}
/**
@@ -243,7 +245,7 @@ public class JSONObject {
* @throws JSONException
*/
public JSONObject(Map<String, Object> map) {
- this.map = new HashMap<String, Object>();
+ this.map = new LinkedHashMap<String, Object>();
if (map != null) {
Iterator<Entry<String, Object>> i = map.entrySet().iterator();
while (i.hasNext()) {
You can try the QueryPerformanceCounter
native method. See http://www.pinvoke.net/default.aspx/kernel32/QueryPerformanceCounter.html for more information. This is what the Stopwatch
class uses.
See How to get timestamp of tick precision in .NET / C#? for more information.
Stopwatch.GetTimestamp()
gives access to this method:
public static long GetTimestamp() {
if(IsHighResolution) {
long timestamp = 0;
SafeNativeMethods.QueryPerformanceCounter(out timestamp);
return timestamp;
}
else {
return DateTime.UtcNow.Ticks;
}
}
I solved this using attribute minChars:0 and after, trigger two clicks. (autocomplete shows after 1 click on input) my code
<input type='text' onfocus='setAutocomplete(this)'>
function setAutocomplete(el){
$(el).unbind().autocomplete("./index.php", {autoFill:false, minChars:0, matchContains:true, max:20});
$(el).trigger("click");$(el).trigger("click");
}
As Ben said, you'll need to work with the UIView's
layer, using a CATransform3D
to perform the layer's
rotation
. The trick to get perspective working, as described here, is to directly access one of the matrix cells
of the CATransform3D
(m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:
Objective-C
UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;
Swift 5.0
if let myView = self.subviews.first {
let layer = myView.layer
var rotationAndPerspectiveTransform = CATransform3DIdentity
rotationAndPerspectiveTransform.m34 = 1.0 / -500
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
layer.transform = rotationAndPerspectiveTransform
}
which rebuilds the layer transform from scratch for each rotation.
A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers
, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.
The sublayerTransform
you refer to in your response is a transform that is applied to the sublayers of your UIView's
CALayer
. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers
contained within the one layer that I'm rotating.
i found another way without much effort.
Just simply right click your solution and then click undo pending changes.
Next, VS will ask you for acutally changed file where you want to undo or not specific file.
In this you can click no for such a file where actual change is happende, rest is just undoing. This will not lost your actual changes
Convert the series to a dataframe and transpose it, then append normally.
srs = srs.to_frame().T
df = df.append(srs)
You are using the wrong URL (you are using the URL for the html webpage). Try either of these instead:
https://github.com/facebook/facebook-android-sdk.git
git://github.com/facebook/facebook-android-sdk.git