Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
Bootstrap 4
<div class="col-md-9 col-xs-12 text-md-left text-center">md left, xs center</div>
<div class="col-md-9 col-xs-12 text-md-right text-center">md right, xs center</div>
An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. @pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:
function validatePassword() {
const password = document.getElementById("password");
const confirm_password = document.getElementById("password_confirm");
if (password.value.length === 0) {
return false;
}
if (password.value !== confirm_password.value) {
return false;
}
return true;
}
You can try the following. It's working...
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
template <class T>
string to_string(T t, ios_base & (*f)(ios_base&))
{
ostringstream oss;
oss << f << t;
return oss.str();
}
int main ()
{
cout<<to_string<long>(123456, hex)<<endl;
system("PAUSE");
return 0;
}
in the "global and static" area :)
There are several memory areas in C++:
See here for a detailed answer to your question:
The following summarizes a C++ program's major distinct memory areas. Note that some of the names (e.g., "heap") do not appear as such in the draft [standard].
Memory Area Characteristics and Object Lifetimes
-------------- ------------------------------------------------
Const Data The const data area stores string literals and
other data whose values are known at compile
time. No objects of class type can exist in
this area. All data in this area is available
during the entire lifetime of the program.
Further, all of this data is read-only, and the
results of trying to modify it are undefined.
This is in part because even the underlying
storage format is subject to arbitrary
optimization by the implementation. For
example, a particular compiler may store string
literals in overlapping objects if it wants to.
Stack The stack stores automatic variables. Typically
allocation is much faster than for dynamic
storage (heap or free store) because a memory
allocation involves only pointer increment
rather than more complex management. Objects
are constructed immediately after memory is
allocated and destroyed immediately before
memory is deallocated, so there is no
opportunity for programmers to directly
manipulate allocated but uninitialized stack
space (barring willful tampering using explicit
dtors and placement new).
Free Store The free store is one of the two dynamic memory
areas, allocated/freed by new/delete. Object
lifetime can be less than the time the storage
is allocated; that is, free store objects can
have memory allocated without being immediately
initialized, and can be destroyed without the
memory being immediately deallocated. During
the period when the storage is allocated but
outside the object's lifetime, the storage may
be accessed and manipulated through a void* but
none of the proto-object's nonstatic members or
member functions may be accessed, have their
addresses taken, or be otherwise manipulated.
Heap The heap is the other dynamic memory area,
allocated/freed by malloc/free and their
variants. Note that while the default global
new and delete might be implemented in terms of
malloc and free by a particular compiler, the
heap is not the same as free store and memory
allocated in one area cannot be safely
deallocated in the other. Memory allocated from
the heap can be used for objects of class type
by placement-new construction and explicit
destruction. If so used, the notes about free
store object lifetime apply similarly here.
Global/Static Global or static variables and objects have
their storage allocated at program startup, but
may not be initialized until after the program
has begun executing. For instance, a static
variable in a function is initialized only the
first time program execution passes through its
definition. The order of initialization of
global variables across translation units is not
defined, and special care is needed to manage
dependencies between global objects (including
class statics). As always, uninitialized proto-
objects' storage may be accessed and manipulated
through a void* but no nonstatic members or
member functions may be used or referenced
outside the object's actual lifetime.
All objects that would be associated with the .click must exist when you set the event.
Example: (in pseudo code) the append can be $("body").append()
for example
append('<div id="foo" class="something">...</div>');
$("div.something").click(function(){...});
append('<div id="bar" class="something">...</div>');
Click works for foo but doesn't work for bar
Example2:
append('<div id="foo" class="something">...</div>');
$("div.something").live("click",function(){...});
append('<div id="bar" class="something">...</div>');
click works for both foo and bar
With .live('click'... you can dynamicaly add more objects after you created the event and the clicking event will still work.
I am willing to bet some of my reputation that there is no such thing.
Partially because if you are worried about cross-platform SQL compatibility, your best bet in turn is to abstract your database code with some API or ORM tool that handles these things for you, and is well supported, so will deal with newer database versions as they come out.
Exact kind of API available to you will be dependent on your programming language/platform. For example, PHP has Pear:DB and others, I personally have found quite nice Python's ORM features implemented in Django framework. I presume there should be some of these things available on other platforms as well.
For ones who got permission denied
for saving operation, here is the command that worked for me:
$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png --output py.png
I didn't have much luck with many of these solutions on all browsers. This is the solution that worked for me.
For router changes:
router.events.subscribe((val) => {
setTimeout(() => {
if (this.searchElement) {
this.searchElement.nativeElement.focus();
}
}, 1);
})
Then ngAfterViewInit()
for the onload scenario.
As of API 26, getDeviceId() is deprecated. If you need to get the IMEI of the device, use the following:
String deviceId = "";
if (Build.VERSION.SDK_INT >= 26) {
deviceId = getSystemService(TelephonyManager.class).getImei();
}else{
deviceId = getSystemService(TelephonyManager.class).getDeviceId();
}
First, you use include_directories()
to tell CMake to add the directory as -I
to the compilation command line. Second, you list the headers in your add_executable()
or add_library()
call.
As an example, if your project's sources are in src
, and you need headers from include
, you could do it like this:
include_directories(include)
add_executable(MyExec
src/main.c
src/other_source.c
include/header1.h
include/header2.h
)
It's useful to work with Deferred Object in this case, and return promise:
function readImage(inputElement) {
var deferred = $.Deferred();
var files = inputElement.get(0).files;
if (files && files[0]) {
var fr= new FileReader();
fr.onload = function(e) {
deferred.resolve(e.target.result);
};
fr.readAsDataURL( files[0] );
} else {
deferred.resolve(undefined);
}
return deferred.promise();
}
And above function could be used in this way:
var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
alert(base64Data);
});
Or in your case:
$(input).on('change',function(){
readImage($(this)).done(function(base64Data){ alert(base64Data); });
});
Hm.
You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo)
Following code works well for me
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
Point p = e.GetPosition(this);
}
I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow
will help you.
@Adam Rosenfield's solution, although correct, could be implemented with a more lightweight circular_buffer
structure that does not invlove count
and capacity
.
The structure could only hold the following 4 pointers:
buffer
: Points to the start of the buffer in memory.buffer_end
: Points to the end of the buffer in memory.head
: Points to the end of stored data.tail
: Points to the start of stored data.We could keep the sz
attribute to allow the parametrisation of the unit of storage.
Both the count
and the capacity
values should be derive-able using the above pointers.
capacity
is straight forward, as it can be derived by dividing the distance between the buffer_end
pointer and the buffer
pointer by the unit of storage sz
(snippet below is pseudocode):
capacity = (buffer_end - buffer) / sz
For count though, things get a bit more complicated. For example, there is no way to determine whether the buffer is empty or full, in the scenario of head
and tail
pointing to the same location.
To tackle that, the buffer should allocate memory for an additional element. For example, if the desired capacity of our circular buffer is 10 * sz
, then we need to allocate 11 * sz
.
Capacity formula will then become (snippet below is pseudocode):
capacity_bytes = buffer_end - buffer - sz
capacity = capacity_bytes / sz
This extra element semantic allows us to construct conditions that evaluate whether the buffer is empty or full.
In order for the buffer to be empty, the head
pointer points to the same location as the tail
pointer:
head == tail
If the above evaluates to true, the buffer is empty.
In order for the buffer to be full, the head
pointer should be 1 element behind the tail
pointer. Thus, the space needed to cover in order to jump from the head
location to the tail
location should be equal to 1 * sz
.
tail
is larger that head
:tail - head == sz
If the above evaluates to true, the buffer is full.
head
is larger that tail
:buffer_end - head
returns the space to jump from the head
to the end of the buffer.tail - buffer
returns the space needed to jump from the start of the buffer to the `tail.head
to the tail
1 * sz
(buffer_end - head) + (tail - buffer) == sz
=> buffer_end - buffer - head + tail == sz
=> buffer_end - buffer - sz == head - tail
=> head - tail == buffer_end - buffer - sz
=> head - tail == capacity_bytes
If the above evaluates to true, the buffer is full.
Modifying @Adam Rosenfield's to use the above circular_buffer
structure:
#include <string.h>
#define CB_SUCCESS 0 /* CB operation was successful */
#define CB_MEMORY_ERROR 1 /* Failed to allocate memory */
#define CB_OVERFLOW_ERROR 2 /* CB is full. Cannot push more items. */
#define CB_EMPTY_ERROR 3 /* CB is empty. Cannot pop more items. */
typedef struct circular_buffer {
void *buffer;
void *buffer_end;
size_t sz;
void *head;
void *tail;
} circular_buffer;
int cb_init(circular_buffer *cb, size_t capacity, size_t sz) {
const int incremented_capacity = capacity + 1; // Add extra element to evaluate count
cb->buffer = malloc(incremented_capacity * sz);
if (cb->buffer == NULL)
return CB_MEMORY_ERROR;
cb->buffer_end = (char *)cb->buffer + incremented_capacity * sz;
cb->sz = sz;
cb->head = cb->buffer;
cb->tail = cb->buffer;
return CB_SUCCESS;
}
int cb_free(circular_buffer *cb) {
free(cb->buffer);
return CB_SUCCESS;
}
const int _cb_length(circular_buffer *cb) {
return (char *)cb->buffer_end - (char *)cb->buffer;
}
int cb_push_back(circular_buffer *cb, const void *item) {
const int buffer_length = _cb_length(cb);
const int capacity_length = buffer_length - cb->sz;
if ((char *)cb->tail - (char *)cb->head == cb->sz ||
(char *)cb->head - (char *)cb->tail == capacity_length)
return CB_OVERFLOW_ERROR;
memcpy(cb->head, item, cb->sz);
cb->head = (char*)cb->head + cb->sz;
if(cb->head == cb->buffer_end)
cb->head = cb->buffer;
return CB_SUCCESS;
}
int cb_pop_front(circular_buffer *cb, void *item) {
if (cb->head == cb->tail)
return CB_EMPTY_ERROR;
memcpy(item, cb->tail, cb->sz);
cb->tail = (char*)cb->tail + cb->sz;
if(cb->tail == cb->buffer_end)
cb->tail = cb->buffer;
return CB_SUCCESS;
}
It's not strictly a jQuery answer - but useful to mention for debugging.
In Firebug you can right-click on an element in the DOM tree and set up 'Break on Attribute Change':
When an attribute is changed in a script, the debug window will appear and you can track down what it going on. There is also an option for element insertion and element removal below (unhelpfully obscured by the popup in the screengrab).
Defining static properties and methods of a class is described in 8.2.1 of the Typescript Language Specification:
class Point {
constructor(public x: number, public y: number) {
throw new Error('cannot instantiate using a static class');
}
public distance(p: Point) {
var dx = this.x - p.x;
var dy = this.y - p.y;
return Math.sqrt(dx * dx + dy * dy);
}
static origin = new Point(0, 0);
static distance(p1: Point, p2: Point) {
return p1.distance(p2);
}
}
where Point.distance()
is a static (or "class") method.
If for some reason you have created a mixed-case or upper-case column name, you need to quote it, or get this error:
test=> create table moo("FOO" int);
CREATE TABLE
test=> select * from moo;
FOO
-----
(0 rows)
test=> select "foo" from moo;
ERROR: column "foo" does not exist
LINE 1: select "foo" from moo;
^
test=> _
Note how the error message gives the case in quotes.
The best way to do this is this:
datetimepicker.Format = DatetimePickerFormat.Custom;
datetimepicker.CustomFormat = "HH:mm tt";
datetimepicker.ShowUpDowm = true;
In vb.net or C# I would expect that the fastest general approach to compare a variable against any reasonable number of separately-named objects (as opposed to e.g. all the things in a collection) will be to simply compare each object against the comparand much as you have done. It is certainly possible to create an instance of a collection and see if it contains the object, and doing so may be more expressive than comparing the object against all items individually, but unless one uses a construct which the compiler can explicitly recognize, such code will almost certainly be much slower than simply doing the individual comparisons. I wouldn't worry about speed if the code will by its nature run at most a few hundred times per second, but I'd be wary of the code being repurposed to something that's run much more often than originally intended.
An alternative approach, if a variable is something like an enumeration type, is to choose power-of-two enumeration values to permit the use of bitmasks. If the enumeration type has 32 or fewer valid values (e.g. starting Harry=1, Ron=2, Hermione=4, Ginny=8, Neville=16) one could store them in an integer and check for multiple bits at once in a single operation ((if ((thisOne & (Harry | Ron | Neville | Beatrix)) != 0) /* Do something */. This will allow for fast code, but is limited to enumerations with a small number of values.
A somewhat more powerful approach, but one which must be used with care, is to use some bits of the value to indicate attributes of something, while other bits identify the item. For example, bit 30 could indicate that a character is male, bit 29 could indicate friend-of-Harry, etc. while the lower bits distinguish between characters. This approach would allow for adding characters who may or may not be friend-of-Harry, without requiring the code that checks for friend-of-Harry to change. One caveat with doing this is that one must distinguish between enumeration constants that are used to SET an enumeration value, and those used to TEST it. For example, to set a variable to indicate Harry, one might want to set it to 0x60000001, but to see if a variable IS Harry, one should bit-test it with 0x00000001.
One more approach, which may be useful if the total number of possible values is moderate (e.g. 16-16,000 or so) is to have an array of flags associated with each value. One could then code something like "if (((characterAttributes[theCharacter] & chracterAttribute.Male) != 0)". This approach will work best when the number of characters is fairly small. If array is too large, cache misses may slow down the code to the point that testing against a small number of characters individually would be faster.
I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib). This means they either implement an interface at runtime (that's what EasyMock does if I'm not mistaken), or they inherit from the class to mock (that's what Mockito does if I'm not mistaken). Both approaches do not work for static members, since you can't override them using inheritance.
The only way to mock statics is to modify a class' byte code at runtime, which I suppose is a little more involved than inheritance.
That's my guess at it, for what it's worth...
[Closure and strong reference cycles]
As you know Swift's closure can capture the instance. It means that you are able to use self
inside a closure. Especially escaping closure
[About] can create a strong reference cycle
[About]. By the way you have to explicitly use self
inside escaping closure
.
Swift closure has Capture List
feature which allows you to avoid such situation and break a reference cycle because do not have a strong reference to captured instance. Capture List element is a pair of weak
/unowned
and a reference to class or variable.
For example
class A {
private var completionHandler: (() -> Void)!
private var completionHandler2: ((String) -> Bool)!
func nonescapingClosure(completionHandler: () -> Void) {
print("Hello World")
}
func escapingClosure(completionHandler: @escaping () -> Void) {
self.completionHandler = completionHandler
}
func escapingClosureWithPArameter(completionHandler: @escaping (String) -> Bool) {
self.completionHandler2 = completionHandler
}
}
class B {
var variable = "Var"
func foo() {
let a = A()
//nonescapingClosure
a.nonescapingClosure {
variable = "nonescapingClosure"
}
//escapingClosure
//strong reference cycle
a.escapingClosure {
self.variable = "escapingClosure"
}
//Capture List - [weak self]
a.escapingClosure {[weak self] in
self?.variable = "escapingClosure"
}
//Capture List - [unowned self]
a.escapingClosure {[unowned self] in
self.variable = "escapingClosure"
}
//escapingClosureWithPArameter
a.escapingClosureWithPArameter { [weak self] (str) -> Bool in
self?.variable = "escapingClosureWithPArameter"
return true
}
}
}
weak
- more preferable, use it when it is possibleunowned
- use it when you are sure that lifetime of instance owner is bigger than closureCheck out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)
Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.
If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:
my %new_hash = %hash1; # make a copy; leave %hash1 alone
foreach my $key2 ( keys %hash2 )
{
if( exists $new_hash{$key2} )
{
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else
{
$new_hash{$key2} = $hash2{$key2};
}
}
If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.
foreach my $key2 ( keys %hash2 )
{
if( exists $hash1{$key2} )
{
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else
{
$hash1{$key2} = $hash2{$key2};
}
}
If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:
@hash1{ keys %hash2 } = values %hash2;
The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.
15.1.2 UAS Behavior==> BYE Handling in RFC 3261
The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.
This is my solution to this problem:
vector<string> get_tokens(string str) {
vector<string> dt;
stringstream ss;
string tmp;
ss << str;
for (size_t i; !ss.eof(); ++i) {
ss >> tmp;
dt.push_back(tmp);
}
return dt;
}
This function returns a vector of strings.
If this needs to work in IE 7 or lower you need to remember that getElementsByClassName does not exist in all browsers. Because of this you can create your own getElementsByClassName or you can try this.
var fooDiv = document.getElementById("foo");
for (var i = 0, childNode; i <= fooDiv.childNodes.length; i ++) {
childNode = fooDiv.childNodes[i];
if (/bar/.test(childNode.className)) {
childNode.innerHTML = "Goodbye world!";
}
}
A good example of real time found from here:-
A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.
A business example:
I have a persistance engine that will work against any data sourcer (XML, ASCII (delimited and fixed-length), various JDBC sources (Oracle, SQL, ODBC, etc.) I created a base, abstract class to provide common functionality in this persistance, but instantiate the appropriate "Port" (subclass) when persisting my objects. (This makes development of new "Ports" much easier, since most of the work is done in the superclasses; especially the various JDBC ones; since I not only do persistance but other things [like table generation], I have to provide the various differences for each database.) The best business examples of Interfaces are the Collections. I can work with a java.util.List without caring how it is implemented; having the List as an abstract class does not make sense because there are fundamental differences in how anArrayList works as opposed to a LinkedList. Likewise, Map and Set. And if I am just working with a group of objects and don't care if it's a List, Map, or Set, I can just use the Collection interface.
This is whole story how date problem was and how Big DBMSs handled these problems.
During the period between 1 A.D. and today, the Western world has actually used two main calendars: the Julian calendar of Julius Caesar and the Gregorian calendar of Pope Gregory XIII. The two calendars differ with respect to only one rule: the rule for deciding what a leap year is. In the Julian calendar, all years divisible by four are leap years. In the Gregorian calendar, all years divisible by four are leap years, except that years divisible by 100 (but not divisible by 400) are not leap years. Thus, the years 1700, 1800, and 1900 are leap years in the Julian calendar but not in the Gregorian calendar, while the years 1600 and 2000 are leap years in both calendars.
When Pope Gregory XIII introduced his calendar in 1582, he also directed that the days between October 4, 1582, and October 15, 1582, should be skipped—that is, he said that the day after October 4 should be October 15. Many countries delayed changing over, though. England and her colonies didn't switch from Julian to Gregorian reckoning until 1752, so for them, the skipped dates were between September 4 and September 14, 1752. Other countries switched at other times, but 1582 and 1752 are the relevant dates for the DBMSs that we're discussing.
Thus, two problems arise with date arithmetic when one goes back many years. The first is, should leap years before the switch be calculated according to the Julian or the Gregorian rules? The second problem is, when and how should the skipped days be handled?
This is how the Big DBMSs handle these questions:
- Pretend there was no switch. This is what the SQL Standard seems to require, although the standard document is unclear: It just says that dates are "constrained by the natural rules for dates using the Gregorian calendar"—whatever "natural rules" are. This is the option that DB2 chose. When there is a pretence that a single calendar's rules have always applied even to times when nobody heard of the calendar, the technical term is that a "proleptic" calendar is in force. So, for example, we could say that DB2 follows a proleptic Gregorian calendar.
- Avoid the problem entirely. Microsoft and Sybase set their minimum date values at January 1, 1753, safely past the time that America switched calendars. This is defendable, but from time to time complaints surface that these two DBMSs lack a useful functionality that the other DBMSs have and that the SQL Standard requires.
- Pick 1582. This is what Oracle did. An Oracle user would find that the date-arithmetic expression October 15 1582 minus October 4 1582 yields a value of 1 day (because October 5–14 don't exist) and that the date February 29 1300 is valid (because the Julian leap-year rule applies). Why did Oracle go to extra trouble when the SQL Standard doesn't seem to require it? The answer is that users might require it. Historians and astronomers use this hybrid system instead of a proleptic Gregorian calendar. (This is also the default option that Sun picked when implementing the GregorianCalendar class for Java—despite the name, GregorianCalendar is a hybrid calendar.)
for Oralce Java 6:
private static int chmod(String filename, int mode) {
try {
Class<?> fspClass = Class.forName("java.util.prefs.FileSystemPreferences");
Method chmodMethod = fspClass.getDeclaredMethod("chmod", String.class, Integer.TYPE);
chmodMethod.setAccessible(true);
return (Integer)chmodMethod.invoke(null, filename, mode);
} catch (Throwable ex) {
return -1;
}
}
works under solaris/linux.
guess you could echo the meta tag to do the refresh in regular intervals ... like
<meta http-equiv="refresh" content="600" url="your-url-here">
This error can be caused by the permissions to the file, which you should check, however recently I noticed that the same is thrown if the file has been transferred and windows has marked the file as 'Encrypt Contents to Secure Data'.
You can find this by bringing up the .bak file properties and clicking the advanced button, it appears as the last check box on the dialog.
Hope that helps someone!
There is a very good real-life example of the pattern - The car starter engine.
As drivers, we just turn the key on and the car get started. As simple as possible. Behind the scenes, many other car systems are involved (as battery, engine, fuel, etc.), in order the car to start successfully, but they are hidden behind the starter.
As you can see, the car starter is the Facade. It gives us easy to use interface, without worrying about the complexity of all other car systems.
Let's summarize:
The Facade pattern simplifies and hides the complexity of large code blocks or APIs, providing a cleaner, understandable and easy of use interface.
I too got this error. Incidentally, i typed __int__ instead of __init__.
I think, in many mistype cases the IDE i am using (IntelliJ) would have changed the color to the default set for Function definition. But, in my case __int__ being another dunder/magic method, color remained same as the one which IDE displays for __init__ (default Predefined item definition color), which took me some time in spotting the missing i.
I really like the MySQL collection of of GUI Tools. They aren't too large or resource hungry.
There are quite a few options here as well. Of the applications presented on that page, I like SQL Buddy - it does require a web server, however.
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as @eumiro has pointed out in comments - strftime
The three dot (...) notation is actually borrowed from mathematics, and it means "...and so on".
As for its use in Java, it stands for varargs
, meaning that any number of arguments can be added to the method call. The only limitations are that the varargs
must be at the end of the method signature and there can only be one per method.
For DEFAULT CURRENT_TIMESTAMP:
ALTER TABLE tablename
CHANGE COLUMN columnname1 columname1 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHANGE COLUMN columnname2 columname2 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Please note double columnname declaration
Removing DEFAULT CURRENT_TIMESTAMP:
ALTER TABLE tablename
ALTER COLUMN columnname1 DROP DEFAULT,
ALTER COLUMN columnname2 DROPT DEFAULT;
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
I use backgroundrb.
http://backgroundrb.rubyforge.org/
I use it to run scheduled tasks as well as tasks that take too long for the normal client/server relationship.
The problem appears to be that despite listing your dependencies in the pom.xml, IntelliJ IDEA does not rebuild those dependencies when you run your project.
What worked for me is this:
Go to 'Run' -> 'Edit Configurations...', find your application, make sure the "Before launch:" section is expanded, click the green plus sign, and select "Build Project".
You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).
Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.
Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.
I guess the most universal solution here - is to check for undefined
and null
first, then just call constructor.name.toLowerCase()
.
const getType = v =>
v === undefined
? 'undefined'
: v === null
? 'null'
: v.constructor.name.toLowerCase();
console.log(getType(undefined)); // 'undefined'
console.log(getType(null)); // 'null'
console.log(getType('')); // 'string'
console.log(getType([])); // 'array'
console.log(getType({})); // 'object'
console.log(getType(new Set())); // `set'
console.log(getType(Promise.resolve())); // `promise'
console.log(getType(new Map())); // `map'
To save $4.99 for a one time use and no dealing with HomeBrew and no counting empty lines.
find . -name "*.swift" -print0 | xargs -0 wc -l
If you want to exclude pods:
find . -path ./Pods -prune -o -name "*.swift" -print0 ! -name "/Pods" | xargs -0 wc -l
If your project has objective c and swift:
find . -type d \( -path ./Pods -o -path ./Vendor \) -prune -o \( -iname \*.m -o -iname \*.mm -o -iname \*.h -o -iname \*.swift \) -print0 | xargs -0 wc -l
If you are using apache 2.2 inside your virtual host you should add following directive (mod_authz_host):
Order deny,allow
Deny from all
Allow from 10.0.0.1
You can even specify a subnet
Allow from 10.0.0
Apache 2.4 looks like a little different as configuration. Maybe better you specify which version of apache are you using.
I don't know why but you have to add a setTimeout with at least for me 200ms:
setTimeout( function() {$("#DIV_ID").scrollTop(0)}, 200 );
Tested with Firefox / Chrome / Edge.
Perhaps adobe's flash player detection kit could be helpful here?
http://www.adobe.com/products/flashplayer/download/detection_kit/
By lines I assume you mean rows in the table person
. What you're looking for is:
select p.name
from person p
where p.name LIKE '%A%'; --contains the character 'A'
The above is case sensitive. For a case insensitive search, you can do:
select p.name
from person p
where UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'
For the special character, you can do:
select p.name
from person p
where p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)
The LIKE
operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the %
sign as it means match zero or more characters.
As in 2016 from Firefox v45, innerText
works on firefox, take a look at its support: http://caniuse.com/#search=innerText
If you want it to work on previous versions of Firefox, you can use textContent
, which has better support on Firefox but worse on older IE versions: http://caniuse.com/#search=textContent
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options): https://jsfiddle.net/59x3m6op/1/
This will work :
<script type="text/javascript">
function closeWindowNoPrompt()
{
window.open('', '_parent', '');
window.close();
}
</script>
In the examples below the client is the browser and the server is the webserver hosting the website.
Before you can understand these technologies, you have to understand classic HTTP web traffic first.
The server sends an event to the client when there's new information available.
The server and the client can now send each other messages when new data (on either side) is available.
Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.
Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?
You can use PHP with WebSockets, check out Ratchet.
after passing the vector by reference
swap(vector[position],vector[otherPosition]);
will produce the expected result.
Make a batch file "Pc.bat" as, typeperf -sc 1 "\mukit\processor(_Total)\%% Processor Time"
You can use the class MProcess,
/* *Md. Mukit Hasan *CSE-JU,35 **/ import java.io.*;public class MProcessor {
public MProcessor() { String s; try { Process ps = Runtime.getRuntime().exec("Pc.bat"); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); while((s = br.readLine()) != null) { System.out.println(s); } } catch( Exception ex ) { System.out.println(ex.toString()); } }
}
Then after some string manipulation, you get the CPU use. You can use the same process for other tasks.
--Mukit Hasan
If you plan to use the signed distance calculation snippet posted by phi (like I did) and your b might have value 0, you probably want to fix the code as described below:
import math
def distance(a, b):
if (a == b):
return 0
elif (a < 0) and (b < 0) or (a > 0) and (b >= 0): # fix: b >= 0 to cover case b == 0
if (a < b):
return (abs(abs(a) - abs(b)))
else:
return -(abs(abs(a) - abs(b)))
else:
return math.copysign((abs(a) + abs(b)),b)
The original snippet does not work correctly regarding sign when a > 0 and b == 0.
In JSX/ React prevent text from wrapping
<div style={{ whiteSpace: "nowrap", overflow: "hidden" }}>
Text that will never wrap
</div>
There is a much easier way using the library http://svg.codeplex.com/ (Newer version @GIT, @NuGet). Here is my code
var byteArray = Encoding.ASCII.GetBytes(svgFileContents);
using (var stream = new MemoryStream(byteArray))
{
var svgDocument = SvgDocument.Open(stream);
var bitmap = svgDocument.Draw();
bitmap.Save(path, ImageFormat.Png);
}
Use the following commands:
openssl req -x509 -nodes -days 365 -sha256 -newkey rsa:2048 -keyout mycert.pem -out mycert.pem
Loading 'screen' into random state - done
Generating a 2048 bit RSA private key
.............+++
..................................................................................................................................................................+++
writing new private key to 'mycert.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
If you check there will be a file created by the name : mycert.pem
openssl rsa -in mycert.pem -pubout > mykey.txt
writing RSA key
If you check the same file location a new public key mykey.txt
has been created.
Use compareTo()
function that's built into the class.
Build.SERIAL
is the simplest way to go, although not entirely reliable as it can be empty or sometimes return a different value (proof 1, proof 2) than what you can see in your device's settings.
There are several ways to get that number depending on the device's manufacturer and Android version, so I decided to compile every possible solution I could found in a single gist. Here's a simplified version of it :
public static String getSerialNumber() {
String serialNumber;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serialNumber = (String) get.invoke(c, "gsm.sn1");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "ril.serialnumber");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "ro.serialno");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "sys.serialnumber");
if (serialNumber.equals(""))
serialNumber = Build.SERIAL;
// If none of the methods above worked
if (serialNumber.equals(""))
serialNumber = null;
} catch (Exception e) {
e.printStackTrace();
serialNumber = null;
}
return serialNumber;
}
This is documented in section 3.9.3 of the Spring 3.0 manual:
For a fallback match, the bean name is considered a default qualifier value.
In other words, the default behaviour is as though you'd added @Qualifier("country")
to the setter method.
[Mac only]
If you need to delete your authentication, use
git credential-osxkeychain erase
host=github.com
protocol=https
on Mac.
See https://help.github.com/articles/updating-credentials-from-the-osx-keychain/
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
distinct
is not a function. It always operates on all columns of the select list.
Your problem is a typical "greatest N per group" problem which can easily be solved using a window function:
select ...
from (
select IDNo,
FirstName,
LastName,
....,
row_number() over (partition by lower(idno) order by firstname) as rn
from people
) t
where rn = 1;
Using the order by
clause you can select which of the duplicates you want to pick.
The above can be used in a left join, see below:
select ...
from x
left join (
select IDNo,
FirstName,
LastName,
....,
row_number() over (partition by lower(idno) order by firstname) as rn
from people
) p on p.idno = x.idno and p.rn = 1
where ...
By using absolute positioning, you can make <body>
or <form>
or <div>
, fit to your browser page. For example:
<body style="position: absolute; bottom: 0px; top: 0px; left: 0px; right: 0px;">
and then simply put a <div>
inside it and use whatever percentage of either height
or width
you wish
<div id="divContainer" style="height: 100%;">
I would have a directory somewhere called scripts under the WWW folder so that it's not reachable from the web but is reachable by PHP.
e.g. /var/www/scripts/testscript
Make sure the user/group for your testscript
is the same as your webfiles. For instance if your client.php
is owned by apache:apache
, change the bash script to the same user/group using chown
. You can find out what your client.php
and web files are owned by doing ls -al
.
Then run
<?php
$message=shell_exec("/var/www/scripts/testscript 2>&1");
print_r($message);
?>
EDIT:
If you really want to run a file as root from a webserver you can try this binary wrapper below. Check out this solution for the same thing you want to do.
You can design a lowpass Butterworth filter in runtime, using butter()
function, and then apply that to the signal.
fc = 300; % Cut off frequency
fs = 1000; % Sampling rate
[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal
Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html
You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):
SELECT DISTINCT Left(LastName, 1)
FROM Authors;
SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;
Get Date::Manip from CPAN, then:
use Date::Manip;
$string = '18-Sep-2008 20:09'; # or a wide range of other date formats
$unix_time = UnixDate( ParseDate($string), "%s" );
edit:
Date::Manip is big and slow, but very flexible in parsing, and it's pure perl. Use it if you're in a hurry when you're writing code, and you know you won't be in a hurry when you're running it.
e.g. Use it to parse command line options once on start-up, but don't use it parsing large amounts of data on a busy web server.
See the authors comments.
(Thanks to the author of the first comment below)
From developer command prompt type
csc -langversion:?
That will display all C# versions supported including the default:
1
2
3
4
5
6
7.0 (default)
7.1
7.2
7.3 (latest)
In Route.config
namespaces: new[] { "Appname.Controllers" }
Potential danger of INSERT IGNORE. If you are trying to insert VARCHAR value longer then column was defined with - the value will be truncated and inserted EVEN IF strict mode is enabled.
I needed to extract all the matched search lines (using regex) in a file
selectHighlights
)Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes
https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task
As for me, this approach is prettier:
String.prototype.embraceWith = function(tag) {
return "<" + tag + ">" + this + "</" + tag + ">";
};
var results = [
{type:"Fiat", model:500, color:"white"},
{type:"Mercedes", model: "Benz", color:"black"},
{type:"BMV", model: "X6", color:"black"}
];
var tableHeader = ("Type".embraceWith("th") + "Model".embraceWith("th") + "Color".embraceWith("th")).embraceWith("tr");
var tableBody = results.map(function(item) {
return (item.type.embraceWith("td") + item.model.toString().embraceWith("td") + item.color.embraceWith("td")).embraceWith("tr")
}).join("");
var table = (tableHeader + tableBody).embraceWith("table");
$("#result-holder").append(table);
From the Android documentation:
The
CookieSyncManager
is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.To use the
CookieSyncManager
, the host application has to call the following when the application starts:CookieSyncManager.createInstance(context)
To set up for sync, the host application has to call
CookieSyncManager.getInstance().startSync()
in Activity.onResume(), and call
CookieSyncManager.getInstance().stopSync()
in Activity.onPause().
To get instant sync instead of waiting for the timer to trigger, the host can call
CookieSyncManager.getInstance().sync()
The sync interval is 5 minutes, so you will want to force syncs manually anyway, for instance in onPageFinished(WebView, String). Note that even sync() happens asynchronously, so don't do it just as your activity is shutting down.
Finally something like this should work:
// use cookies to remember a logged in status
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
setContentView(webview);
webview.loadUrl([MY URL]);
Add those line to your onBackPressed() Method. popBackStackImmediate() method will get you back to the previous fragment if you have any fragment on back stack `
if(getFragmentManager().getBackStackEntryCount() > 0){
getFragmentManager().popBackStackImmediate();
}
else{
super.onBackPressed();
}
`
Define 'active user'.
If the question is 'who is the logged in user', then 'who am i' or 'whoami' is fine (though they give different answers - 'whoami' reports just a user name; 'who am i' reports on terminal and login time too).
If the question is 'which user ID is the effective ID for the shell', then it is often better to use 'id'. This reports on the real and effective user ID and group ID, and on the supplementary group IDs too. This might matter if the shell is running SUID or SGID.
Since this is still the first result on the Googler when searching how to remove all modules in NPM, I figured I'd share a small script for Powershell to remove all dependencies through NPM:
#Create a Packages Array to add package names to
$Packages = New-Object System.Collections.ArrayList
#Get all Production Dependencies by name
(Get-Content .\Package.json | ConvertFrom-JSON).dependencies.psobject.properties.name |
ForEach-Object { $Packages.Add($_) | Out-Null }
#Get all Dev Dependencies by name
(Get-Content .\Package.json | ConvertFrom-JSON).devDependencies.psobject.properties.name |
ForEach-Object { $Packages.Add($_) | Out-Null }
#Remove each package individually
Foreach($Package in ($Packages | select -unique))
{ npm uninstall $Package }
#Clean up any remaining packages
$Modules = Get-ChildItem "node_modules"
if($Modules)
{ $Modules | ForEach-Object { Remove-Item ".\node_modules\$_" -Force -Recurse } }
This runs a more specific removal, rather than removing each module from node_modules individually.
In python3, if you a string of b'bytes'
, with json
you have to .decode()
the content before you can load it. simplejson
takes care of this so you can just do simplejson.loads(byte_string)
.
I can't leave this question in this state with that final code in the question hanging over me...
dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:
There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.
The with
statement (recommended in another answer) removes the bother of closing the file through the context handler.
Use a dictionary instead of two lists.
A generator comprehension ((x for y in z)
) is used to do the translation in one line.
Wrap as little code as you can in a try
/except
block to reduce the probability of catching an exception you didn't mean to.
Use the input()
argument rather than print()
ing first - Use '\n'
to get the new line you want.
Don't write code across multiple lines or with intermediate variables like this just for the sake of it:
a = a.b()
a = a.c()
b = a.x()
c = b.y()
Instead, write these constructs like this, chaining the calls as is perfectly valid:
a = a.b().c()
c = a.x().y()
code = {}
with open('morseCode.txt', 'r') as morse_code_file:
# line format is <letter>:<morse code translation>
for line in morse_code_file:
line = line.rstrip() # Remove NL
code[line[0]] = line[2:]
user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
try:
print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
except KeyError:
print("Error in input. Only alphanumeric characters, a comma, and period allowed")
user_input = input("Try again or press <enter> to quit\n")
This line right here:
export JAVA_LIBRARY_PATH=$HADOOP_HOME/lib/native:$JAVA_LIBRARY_PATH
From KunBetter's answer is where the money is
I had similar issue, the problem i faced was i added the selenium-server-standalone-3.141.59.jar under modulepath instead it should be under classpath
so select classpath via (project -> Properties -> Java Bbuild Path -> Libraries) add the downloaded latest jar
After adding it must be something like this
And appropriate driver for browser has to be downloaded for me i checked and downloaded the same version of chrom for chrome driver and added in the C:\Program Files\Java
And following is the code that worked fine for me
public class TestuiAautomation {
public static void main(String[] args) {
System.out.println("Jai Ganesha");
try {
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Java\\chromedriver.exe");
System.out.println(System.getProperty("webdriver.chrome.driver"));
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("no-sandbox");
chromeOptions.addArguments("--test-type");
chromeOptions.addArguments("disable-extensions");
chromeOptions.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://www.google.com");
System.out.println("Google is selected");
} catch (Exception e) {
System.err.println(e);
}
}
}
In Prepared Statements the user is forced to enter data as parameters . If user enters some vulnerable statements like DROP TABLE or SELECT * FROM USERS then data won't be affected as these would be considered as parameters of the SQL statement
This is a great resource and has worked very well, the few times I've used it. Creates the following code....
<style>
.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; }
.embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
</style>
<div class='embed-container'>
<iframe src='http://player.vimeo.com/video/66140585' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
</div>
you can use Vuex to handle all your global data
the answer is
Dictionary
take look at my function, its simple add uses most important member functions inside Dictionary
this function return false if the list contain Duplicates items
public static bool HasDuplicates<T>(IList<T> items)
{
Dictionary<T, bool> mp = new Dictionary<T, bool>();
for (int i = 0; i < items.Count; i++)
{
if (mp.ContainsKey(items[i]))
{
return true; // has duplicates
}
mp.Add(items[i], true);
}
return false; // no duplicates
}
Two comments on the use of SimpleDateFormat.
it should be declared as a static instance if declared as static access should be synchronized as it is not thread safe
IME that is better that instantiating an instance for each parse of a date.
You need to put the directory that has php.exe
in you WAMP
installation into your PATH
. It is usually something like C:\wamp\xampp\php
<!DOCTYPE html>
<html>
<head></head>
<body>
<p data-foo="0"></p>
<h6 data-foo="1"></h6>
<script>
var a = document.querySelectorAll('[data-foo]');
for (var i in a) if (a.hasOwnProperty(i)) {
alert(a[i].getAttribute('data-foo'));
}
</script>
</body>
</html>
Using the Promise pattern:
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
})
}
And when calling the function we can handle its response or error quite neatly.
getImage('imgUrl').then(function(successUrl){
//do stufff
}).catch(function(errorUrl){
//do stuff
})
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
Your code looks syntactically correct, but I think your property doesn't exist to create the URL.
I just tested it, and it works fine for me.
Try using category.idCategory
instead of category.id
, for example…
<tr th:each="category : ${categories}">
<td th:text="${category.idCategory}"></td>
<td th:text="${category.name}"></td>
<td>
<a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>
</td>
</tr>
If the millis value is number of millis since Jan 1, 1970 GMT, as is standard for the JVM, then that is independent of time zone. If you want to format it with a specific time zone, you can simply convert it to a GregorianCalendar object and set the timezone. After that there are numerous ways to format it.
I like bobince's answer:
placeholder= '?' # For SQLite. See DBAPI paramstyle.
placeholders= ', '.join(placeholder for unused in l)
query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
cursor.execute(query, l)
But I noticed this:
placeholders= ', '.join(placeholder for unused in l)
Can be replaced with:
placeholders= ', '.join(placeholder*len(l))
I find this more direct if less clever and less general. Here l
is required to have a length (i.e. refer to an object that defines a __len__
method), which shouldn't be a problem. But placeholder must also be a single character. To support a multi-character placeholder use:
placeholders= ', '.join([placeholder]*len(l))
From my experience, the way I do it is create a snapshot of your current image, then once its done you'll see it as an option when launching new instances. Simply launch it as a large instance at that point.
This is my approach if I do not want any downtime(i.e. production server) because this solution only takes a server offline only after the new one is up and running(I also use it to add new machines to my clusters by using this approach to only add new machines). If Downtime is acceptable then see Marcel Castilho's answer.
Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.
Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.
And fight the temptation of using eval
, that's not safe.
Weird! You are saying that you want to generate a recursion of 1<<15 depth???!!!!
I'd suggest DON'T try it. The size of the stack will be 2^15 * sizeof(stack-frame)
. I don't know what stack-frame size is, but 2^15 is 32.768. Pretty much... Well, if it stops at 1024 (2^10) you'll have to make it 2^5 times bigger, it is, 32 times bigger than with your actual setting.
jQuery doesn't have a convenient function for this. You need to combine contents()
, which will give just child nodes but includes text nodes, with find()
, which gives all descendant elements but no text nodes. Here's what I've come up with:
var getTextNodesIn = function(el) {
return $(el).find(":not(iframe)").addBack().contents().filter(function() {
return this.nodeType == 3;
});
};
getTextNodesIn(el);
Note: If you're using jQuery 1.7 or earlier, the code above will not work. To fix this, replace addBack()
with andSelf()
. andSelf()
is deprecated in favour of addBack()
from 1.8 onwards.
This is somewhat inefficient compared to pure DOM methods and has to include an ugly workaround for jQuery's overloading of its contents()
function (thanks to @rabidsnail in the comments for pointing that out), so here is non-jQuery solution using a simple recursive function. The includeWhitespaceNodes
parameter controls whether or not whitespace text nodes are included in the output (in jQuery they are automatically filtered out).
Update: Fixed bug when includeWhitespaceNodes is falsy.
function getTextNodesIn(node, includeWhitespaceNodes) {
var textNodes = [], nonWhitespaceMatcher = /\S/;
function getTextNodes(node) {
if (node.nodeType == 3) {
if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) {
textNodes.push(node);
}
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
getTextNodes(node.childNodes[i]);
}
}
}
getTextNodes(node);
return textNodes;
}
getTextNodesIn(el);
Yet another (dynamic) way:
$("form").validate().settings.ignore = "*";
And to re-enable it, we just set back the default value:
$("form").validate().settings.ignore = ":hidden";
Source: https://github.com/jzaefferer/jquery-validation/issues/725#issuecomment-17601443
It's easy way to use .match()
method to string.
var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));
Wish you a nice day, sir!
keytool
comes with the JDK installation (in the bin
folder):
keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"
This will create a new keystore and add just your certificate to it.
So, you can't convert a certificate to a keystore: you add a certificate to a keystore.
Use String#toLowerCase()
or String#equalsIgnoreCase()
methods
Some examples:
String abc = "Abc".toLowerCase();
boolean isAbc = "Abc".equalsIgnoreCase("ABC");
This will be the simplest solution. I tried most of the solutions in the internet but only this helped me.
@print{
@page :footer {color: #fff }
@page :header {color: #fff}
}
One-liner that does not change given array.
a[0].map((col, i) => a.map(([...row]) => row[i]))
First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.
Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.
How to decide whether to use Tomcat or a full stack Java EE
application server:
When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:
In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.
Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.
my 2 cent
Not CSS, but inline:
<a href="#"
onmouseover = "this.style.textDecoration = 'none'"
onmouseout = "this.style.textDecoration = 'underline'">Hello</a>
Others have explained that no, you don't want this in version control. You should configure your version control system to ignore the file (e.g. via a .gitignore
file).
To really understand why, it helps to see what's actually in this file. I wrote a command line tool that lets you see the .suo
file's contents.
Install it on your machine via:
dotnet tool install -g suo
It has two sub-commands, keys
and view
.
suo keys <path-to-suo-file>
This will dump out the key for each value in the file. For example (abridged):
nuget
ProjInfoEx
BookmarkState
DebuggerWatches
HiddenSlnFolders
ObjMgrContentsV8
UnloadedProjects
ClassViewContents
OutliningStateDir
ProjExplorerState
TaskListShortcuts
XmlPackageOptions
BackgroundLoadData
DebuggerExceptions
DebuggerFindSource
DebuggerFindSymbol
ILSpy-234190A6EE66
MRU Solution Files
UnloadedProjectsEx
ApplicationInsights
DebuggerBreakpoints
OutliningStateV1674
...
As you can see, lots of IDE features use this file to store their state.
Use the view
command to see a given key's value. For example:
$ suo view nuget --format=utf8 .suo
nuget
?{"WindowSettings":{"project:MyProject":{"SourceRepository":"nuget.org","ShowPreviewWindow":false,"ShowDeprecatedFrameworkWindow":true,"RemoveDependencies":false,"ForceRemove":false,"IncludePrerelease":false,"SelectedFilter":"UpdatesAvailable","DependencyBehavior":"Lowest","FileConflictAction":"PromptUser","OptionsExpanded":false,"SortPropertyName":"ProjectName","SortDirection":"Ascending"}}}
More information on the tool here: https://github.com/drewnoakes/suo
I did this solution: if you want plot more than one plot in one figure, make sure before plotting next plots you have set right matplotlib.pyplot.hold(True)
to able adding another plots.
Concerning the datetime values on the X axis, a solution using the alignment of bars works for me. When you create another bar plot with matplotlib.pyplot.bar()
, just use align='edge|center'
and set width='+|-distance'
.
When you set all bars (plots) right, you will see the bars fine.
val wifi = context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
if (wifi!!.isWifiEnabled)
//do action here
else
//do action here
postgres
UPDATE table1
SET COLUMN = value
FROM table2,
table3
WHERE table1.column_id = table2.id
AND table1.column_id = table3.id
AND table1.COLUMN = value
AND table2.COLUMN = value
AND table3.COLUMN = value
Personally I would remove the returns and keep the breaks. I would use the switch statement to assign a value to a variable. Then return that variable after the switch statement.
Though this is an arguable point I've always felt that good design and encapsulation means one way in and one way out. It is much easier to guarantee the logic and you don't accidentally miss cleanup code based on the cyclomatic complexity of your function.
One exception: Returning early is okay if a bad parameter is detected at the beginning of a function--before any resources are acquired.
There will definitely be a bean also containing fields related to Birthday So use this and your issue will be resolved
@SpringBootApplication
@EntityScan("com.java.model*") // base package where bean is present
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
You can use the cross-env npm package. It will take care of trimming the environment variable, and will also make sure it works across different platforms.
In the project root, run:
npm install cross-env
Then in your package.json, under scripts, add:
"start": "cross-env NODE_ENV=dev node your-app-name.js"
Then in your terminal, at the project root, start your app by running:
npm start
The environment variable will then be available in your app as process.env.NODE_ENV
, so you could do something like:
if (process.env.NODE_ENV === 'dev') {
// Your dev-only logic goes here
}
The following line in your code creates a new array, copies all object references from genericItems
into that new array, and assigns it to backupData
:
this.backupData = this.genericItems.slice();
So while backupData
and genericItems
are different arrays, they contain the same exact object references.
You could bring in a library to do deep copying for you (as @LatinWarrior mentioned).
But if Item
is not too complex, maybe you can add a clone
method to it to deep clone the object yourself:
class Item {
somePrimitiveType: string;
someRefType: any = { someProperty: 0 };
clone(): Item {
let clone = new Item();
// Assignment will copy primitive types
clone.somePrimitiveType = this.somePrimitiveType;
// Explicitly deep copy the reference types
clone.someRefType = {
someProperty: this.someRefType.someProperty
};
return clone;
}
}
Then call clone()
on each item:
this.backupData = this.genericItems.map(item => item.clone());
If you want to use a column with 24/11/15 (for 24th November 2015) in your Pivot that will sort correctly, you can make sure it is properly formatted by doing the following - highlight the column, go to Data – Text to Columns – click Next twice, then select “Date” and use the default of DMY (or select as applicable to your data) and click ok
When you pivot now you should see it sorting properly as we have properly formatted that column to be a date field so Excel can work with it
Is there any command in Linux through which i can know if the process is in hang state.
There is no command, but once I had to do a very dumb hack to accomplish something similar. I wrote a Perl script which periodically (every 30 seconds in my case):
ps
to find list of PIDs of the watched processes (along with exec time, etc)gdb
attaching to the process using its PID, dumping stack trace from it using thread apply all where
, detaching from the processBut that was very very very very crude hack, done to reach an about-to-be-missed deadline and it was removed a few days later, after a fix for the buggy application was finally installed.
Otherwise, as all other responders absolutely correctly commented, there is no way to find whether the process hung or not: simply because the hang might occur for way to many reasons, often bound to the application logic.
The only way is for application itself being capable of indicating whether it is alive or not. Simplest way might be for example a periodic log message "I'm alive".
TryGetValue is slightly faster, because FindEntry will only be called once.
How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.
FYI: It's not actually catching an error.
It's calling:
public bool TryGetValue(TKey key, out TValue value)
{
int index = this.FindEntry(key);
if (index >= 0)
{
value = this.entries[index].value;
return true;
}
value = default(TValue);
return false;
}
ContainsKey is this:
public bool ContainsKey(TKey key)
{
return (this.FindEntry(key) >= 0);
}
class department:
campus_name="attock"
def printer(self):
print(self.campus_name)
class CS_dept(department):
def overr_CS(self):
department.printer(self)
print("i am child class1")
c=CS_dept()
c.overr_CS()
This will work as well:
.clearfix:before,
.clearfix:after {
content: "";
display: table;
}
.clearfix:after {
clear: both;
}
/* IE 6 & 7 */
.clearfix {
zoom: 1;
}
Give the class clearfix
to the parent element, for example your ul
element.
You can use the CSS property "background-color: transparent;", or use apha on rgba color representation. Example: "background-color: rgba(216,240,218,0);"
The apha is the last value. It is a decimal number that goes from 0 (totally transparent) to 1 (totally visible).
So why don't you simply use a key-value literal?
var params = {
'slide0001.html': 'Looking Ahead',
'slide0002.html': 'Forecase',
...
};
return params['slide0001.html']; // returns: Looking Ahead
If you're struggling with such an issue using Lollipop (Android 5.*) probably you guys should do one simple step that I'd done before my ADB (I use Ubuntu) got my phone:
Change USB PC connection type to "Send images(PTP)" (before I've been using "Media device(MTP)")
Just like this:
And don't forget to activate checkbox "USB debugging".
You cannot animate two things (like zoom in and go to my location) in one google map.
So use move and animate Camera to zoom
googleMapVar.moveCamera(CameraUpdateFactory.newLatLng(LocLtdLgdVar));
googleMapVar.animateCamera(CameraUpdateFactory.zoomTo(10));
Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist()
it's trying to make a histogram of both columns hence the str error.
This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.
df.reset_index().pivot('index','Letter','N').hist()
The reset_index()
is just to shove the current index into a column called index
. Then pivot
will take your data frame, collect all of the values N
for each Letter
and make them a column. The resulting data frame as 400 rows (fills missing values with NaN
) and three columns (A, B, C
). hist()
will then produce one histogram per column and you get format the plots as needed.
A very simple (and lame) one line solution is to use the window.onblur()
event to close the loading dialog. Of course, if it takes too long and the user decides to do something else (like reading emails) the loading dialog will close.
label {
position: relative;
display: inline-block;
}
select {
display: inline-block;
padding: 4px 3px 5px 5px;
width: 150px;
outline: none;
color: black;
border: 1px solid #C8BFC4;
border-radius: 4px;
box-shadow: inset 1px 1px 2px #ddd8dc;
background-color: lightblue;
}
This uses a background color for select elements and I removed the image..
I would rewrite your dequeue function as:
std::string FileQueue::dequeue(const std::chrono::milliseconds& timeout)
{
std::unique_lock<std::mutex> lock(qMutex);
while(q.empty()) {
if (populatedNotifier.wait_for(lock, timeout) == std::cv_status::timeout )
return std::string();
}
std::string ret = q.front();
q.pop();
return ret;
}
It is shorter and does not have duplicate code like your did. Only issue it may wait longer that timeout. To prevent that you would need to remember start time before loop, check for timeout and adjust wait time accordingly. Or specify absolute time on wait condition.
Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.
I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.
PHP regex strings need delimiters. Try:
$numpattern="/^([0-9]+)$/";
Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/
.
Example: http://ideone.com/Ec3zh
See also: PHP - Delimiters
First think you should create object $res = new \stdClass();
then assign object with key and value thay $res->success = false;
document.getElementById("").readOnly = true
You can also use PowerShell to quickly replace words or character reptitions. PowerShell is for Windows. Current version is 3.0.
$oldfile = "$env:windir\WindowsUpdate.log"
$newfile = "$env:temp\newfile.txt"
$text = (Get-Content -Path $oldfile -ReadCount 0) -join "`n"
$text -replace '/(.)\1{9,}/', ' ' | Set-Content -Path $newfile
without site name
{{Storage::url($photoLink)}}
if you want to add site name to it example to append on api JSON felids
public function getPhotoFullLinkAttribute()
{
return env('APP_URL', false).Storage::url($this->attributes['avatar']) ;
}
Update 17 October 2019
https://developer.android.com/guide/app-bundle/in-app-updates
Update 24 april 2019:
Android announced a feature which will probably fix this problem. Using the in-app Updates API: https://android-developers.googleblog.com/2018/11/unfolding-right-now-at-androiddevsummit.html
Original:
As far a I know, there is no official Google API which supports this.
You should consider to get a version number from an API.
Instead of connecting to external APIs or webpages (like Google Play Store). There is a risk that something may change in the API or the webpage, so you should consider to check if the version code of the current app is below the version number you get from your own API.
Just remember if you update your app, you need to change the version in your own API with the app version number.
I would recommend that you make a file in your own website or API, with the version number. (Eventually make a cronjob and make the version update automatic, and send a notification when something goes wrong)
You have to get this value from your Google Play Store page (is changed in the meantime, not working anymore):
<div class="content" itemprop="softwareVersion"> x.x.x </div>
Check in your app if the version used on the mobile is below the version nummer showed on your own API.
Show indication that she/he needs to update with a notification, ideally.
pandas 0.21 introduces new functions for Parquet:
pd.read_parquet('example_pa.parquet', engine='pyarrow')
or
pd.read_parquet('example_fp.parquet', engine='fastparquet')
The above link explains:
These engines are very similar and should read/write nearly identical parquet format files. These libraries differ by having different underlying dependencies (fastparquet by using numba, while pyarrow uses a c-library).
Create a file named filesize.cmd (and put into folder C:\Windows\System32):
@echo %~z1
Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads
From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.
-z string
True if the string is null (an empty string)
My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.
As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)
You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:
YOU: /setjoingroups
BotFather: Choose a bot to change group membership settings.
YOU: @YourBot
BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED
YOU: Enable
BotFather: Success! The new status is: ENABLED.
After this you will see button "Add to Group" in your bot's profile.
The following configs works on Cent OS 6 or earlier
As stated above first have to disable selinux.
Step 1 nano /etc/sysconfig/selinux
Make sure the file has this configurations
SELINUX=disabled
SELINUXTYPE=targeted
Then restart the system
Step 2
iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
Step 3
sudo service iptables save
For Cent OS 7
step 1
firewall-cmd --zone=public --permanent --add-port=8080/tcp
Step 2
firewall-cmd --reload
You can use this:
bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month
def bank_holiday(month):
month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
print(bankHoliday[month])
bank_holiday(int(input("Which month would you like to check out: ")))
If sleep.sh
has the shebang #!/bin/sh
and it has appropriate file permissions -- run chmod u+rx sleep.sh
to make sure and it is in $PATH
then your code should work as is:
import subprocess
rc = subprocess.call("sleep.sh")
If the script is not in the PATH then specify the full path to it e.g., if it is in the current working directory:
from subprocess import call
rc = call("./sleep.sh")
If the script has no shebang then you need to specify shell=True
:
rc = call("./sleep.sh", shell=True)
If the script has no executable permissions and you can't change it e.g., by running os.chmod('sleep.sh', 0o755)
then you could read the script as a text file and pass the string to subprocess
module instead:
with open('sleep.sh', 'rb') as file:
script = file.read()
rc = call(script, shell=True)
You can try this,
using System.Linq;
string[] arrString = { "A", "B", "C"};
List<string> listofString = arrString.OfType<string>().ToList();
Hope, this code helps you.
public boolean isConnectedToWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
if (capabilities == null) {
return false;
}
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo == null) {
return false;
}
return networkInfo.isConnected();
}
}
<a href="1.html"><input type="text" class="button_active" value="1"></a>
<a href="2.html"><input type="text" class="button" value="2"></a>
<a href="3.html"><input type="text" class="button" value="3"></a>
Try that. Unless you truly need to stick with the type as submit, then what I provided should work. If you are going to stick with submit, then everything mentioned above is correct, it makes no sense.
You could json encode a generic object.
$post_data = new stdClass();
$post_data->item = new stdClass();
$post_data->item->item_type_id = $item_type;
$post_data->item->string_key = $string_key;
$post_data->item->string_value = $string_value;
$post_data->item->string_extra = $string_extra;
$post_data->item->is_public = $public;
$post_data->item->is_public_for_contacts = $public_contacts;
echo json_encode($post_data);
For concatenating it's:
input[name="Sex"][value="M"] {}
And for taking union it's:
input[name="Sex"], input[value="M"] {}
To pass some context data to javascript code, you have to serialize it in a way it will be "understood" by javascript (namely JSON). You also need to mark it as safe using the safe
Jinja filter, to prevent your data from being htmlescaped.
You can achieve this by doing something like that:
import json
@app.route('/')
def my_view():
data = [1, 'foo']
return render_template('index.html', data=json.dumps(data))
<script type="text/javascript">
function test_func(data) {
console.log(data);
}
test_func({{ data|safe }})
</script>
So, to achieve exactly what you want (loop over a list of items, and pass them to a javascript function), you'd need to serialize every item in your list separately. Your code would then look like this:
import json
@app.route('/')
def my_view():
data = [1, "foo"]
return render_template('index.html', data=map(json.dumps, data))
{% for item in data %}
<span onclick=someFunction({{ item|safe }});>{{ item }}</span>
{% endfor %}
In my example, I use Flask
, I don't know what framework you're using, but you got the idea, you just have to make it fit the framework you use.
NEVER EVER DO THIS WITH USER-SUPPLIED DATA, ONLY DO THIS WITH TRUSTED DATA!
Otherwise, you would expose your application to XSS vulnerabilities!
Two-way binding just means that:
Backbone doesn't have a "baked-in" implementation of #2 (although you can certainly do it using event listeners). Other frameworks like Knockout do wire up two-way binding automagically.
In Backbone, you can easily achieve #1 by binding a view's "render" method to its model's "change" event. To achieve #2, you need to also add a change listener to the input element, and call model.set
in the handler.
Here's a Fiddle with two-way binding set up in Backbone.
It's weird. Unicode is a standard, not an encoding. As it is possible to specify the endianness I guess it's effectively UTF-16 or maybe 32.
Where does this menu provide from?
Since the name is likely to change in future versions of Android (currently the latest is AppCompatActivity
but it will probably change at some point), I believe a good thing to have is a class Activity
that extends AppCompatActivity
and then all your activities extend from that one. If tomorrow, they change the name to AppCompatActivity2
for instance you will have to change it just in one place.
Yes you can: Take this utility function that I have written today:
function shangMergeCol() {
tcol= db.getCollection(arguments[0]);
for (var i=1; i<arguments.length; i++){
scol= db.getCollection(arguments[i]);
scol.find().forEach(
function (d) {
tcol.insert(d);
}
)
}
}
You can pass to this function any number of collections, the first one is going to be the target one. All the rest collections are sources to be transferred to the target one.
This should group an associative array Ejm Group By Country
function getGroupedArray($array, $keyFieldsToGroup) {
$newArray = array();
foreach ($array as $record)
$newArray = getRecursiveArray($record, $keyFieldsToGroup, $newArray);
return $newArray;
}
function getRecursiveArray($itemArray, $keys, $newArray) {
if (count($keys) > 1)
$newArray[$itemArray[$keys[0]]] = getRecursiveArray($itemArray, array_splice($keys, 1), $newArray[$itemArray[$keys[0]]]);
else
$newArray[$itemArray[$keys[0]]][] = $itemArray;
return $newArray;
}
$countries = array(array('Country'=>'USA', 'State'=>'California'),
array('Country'=>'USA', 'State'=>'Alabama'),
array('Country'=>'BRA', 'State'=>'Sao Paulo'));
$grouped = getGroupedArray($countries, array('Country'));
Here all of the above outputs are giving a 10 digit number, but along with that the input field is accepting characters also, which is not the full solution. In order to set the 10 digit numbers only, we can use an input tag along with that type as number, and in that we can remove the up-down array by writing some small code in css which is shown below along with the input tag.
<input name="phone" maxlength="10" pattern="[1-9]{1}[0-9]{9}" class="form-control" id="mobile" placeholder="Enter your phone Number" type="number">
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
margin: 0;
}
Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.
You can also use $inject
to add a dependency:
var MyController = function($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];
.h
) not for source files ( i.e., .cpp
). LinearNode.h:
#ifndef LINEARNODE_H
#define LINEARNODE_H
class LinearNode
{
// .....
};
#endif
LinearNode.cpp:
#include "LinearNode.h"
#include <iostream>
using namespace std;
// And now the definitions
LinkedList.h:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
class LinearNode; // Forward Declaration
class LinkedList
{
// ...
};
#endif
LinkedList.cpp
#include "LinearNode.h"
#include "LinkedList.h"
#include <iostream>
using namespace std;
// Definitions
test.cpp is source file is fine. Note that header files are never compiled. Assuming all the files are in a single folder -
g++ LinearNode.cpp LinkedList.cpp test.cpp -o exe.out
You can use the index
method
ints = [8, 23, 45, 12, 78]
inds = [ints.index(i) for i in ints]
EDIT
Highlighted in the comment that this method doesn’t work if there are duplicates in ints
, the method below should work for any values in ints
:
ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup[0] for tup in enumerate(ints)]
Or alternatively
ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup for tup in enumerate(ints)]
if you want to get both the index and the value in ints
as a list of tuples.
It uses the method of enumerate
in the selected answer to this question, but with list comprehension, making it faster with less code.
I tried this: When you are creating your Retrofit instance, add this converter factory to the retrofit builder:
gsonBuilder = new GsonBuilder().serializeNulls()
your_retrofit_instance = Retrofit.Builder().addConverterFactory( GsonConverterFactory.create( gsonBuilder.create() ) )
MVC doesn't do events. Just put a form and submit button on the page and the method decorated with the HttpPost attribute will process that request.
You might want to read a tutorial or two on how to create views, forms and controllers.
A little late here but generally I've seen this problem occur when you get a 'tablespace full' error when running in a 'innodb_file_per_table' mode. Without going into too much detail (more here), the database server's tablespace is defined by the innodb_data_file_path setting and by default is rather small. Even made larger, the 'tablespace full' can still occur with larger queries and such (lots of non-table 'stuff' is stored in there, undo logs, caches, etc...).
Anyways, I found that if you look in the OS directory where the files-per-table are stored, /var/lib/mysql by default on OSX, /usr/local/var/mysql with homebrew iirc, you'll find an orphaned tablename.ibd file without it's normal companion tablename.frm file. If you move that .ibd file to a safe temporary location (just to be safe) that should fix the problem.
$ ls /var/lib/mysql
table1.frm
table1.idb
table2.frm
table2.ibd
table3.idb <- problem table, no table3.frm
table4.frm
table4.idb
$ mkdir /tmp/mysql_orphans
$ mv /var/lib/mysql/table3.ibd /tmp/mysql_orphans/
One caveat though, make sure what ever is causing the problem originally, e.g. long running query, locked table, etc... has been cleared. Otherwise you just end up with another orphaned .ibd file when you try a second time.
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
To execute your command directly from within C#, you would use the SqlCommand class.
Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:
string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
This Problem is due to Security, Better open Developer Command prompt for VS 2012 in RUN AS ADMINISTRATOR and install your Service, it fix your problem surely.
I would write the code like this:
def search_book(request):
form = SearchForm(request.POST or None)
if request.method == "POST" and form.is_valid():
stitle = form.cleaned_data['title']
sauthor = form.cleaned_data['author']
scategory = form.cleaned_data['category']
return HttpResponseRedirect('/thanks/')
return render_to_response("books/create.html", {
"form": form,
}, context_instance=RequestContext(request))
Pretty much like the documentation.
"find '-maxdepth' " does not work with my old version of bash, therefore I use:
for f in $(ls) ; do if [ -f $f ] ; then echo $f ; fi ; done
If you're new to the library, consider double-checking whether the functionality you need is already offered by those Pandas objects.
My solution: use to_dict()
dict_of_lists = df.to_dict(orient='split')
This will give you a dictionary with three lists: index
, columns
, data
. If you decide you really don't need the columns and index names, you get the data with
dict_of_lists['data']
Good to see someone's chimed in about Lucene - because I've no idea about that.
Sphinx, on the other hand, I know quite well, so let's see if I can be of some help.
I've no idea how applicable to your situation this is, but Evan Weaver compared a few of the common Rails search options (Sphinx, Ferret (a port of Lucene for Ruby) and Solr), running some benchmarks. Could be useful, I guess.
I've not plumbed the depths of MySQL's full-text search, but I know it doesn't compete speed-wise nor feature-wise with Sphinx, Lucene or Solr.
I agree on performing the replace on the SQL side, but using the ISNULL function would be the way I'd go.
SELECT ISNULL(table.MyField, "NA") AS MyField
I usually do as much processing of data on our SQL servers and try to do as little data manipulation in SSRS as possible. This is mainly because my SQL server is considerably more powerful than my SSRS server.
If the images are in an array and you want to iterate through each element and print it, you can write the code as follows:
plt.figure(figsize=(10,10)) # specifying the overall grid size
for i in range(25):
plt.subplot(5,5,i+1) # the number of images in the grid is 5*5 (25)
plt.imshow(the_array[i])
plt.show()
Also note that I used subplot and not subplots. They're both different
If you look at the scope of the variable 'hoursWorked' you will see that it is a member of the class (declared as private int)
The two variables you are having trouble with are passed as parameters to the constructor.
The error message is because 'hours' is out of scope in the setter.
To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.
Click the Clone or download button and choose your method. I placed these into a dev/py/libs
directory in my user home directory. It does not matter where they are saved, because they will not be installed there.
You will need to run the following inside the setup-tools directory.
python bootstrap.py
python setup.py install
Now you can navigate to the more-itertools direcotry and install it as normal.
cd ...
) into the directory containing setup.py
python setup.py install
if you have a date in a string with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy",
CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");
Here you can check to show the model state error one by one
public HttpResponseMessage CertificateUpload(employeeModel emp)
{
if (!ModelState.IsValid)
{
string errordetails = "";
var errors = new List<string>();
foreach (var state in ModelState)
{
foreach (var error in state.Value.Errors)
{
string p = error.ErrorMessage;
errordetails = errordetails + error.ErrorMessage;
}
}
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("error", errordetails);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
//do something
}
}
}
You need to read and write document.cookie
if (document.cookie.indexOf("visited=") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
Matthias' answer is mostly right but it's still not filling the entire screen as it has a small padding on each side (pointed out by @Holmes). In addition to his code, we could fix this by extending Theme.Dialog style and add some attributes like this.
<style name="MyDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
</style>
Then we simply declare Activity with theme set to MyDialog
:
<activity
android:name=".FooActivity"
android:theme="@style/MyDialog" />
Just download and re-install the node from this and this will fix all the path issues.
Don't forget to restart your command prompt or terminal.
Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from
result.replace(/"/g,'"')
to
result.replace(/"/g,'"')
Instead of this I use that:
result.replace(/("\;)/g,"\"")
By this notation it works.
private string gettxtbettwen(string txt, string first, string last)
{
StringBuilder sb = new StringBuilder(txt);
int pos1 = txt.IndexOf(first) + first.Length;
int len = (txt.Length ) - pos1;
string reminder = txt.Substring(pos1, len);
int pos2 = reminder.IndexOf(last) - last.Length +1;
return reminder.Substring(0, pos2);
}
In Python:
# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M)
or more rigorous:
# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()
How about calling a function from within your callback instead of returning a value in sync_call()?
function sync_call(input) {
var value;
// Assume the async call always succeed
async_call(input, function(result) {
value = result;
use_value(value);
} );
}
Might not solve all the problems in the original question, but since this seems to be the de facto post on how mercurial can amend to previous commit, I'll add my 2 cents worth of information.
If you are like me, and only wish to modify the previous commit message (fix a typo etc) without adding any files, this will work
hg commit -X 'glob:**' --amend
Without any include or exclude patterns hg commit
will by default include all files in working directory. Applying pattern -X 'glob:**'
will exclude all possible files, allowing only to modify the commit message.
Functionally it is same as git commit --amend
when there are no files in index/stage.
-save-temps
This is another good option to have in mind:
gcc -save-temps -c -o main.o main.c
main.c
#define INC 1
int myfunc(int i) {
return i + INC;
}
and now, besides the normal output main.o
, the current working directory also contains the following files:
main.i
is the desired prepossessed file containing:
# 1 "main.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "main.c"
int myfunc(int i) {
return i + 1;
}
main.s
is a bonus :-) and contains the generated assembly:
.file "main.c"
.text
.globl myfunc
.type myfunc, @function
myfunc:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl %edi, -4(%rbp)
movl -4(%rbp), %eax
addl $1, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size myfunc, .-myfunc
.ident "GCC: (Ubuntu 8.3.0-6ubuntu1) 8.3.0"
.section .note.GNU-stack,"",@progbits
If you want to do it for a large number of files, consider using instead:
-save-temps=obj
which saves the intermediate files to the same directory as the -o
object output instead of the current working directory, thus avoiding potential basename conflicts.
The advantage of this option over -E
is that it is easy to add it to any build script, without interfering much in the build itself.
Another cool thing about this option is if you add -v
:
gcc -save-temps -c -o main.o -v main.c
it actually shows the explicit files being used instead of ugly temporaries under /tmp
, so it is easy to know exactly what is going on, which includes the preprocessing / compilation / assembly steps:
/usr/lib/gcc/x86_64-linux-gnu/8/cc1 -E -quiet -v -imultiarch x86_64-linux-gnu main.c -mtune=generic -march=x86-64 -fpch-preprocess -fstack-protector-strong -Wformat -Wformat-security -o main.i
/usr/lib/gcc/x86_64-linux-gnu/8/cc1 -fpreprocessed main.i -quiet -dumpbase main.c -mtune=generic -march=x86-64 -auxbase-strip main.o -version -fstack-protector-strong -Wformat -Wformat-security -o main.s
as -v --64 -o main.o main.s
Tested in Ubuntu 19.04 amd64, GCC 8.3.0.
CMake predefined targets
CMake automatically provides a targets for the preprocessed file:
make help
shows us that we can do:
make main.i
and that target runs:
Preprocessing C source to CMakeFiles/main.dir/main.c.i
/usr/bin/cc -E /home/ciro/bak/hello/main.c > CMakeFiles/main.dir/main.c.i
so the file can be seen at CMakeFiles/main.dir/main.c.i
Tested on cmake 3.16.1.
Run this command in project root directory.
1>. List of iPhone devices for found the connected Real Devices and Simulator. same as like adb devices command for android.
xcrun instruments -s devices
2>. Select device using this command which you want to run your app
Using Device Name
react-native run-ios --device "Kool's iPhone"
Using UDID
react-native run-ios --device --udid 0412e2c2******51699
wait and watch to run your app in specific devices - K00L ;)
I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!
#include<stdio.h>
int iFunctErrorCheck(int iLowerBound, int iUpperBound){
int iUserInput=0;
while (iUserInput==0){
scanf("%i", &iUserInput);
if (iUserInput==0){
printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
getchar();
}
if ((iUserInput!=0) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
iUserInput=0;
}
}
return iUserInput;
}
I have spent more time researching this topic that I'd like to admit. Luckily there are great open source solutions in the wild.
These are two great approaches, even if not well known enough (yet),
You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.
Date to LocalDate
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate to Date
LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
Pass 65536
to mysql_connect
as 5th parameter.
Example:
$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */)
or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
INSERT INTO table1 (field1,field2) VALUES(1,2);
INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);
DELETE FROM table3 WHERE field6 = 6;
UPDATE table4 SET field7 = 7 WHERE field8 = 8;
INSERT INTO table5
SELECT t6.field11, t6.field12, t7.field13
FROM table6 t6
INNER JOIN table7 t7 ON t7.field9 = t6.field10;
-- etc
");
When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid.
For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*. It is okay to use mysql_affected_rows to return how many rows inserted.
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
INSERT INTO table1 (field1,field2) VALUES(1,2);
SELECT * FROM table2;
");
Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement.
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
SELECT * FROM table2;
INSERT INTO table1 (field1,field2) VALUES(1,2);
");
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
In addition to already posted examples, here is another approach using express-async-wrap and asynchronous functions (ES2017).
Router
router.put('/:id/settings/profile', wrap(async function (request, response, next) {
const username = request.body.username
const email = request.body.email
const userWithEmail = await userService.findUserByEmail(email)
if (userWithEmail) {
return response.status(409).send({message: 'Email is already taken.'})
}
const userWithUsername = await userService.findUserByUsername(username)
if (userWithUsername) {
return response.status(409).send({message: 'Username is already taken.'})
}
const user = await userService.updateProfileSettings(userId, username, email)
return response.status(200).json({user: user})
}))
UserService
async function updateProfileSettings (userId, username, email) {
try {
return User.findOneAndUpdate({'_id': userId}, {
$set: {
'username': username,
'auth.email': email
}
}, {new: true})
} catch (error) {
throw new Error(`Unable to update user with id "${userId}".`)
}
}
async function findUserByEmail (email) {
try {
return User.findOne({'auth.email': email.toLowerCase()})
} catch (error) {
throw new Error(`Unable to connect to the database.`)
}
}
async function findUserByUsername (username) {
try {
return User.findOne({'username': username})
} catch (error) {
throw new Error(`Unable to connect to the database.`)
}
}
// other methods
export default {
updateProfileSettings,
findUserByEmail,
findUserByUsername,
}
Resources
At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.
$mail->ClearReplyTos();
$mail->addReplyTo([email protected], 'EXAMPLE');
You can also solve this issue by removing the value "256m" under the line "-launcher.XXMaxPermSize”.
For some reason, I need float
property of a pseudo-element to be set to left
or right
for the image to appear. height
and width
of the pseudo-element should be both set but not in percentage. I'm on Firefox 67.
As in interface,we are just declaring methods,concrete class which implements these both interfaces understands is that there is only one method(as you described both have same name in return type). so there should not be an issue with it.You will be able to define that method in concrete class.
But when two interface have a method with the same name but different return type and you implement two methods in concrete class:
Please look at below code:
public interface InterfaceA {
public void print();
}
public interface InterfaceB {
public int print();
}
public class ClassAB implements InterfaceA, InterfaceB {
public void print()
{
System.out.println("Inside InterfaceA");
}
public int print()
{
System.out.println("Inside InterfaceB");
return 5;
}
}
when compiler gets method "public void print()" it first looks in InterfaceA and it gets it.But still it gives compile time error that return type is not compatible with method of InterfaceB.
So it goes haywire for compiler.
In this way, you will not be able to implement two interface having a method of same name but different return type.
With JDK8 it does have some support for them.
We may yet see full support of unsigned types in Java despite Gosling's concerns.
Move doSomething
definition outside of its class declaration and after B
and also make add
accessible to A
by public
-ing it or friend
-ing it.
class B;
class A
{
void doSomething(B * b);
};
class B
{
public:
void add() {}
};
void A::doSomething(B * b)
{
b->add();
}
There is one another technique to identify your class You can store ref to your class in instance like bellow.
class MyClass {
static myStaticProperty = 'default';
constructor() {
this.__class__ = new.target;
this.showStaticProperty = function() {
console.log(this.__class__.myStaticProperty);
}
}
}
class MyChildClass extends MyClass {
static myStaticProperty = 'custom';
}
let myClass = new MyClass();
let child = new MyChildClass();
myClass.showStaticProperty(); // default
child.showStaticProperty(); // custom
myClass.__class__ === MyClass; // true
child.__class__ === MyClass; // false
child.__class__ === MyChildClass; // true