text:
Q: Do I require a Thread Lock object? Hey, I am in the process of refactoring a program that requires some amount of threading. However, I do not have much prior experience with threading, so here's a (i'm guessing) simple question I need help with.
The program watches certain files (each watcher runs on a different thread), and when a change is detected, it calls a method call Notify(). Notify() method simply sends an email.
In case two or more threads detect a change at the same time, and call Notify() at the same time, will that be a problem?
I'm guessing that since Notify() isn't accessing any file that can't be opened multiple times or any such thing, there shouldn't be a problem Notify() is called by multiple threads at the same time. But I could be wrong.
And if I am wrong, is the best method to create an object and use Lock(object) before the call to Notify()?

A: Locking is required if multiple threads need to access shared state (static or non-static) and some of them trying to change. If all they are doing is to read, it is safe for them to access it. Also if you do not have a shared state then it is fine.

A: If notify method uses a shared resource (like a static variable which is being used by Notify() method) you may have some threading problems and locking might be necessary, if not, there will be no problems.

A: The only reason you would need to do any locking is if there are variables inside Notify() that might be changed by multiple instances of Notify() running at the same time.
So let's say you have a List<> of files that have been detected (say, to prevent re-notification), and your Notify() method adds the file it detects to that List<>.  Multiple instances of Notify() might attempt to access that list at the same time, in which case you would consider locking (or otherwise synchronizing) that List<>.
From what you've described though, I don't think you need to worry about it.


text:
Q: Simple question about recursive sequence format regarding $a(n+2) = -4a(n+1) + 5a(n)$ Suppose there's a recursive sequence $a(n+2) = -4a(n+1) + 5a(n)$
How can i convert it into the form $a(n)$ because I am most comfortable solving questions in this form.
I tried to find out but I'm not sure if i am correct.
To make it $a(n)$:
$\Rightarrow $ $a(n+2-2) = -4a(n+1-2) + 5a(n-2)$
$\Rightarrow $ $a(n) = -4a(n-1) + 5a(n-2)$ for $n\geq 2$
Would this be correct?

A: Yes, that works, provided that $n$ doesn't have some specific value. It works because you implicitly say "this is true for any $n$ you care to name;" that means you can swap in anything for $n$, including $n-2$, and it still works (GEdgar's comment basically shows how swapping $n-2$ in for $n$ gives you your last expression).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert NSString to NSDate and timeZone? Ive been racking my brains with no luck. Could someone please tell my how i would convert this string:
 NSString *dateTimeStr =[[self.responseArray objectAtIndex:indexPath.row]objectForKey:@"date_time"];

2014-04-13T17:00:00+11:0
into a NSDate? and time format ?
how can i covert this date into time format ?
here is my code:
NSString *dateTimeStr =[[self.responseArray objectAtIndex:indexPath.row]objectForKey:@"date_time"];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];

[dateFormatter setDateFormat:@"yyyy-MM-ddHH:mm:ss"];

NSDate *date = [dateFormatter dateFromString:dateTimeStr];

NSLog(@"date %@", date);

NSTimeInterval seconds = [date timeIntervalSinceReferenceDate];

in console
NSLog(@"seconds==> %f", seconds);

i have time in miliseconds then how can i take out minutes/hours/ ?

A: NSString *dateString = @"2014-04-13T17:00:00+11:00";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

NSDate *date = [dateFormatter dateFromString:dateString];

NSDateComponents *dateComponents = [[NSCalendar currentCalendar]
                                    components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
                                    fromDate:date];

NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];


text:
Q: Why boost::thread constructor doesn't accept boost::thread::attributes parameter? Following boost::thread's tutorial on thread parameters I came up with the following snippet (which according to boost's manual should work):
#include <boost/thread.hpp>

void WorkerThread(int i)
{
  (void)i;
}

int main(int argc, char** argv)
{
  boost::thread::attributes attrs;
  attrs.set_stack_size(4096*2);
  boost::thread th(attrs, WorkerThread, 10);
  th.join();
}

which gives the following output (from http://coliru.stacked-crooked.com/a/f5710518cc527147)
clang =============
In file included from main.cpp:1:
In file included from /usr/local/include/boost/thread.hpp:13:
In file included from /usr/local/include/boost/thread/thread.hpp:12:
In file included from /usr/local/include/boost/thread/thread_only.hpp:22:
In file included from /usr/local/include/boost/thread/detail/thread.hpp:30:
In file included from /usr/local/include/boost/bind.hpp:22:
/usr/local/include/boost/bind/bind.hpp:319:9: error: type 'boost::thread_attributes' does not provide a call operator
        unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/boost/bind/bind.hpp:1222:16: note: in instantiation of function template specialization 'boost::_bi::list2<boost::_bi::value<void (*)(int)>, boost::_bi::value<int> >::operator()<boost::thread_attributes, boost::_bi::list0>' requested here
        return l_( type<result_type>(), f_, a, 0 );
               ^
/usr/local/include/boost/thread/detail/thread.hpp:116:17: note: in instantiation of member function 'boost::_bi::bind_t<void, boost::thread_attributes, boost::_bi::list2<boost::_bi::value<void (*)(int)>, boost::_bi::value<int> > >::operator()' requested here
                f();
                ^
/usr/local/include/boost/thread/detail/thread.hpp:96:15: note: in instantiation of member function 'boost::detail::thread_data<boost::_bi::bind_t<void, boost::thread_attributes, boost::_bi::list2<boost::_bi::value<void (*)(int)>, boost::_bi::value<int> > > >::run' requested here
              thread_data(BOOST_THREAD_RV_REF(F) f_):
              ^
/usr/local/include/boost/thread/pthread/thread_heap_alloc.hpp:24:24: note: in instantiation of member function 'boost::detail::thread_data<boost::_bi::bind_t<void, boost::thread_attributes, boost::_bi::list2<boost::_bi::value<void (*)(int)>, boost::_bi::value<int> > > >::thread_data' requested here
            return new T(static_cast<A1&&>(a1));
                       ^
/usr/local/include/boost/thread/detail/thread.hpp:211:52: note: in instantiation of function template specialization 'boost::detail::heap_new<boost::detail::thread_data<boost::_bi::bind_t<void, boost::thread_attributes, boost::_bi::list2<boost::_bi::value<void (*)(int)>, boost::_bi::value<int> > > >, boost::_bi::bind_t<void, boost::thread_attributes, boost::_bi::list2<boost::_bi::value<void (*)(int)>, boost::_bi::value<int> > > >' requested here
            return detail::thread_data_ptr(detail::heap_new<detail::thread_data<typename boost::remove_reference<F>::type> >(
                                                   ^
/usr/local/include/boost/thread/detail/thread.hpp:397:25: note: in instantiation of function template specialization 'boost::thread::make_thread_info<boost::_bi::bind_t<void, boost::thread_attributes, boost::_bi::list2<boost::_bi::value<void (*)(int)>, boost::_bi::value<int> > > >' requested here
            thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2)))
                        ^
main.cpp:12:21: note: in instantiation of function template specialization 'boost::thread::thread<boost::thread_attributes, void (*)(int), int>' requested here
      boost::thread th(attrs, WorkerThread, 10);
                    ^
1 error generated.

gcc =============
In file included from /usr/local/include/boost/bind.hpp:22:0,
                 from /usr/local/include/boost/thread/detail/thread.hpp:30,
                 from /usr/local/include/boost/thread/thread_only.hpp:22,
                 from /usr/local/include/boost/thread/thread.hpp:12,
                 from /usr/local/include/boost/thread.hpp:13,
                 from main.cpp:1:
/usr/local/include/boost/bind/bind.hpp: In instantiation of 'void boost::_bi::list2<A1, A2>::operator()(boost::_bi::type<void>, F&, A&, int) [with F = boost::thread_attributes; A = boost::_bi::list0; A1 = boost::_bi::value<void (*)(int)>; A2 = boost::_bi::value<int>]':
/usr/local/include/boost/bind/bind.hpp:1222:50:   required from 'boost::_bi::bind_t<R, F, L>::result_type boost::_bi::bind_t<R, F, L>::operator()() [with R = void; F = boost::thread_attributes; L = boost::_bi::list2<boost::_bi::value<void (*)(int)>, boost::_bi::value<int> >; boost::_bi::bind_t<R, F, L>::result_type = void]'
/usr/local/include/boost/thread/detail/thread.hpp:116:17:   required from 'void boost::detail::thread_data<F>::run() [with F = boost::_bi::bind_t<void, boost::thread_attributes, boost::_bi::list2<boost::_bi::value<void (*)(int)>, boost::_bi::value<int> > >]'
main.cpp:14:5:   required from here
/usr/local/include/boost/bind/bind.hpp:319:35: error: no match for call to '(boost::thread_attributes) (void (*&)(int), int&)'
         unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);
         ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

what seems to be the problem?

A: It calls a wrong boost::thread constructor.
The constructor that accepts the attributes only accepts the callable (the thread function) without arguments. Hence, you have to create a callable object yourself with boost::bind, std::bind or C++11 lambda expression.
E.g.:
boost::thread th(attrs, boost::bind(WorkerThread, 10));


text:
Q: What is backward reasoning in logic proofs? I was reading about Backward Reasoning, but I was not able to figure out how it works and what it really is.
While reading I came across the following example mentioned in Kenneth Rosen book.

Question:  Given two positive real numbers x and y, their arithmetic mean is (x + y)/2 and their geometric mean is √xy. When we compare the arithmetic and geometric means of pairs of distinct positive real numbers, we find that the arithmetic mean is always greater than the geometric mean. [For example, when x = 4 and y = 6, we have 5 = (4 + 6)/2 > √4 · 6 =√24.] Can we prove that this inequality is always true?
Solution: To prove that (x + y)/2 > √xy when x and y are distinct positive real numbers, we can work backward. We construct a sequence
of equivalent inequalities. The equivalent inequalities are
(x + y)/2 > √xy,
(x + y)2/4 > xy,
(x + y)2 > 4xy,
x2 + 2xy + y2 > 4xy,
x2 − 2xy + y2 > 0,
(x − y)2 > 0.
Because (x − y)2 > 0 when x != y, it follows that the
final inequality is true. Because all these inequalities are
equivalent, it follows that (x + y)/2 > √xy when x != y. Once we have
carried out this backward reasoning, we can easily reverse the steps
to construct a proof using forward reasoning. We now give this proof.
Suppose that x and y are distinct positive real numbers. Then (x − y)2 > 0 because the square of a nonzero real number is positive. Because (x − y)2 =  x2 - 2xy + y2 > 0. Adding 4xy to both sides, we obtain x2 + 2xy + y2 > 4xy. Because x2 + 2xy + y2 = (x + y)2, this means that (x + y)2 ≥ 4xy.
Dividing both sides of this equation by 4, we see that (x + y)2/4 > xy. Finally, taking square roots of both sides (which preserves the inequality because both sides are positive) yields (x + y)/2 > √xy. We conclude that if x and y are distinct positive real numbers, then their arithmetic mean (x + y)/2 is greater than their geometric mean √xy.

I didn't understand this proof. This proof is like if you have to prove a = b, then you add 5 both sides and get a+5 = b+5. Now using forward reasoning you prove a = b. Correct me if I am wrong.
Also, please illustrate how backward reasoning works.You can use appropriate examples.
Thank You.

A: Ordinarily, when proving something, you start with something you already know to be true, perform some steps which shows intermediate true things, and then reach a conclusion. In backwards reasoning you start from the thing you want to prove, and then look for what conclusions you can draw from it. While doing this, you try to make your steps reversible -- for example, from $x = y$ you can always conclude $0\cdot x = 0 \cdot y$, but that doesn't really help you because that step is not reversible.
Once you reach a "conclusion" that is obviously true, and every step in the proof is reversible, just reversing your backwards proof gives you an ordinary proof.
In my opinion, you should think of this less as a proof strategy and more as a strategy for exploring a problem.

A: There are really two completely separate parts to the "solution". The first part is a method for discovering a way to prove the desired fact.
The second part is the actual proof.
Suppose you have a homework assignment to prove that
$(x + y)/2 > \sqrt{xy}$ when $x$ and $y$ are distinct positive real numbers.
Then everything in Rosen's "solution" from the beginning

To prove that $(x + y)/2 > \sqrt{xy}$ when $x$ and $y$ are distinct positive real numbers, we can work backward

up to and including the words

We now give this proof

represents things that you would think to yourself or write down on a
piece of scrap paper.
Unless the instructor has explicitly said that you are to submit
every scrap of doodling you did while working on the problem,
none of this should be written on the homework answer that
you hand in.
What should appear on your answer paper
(assuming this is a math homework in the traditional format)
is just the part that starts,

Suppose that $x$ and $y$ are distinct positive real numbers. Then $(x − y)^2 > 0$ because the square of a nonzero real number is positive.

The first sentence is justified because the thing you have to prove
only needs to be true "when $x$ and $y$ are distinct positive real numbers".
The second sentence is true for the reason stated in that sentence,
namely, we know $x - y$ is not zero (because $x$ and $y$ are real and
not equal to each other), so when we square it we get a positive number.
Neither of these sentences, nor anything that follows them, makes
any reference to any of the "scrap paper doodlings" from the first part
of the "solution".
In other words, the answer you hand in starts with the assumptions that
the theorem to be proved allows you to make, and proceeds by deriving
new statements from those assumptions, ending with the assertion of the theorem. It's a direct path from $A$ to $B$, not a circular route from $B$ to $A$ and back again to $B$.
So what was the point of the first part of the "solution"?
Think of it as a kind of road map or crib sheet that you keep handy
while you write up the actual proof.
After all, if you were just trying to write up this proof one line
at a time without having doodled anything, why would it occur to you
to square the quantity $(x - y)$?
And if you were somehow inspired to do that, why would you then
add the quantity $4xy$ to the result?
Some of us might think of this without the crib sheet, but probably only
because we've seen this kind of proof so many times before that
we remember how it goes without having to work it through backward.

A: The most common kind of proof starts from the hypotheses, does some manipulations, and gets to the conclusion. Sometimes it's not so obvious how to do this, though. In this case, you can think about what would imply your conclusion, attempting to make what's in front of you look more like your hypotheses, or like some result you already know. There are essentially two kinds of ways to do this: you can perform reversible steps, or you can come up with stronger statements that might be easier to prove from your hypotheses. The former is more common in more elementary subjects, but the latter is common too (since often the stronger statement is actually simpler).
In your example, provided that you explicitly write equivalences between each line, the "backward" proof would actually be a completely rigorous proof of the AM-GM inequality. Moreover, I think most people would actually find this easier to read, because it would not seem so sudden and arbitrary to introduce $(x-y)^2>0$ for $x \neq y$ at the start of the proof.
A very common variant of this situation occurs in "epsilon-delta" proofs in real analysis. You write the epsilon-delta implication that you want to have (where $\varepsilon$ is arbitrary and $\delta$ is to be found). Then you do some manipulations. Usually some of the manipulations are irreversible. At the end you come up with a suitable $\delta$. You could now turn the proof around, going from your chosen $\delta$ to the desired $\varepsilon$...but then, like in your AM-GM example, the start of the proof seems quite arbitrary until the middle of the proof.


text:
Q: How to skip null/empty variables in the firestore collection? Like firebase real-time database, I don't want store null/empty value in firestore collection .so how i can skip or remove null fields from firestore collection
below function save data to firestore
private void saveTofireStore(String path, User userObject,Class<?> classType){

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    documentReference = db.document(path);
    Log.d(TAG,""+documentReference.getPath());
   documentReference
            .set(userObject)
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()){
                  appearanceMutableLiveData.setValue(task.getResult());
                }else {
                    appearanceMutableLiveData.setValue(null);
                }
            });

}

A: I found an easy way using Gson to serialize object then convert into the map then you can save that object
private Map<String, Object> removeNullValues(User userObject) {
    Gson gson = new GsonBuilder().create();

    Map<String, Object> map = new Gson().fromJson(
            gson.toJson(userObject), new TypeToken<HashMap<String, Object>>() {
            }.getType()
    );

    return map;
}

and then
documentReference
.set( removeNullValues( userObject) )
.addOnSuccessListener {}

If you are using proguard then make sure add this rules
-keepclassmembers enum * { *; }

A: My solution was to add a method called toFirestoreJson.
import 'package:cloud_firestore/cloud_firestore.dart';

class User {
  String documentID;
  final String name;
  final String city;
  final String postalCode;
  final String state;
  final String address;
  final List<String> emails;

  User(
      {this.name,
      this.city,
      this.postalCode,
      this.state,
      this.address,
      this.emails});

  factory User.fromFirestore(DocumentSnapshot documentSnapshot) {
    User data = User.fromJson(documentSnapshot.data);
    data.documentID = documentSnapshot.documentID;
    return data;
  }

  factory User.fromJson(Map<String, dynamic> json) => User(
        name: json["name"] == null ? null : json["name"],
        city: json["city"] == null ? null : json["city"],
        postalCode: json["postal_code"] == null ? null : json["postal_code"],
        state: json["state"] == null ? null : json["state"],
        address: json["address"] == null ? null : json["address"],
        emails: json["emails"] == null
            ? null
            : List.castFrom(json["emails"]),
      );

  Map<String, dynamic> toFirestoreJson() {
    Map json = toJson();
    json.removeWhere((key, value) => value == null);
    return json;
  }

  Map<String, dynamic> toJson() => {
        "name": name == null ? null : name,
        "city": city == null ? null : city,
        "postal_code": postalCode == null ? null : postalCode,
        "state": state == null ? null : state,
        "address": address == null ? null : address,
        "emails" : emails == null ? null : emails,
      };
}


text:
Q: Converting PDF to a collection of images on the server using GhostScript These are the steps I am trying to achieve:

*

*Upload a PDF document on the server.

*Convert the PDF document to a set of images using GhostScript (every page is converted to an image).

*Send the collection of images back to the client.

So far, I am interested in #2.
First, I downloaded both gswin32c.exe and gsdll32.dll and managed to manually convert a PDF to a collection of images(I opened cmd and run the command bellow):
gswin32c.exe -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dMaxStripSize=8192 -sOutputFile=image_%d.jpg somepdf.pdf

Then I thought, I'll put gswin32c.exe and gsdll32.dll into ClientBin of my web project, and run the .exe via a Process.
System.Diagnostics.Process process1 = new System.Diagnostics.Process();
process1.StartInfo.WorkingDirectory = Request.MapPath("~/");
process1.StartInfo.FileName = Request.MapPath("ClientBin/gswin32c.exe");
process1.StartInfo.Arguments = "-dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dMaxStripSize=8192 -sOutputFile=image_%d.jpg somepdf.pdf"
process1.Start();

Unfortunately, nothing was output in ClientBin. Anyone got an idea why? Any recommendation will be highly appreciated.

A: I've tried your code and it seem to be working fine. I would recommend checking following things:

*

*verify if your somepdf.pdf is in the working folder of the gs process or specify the full path to the file in the command line. It would also be useful to see ghostscript's output by doing something like this:
....
process1.StartInfo.RedirectStandardOutput = true;
process1.StartInfo.UseShellExecute = false;
process1.Start();
// read output
string output = process1.StandardOutput.ReadToEnd();
...
process1.WaitForExit();
...
if gs can't find your file you would get an "Error: /undefinedfilename in (somepdf.pdf)" in the output stream.

*another suggestion is that you proceed with your script without waiting for the gs process to finish and generate resulting image_N.jpg files. I guess adding process1.WaitForExit should solve the issue.


text:
Q: XJC does not generate enum inside xs:union I have several XSD files containing structures like the following:
<xs:complexType name="SomeThing" abstract="false">
    <xs:sequence>
        <xs:element name="id" type="schema2:SomeIdTypeClass" minOccurs="1" maxOccurs="1"/>
        <xs:element name="myType" type="schema1:MyType" minOccurs="1" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

<xs:simpleType name="MyType">
    <xs:union>
        <xs:simpleType>
            <xs:restriction base="xs:string">
                    <xs:enumeration value="APPLE"/>
                    <xs:enumeration value="ORANGE"/>
                    <xs:enumeration value="BANANA"/>
                </xs:restriction>
            </xs:simpleType>
            <xs:simpleType>
                <xs:restriction base="xs:string">
                <xs:pattern value="OTHER:[a-zA-Z_][a-zA-Z0-9_]*"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:union>
</xs:simpleType>

I am using the XJC command to generate the Java classes on the console, not maven or ant or any other build tool.
All Classes seem to be generated fine except these kind of enums. The Classes that are using the enum Type are only referecning it as String, e.g. the Something class contains MyType only as a String, and not as an ENUM, as I would expect it.
In another file I have something like this, where the Enums are generated without problems and referencing classes are using it as Enums as they should.
<xs:simpleType name="SizeType">
<xs:restriction base="xs:string">
        <xs:enumeration value="SMALL"/>
        <xs:enumeration value="MEDIUM"/>
        <xs:enumeration value="LARGE"/>
</xs:restriction>

I do not want to alternate the XSD files since they are not generated by myself and I have a few files with many of those elements.
I came to the conclusion that i need to use some kind of XJB binding file, but I cannot figure out, what exactly i need to write there:
The following gives me only the error "results in too many target nodes"
<jaxb:bindings version="2.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:extensionBindingPrefixes="xjc">
    <jaxb:bindings schemaLocation="MySchema.xsd" node="/xs:schema">
        <jaxb:bindings node="//xs:simpleType[@name='MyType']/xs:union/xs:simpleType">
            <jaxb:typesafeEnumClass name="MyType"/>
        </jaxb:bindings>
    </jaxb:bindings>
</jaxb:bindings>

Adding multiple="true" solves that but still does not give me the Enums that I want.
Edit:
When i remove the xs:union so that i have a normal xs:simpleType like this:
<xs:simpleType name="MyType">
    <xs:restriction base="xs:string">
    <xs:pattern value="OTHER:[a-zA-Z_][a-zA-Z0-9_]*"/>
    <xs:enumeration value="APPLE"/>
    <xs:enumeration value="ORANGE"/>
    <xs:enumeration value="BANANA"/>
    </xs:restriction>
</xs:simpleType>

Then it works as intended. I still dont want to go down that route and edit the schemas if I dont have to. There must be some way around.

A: Ok I have been spending some time on the subject, I googled a lot and made some tests.
Short answer : it's not possible
Detailled answer :
This question on SO is about a guy having the same issue but simpler : he had an union containing a single simpleType (a restriction with some enumeration), which is weird because the union is pointless but anyway.
So the guy is stuck and this answer was quite interesting :

It looks like unions are not well supported
  https://jaxb.java.net/tutorial/section_2_2_10-Defining-a-Type-Union.html
If you could modify the schema you could extract the enumerated
  anonymous simple type to a named type and then use in your code the
  Java enum generated for this new type....

Not well supported... But not well as in "not at all" or as in "in some case" ?
Unfortunalely the link is broken but thanks to our friend The Internet Archive, I pulled out the information I needed :

In Java, there is no convenient way of expressing unions of simple
  types. The JAXB compiler simply inserts Java's String type wherever
  the union type is used and leaves it up to the application programmer
  to handle the rest. Try to avoid xsd:union.

So that's the end of the road, you are stuck. As long as union are present in your schema, no emum class will be generated and String will always be picked as default type.
Moreover, I found this article, Extend enumerated lists in XML schema. In some solutions, the author advocates to use union but ultimately say :

Requires <xsd:union> tag support, which is sometimes not implemented in tools

Finally, the best solution is maybe the first one in the article : Edit the original schema to include the new enumerated values

A: You need to use the following binding.
<jaxb:bindings version="2.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:extensionBindingPrefixes="xjc">
<jaxb:bindings schemaLocation="MySchema.xsd" node="/xs:schema">
<jxb:bindings node="//xs:element[@name='MyType']">
            <jxb:property >
                <jxb:baseType name="java.lang.String"></jxb:baseType>
            </jxb:property>
        </jxb:bindings>
        </jxb:bindings>


text:
Q: Get Window Object in WPF ResourceDictionary based window In VS2008, I add a Resource Dictionary template in my solution, I named this template as "MyWinStyle.xaml".
Below is the style used in my window:

     ......

<!--Window Template-->
<ControlTemplate x:Key="MyWindowTemplate" TargetType="{x:Type Window}">
.....
</ControlTemplate>

<!--Window Style-->
<Style x:Key="MacWindowStyle" TargetType="Window">
    ....
    <Setter Property="Template" Value="{StaticResource MyWindowTemplate}" />
</Style>

</ResourceDictionary>

this is my XMAL code, when I want to add the function to make the ownerdraw window resizable, I encounter a problem, that is, I can't get the Window Object in its constructor.(based on this article, I want to make my window resizable: http://blog.kirupa.com/?p=256)
below is my code:
public partial class MyStyledWindow : ResourceDictionary
{
    private const int WM_SYSCOMMAND = 0x112;
    private HwndSource hwndSource;
    IntPtr retInt = IntPtr.Zero;

    public MacStyledWindow()
    {
        InitializeComponent();
        /**
         **Would anyone suggest on this? I can't get window object
         **/
Window.SourceInitialized += new EventHandler(MainWindow_SourceInitialized);
    }

    private void MainWindow_SourceInitialized(object sender, EventArgs e)
    {
        hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
        hwndSource.AddHook(new HwndSourceHook(WndProc));
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        Debug.WriteLine("WndProc messages: " + msg.ToString());
        //
        // Check incoming window system messages
        //
        if (msg == WM_SYSCOMMAND)
        {
            Debug.WriteLine("WndProc messages: " + msg.ToString());
        }

        return IntPtr.Zero;
    }

    public enum ResizeDirection
    {
        Left = 1,
        Right = 2,
        Top = 3,
        TopLeft = 4,
        TopRight = 5,
        Bottom = 6,
        BottomLeft = 7,
        BottomRight = 8,
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    private void ResizeWindow(ResizeDirection direction)
    {
        SendMessage(hwndSource.Handle, WM_SYSCOMMAND, (IntPtr)(61440 + direction), IntPtr.Zero);
    }

    private void ResetCursor(object sender, MouseEventArgs e)
    {
        var window = (Window)((FrameworkElement)sender).TemplatedParent;
        if (Mouse.LeftButton != MouseButtonState.Pressed)
        {
            window.Cursor = Cursors.Arrow;
        }
    }

    private void Resize(object sender, MouseButtonEventArgs e)
    {
        Rectangle clickedRectangle = sender as Rectangle;
        var window = (Window)((FrameworkElement)sender).TemplatedParent;
        switch (clickedRectangle.Name)
        {
            case "top":
                window.Cursor = Cursors.SizeNS;
                ResizeWindow(ResizeDirection.Top);
                break;
            case "bottom":
                window.Cursor = Cursors.SizeNS;
                ResizeWindow(ResizeDirection.Bottom);
                break;
            case "left":
                window.Cursor = Cursors.SizeWE;
                ResizeWindow(ResizeDirection.Left);
                break;
            case "right":
                window.Cursor = Cursors.SizeWE;
                ResizeWindow(ResizeDirection.Right);
                break;
            case "topLeft":
                window.Cursor = Cursors.SizeNWSE;
                ResizeWindow(ResizeDirection.TopLeft);
                break;
            case "topRight":
                window.Cursor = Cursors.SizeNESW;
                ResizeWindow(ResizeDirection.TopRight);
                break;
            case "bottomLeft":
                window.Cursor = Cursors.SizeNESW;
                ResizeWindow(ResizeDirection.BottomLeft);
                break;
            case "bottomRight":
                window.Cursor = Cursors.SizeNWSE;
                ResizeWindow(ResizeDirection.BottomRight);
                break;
            default:
                break;
        }
    }

    private void DisplayResizeCursor(object sender, MouseEventArgs e)
    {
        Rectangle clickedRectangle = sender as Rectangle;
        var window = (Window)((FrameworkElement)sender).TemplatedParent;
        switch (clickedRectangle.Name)
        {
            case "top":
                window.Cursor = Cursors.SizeNS;
                break;
            case "bottom":
                window.Cursor = Cursors.SizeNS;
                break;
            case "left":
                window.Cursor = Cursors.SizeWE;
                break;
            case "right":
                window.Cursor = Cursors.SizeWE;
                break;
            case "topLeft":
                window.Cursor = Cursors.SizeNWSE;
                break;
            case "topRight":
                window.Cursor = Cursors.SizeNESW;
                break;
            case "bottomLeft":
                window.Cursor = Cursors.SizeNESW;
                break;
            case "bottomRight":
                window.Cursor = Cursors.SizeNWSE;
                break;
            default:
                break;
        }
    }

    private void Drag(object sender, MouseButtonEventArgs e)
    {
        var window = (Window)((FrameworkElement)sender).TemplatedParent;
        window.DragMove();
    }
}
}

A: Why are you using ResourceDictionary as a base class for your window? Change your base class to Window and you'll be able to subscribe to SourceInitialized event. That is:
    public partial class MyStyledWindow : Window
    {
    //other code


text:
Q: Kernel's not found error in arch I run this command:
sudo dkms autoinstall -k 3.11.6-1-ARCH

and have error:
Error! echo
Your kernel headers for kernel 3.11.6-1-ARCH cannot be found at
/usr/lib/modules/3.11.6-1-ARCH/build or /usr/lib/modules/3.11.6-1-ARCH/source.
Error! echo
Your kernel headers for kernel 3.11.6-1-ARCH cannot be found at
/usr/lib/modules/3.11.6-1-ARCH/build or /usr/lib/modules/3.11.6-1-ARCH/source.

what should I do?

A: Do you actually have kernel headers for the stock repo kernel installed? They're not installed by default, so unless you explicitly did, you probably don't. Try running:
pacman -Sy linux-headers

and see what happens.
Also, does the kernel version you have match with what you're trying to run against it? If the above doesn't fix the problem, please post the output of
uname -a


text:
Q: Console application, windows service, or web service for reading from Azure SQL database every 5 minutes? I want to have a method that checks table in Azure database every 5 minutes with no condition, so it's just a scheduled task that runs every 5 minutes regardless of anything.
Not sure what is the best application template I should use for this, I'm choosing between Console application, Windows service, Web service, or something else.
Please let me know which one will do the job better and will be easier for scheduling.

A: If you want to run something in the cloud, consider using an Azure Logic App. You will probably want to check the database and then take some action based on the result of your query. With Logic Apps you can implement  a workflow using the designer. It requires minimal coding since various connectors are already available out of the box. Additionally you are charged only for the compute time during which the app is run.
If you have some enhanced logic to execute you can consider writing an Azure Function and call it from the Logic App.
You say you want to periodically check a queue and perform some action if a message exists. You have 2 options

*

*Azure function that is triggered whenever a new message arrives in the queue. It would be cheaper and easier to have your function called by Azure whenever a message arrives in the queue rather than continuously polling the queue every 5 minutes and check for a message.

*Logic App that describes the workflow. Here you can easily configure which Queue to poll, perform checks on the message and use existing connectors to easily access the SQL table whenever your conditions are satisfied.

A: The best would be ConsoleApplication.
If you want to run it from your computer, just run it. If you want to run it in Azure - use Azure Web Jobs.

Create AppServie in Azure, then select this blade on the AppService page and follow instructions. These web jobs can run regular ConsoleApplications from Azure. Application can do whatever it wants.


text:
Q: Null records in data comparison I am building a VIEW by comparing two tables having columns namely RUN_DATE(TABLE 1) of date format and FT_Data_cut(TABLE 2 ) of date format. I need to fetch the latest data from Table 2

into View. My below condition is not working.
SELECT
FROM "XYZ"."DATA_LAKE"."STE_INCOMING"
WHERE FT_DATA_CUT = (
  select max(RUN_DATE)
  from "XYZ"."OUTBOUND"."CONTROL_TABLE"
  where release_flag = 'RELEASED'
  and table_name='STE_INCOMING');

On brief checking,
select max(RUN_DATE)
from "XYZ"."OUTBOUND"."CONTROL_TABLE"
where release_flag = 'RELEASED'
and table_name='STE_INCOMING'

(Working fine)
My above query is working properly but I am not able to compare the two dates. It is returning Zero Rows in output. But we have a common date(ex- 2022-02-21) in both columns. The data type is also the same for both tables as I discussed earlier. I don't know why it is not able to compare the two dates


text:
Q: How to set a bootstrap 3 container to 100% of browser height with a sticky footer? Like the title says, how do I set a bootstrap 3 container (wrapper) to 100% of the height of a browser window using a sticky footer?
BootPly
UPDATE:
the sticky footer works fine, it's the first '<div class="container">' that I need to be 100% height

A: You can set the page height to 100% and then put the footer at the bottom with a margin of it's height.
Like done here: http://getbootstrap.com/examples/sticky-footer-navbar/
Start by adding this to your css:
html {
  position: relative;
  min-height: 100%;
}

And for the footer add this
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #f5f5f5;
}


text:
Q: Excluding one thread from executing boost::fibers I'm creating a multi-threaded program which highly relays on boost::fibers when it comes to executing the actual execution heavy code.
What I want to achieve:
My main thread knows when to activate and run which fiber and when to collect the future provided after the execution of the fiber.
As my software is running in a highly parallel environment with over 100 cores, I start as many worker threads if possible. The worker threads should run a fiber scheduler like boost::fibers::algo::work_stealing. Therefore they should execute all the fibers my main thread produces.
What's the issue:
As my main thread is quite buisy with creating and timing all the fibers for the over 100 worker threads I want to avoid the main thread from joining the execution of any fibers.
This means, my main thread should solely care about starting fibers and gathering their futures after they completed executing.
However, I do not know how to exclude my main fiber from executing fibers, too.
Possible, naive, solutions:
Even though I don't know how to solve my problem properly, I thougt about a few possibilities.

*

*Create my own fiber scheduler: The scheduler is a customization point of boost::fibers. Hence, there might be the possibility to wirte a custome scheduler which excludes the main tread from execution.

*Use a boost::fibers::buffered_channel to transmit tasks between threads: However, I don't if this is a good solution as this removes the great possibilities from using a fiber scheduler.

*Ohter great way I don't know yet: I gues there might be another, simple way from excluding the main thread, which creates the fibers, from participating in the execution scheduling of boost::fibers
As I'm quite new in the boost::fibers library, I wonder what is the best way to achieve my goal?
Regards and thank you for your help!


text:
Q: WebDriver dismiss an Alert box how to dismiss a alert box by clicking "OK" button? I saw on WebDriver Google group that Simon is adding this feature. I am not sure whether this is supported or not.

A: Take a look at issue 27 in the Google Code Issues List. Use the JavascriptExecutor to override the browser's alert:
((JavascriptExecutor)driver).executeScript("window.alert = function(msg){};");

It's a similar solution to handle confirmation dialogs.
((JavascriptExecutor)driver).executeScript("window.confirm = function(msg){return true;};");

This is a pretty popular request so hopefully it'll get implemented soon. The downside to these approaches is that it's not easy to validate the text in the message. You may want to step down to Selenium to do that.

A: C# code:
IAlert alert = driver.SwitchTo().Alert();
alert.Accept();
System.Threading.Thread.Sleep(milliseconds);

A: driver.findElement(By.id("updateButton")).click();

//pop up with id "updateButton" opens
Alert alert = driver.switchTo().alert();
//update is executed
alert.accept();

A: Python code:
driver.switch_to_alert().accept()

See:

site-packages/selenium/webdriver/remote/webdriver.py
site-packages/selenium/webdriver/common/alert.py


text:
Q: Checking equality of objects following different attrbutes I have two lists of objects and I need to find matching objects according to two different sets of attributes. Let's say, I have Vehicle() objects and I need to first match all vehicles of the first list that are eqal to vehicles in the second, first looking on matching colors then looking on matching brands.
I have two solutions, but I am not sure if this is the best I can do. (I really need to optimise this performance wise)
So let's say I have:
class Vehicle(object):
    def __init__(self, color, brand):
        self._color = color
        self._brand = brand

and lists of objects as such :
vehicles1= [Vehicle('blue','fiat'), Vehicle('red','volvo'), Vehicle('red','fiat')]

vehicles2 = [Vehicle('blue', 'volvo'), Vehicle('red', 'BMW')]

The first solution, which seems rediculously slow, is to work only by list inclusions :
inersect_brand_wise = [x for x in vehicles1 for y in vehicles2 if x._brand == y._brand]

then
 intersect_color_wise = [x for x in vehicles1 for y in vehicles2 if x._color == y._color]

The second solution I foud is to elaborate equality:
class Vehicle(object):
    def __init__(self, color, brand):
        self._color = color
        self._brand = brand

    def __eq__(self, other):
        if isinstance(other, Vehicle):
            return self._brand == other._brand
        return False
    def __hash__(self):
        return hash((self._color, self._brand))

Now getting the intersection brand-wise is trivial :
inersect_brand_wise = [x for x in vehicles1 if x in vehicles2]

in order to get intersection color-wise, I did the following :
class Car(Vehicle):
    def __init__(self, color, brand):
        Vehicle.__init__(self,color, brand)

def __hash__(self):
    return Vehicle.__hash__

def __eq__(self, other):
    if isinstance(other, Car):
        return other._color == self._color
    return False

def change_to_car(obj):
    obj.__class__ = Car
    return obj

cars1 = map(change_to_car, vehicles1)
cars2  = map(change_to_car, vehicles2)

And thus,
intersect_color_wise = [x for x in cars1 if x in cars2]

gives the second intersection.
However, this appears to me as a very clumsy way to do things, and I actually need good performance on this one.
Any suggestions on how to do better than all that?
Thanks in advance,
M

A: How is the performance in this case? Don't have a full set of data to emulate the performance for proper testing...:
def get_intersections(list1, list2):
    brands, colors = map(set, zip(*[(v._brand, v._color) for v in list2]))
    inter_brands = [v for v in list1 if v._brand in brands]
    inter_colors = [v for v in list1 if v._colors in colors]
    return inter_brands, inter_colors

You can also write individual intersections if you want:
from operator import attrgetter

def get_intersection(list1, list2, attr:str):
    getter = attrgetter(attr)
    t_set = {getter(v) for v in list2}
    results = [v for v in list1 if getter(v) in t_set]
    return results

# use it like this:
get_intersection(vehicles1, vehicles2, "_brand")

You can also scale the first function with attrgetter to get an arbitrary number of attributes:
def get_intersections(list1, list2, *attrs:str):
    getter = attrgetter(*attrs)
    if len(attrs) > 1:
        sets = list(map(set, zip(*[getter(v) for v in list2])))
    else:
        sets = [{getter(v) for v in list2}]
    results = {attr: [v for v in vehicles1 if getattr(v, attr) in sets[s]] for s, attr in enumerate(attrs)}
    return results

Test:
>>> get_intersections(vehicles1, vehicles2, "_brand", "_color")

{'_brand': [<__main__.Vehicle object at 0x03588910>], '_color': [<__main__.Vehicle object at 0x035889D0>, <__main__.Vehicle object at 0x03588910>, <__main__.Vehicle object at 0x035889F0>]}

>>> get_intersections(vehicles1, vehicles2, "_brand")

{'_brand': [<__main__.Vehicle object at 0x03588910>]}

A: In fact Python is a dynamic language. That means that you can monkey patch the Vehicle class at will to make it suit your needs. You prepare 2 other classes (I made them subclasses of Vehicle so that autocompletion works in IDE) with respectively brand equality and color equality, and just assign their members to the Vehicle class:
class Vehicle(object):
    def __init__(self, color, brand):
        self._color = color
        self._brand = brand

class Vehicle_brand(Vehicle):
    def __eq__(self, other):
        return self._brand == other._brand
    def __hash__(self):
        return hash(self._brand)

class Vehicle_color(Vehicle):
    def __eq__(self, other):
        return self._color == other._color
    def __hash__(self):
        return hash(self._color)

To obtain brand intersection:
Vehicle.__eq__ = Vehicle_brand.__eq__
Vehicle.__hash__ = Vehicle_brand.__hash__
intersect_brand_wise = [x for x in vehicles1 if x in vehicles2]

Then to obtain color intersection:
Vehicle.__eq__ = Vehicle_color.__eq__
Vehicle.__hash__ = Vehicle_color.__hash__
intersect_color_wise = [x for x in vehicles1 if x in vehicles2]

The good news here, is that if your Vehicle class has other members, they are left untouched when you change the equality part, and you never copy or duplicate any objects: only 2 methods in the class objects.
It may not be very OO pure, but it should work...

A:
Question: Checking equality of objects following different attrbutes

Instead to find equal objects afterwards, doing loop in loop, check for equality at instantiation.
To save memory, save only the equal hashes of objects.

*

*Use class attributs to hold a dict of the objects from set 1
and a list to hold the _hash of equal objects.
class VehicleDiff:
    ref1 = {}
    _intersection = []

    def __init__(self, set, color, brand):
        self.color = color
        self.brand = brand

*Save a reference of set 1 objects in the dict ref1.
Check only objects from set 2 against the dict ref1 and save only if equal.
        _hash = hash((color, brand))
        if set == 1:
            VehicleDiff.ref1[_hash] = self

        elif _hash in VehicleDiff.ref1:
            VehicleDiff._intersection.append(_hash)

*Helper methode intersection to get a VehicleDiff object from _hash.
    @staticmethod
    def intersection():
        print('intersection:{}'.format(VehicleDiff._intersection))
        for _hash in VehicleDiff._intersection:
            yield VehicleDiff.ref1[_hash]

*String representation of a VehicleDiff object.
    def __str__(self):
        return 'color:{}, brand:{}'.format(self.color, self.brand)

*There is no need to hold the objects in a list.

Note: As the given example data have no intersection, I added ('red', 'fiat') to set 2

for p in [('blue', 'fiat'), ('red', 'volvo'), ('red', 'fiat')]:
    VehicleDiff(1, *p)

for p in [('blue', 'volvo'), ('red', 'BMW'), ('red', 'fiat')]:
    VehicleDiff(2, *p)

*Print the result, if any.
for vehicle in VehicleDiff.intersection():
    print('vehicle:{}'.format(vehicle))

Output:
intersection:[2125945310]
vehicle:color:red, brand:fiat

Tested with Python: 3.4.2


text:
Q: unable to set up lwjgl for eclipse on ubuntu hey am trying to setup lwjgl for eclipse on ubuntu and i am having some problems need help i have added the lwjgl jar to the build path and poited it to the native folder but no luck when i try to run the test code provided on the site i get this error

here is the code
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;

import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;

public class HelloWorld {

// The window handle
private long window;

public void run() {
    System.out.println("Hello LWJGL " + Version.getVersion() + "!");

    try {
        init();
        loop();

        // Free the window callbacks and destroy the window
        glfwFreeCallbacks(window);
        glfwDestroyWindow(window);
    } finally {
        // Terminate GLFW and free the error callback
        glfwTerminate();
        glfwSetErrorCallback(null).free();
    }
}

private void init() {
    // Setup an error callback. The default implementation
    // will print the error message in System.err.
    GLFWErrorCallback.createPrint(System.err).set();

    // Initialize GLFW. Most GLFW functions will not work before doing this.
    if ( !glfwInit() )
        throw new IllegalStateException("Unable to initialize GLFW");

    // Configure our window
    glfwDefaultWindowHints(); // optional, the current window hints are already the default
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable

    int WIDTH = 300;
    int HEIGHT = 300;

    // Create the window
    window = glfwCreateWindow(WIDTH, HEIGHT, "Hello World!", NULL, NULL);
    if ( window == NULL )
        throw new RuntimeException("Failed to create the GLFW window");

    // Setup a key callback. It will be called every time a key is pressed, repeated or released.
    glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
        if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE )
            glfwSetWindowShouldClose(window, true); // We will detect this in our rendering loop
    });

    // Get the resolution of the primary monitor
    GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    // Center our window
    glfwSetWindowPos(
        window,
        (vidmode.width() - WIDTH) / 2,
        (vidmode.height() - HEIGHT) / 2
    );

    // Make the OpenGL context current
    glfwMakeContextCurrent(window);
    // Enable v-sync
    glfwSwapInterval(1);

    // Make the window visible
    glfwShowWindow(window);
}

private void loop() {
    // This line is critical for LWJGL's interoperation with GLFW's
    // OpenGL context, or any context that is managed externally.
    // LWJGL detects the context that is current in the current thread,
    // creates the GLCapabilities instance and makes the OpenGL
    // bindings available for use.
    GL.createCapabilities();

    // Set the clear color
    glClearColor(1.0f, 0.0f, 0.0f, 0.0f);

    // Run the rendering loop until the user has attempted to close
    // the window or has pressed the ESCAPE key.
    while ( !glfwWindowShouldClose(window) ) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

        glfwSwapBuffers(window); // swap the color buffers

        // Poll for window events. The key callback above will only be
        // invoked during this call.
        glfwPollEvents();
    }
}

public static void main(String[] args) {
    new HelloWorld().run();
}

}

picture of project hierarchy

and build path image

A: LWJGL requires Java 8 or higher from the latest nightly builds on. The jar you downloaded has been compiled with JDK 8, which uses a file format version that is not supported by Java 7 JREs.
On Ubuntu you can install the openjdk-8-jdk package, although if you are using Ubuntu 14.04 you will have to use a PPA or alternative package since OpenJDK 8 is not available there.


text:
Q: dataframe merging + comparison with existence test I am looking to perform the following task:

Given 2 pandas DataFrames, each with one column but of different length, create a new DataFrame whose index is the union of the 2 other DataFrames and possesses two columns: one indicating whether DataFrame 1 contained a value for that particular index, and one indicating whether DataFrame 2 contained a value for that particular index.

I have the following example data:
rng = pd.date_range('1/1/2017', periods=365, freq='D')
rng2 = pd.date_range('1/1/2016',periods=730, freq='D')
x1 = np.random.randn(365)
x2 = np.random.randn(730)
df1 = pd.DataFrame({'x':x1}, index=rng)
df2 = pd.DataFrame({'x':x2}, index=rng2)

I can obtain the union of the indices by doing:
idx = df1.index.union(df2.index)

Now, I would like to create a new DataFrame, df3, which has index of idx and 2 columns populated with zeroes and ones as per the above requirements.
I have explored using the .isin() functionality but from what I can tell that might require knowing a little bit too much about the DataFrames beforehand, while I would like to achieve this more flexibly.

A: An outer join and a test for notnull() achieves the desired behavior.  With your example data it would look something like:
notnull = df1.join(df2.rename(columns={'x': 'x2'}), how='outer').notnull()

Sample Data:
rng1 = pd.date_range('1/2/2017', periods=4, freq='D')
rng2 = pd.date_range('1/1/2017', periods=4, freq='D')
x = np.random.randn(4)
df1 = pd.DataFrame({'x': x}, index=rng1)
df2 = pd.DataFrame({'x': x}, index=rng2)

Test it:
notnull = df1.join(df2.rename(columns={'x': 'x2'}), how='outer').notnull()
print(notnull)

Output:
                x     x2
2017-01-01  False   True
2017-01-02   True   True
2017-01-03   True   True
2017-01-04   True   True
2017-01-05   True  False

Update from the Comments:
If you want actual ones and zeros instead of bool,
ones_and_zeros= df1.join(df2.rename(columns={'x': 'x2'}),
                                    how='outer').notnull().astype(np.uint8)
print(ones_and_zeros)

Output:
            x  x2
2017-01-01  0   1
2017-01-02  1   1
2017-01-03  1   1
2017-01-04  1   1
2017-01-05  1   0


text:
Q: Trying to create a new youtube channel using selenium, but javascript is required to be enabled I am trying to use selenium to create a new youtube channel. I am able to login, set a channel name, then click the create channel button; however, it says I am not able to create a channel. I have looked threw the code and it says that I need to have javascript enabled, which I have done. But it is still not working, any suggestions?
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--enable-javascript")
#chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path="chromedriver.exe", options=chrome_options)

driver.get("https://www.youtube.com/account")

emailField = driver.find_element_by_xpath("//input[@type='email']")
emailField.send_keys(email)
emailField.send_keys(Keys.RETURN)

time.sleep(1)
passwordField = driver.find_element_by_xpath("//input[@type='password']")
passwordField.send_keys(password)
passwordField.send_keys(Keys.RETURN)

time.sleep(2)
driver.find_element_by_xpath("//a[contains(text(),'Add or manage your channel(s)')]").click()
time.sleep(2)
driver.find_element_by_xpath("//a[@href='/create_channel?action_create_new_channel_redirect=true']").click()
time.sleep(2)
driver.find_element_by_xpath("//input[@id='PlusPageName']").send_keys('Test{}'.format(random.randint(1,100)))
driver.find_element_by_xpath("//input[@id='submitbutton']").click()

A: It's probably becuase of youtubes bot detection, did something simlair with instagram a while ago and had to create a script that moved the mouse to some exact coordinates.


text:
Q: Rtrim does not work Help rtrim would not work whatever I do. I also tried to add whitespace after "," like it was on one of the topics i searched here
$this->items = array();
$xcount='(';
foreach ($items as $v) {
   $this->items[$v['id']] = $v;
   $xcount.=$v['id'].',';
};
rtrim($xcount, ",");

$xcount.=')';

A: The rtrim() returns a value and does not modify the original value. Please use it this way:
$xcount = rtrim($xcount, ",");

From the rtrim():

This function returns a string with whitespace (or other characters) stripped from the end of str.

A: rtrim() for me is not working. I do believe that it is related to the fact that I use greek characters. Check regex instead.


text:
Q: Can I add code to the default constructor and another dilemma I am dynamically assigning a form (think of it as a "pseudo tab page") to a tabcontrol.
I was doing it this way:
// Main form, which has the TabControl at design-time:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
    int TabControlWidth = tabPageBasicInfo.Size.Width;
    int TabControlHeight = tabPageBasicInfo.Size.Height;

    if (e.Node.Name == "NodeWhatever")
    {
        BasicInfoPseudoTab bipt = new BasicInfoPseudoTab(TabControlWidth, TabControlHeight);
        tabPageBasicInfo.Controls.Add(bipt);
        bipt.Show();
    }
    // else NodeThis, NodeThat
}

// Constructor on the form that is the "pseudo tab page":
// overloaded constructor, passing in the dimensions of the tab page
public BasicInfoPseudoTab(int ATabPageWidth, int ATabPageHeight)
{
    this.TopLevel = false;
    this.FormBorderStyle = FormBorderStyle.None;
    this.Width = ATabPageWidth;
    this.Height = ATabPageHeight;
    this.Visible = true;
}

...but then I experimented with setting the Dock property:
public BasicInfoPseudoTab(int ATabPageWidth, int ATabPageHeight)
{
    this.TopLevel = false;
    this.FormBorderStyle = FormBorderStyle.None;
    //this.Width = ATabPageWidth;
    //this.Height = ATabPageHeight;
    this.Visible = true;
    this.Dock = DockStyle.Fill;
}

...and it works great, so I thought I'd just use the "in the box" constructor by stripping out the two args. However, that's not allowed, as get, "Type 'UserControlsOnTabPagePOCApp.BasicInfoPseudoTab' already defines a member called 'BasicInfoPseudoTab' with the same parameter types"
The Load() event is too late (when I was setting the TopLevel property there, it gave me an err msg until I moved it to the constructor).
What do I need to do to override (rather than overload) the constructor, or what other event should I use (does anything come before the Load() event?)
ALSO (I didn't want to put the same code in two different questions): the form itself displays fine on the TabControl, but the controls I've added to the form/pseudo Tag page at design-time do not display at run-time - why?

A: It's not a matter of overriding a constructor (constructors aren't polymorphic like that anyway) - it's a matter of the constructor already existing. I'd expect it to be present already in your code - something like this:
public BasicInfoPseudoTab()
{
    InitializeComponent();
}

You can edit that constructor, rather than declaring another parameterless one. Note that your other constructor should either chain to that one or call InitializeComponent() itself, so that all the designer code can do its stuff.


text:
Q: Possible memory leak (Android, Glide, Activity stack) I am facing a very common and nasty problem as OutOfMemory exception.
To introduce my APP, it is heavy picture content one. And I discovered, I receive a OOM at 256mb in my device (Xiaomi 5s). I cannot find the memory leak (tried https://github.com/square/leakcanary). My APP crashes at ~10th activity loaded. Weird thing happens with GC. Most of the memory gets freed up only if I am fully back to the start.
For image loading I am using Glide. I changed Decoding from 8888 to 565 (default). With 8888 OOM happened faster.
What I was thinking is just to start finishing activities from the stack. Let's say if we have 8 activities, at 9th activity open, 1st activity will be finished and so on.
Before doing so, I would like to hear your guys suggestions!
EDIT
Mostly happens when trying to load a new activity and trying to load images
  java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: Failed to allocate a 331212 byte allocation with 254848 free bytes and 248KB until OOM
                                                                          at java.util.concurrent.FutureTask.report(FutureTask.java:94)
                                                                          at java.util.concurrent.FutureTask.get(FutureTask.java:164)
                                                                          at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor.afterExecute(FifoPriorityThreadPoolExecutor.java:96)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1121)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                          at java.lang.Thread.run(Thread.java:818)
                                                                          at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor$DefaultThreadFactory$1.run(FifoPriorityThreadPoolExecutor.java:118)
                                                                       Caused by: java.lang.OutOfMemoryError: Failed to allocate a 331212 byte allocation with 254848 free bytes and 248KB until OOM
                                                                          at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                          at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
                                                                          at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:635)
                                                                          at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:611)
                                                                          at com.bumptech.glide.load.resource.bitmap.Downsampler.decodeStream(Downsampler.java:329)
                                                                          at com.bumptech.glide.load.resource.bitmap.Downsampler.downsampleWithSize(Downsampler.java:220)
                                                                          at com.bumptech.glide.load.resource.bitmap.Downsampler.decode(Downsampler.java:153)
                                                                          at com.bumptech.glide.load.resource.bitmap.StreamBitmapDecoder.decode(StreamBitmapDecoder.java:50)
                                                                          at com.bumptech.glide.load.resource.bitmap.StreamBitmapDecoder.decode(StreamBitmapDecoder.java:19)
                                                                          at com.bumptech.glide.load.resource.bitmap.ImageVideoBitmapDecoder.decode(ImageVideoBitmapDecoder.java:39)
                                                                          at com.bumptech.glide.load.resource.bitmap.ImageVideoBitmapDecoder.decode(ImageVideoBitmapDecoder.java:20)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decodeBitmapWrapper(GifBitmapWrapperResourceDecoder.java:121)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decodeStream(GifBitmapWrapperResourceDecoder.java:94)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:71)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:61)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:22)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperStreamResourceDecoder.decode(GifBitmapWrapperStreamResourceDecoder.java:24)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperStreamResourceDecoder.decode(GifBitmapWrapperStreamResourceDecoder.java:14)
                                                                          at com.bumptech.glide.load.resource.file.FileToStreamDecoder.decode(FileToStreamDecoder.java:39)
                                                                          at com.bumptech.glide.load.resource.file.FileToStreamDecoder.decode(FileToStreamDecoder.java:17)
                                                                          at com.bumptech.glide.load.engine.DecodeJob.loadFromCache(DecodeJob.java:222)
                                                                          at com.bumptech.glide.load.engine.DecodeJob.decodeResultFromCache(DecodeJob.java:85)
                                                                          at com.bumptech.glide.load.engine.EngineRunnable.decodeFromCache(EngineRunnable.java:108)
                                                                          at com.bumptech.glide.load.engine.EngineRunnable.decode(EngineRunnable.java:99)
                                                                          at com.bumptech.glide.load.engine.EngineRunnable.run(EngineRunnable.java:58)
                                                                          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                          at java.lang.Thread.run(Thread.java:818)
                                                                          at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor$DefaultThreadFactory$1.run(FifoPriorityThreadPoolExecutor.java:118)

Can happen also when opening an activity while memory is almost dead.
What I was thinking that it is correct, that while opening a new activity, old one stays in memory with images loaded -> which means that memory is being used. But opening only 10 activities is rather little.. Image sizes are 40-100kb. Normally in the activity are >20 images.
I also use lots of programmically created views as well as custom adapters (APP is rather big, we discovered this OOM issue just recently). I was trying to play around with passing different contexts into Glide/ImageViews, but memory usage didn't seem to change.
EDIT2
Heap dump at 178mb

A: I also had an OOM problem with glide, I decoded GIF and I kept references to drawables in an Arraylist and those drawables were not freed, the solution was to set all nulls in the arraylist and then call ArrayList.clear().
/// Free drawables
    for (int i = 0; i < mDrawables.size(); i++) {
                mDrawables.set(i, null);
            }
            mDrawables.clear();


text:
Q: Eclipse changes my font size back to 10 after I changed it to 12 I use the preference dialog to change the editor text to 12.
When I quit eclipse and restart it,
the text is drawn at size 12, but after a second or two, it gets drawn at size 10 and I have to change it again.
Is there a way to change the text size so it stays at that size?

A: One way is Goto Windows-> Preference -> General -> Color and Fonts
And other is
Cltr and + will increase the font size
Cltr and - will decrease font size.


text:
Q: Why is it "hats off" and not "hat's off"? Meriam-Webster has a page for "hats off to" to indicate praise and uses the example "Hats off to Susan for doing such a great job".
I'm surprised that it's not "Hat's off to" as in "Hat is off to". Without the apostrophe it looks like there are multiple hats.
What's the explanation for the expression being without an apostrophe?

A: It's "hats" because it's implied that there are multiple hats involved.

Hats off to Susan for doing such a great job.

This is an invitation for everyone (except Susan) to take their (figurative) hats off to congratulate Susan on her hard work.


text:
Q: Why can't I use || OR Operator in C++ Switch statement? I've been working with VB.NET for years and I luv the language. Now dispersing myself into C++ I'm having a tough time to grasp the logics of C++.
Kindly tell me any workaround. Thanks a lot !

A: That is quite an unclear question, but you are probably asking why you cannot do this:
switch(mynumber) { //assuming an int here
  case 1:
    printf("Something.");
    break;
  case 2 || 3:
    printf("Something else.");
    break;
 }

This will not work as you expected: the || operator in C++ will actually do 2 || 3, evaluating to 1. Instead, you can replicate your case statements:
switch(mynumber) {
  case 1:
    printf("Something.");
    break;
  case 2:
  case 3:
    printf("Something else.");
    break;
 }

A: Looks like VB.NET supports expression in case statements while C++ does not.


text:
Q: Google Visualization Column Chart - How to make labels as currency I'm just trying to figure out to format my labels to be shown as a currency and not just a number:
echo '

';

I would like the Sales column to be shown as a USD currency value.  How can I do that?  I see how to do it using the URL request, but that does not help this situation.
I just can't seem to find any good example on this.

A: it looks like you might want to look at setFormattedValue
http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable_setFormattedValue
and for the format stuff look at
http://code.google.com/apis/chart/interactive/docs/reference.html#formatters
I haven't tried this out, but from what I can tell this could work for you:
echo '

';

references:
http://code.google.com/p/google-visualization-api-issues/issues/detail?id=282


text:
Q: Google geocoder I am using google Geocoder Javascript API for my Google store locator. Following is the javascript code I'm using for getting results from user input:
var searchValue = $('#searchValue').val(); //search input

var gg = new google.maps.Geocoder();
gg.geocode({'address': searchValue, 'componentRestrictions' : {country: 'XX'}}, function (data, status) {
  console.log(data);   //results data with the country name
  console.log(status);  // results OK
});

the above code results data with country name even though user enters junk value like 'sdfsdfdsf'
Problem is if user searches with the country name, its returning the same result as the value entered as junk values like 'asdfddv' or some wrong postal codes like '870'
How can I filter such results if user enters some junk values?
Is there a way to stop showing results if user enters junk values?

A: The geocoding service tries to find the best possible match for your input. If it's not possible to find match for an address parameter it will search the best match for address components.
Please note that Google maps geocoding is not an address validation API, its purpose is resolving the input to the best matching coordinate.
I would suggest using a places autocomplete widget in conjunction with your search input to prevent the user from entering wrong addresses.
You can look at this example http://jsbin.com/zodayaz/edit?html,output


text:
Q: Angular OpenStreetMap with $routeProvider Here is the single page app.
There is what I need
https://github.com/tombatossals/angular-leaflet-directive/blob/master/examples/simple-example.html
but I want add menu...

<link rel="stylesheet" href="//.../bootstrap.min.css" />
<link rel="stylesheet" href="//.../bootstrap.css" />
<link rel="stylesheet" href="//.../font-awesome.css" />

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.css">

home.html and about.html consist of

 home

 about

Thanks!!!

A: for routing to work you need to be sure you are injecting ngRoute:

var App = angular.module('App', ['leaflet-directive', 'ngRoute']);

I would recommend getting routing working before you start adding other directives.


text:
Q: express-session not saving nodejs This simple example is not working. In every request the session is
created again, I don't know how to solve it.
var express = require('express'),
    expressSession = require('express-session'),
    app = express();

app.use(expressSession({
    secret:'secret',
    resave:true,
    saveUninitialized:true,
    cookie:{
        httpOnly:false,
        expires:false
    }
}));

app.all('/',function(req,res,next){
    var session = req.session;
    if(session.count){
        session.count++;
    }
    else{
        session.count = 1;
    }
    console.log('id:',req.sessionID);
    console.log('count:',session.count);
    res.end();
});

app.listen(9090);
console.log('server is running at http://localhost:9090');

I tried  to save the count of  requests, but the session is created
every time when i make a request.
//request
>GET http://localhost:9090

//response
id: gOqbVisxaW34qafRdb7-6shqYV0UurRg
count: 1

//request again
>GET http://localhost:9090

//response
id: P2iyXKHElJF8u86tHu7mIl7Encteebju
count: 1

A: I solved the problem, i made requests from other origins and with ajax. i  added the following middleware on server:
app.use(function (req, res, next) {
            // Website you wish to allow to connect
            res.setHeader('Access-Control-Allow-Origin', req.headers.origin);

            // Request methods you wish to allow
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
            // Request headers you wish to allow
            res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
            // Set to true if you need the website to include cookies in the requests sent
            // to the API (e.g. in case you use sessions)
            res.setHeader('Access-Control-Allow-Credentials', 'true');
            // Pass to next layer of middleware
            next();
        });

and in ajax request i put an option withCredentials in xhrFields
 $(document).ready(function(){
            setInterval(function(){
                $.ajax({
                    url:'http://localhost:9090/',
                    type:'post',
                    dataType:'json',
                    success:function(data){
                        console.log(data);
                    },
                    xhrFields:{
                        withCredentials:true
                    }
                });
            },1000);
        });


text:
Q: How to model a binary vector by the Beta-Bernoulli distribution in R or Python? I have a set of data $x=(x_1,x_2,x_3,...)$;e.g:$x=(0.1,0.003,0.78,...)$
which follows a beta distribution. Since $x_i$ in my data $x :x_i ~ Bernoulli(p)$, where $p$ is the prior of average $x$ and follows the Beta prior distribution, $p~Beta( α, β)$. So is there any R or python script to model a binary vector by the Beta-Bernoulli distribution from my data $x$?

A: Is this really what your data looks like? If the xi I were to follow a Bernoulli distribution, should it not be x=(0,1,0,0,1,1,0...)? I.e. all 1 or 0?
If you have that kind of 0-1 data it's pretty easy to model. E.g. the aod R package can fit beta-binomial data (and e.g. in the rstan R package or the pystan python pacakge you could easily fit a hierachical model of this type either using maximum-likelihood or in a Bayesian way after specifying it in the Stan modeling language). Obviously, any package for beta-binomial data can deal with beta-Bernoulli/binary data, because that's just the special case with 1 binomial sample per unit.
If you only have the (binomial) proportions as you seem to show in your example data, then beta-regression may be what you could use. However, that has its problems, because for a small finite number of samples the observed proportions have a rather discrete distribution. On the other hand, if the observed proportions are based on huge numbers of samples that does not vary too much across units, that may be a non-problem.


text:
Q: Why mongoose middleware "pre" remove with { query: true } is not called? I'm a bit stuck on this problem.
I have read all the mongoose documentation about middleware and some stackoverflow issue and was unable to find-out how to solve my problem without duplicating queries (find then remove).
Normally, pre middleware on remove will not fire when call from Model and not from document. But according with the doc, if I add {query: true}, my function will be called from model query.
I use the latest monngoose version (5.4.16)
Here is my code.
let mySchema= new mongoose.Schema({
  name: String,
  comment: String
}, { usePushEach: true });

mySchema.pre('remove', { document: true }, function() {
  console.log('remove document');
});
mySchema.pre('remove', { query: true }, function() {
  console.log('remove');
});
const MyModel = mongoose.model('MyModel', mySchema);

And the call here
MyModel.deleteOne({ _id: modelId }, (errorRm) => {
  if (errorRm) {
    return res.json({ success: false, message: `${errorRm.message}` });
  }
    return res.json({ success: true, message: 'Model successfully removed' });
  });

The model is successfully removed but nothing is logged from the "pre" functions...
Any help would be welcomed.

A: It's because you're using MyModel.deleteOne(). Use MyModel.remove() and it will work.
Acoording to the documentation:

You can pass options to Schema.pre() and Schema.post() to switch whether Mongoose calls your remove() hook for Document.remove() or Model.remove():


text:
Q: Incorrect syntax near the keyword 'Order' - Order is column name I keep getting the following exception:
Incorrect syntax near the keyword 'Order'.

I have a TABLE with columns: Name, Credits, Extension, Order. Order is of type bigint. Now when I go to INSERT a single record into this table, it gives me the above exception.
I have put it in a try/catch block and caught the exception, I have set breakpoints and it does not reveal anything other than the above message.
Can anybody please help shed some light on this? I'm sitting here, scratching my head wondering what the heck is going on and I just can't figure it out. I don't see where I've gone wrong.
        try
        {
            // Insert into database
            sqlconnection = new SqlConnection(@"Data Source=sblah blah blah... intentionally  removed;");

            sqlconnection.Open();

            using (var command = new SqlCommand("Insert Into Images(Name, Credits, Extension, Order) VALUES (@Name, @Credits, @Extension, @Order)", sqlconnection))
            {
                command.CommandTimeout = 240;

                command.Parameters.AddWithValue("Name", workingPicture.Properties.Filename);
                command.Parameters.AddWithValue("Credits", workingPicture.Properties.Credits);
                command.Parameters.AddWithValue("Extension", workingPicture.Properties.Extension);
                command.Parameters.AddWithValue("Order", workingPicture.Properties.Order);

                command.ExecuteNonQuery();

                doneUpdatingDB = true;
            }
        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.Message);
            doneUpdatingDB = false;
        }

The value of Order is 0.

A: ORDER is a reserved keyword in SQL Server. You have to enclose is in square brackets if you want to use it as a column name:
"Insert Into Images(Name, Credits, Extension, [Order]) VALUES (@Name, @Credits, @Extension, @Order)"

It is best to avoid using reserved keywords to name your objects (tables, columns, stored procs, etc.).

A: Order is the keyword in the SQL, Change the name of the field in the DB or make [] around the order keyword like "[order]"


text:
Q: Ideal, not finitely generated This exercise is driving me insane. I think there might be a mistake in it.

Consider the ring $R$ of matrices of the form:
$ R = \lbrace \begin{pmatrix}
  z & q_{1}  \\
  0 & q_{2}  \\
 \end{pmatrix} , z\in\mathbb{Z}, q_{1},q_{2}\in\mathbb{Q} \rbrace$
I have to find a left ideal of $R$ which is not finitely generated.

I write:
$R = R_{1} \times R_{2}$ where
$R_{1} = \lbrace \begin{pmatrix}
  z & q_{1}  \\
  0 & 0  \\
 \end{pmatrix} , z\in\mathbb{Z}, q_{1}\in\mathbb{Q} \rbrace$
$R_{2} = \lbrace \begin{pmatrix}
  0 & 0  \\
  0 & q_{2}  \\
 \end{pmatrix} , z\in\mathbb{Z}, q_{2}\in\mathbb{Q} \rbrace $
Every ideal of $R$ must have the form (since both $R_{1}, R_{2}$ contain an identity element):
$I\times J$ where $I$ is an ideal of $R_{1}$, $J$ is an ideal of $R_{2}$.
The ideals of $R_{1}$:
$ R_{1} = \lbrace \begin{pmatrix}
  z & q_{1}  \\
  0 & 0  \\
 \end{pmatrix} , z\in\mathbb{Z}, q_{1}\in\mathbb{Q} \rbrace$
$ \lbrace \begin{pmatrix}
  0 & q_{1}  \\
  0 & 0  \\
 \end{pmatrix} , q_{1}\in\mathbb{Q} \rbrace$
$0 = \lbrace \begin{pmatrix}
  0 & 0  \\
  0 & 0  \\
 \end{pmatrix} \rbrace$
Let $n\in\mathbb{Z}$:
$\lbrace \begin{pmatrix}
  n\cdot z & q_{1}\\
  0 & 0  \\
 \end{pmatrix} ,  q_{1}\in\mathbb{Q}, z\in\mathbb{Z} \rbrace$
The ideals of $R_{2}$
$R_{2} = \lbrace \begin{pmatrix}
  0 & 0  \\
  0 & q_{2} \\
 \end{pmatrix} ,  q_{2}\in\mathbb{Q} \rbrace$
$0 = \lbrace \begin{pmatrix}
  0 & 0  \\
  0 & 0  \\
 \end{pmatrix}   \rbrace$
When I check the possible constructions I obtain that they are all finitely generated. Is there a mistake in this exercise (maybe a right ideal of $R$ instead of left??) or where is the mistake?

A: The left ideal $I=\{\begin{pmatrix} 0 & q_{1} \\ 0 & 0\end{pmatrix} | q_1 \in \mathbb{Q} \}$ is not finitely generated. This follows by the fact that $\mathbb{Q}$ is not a finitely generated $\mathbb{Z}$-module. (What happens when you multiply elements of $I$ by elements in $R$?)


text:
Q: Using a ternary if the condition block is short I've got a piece of that is working, but I've been advised that I should use a ternary if the condition block is short.
module PayerContractsHelper

  def showPayerContractRate(val)
    json_val = JSON.parse(val)
    if(json_val['amount'].present?)
      "display:block"
    else
      "display:none"
    end
  end

end

How exactly can I make this a ternary with this piece of code? I assume it will be less code and more precise. How can I make this happen?

A: The ternary conditions is defined as:
condition ? if-true : if-false

In your case the following code
json_val = JSON.parse(val)
if json_val['amount'].present?
  "display:block"
else
  "display:none"
end

will become
JSON.parse(val)['amount'].present? ? "display:block" : "display:none"

or
json_val = JSON.parse(val)
json_val['amount'].present? ? "display:block" : "display:none"

The following version is the most readable to me
module PayerContractsHelper

  def showPayerContractRate(val)
    json_val = JSON.parse(val)
    "display:" + (json_val['amount'].present? ? "block" : "none")
  end

end

Also note that the Ruby naming convention for methods is underscore_case:
module PayerContractsHelper

  def show_payer_contract_rate(val)
    json_val = JSON.parse(val)
    "display:" + (json_val['amount'].present? ? "block" : "none")
  end

end


text:
Q: Javascript to outline a png image? I have a map which is a png file. I use getBoundingClientRect() with 2 div containers to check for overlapping divs througout my game. (Works fine to check for collison).
I was wondering if it's possible to outline a specific part of an image or wherever the transparency starts so I can then add a onclick event to that part of the div so the user cannot click outside of the map.

Hope this kind of makes sense.. If you need any more information let me know. Thanks

A: I think this is what you are looking for:
http://www.outsharked.com/imagemapster/
You add an area tag with the coords you need, then you can apply something over it. I recommend you this plugin since it's very powerful, easy to use.


text:
Q: How do I find the shipping class id in WooCommerce? Using Hide shipping method for specific shipping classes in woocommerce answer code, I'm trying to hide shipping options based on shipping class.
Large items and small items have their own shipping class on our website and we only want to offer express shipping on small items.
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define your shipping class to find
    $class = 92;

    // HERE define the shipping method to hide
    $method_key_id = 'flat_rate:7';

    // Checking in cart items
    foreach( WC()->cart->get_cart() as $cart_item ){
        // If we find the shipping class
        if( $cart_item['data']->get_shipping_class_id() == $class ){
            unset($rates[$method_key_id]); // Remove the targeted method
            break; // Stop the loop
        }
    }
    return $rates;
}

I understand how to implement the code, however I don't know where to find the shipping class id, I can only find the slug and shipping class name
// HERE define your shipping class to find

$class = 92;

in the above example, where do I find the Id to replace the 92?
Thanks In advance.
Will

A: To make it work with shipping class "Slugs" you will use WC_Product get_shipping_class() method instead this way:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define your shipping class SLUG
    $class_slug = 'large';

    // HERE define the shipping method to hide
    $method_key_id = 'flat_rate:7';

    // Checking in cart items
    foreach( WC()->cart->get_cart() as $cart_item ){
        // If we find the shipping class
        if( $cart_item['data']->get_shipping_class() == $class_slug ){
            unset($rates[$method_key_id]); // Remove the targeted method
            break; // Stop the loop
        }
    }
    return $rates;
}

Code goes in function.php file of your active child theme (or active theme)...

Sometimes, you should may be need to refresh shipping methods going to shipping areas, then disable / save and re-enable / save your "flat rates" shipping methods.
To find the shipping methods IDs and the shipping classes IDs see below…

Finding the shipping class ID.
1) In the database under wp_terms table:
Search for a term name or a term slug and you will get the term ID (the shipping class ID).
2) On Woocommerce shipping settings editing a "Flat rate", with your browser html inspector tool, inspect a shipping Class rate field like:

In the imput name attribute you have woocommerce_flat_rate_class_cost_64. So 64 is the ID for the shipping class.

Get the shipping method rate ID:

To get the related shipping methods rate IDs, something like flat_rate:12, inspect with your browser code inspector each related radio button attribute name like:


text:
Q: Best way to overwrite directory using phonegap File API I am working with ios & phonegap 2.7.0 with the native file system.
I need to overwrite an existing directory :
/Documents/data
with another folder :
/tmp/data1234
But it seems that overwriting an existing directory using the FileEntry.copyTo API raises a FileError.INVALID_MODIFICATION_ERR exception.
It works if I delete the /Documents/data folder before copying.
So I have a simple question : what is the best way to overwrite a directory in phonegap using the File API?
Should I make a recursive process from /tmp/data1234 and replace each file in  /Documents/data ?
Thanks for your help.


text:
Q: Migrating Full Trust solutions to App Model IS there a way/tool to convert existing Full trust Farm solutions to App Model or we will have to rewrite and re-architect all solutions?

A: Since you need to use the Client Object Model for apps, you will have to rewrite large parts (if not all) of your back-end code.


text:
Q: Use HtmlUnit as crawler I needed a headless browser to parse pages.
HtmlUnit allow me to setup a Heroku Java app to fullfil this purpose.
But now I'm meeting with couple of issues.
The current one is malformed url "//path" instead of "/path" or "http(s)://path".
I downloaded sources of the 2.9.4 version and pushed tiny fixes in the sources ...
It's not really efficient to modify standard sources for obvious maintainability reasons.
I'm so wondering if i'm not digging in the wrong direction.
HtmlUnit is designed to browse pages in a testing purpose. Mine is to do like a browser, so make page working the most possible, especially because my damned targeted websites are the kind of ultra-dirty-not-respecting-anything...
What is your opinion about this retrospection ?

A: HTML Unit is used in Selenium 2/Web Driver for headless browser "simulation". There it works fine.
So I see no reason not to try Html Unit. May you can have a look at Selenium 2/Web Driver too.


text:
Q: Pass object between two Around functions - AOP I am doing Auditing for my Controller, Service and Dao layer. I have three Around aspect functions for Controller, Service and Dao respectively. I use a custom annotation which if present on the Controller method will invoke an Around aspect function. Inside the annotation I set a property which I wish to pass from the Controller Around function to the Service around function inside the Aspect class.
public @interface Audit{
   String getType();
}

I will set the value of this getType from an interface.
@Around("execution(* com.abc.controller..*.*(..)) && @annotation(audit)")
public Object controllerAround(ProceedingJoinPoint pjp, Audit audit){
  //read value from getType property of Audit annotation and pass it to service around function
}

@Around("execution(* com.abc.service..*.*(..))")
public Object serviceAround(ProceedingJoinPoint pjp){
  // receive the getType property from Audit annotation and execute business logic
}

How can I pass an object between two Around functions?

A: Aspects are, by default, singleton objects. However, there are different instantiation models, which could be useful in use cases like yours. Using a percflow(pointcut) instantiation model, you could store the value of the annotation in your controller around advice and retrieve it in your service around advice. The following is just an example on how it would look like:
@Aspect("percflow(controllerPointcut())")
public class Aspect39653654 {

    private Audit currentAuditValue;

    @Pointcut("execution(* com.abc.controller..*.*(..))")
    private void controllerPointcut() {}

    @Around("controllerPointcut() && @annotation(audit)")
    public Object controllerAround(ProceedingJoinPoint pjp, Audit audit) throws Throwable {
        Audit previousAuditValue = this.currentAuditValue;
        this.currentAuditValue = audit;
        try {
            return pjp.proceed();
        } finally {
            this.currentAuditValue = previousAuditValue;
        }
    }

    @Around("execution(* com.abc.service..*.*(..))")
    public Object serviceAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("current audit value=" + currentAuditValue);
        return pjp.proceed();
    }

}


text:
Q: PHP Associative Array Unexpected Behavior -- WHY? Following is an associative array I am using in a chunk of PHP code that creates an organized table of performance dates and information using data from a SQL database.  The code appears to have no problems (to me), but is not behaving correctly when the webpage loads (certain dates are not appearing).
$months = array(
    01 => 'January',
    02 => 'February',
    03 => 'March',
    04 => 'April',
    05 => 'May',
    06 => 'June',
    07 => 'July',
    08 => 'August',
    09 => 'September',
    10 => 'October',
    11 => 'November',
    12 => 'December',
);

When I run a 'var_dump', the output is as follows:
array(11) {
    [1]=> string(7) "January"
    [2]=> string(8) "February"
    [3]=> string(5) "March"
    [4]=> string(5) "April"
    [5]=> string(3) "May"
    [6]=> string(4) "June"
    [7]=> string(4) "July"
    [0]=> string(9) "September"
    [10]=> string(7) "October"
    [11]=> string(8) "November"
    [12]=> string(8) "December" }

The whole line for 'August' is missing, and the key for 'September' is now [0].
Can anybody explain where the error is in my code?
Disclaimer: I have solved the issue by removing the leading zeroes from the first nine keys, but I am confused as to why it mattered??  Thanks in advance for any explanation.

A: 08 and 09 are invalid octal literals... So what you need to do is either of:

*

*Name your keys as proper integers (without 0 prefix)

*Or, use your keys as strings, like you mentioned "associative array" in question, your array should be like this:

<?php
$months = array(
    "01" => 'January',
    "02" => 'February',
    "03" => 'March',
    "04" => 'April',
    "05" => 'May',
    "06" => 'June',
    "07" => 'July',
    "08" => 'August',
    "09" => 'September',
    "10" => 'October',
    "11" => 'November',
    "12" => 'December',
);

sorry wanted to comment but couldn't, new user here


text:
Q: Node.js package installation error I had install Node.js 4.2.2
i am trying to install socket.io package using npm install socket.io
but the npm installer just keep running with no error output in console after 30min..

A: Try to install some another package, mongoose for example. If it also fails try to reinstall npm by
npm install -g npm

A: Try the following:
npm install -g npm
npm cache clean
npm install socket.io

Also check if you permission to create node_modules folder in the directory you run npm.
You can downgrade your nodejs to v.4.2.1 for example, don't forget to clean npm cache after that, and then run npm install command.

A: First try to remove these packages and then install. Like
npm remove socket.io

Then
npm install socket.io

may be the incomplete installed files are blocking it to install properly

A: You need to update your npm anyway.
Try from link install:
curl -L https://www.npmjs.com/install.sh | sh

Or you can compile it with make if you clone sources from github


text:
Q: Intro.js in an iframe I wanted it to work in an Iframe but if I define the js. in the parent document it does not recognize the elements that should be "introduced" inside the iframe. If I use it inside the iframe the effect is not what I expect (the overlay covers only the iframe).
[Intro.js being used inside an iframe.png] https://dl.dropboxusercontent.com/u/6421243/Intro.js%20being%20used%20inside%20an%20iframe.png
Is there something I can do with the plugin code so that it searches the elements inside an iframe but still shows the overlay over the parent?
UPDATE: I would like the black overlay over the WHOLE page (so the border of the iframe would also be covered by it).

A: Run intro.js in both iFrame and the parent.
In the parent, remove the toolTip and just highlight the iframe
In the iframe, run whatever toolTips you need
To communication between the two, have a look at this:  How to communicate between iframe and the parent site?

A: First of all you should know that if you define your JavaScript codes outside of iframe, it's no longer available in the inner iframe because you don't have access to them.
So, you should put your codes inside the iframe only.
Update:
So I think you put the container element wrongly so the IntroJs define the overlay wrong wrongly too. Update and change your element container and then you will don't have any problem with that.


text:
Q: How to use xpath to locate an acronym in parenthesis in a title element? For example (ANT) In this xml example:
<concept><title>Another Neat Tool(ANT)</title></concept>

The context is: /concept/title/
I want to return any concept title element that contains any open parenthesis, with any text, and a close parenthesis.  I want it to locate (ANT) or any other text inside ( ).
I was successful with /context/title/text(), "("
But it only located and highlighted (  not (ANT)
How can I modify the xpath 2.0 to locate any concept title element that contains an acronym presented within parenthesis.

A: Try this expression (you may need to adapt it to include your root node):
/concept/title[contains(text(),"(") AND contains(text(),")")]/substring-before(substring-after(text(),"("),")")

Online test code here.
From this:
<concept>
  <title>Automated Teller Machine (ATM)</title>
</concept>
<concept>
  <title>Central Standard Time (CST)</title>
</concept>
<concept>
  <title>OPEN AND CLOSE (ABC)</title>
</concept>
<concept>
  <title>CLOSE ONLY DEF)</title>
</concept>
<concept>
  <title>OPEN ONLY (GHI</title>
</concept>
<concept>
  <title>OPEN AND CLOSE (TEST)</title>
</concept>

It returns this:
ATM
CST
ABC
TEST

A: The XPath expression
/concept/title[matches(., '\([A-Z]{2,}\)')]

will return a sequence of all /concept/title elements that contain an acronym, defined as two or more capital letters in parentheses.
If you want to return the acronym letters themselves, you can use
/concept/title[matches(., '\([A-Z]{2,}\)')]/
   replace(., '^.*\(([A-Z]{2,})\).*$', '$1')


text:
Q: Class Not Found running Scala in IntelliJ SBT project Apologies as this is a newby question. I have the following SBT project containing a scala object. When I run 'Hi'  I get "Class not found" exception. Where to specify the class path?
click here to see the screen shot

A: You need to delete this object and create a new one. Right click on src->main->scala(NOT in target folder) folder new -> Scala class -> type "Hi" in name field in check box choose object.  And paste your:
def main(args: Array[String]) = println("hi")

A: This could be because main method doesn't have return type, try adding Unit so I must be like this:
def main(args:Array[String]):Unit = println("hi")

regards


text:
Q: Webpart to Create CSV file in Local Directory I am facing problem in creating CSV file through webpart in local directory. I have tried different methods to achieve this but in vain.
Anyone here ever before have created file?