Q:

Mule ESB 3 transformer cannot be converted to MessageProcessor

I'm trying to follow the transformer example in the documentation that converts a string input into a list of URLs, but it's throwing an error.
The example is here:  http://www.mulesoft.org/documentation/display/MULE3USER/Transformer+Annotation#TransformerAnnotation-WorkingwithCollections
My code for the transformer is copy-pasted from theirs.
When I first did it, I set the transformer by putting in my config xml:
<custom-transformer class="com.test.transformer.StringToListTransformer" doc:name="StringToUrlList"/>

Noting the requirement to 'register' the transformer, I later added in the beginning of the file (after the opening tag):
<spring:bean id="stringToListTransformer" class="com.test.transformer.StringToListTransformer"/>

However, when I run the app, I get the following error:
Exception in thread "main" org.mule.module.launcher.DeploymentInitException: IllegalStateException: Cannot convert value of type [com.test.transformer.StringToListTransformer] to required type [org.mule.api.processor.MessageProcessor] for property 'messageProcessors[3]': no matching editors or conversion strategy found

A:

You can't use a class annotated with @Transformer as a custom-transformer because it is not a real org.mule.api.processor.MessageProcessor. Only real message processors can be used directly in the XML configuration and invoked explicitly.
As the doc for @Transformer says:

There is no mechanism in Mule 3.x to actually invoke a transformer which is being constructed from an annotated method.

If you want to have your transformer kick-in in a flow, you'll need to use:
<auto-transformer returnClass="java.util.List.class"/>

assuming it returns a list and there are no other suitable registered transformers with a higher priority.
Otherwise, create a real transformer by extending org.mule.transformer.AbstractMessageTransformer and then use it with custom-transformer.


Q:

Why is it desirable to inject reactive power into a transmission system?

This website explains the basics of FACTS technologies and how they can be used to exchange active and reactive power with the transmission system, namely:

SSSCs - can exchange active and reactive power
STATCOM - can exchange reactive power only

But why is this desirable? Why do we want to add or remove reactive power onto the transmission system?

A:

The main reason for reactive power compensation is to regulate the voltage magnitude. Note that the compensation might be both positive and negative (reactive power in, or reactive power out). In a transmission system, there is a strong correlation between reactive power and voltage magnitude, whereas the active power is mainly dependent on the voltage angle. Have a look here for a bit more information.
In the transmission system, a branch might have impedance Z = R + jX, where the reactive X is about 10 times the purely resistive R.
I'm assuming you're familiar with the per unit system. Let me know if you're not and I'll explain it closer.
Let's just review a few basic relationships first:
\begin{align*}
S = V \cdot I^*\\
=> I = (S/ V)^*\\
\Delta V = I^2\cdot Z\\
Z = (R + jX)
\end{align*}
Let's assume we have a very simple power system that looks like this:
G ---|------------------|------------------|----->
     3   Z = R + jX     2   Z = R + jX     1   Load

G is the generator
The verticals lines are buses, labeled 1 - 3
The load is at the end of the radial.
The voltage at bus 1 is assumed to be 1pu with angle 0 degrees.
The load is (1 + j0.2) pu. (If S_base = 100MVA, this would be equal to 100MW + 20MVAr)
Z = 0.01 + j0.1

The current necessary to supply the load is given by:
\begin{align*}
I = (S/ V)^* =((1 + j0.2) / 1)^* = 1 - j0.2\\
\end{align*}
No compesation:
The voltage at bus 2 is give by the voltage at bus 1 plus the voltage rise over the cable (seen from 1 to 2):
\begin{align*}
V_2 = V_1 + I^2 \cdot Z = (1-j0.2)\cdot(0.01 + j0.1)
= 1.054\angle 5.01 ^{\circ}\;\text{pu}
\end{align*}
This means the power injection into the cable between 1 and 2 is:
\begin{align*}
S_2 = V_2 \cdot I^* = (1.031 + j0.302) \;\text{pu}
\end{align*}
The voltage at V3 is:
\begin{align*}
V_3 = V_2 + I^2 \cdot Z = 1.11\angle 9.50^{\circ}\;\text{pu}
\end{align*}
Now we can find the power output from the generator by using the first equation:
\begin{align*}
S_{Gen} = V_3 \cdot I^* = (1.062 + j0.404) \;\text{pu}
\end{align*}
With compensation:
Let us add a capacitor that injects 0.3pu reactive power at bus 2.
The voltage at bus 2 is still given by the voltage at bus 1 and the voltage rise over the cable, so it's still \$\underline{1.054 \angle5.01^{\circ}\;\text{pu}}\$.
Now, the reactive power injection of 0.3pu will give a current injection of:
\begin{align*}
I_{inj} = (Q / V_2)^* = 0.285 \angle{-85.0}^{\circ}\;\text{pu}
\end{align*}
The current through cable 1-2 is equal to the current through cable 2-3 plus the current injection, so:
\begin{align*}
I_3 = I_2 - I_{inj} = 0.979\angle 4.90^{\circ}\;\text{pu}
\end{align*}
You see that the current magnitude is lower than it was without compensation. So, let's have a look at the voltage at bus 3:
\begin{align*}
V_3 = V_2 + {I_3}^2 \cdot Z = 1.06\angle10.22^{\circ}\;\text{pu}
\end{align*}
Now we can find the power output from the generator by using the first equation:
\begin{align*}
S_{Gen} = V_3 \cdot I_3^* = (1.037 + j0.096)\;\text{pu}
\end{align*}
So, to summarize:
       W/O comp:   W comp:
|V1|   1.000       1.000
|V2|   1.054       1.054
|V3|   1.115       1.060

       W/O comp:         W comp:
Gen    1.062 + j0.404    1.033 + j0.096

As you can see from the above results, the voltage is much more stable with compensation. The current gets lower through the cable resulting in lower active losses.
The reason why the reactive power is needed in the first place is because it accounts for the magnetization of the equipment. If there's no reactive power, transformers, generator rotors/stators, machines etc. have no magnetic field. With no magnetic field, there is no torque, no magnetic coupling in the transformer etc. So, a lot of equipment have to consume reactive power in order to work. If there's too little reactive power available the equipment will try to draw more current to compensate. This will lead to higher voltage drops, which in the end might cause voltage collapse.
As Andy points out, it can also be used as power factor correction for large industrial loads. However when we're talking about reactive power compensation it's most often because of what I've described above.
In a meshed grid it can also be used to control power flow. This works because the active power flow through a cable is mainly given by the voltage angle difference over it. If you inject reactive power, the voltage and currents angles will change, thus it will affect the power flow. If you inject the right amount at the right place you can redistribute the power flow the way you want (but only to a small extent).
Hope this answers your question!


Q:

Elegant way to find repeated digits in Raku (née Perl 6)

I'm trying to find groups of repeated digits in a number, e.g. 12334555611 becomes (1 2 33 4 555 6 11).
This works:
$n.comb(/ 0+ | 1+ | 2+ | 3+ | 4+ | 5+ | 6+ | 7+ | 8+ | 9+ /)

but is not very elegant.
Is there a better way to do this?

A:

'12334555611'.comb(/\d+ % <same>/)

Please check the answer of the first task of Perl Weekly Challenge

A:

You may use
$n.comb(/(.) $0*/)

The (.) creates a capturing group and captures any char into Group 1, then there is a backreference to Group 1 that is $0 in Perl6 regex. The * quantifier matches zero or more occurrences of the same char as in Group 1.
Replace the . with \d to match any digit if you need to only match repeated digits.
See a Perl6 demo online.


Q:

Firebase Cloud Function Finished with status ''error''

I am writing my first cloud function to send a push notification when a new user signs up with my android app. I have done the basics like installing Node and firebase cli and got my project initialized.
I have written this test function below to log the user id of any user along with their token, who signs up and deployed to firebase.
 exports.sendSignUpNotification =functions.database.ref('/users/{userId}').onWrite((change, context) => {
const user_id = context.params.userId;
//const notifID = context.params.notification_id;
console.log("User id at signup:\t", user_id);
//console.log("Notification id at signup:\t", notifID);

let token = admin.database().ref(`/users/{userId}/id_token`).once('value');
console.log("User id token:\t", token);

 return new Promise().then(data => {
    const payLoad = {
    notification: {
       title: "Thank You For Signing Up",
       body: "Enjoy the best features by becoming a premium user"
     }
   };
   return admin.messaging().sendToDevice(token, payLoad);
 }).catch(errs => {
  console.error("Error Sending Payload", errs);
});

});

This is the edited code for the full function but somehow I know that I'm doing sth wrong while sending the payload. This is the error I am getting below:
TypeError: Promise resolver undefined is not a function
at exports.sendSignUpNotification.functions.database.ref.onWrite (/user_code/index.js:15:10)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:716:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

and to get the token on client side, I have called this method on signup:
mAuth.getCurrentUser().getIdToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
                            @Override
                            public void onComplete(@NonNull Task<GetTokenResult> task) {
                                if (task.isSuccessful()) {
                                    String idToken = task.getResult().getToken();
                                    Log.d(TAG, "idToken:\t" + idToken);

                                    HashMap<String, String> usersMap = new HashMap<>();
                                    usersMap.put("name", name);
                                    usersMap.put("userId", userId);
                                    usersMap.put("email", email);
                                    usersMap.put("id_token", idToken);
          }

I have saved this token and referenced it in my script for cloud function. Is this the right token or should I use the one from FirebaseInstanceIdService like below:
@Override
public void onTokenRefresh() {
    super.onTokenRefresh();

    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed Token:\t" + refreshedToken);

}

Thank you.

A:

You're using the old beta API with the new 1.x version of the SDK.  The way that database events work has changed.  The changes for the entire SDK are summarized here.  onWrite events now take two parameters, a change and a context.  The change contains the before and after snapshots, and the context contains the wildcard values.
To get the userId wildcard, you would now say:
exports.sendSignUpNotification = functions.database.ref(`/users/{userId}`).onWrite((change, context) => {
    const userId = context.params.userId

Please see the documentation for more current examples.
Also in your code this line has a bug:
let token = admin.database().ref(`/users/{userId}/notificationTokens`).once('value');

The JavaScript syntax for variable interpolation in a backtick delimited string requires a dollar sign:
`/users/${userId}/notificationTokens`

That line has yet another bug.  You're not making use of the promise returned by once() to actually get a hold of the value in the database.  token is going to contain that promise, not the contents of the database.
And you're also going to have to return a promise that resolves when all the async work is done in the function, which you're currently not doing.


Q:

Linear animation on HTML5 Canvas using KineticJS.How to make?

I am developing an HTML5 canvas based mini-game and I can't seem to organize linear animation.
I am using this code for adding a "target" object to the canvas:
var target = new Kinetic.Shape(function(){
    var context = this.getContext();
    context.drawImage(images.target, x, y, 2*radius, 2*radius);
    context.beginPath();
    context.rect(x, y, 2*radius, 2*radius);
    context.closePath();
});
gameLayer.add(target);

I need to animate this object with linear animation, trying this code:
var mx = x;
setInterval(function(){
   mx -= 1;
   target.setPosition(mx, y);
   gameLayer.draw();
}, 500);

But, it didn't work! What is wrong?

A:

I don't know why it doesn't work, but I found the way to do as:
var mx = x;
var my = target.y;
target.transitionTo({
   x: mx,
   y: my,
   rotation: 0,
   scale: {x: 1, y: 1},
   duration: 1, //time to transition in second
});

You can see more details at: http://www.html5canvastutorials.com/kineticjs/html5-canvas-linear-transition-tutorial-with-kineticjs/


Q:

After the subscription is added to disposable in RxAndroid (Observable), the control flow ends without calling subscribe..!

I am trying to use MVP, RX and Dagger 2 in android. The following is the code flow,
LocalDataSource.java
@Singleton
public class LocalDataSource implements DataSource {

@Override
public Observable getServerSettings() {
return mDBHelper.createQuery(ServerSettingsEntry.TABLE_NAME,
DbUtils.getSelectAllQuery(ServerSettingsEntry.TABLE_NAME))
.mapToOne(DbUtils::getServerSettings);

Repository.java
@Singleton
public class MyRepository implements DataSource {
@Override
    public Observable<ServerSettings> getServerSettings() {
        return mLocalDataSource.getServerSettings().compose(RxUtils.applySchedulers());

LoginPresenter.java
public class LoginPresenter implements LoginActivityContract.Presenter{
 @Override
    public void checkServerDbSynced() {
        mCompositeDisposable.clear();
        Disposable subscription = mRepository
                .getServerSettings()
                .doOnSubscribe(disposable -> {
                    Timber.d(" onSubscribe");
                    mView.showLoadingIndicator(true, "Checking Server ....");
                })
                .subscribe(serverSettings -> {
                            if (serverSettings == null) {
                                Timber.d("*** Server Db Synced ****" + "\n" + "*** Checking Licence Key **** ");
                                checkLicenceKey();
                                } else {
                                Timber.d("*** Server Db Not Synced *** " + " \n" + "*** Opening Login Dialog ****");
                                mView.showLoadingIndicator(false, "Db Not Synced ....");
                                mView.openLoginDialog();
                                }
                                },
                        throwable -> {
                            mView.showErrorMessage(throwable.getLocalizedMessage());
                            });
        mCompositeDisposable.add(subscription);
    }
}

    @Override
    public void subscribe() {
        checkServerDbSynced();
    }

    @Override
    public void unSubscribe() {
        mCompositeDisposable.clear();
    }

The problem is the statements inside subscribe is not being called. When debugging, I noticed that after this line composite disposable.add(subscription);  the control flow ended…Kindly help …!!
Edit
public static ServerSettings getServerSettings(@NonNull Cursor cursor) {
ServerSettings s = new ServerSettings();
        s.setAndroidId("1234564453453463dfg");
                s.setDeviceId("tythyerju99");
                s.setIpAddress("6373792092.48949");
                s.setLicenceKey("fhfhdid");
                s.setExpiryDate("hshsh8ehd8");
                s.setId(2);
        Timber.d(" *** " +s.getExpiryDate()+" ****");
        return s;
    }

A:

Your doOnSubscribe executes the content on the same thread where getServerSettings() is executed which belongs to Schedulers.io(). Hence, your mView.showLoadingIndicator(true, "Checking Server ....") is trying to update the UI off the main thread (which is not allowed) and so this error terminates your Observable execution - you may see it in your mView.showErrorMessage(throwable.getLocalizedMessage()) call but I don't know what exactly you're doing there.
What you should do is to send a message from your doOnSubscribe to the main thread as follows:
...
            .doOnSubscribe(disposable -> {
                Timber.d(" onSubscribe");
                new Handler(Looper.getMainLooper()).post(() -> {
                    mView.showLoadingIndicator(true, "Checking Server ....");
                });
            })
...

Update
As it turned out after the discussion, the problem lied in LocalDataSource and getServerSettings method. Specifically, in usage of mapToOne. When a result set was empty then there was nothing to emit and that's why subscribe consumer methods were not called. To make sure that it doesn't happen, use maptoOneOrDefault that emits a specified default value if the result set is empty.


Q:

Cannot convert lambda expression to type 'Delegate' because it is not a delegate type

I am having trouble with an anonymous delegate lambda in C#. I just converted the app to C#5 and the delegates went all haywire on me. Any help would be great. The specific error is:

Cannot convert lambda expression to type 'Delegate' because it is not
  a delegate type

public void UpdateUserList()
{
  if (!Monitor.TryEnter((object)this.LvPerson, 150))
      return;

  if (this.InvokeRequired)
  {
      this.Invoke((Delegate) (() => this.UpdateUserList()));
  }
  else
  { ... }
}

I have also tried
this.Invoke(() => {this.UpdateUserList();});

I'm not sure where the issue is as this was working before I moved the project from Visual Studio 2008 to Visual Studio 2015.
Thanks again for the help!

A:

The Invoke method expects a Delegate type instance, because you use a lambda expression it cannot automatically translate the expression into something like new Delegate() because Delegate has no public constructors. Using
this.Invoke(new Action(() => {this.UpdateUserList();}));

Should solve the problem as Action is a subclass of Delegate. To get rid of the redundant new Action(...) when using Invoke you can write a set of extension methods that take as argument an Action, this way the new Action(...) will be handled by the C# compiler so you won't have to write it every time making your code cleaner.
In case you are using Invoke for some asynchronous operations that may involve other threads look into Task Parallel Library (TPL) and Task-based Asynchronous Pattern (TAP), the latter has built in support into C# and Visual Basic.NET, using await will no longer require a call to Invoke() and allow you to run some operations on the background freeing your UI.


Q:

How do I play a local DVD copy in "DVD mode" using Xine and/or Mplayer?

I have a local copy of entire DVD's VIDEO_TS directory.
How can I use Xine or Mplayer to play it in a "DVD mode"?
That means for me:

that menus are recognized as such,
I can select language and other DVD-related options from DVD's menu,
rather than from command line
I can navigate through titles, rather than VOB files.

A:

Assuming your dvd folder is /path/to/movie/VIDEO_TS, try
xine dvd:///path/to/movie/

or
vlc dvd:///path/to/movie/

mplayer plays the movie, but I couldn't get it to play it in DVD mode. Apparently, the packaged builds of mplayer don't quite have menu navigation support yet.
mplayer dvd:// -dvd-device '/path/to/movie'

If your build of mplayer has dvd menu support, you should be able to invoke it using dvdnav:// instead of dvd://


Q:

Is it any methods in GWT to get screenshot of page region?

I am using GWT. I have a set of dragable widgets that can be placed on page as user wants. I need to get page region screenshot as a handler of some event and save it. Is any way to do this?
Is it possible to get Widget view as an image in GWT?

A:

You will have to create applet to get screenshots. You can embed the applet in your GWT application/


Q:

How would you remove elements of a std::vector based on some property of the elements?

If for instance you have a std::vector<MyClass>, where MyClass has a public method: bool isTiredOfLife(), how do you remove the elements that return true?

A:

I prefer remove_if
v.erase(remove_if(v.begin(), v.end(),
                 mem_fun_ref(&MyClass::isTiredOfLife)),
        v.end());

remove_if returns an iterator pointing after the last element that's still in the sequence. erase erases everything from its first to its last argument (both iterators).

A:

Using remove_if is the "right" way to do this. Be careful NOT to use an iterator to cycle through and erase, because removing items invalidates the iterator. In fact, any example which uses erase() as its primary method is a bad idea on vectors, because erase is O(n), which will make your algorithm O(n^2). This should be an O(n) algorithm.
The method I give below is likely to be faster than remove_if but, unlike remove_if, will NOT preserve the relative order of the elements. If you care about maintaining order (i.e. your vector is sorted), use remove_if, as in the answer above. If you don't care about order, and if the number of items to be deleted is typically less than a quarter of the vector, this method is likely to be faster:
for( size_t i = 0; i < vec.size(); )
   if( vec[i].isTiredOfLife() )
   {
      vec[i] = vec.back();
      vec.pop_back();
   }
   else
      ++i;


Q:

Limit of Function of Convergent Sequence

Let $a_n$ be a real valued sequence.  Assume that
$a_n\to0$ as $n\to\infty$.  Use this to prove that $(1+a_n/n)^n\to1$ as $n\to\infty$.
This proof would be simple if it wasn't for that pesky exponent.  I suspect that I"m supposed to use the Bernoulli inequality to solve this somehow, along with monotone convergence theorem.  But I'm just really struggling to make any progress with this.  Any advice?

A:

Let observe that the limit trivially holds for $a_n=0$, thus without loss of generality assume $a_n\neq 0$.
1. Proof by log
Note that
$$(1+a_n/n)^n=e^{n\log(1+a_n/n)}\sim e^{a_n}\to 1$$
indeed
$$\log(1+a_n/n)=\frac{a_n}{n}\frac{\log(1+a_n/n)}{a_n/n}\sim \frac{a_n}{n}$$
2. Proof by squeeze theorem
As an alternative note that by Bernoulli and by $\left(1+\frac{1}{n}\right)^{n}\le e$ we have that
$$1+a_n=1+n\frac{a_n}{n}\le \left(1+\frac{a_n}{n}\right)^n\le \left(1+\frac{|a_n|}{n}\right)^n=\left[\left(1+\frac{|a_n|}{n}\right)^{\frac{n}{|a_n|}}\right]^{|a_n|}\le e^{|a_n|}$$
thus by squeeze theorem
$$\left(1+\frac{a_n}{n}\right)^n\to 1$$


Q:

Java Sending Email to Different Time Zones At the Same Time Each Day

Turns out this seems to be a complex subject, please tell me if my approach is too simple.
Basically what i'm trying to do is send an email reminder to a list of users (only when they have a reminder coming up, but that is besides the point) at 7 am every morning. Of course 7 am is at a different time based on the server location for everyone all over the world.
The plan is to collect to GMT offset hour via javascript from the user when they register:
var today = new Date();
var offset = -(today.getTimezoneOffset()/60);

Simple enough, I now know the offset hour and store that in a database along with the rest of the users data. Now server side I have a TimerTask set up that runs every hour. I collect the system hour (say its 5 am), see how far away from my target time that is (in this case 2 (7-5)), get the system offset hour (in this case its -5), then pull all users from the database that have a GMT offset hour of -3 (-5 + 2), then do the email sending etc. At this point im assuming I know its 7 am for everyone whos time zone offset is -3 and I can continue with the process. This will run again the next hour and collect all users with a time zone offset of -4. Is this something that will actually work, or am I missing something?
Calendar systemTime = Calendar.getInstance();
int targetHour = 7;
int currentHour = systemTime.get(Calendar.HOUR_OF_DAY); //Its 5 am.
int difference = targetHour - currentHour; //2
int zoneOffset = systemTime.get(Calendar.ZONE_OFFSET) / (1000*60*60); //-5
int targetZone = zoneOffset + difference; //-3

List<User> users = userDAO.findByZoneOffset(targetZone);
for(User user : users) {
    //Send email or whatever I want to do with these users.
}

I understand its possible that the client time zone may be set incorrectly and therefore product an off result, but im willing to take that risk as its not absolutely necessary for the reminders to go out at exactly 7 am, just preferable.

A:

The plan is to collect to GMT offset hour via javascript from the user when they register

That won't be enough to get a time zone consistently. It doesn't take account of daylight saving time. So if the user is anywhere that observes daylight saving time, they'll either get emails at 6am for about half the year, or they'll get emails at 8am for about half the year. You may well be better off guessing their time zone based on IP geolocation + offset.

I have a TimerTask set up that runs every hour.

I would suggest running more often than that. Otherwise, you may well find that you end up waking up just before you would send an email - so you then go back to sleep, and send the email at 7:59 next time... which may be 8:59 with your current scheme, based on client DST changes. At that point you're nearly two hours off your intended send time!

I collect the system hour

Don't do that, either. At this point there are two time zones to take account of - and your server time zone is completely irrelevant. Use UTC until you convert into the client's local time. It's going to make life much simpler. If you're still using Calendar, you can do this simply by setting its time zone.
Looking at your code, it looks like you also could end up missing a bunch of users completely, if you're checking by exact match of hour. If you end up running once at (say) 3:59 and then once at 4:01, you'd miss anyone who had to be run at 4. I would suggest keeping track of when you last sent a mail to each user - or possibly when you last ran - and use that to make sure you always catch everyone.
Finally, I'd strongly advise that you use Joda Time. It's a much cleaner date/time API, which will help you to think about the right concepts to use at the right point in your code.


Q:

Foreign key join using hibernate

Hi all i've got some errors using join with hibernate
I use postgresql 9.5.
My db tables: cart (cart_id - primary key, cart.product_id references product.product_id - foreign key) and product (product_id - primary key)
Java classes Cart and Product
@Entity
@Table(name = "product")
public class Product{
    @Id
    @Column(name = "product_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int productId;

    @Column(name = "article")
    private String article;

    @Column(name = "name")
    private String name;

    @Column(name = "price")
    private BigDecimal price;

    @Column(name = "description")
    private String description;

    @Column(name = "manufacturer")
    private String manufacturer;

    @Column(name = "category")
    private String category;

    @Column(name = "unitsinstock")
    private long unitsInStock;

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    private Cart cart;

and
    @Entity
    @Table(name = "cart")
    public class Cart {
    @Id
    @Column(name = "cart_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int cartId;

    @Column(name = "user_id")
    private int userId;

    @Column(name = "product_id")
    private int productId;

    @Column(name = "quantity")
    private int quantity;

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "cart", cascade = CascadeType.ALL)
    private Product product;

How should i annotate my classes in order to have query SELECT * FROM cart AS c INNER JOIN product p ON c.product_id = p.product_id?
I tried annotane @PrimaryKeyJoinColumn and @JoinColumn with names/referencedColumnName, but got errors or
hibernate made query (mostly) like SELECT * FROM cart AS c INNER JOIN product p ON c.cart_id = p.product_id So it "connects cart_id and product_id, when I need product_id and product_id in cart and product tables.
Upd. It worked fine before, but after dumping/restoring db this errors appeared.
My HQL query is SELECT c FROM Cart c JOIN c.product

A:

Firstly, lazy fetch won't work on @OneToOne. Watch this

You have foreign key on Cart table, so you should map it like this:
Cart entity:
@OneToOne(cascade = CascadeType.All)
@JoinColumn(name = "product_id")
    private Product product;

And for Product entity:
@OneToOne(mappedBy = "product")
    private Cart cart;

Vote it as an answer if i helped you)


Q:

Android Releasing to Google Play Multiple Packages

I am about to release my app to Google Play. My project has multiple packages for organizational purposes. Will this cause a problem? Should I move all my .java files into one package?

A:

You can have as many packages as you want in your project, the only one that matters to the android market is the one that you declare in the manifest file package="com.mypackage.miproyect" because that one will be marked as the application id, so it should be unique.


Q:

Were any non-CGI movies shot in their entirety though a colored lens/filter?

This is a 2-part question:

Is it technically possible to shoot a movie though a colored lens/filter? (as opposed to changing the image color AFTER the movie is shot, via CGI or earlier effects)
If possible, was there ever any mainstream (e.g. not an indie) movie shot in its entirety 100% through a color lens or filter?

A:

It is possible. According to this article, Alexander Sokurov's Faust (2011) was filmed entirely through a "color filter that lends it a faded tone, tending towards blues and greys and very, very stark whites." The film won the Golden Lion Award at the Venice Film Festival. The film may have been changed further through CGI, but this example answers the first part of your question.
http://zapadnik.wordpress.com/2012/02/11/alexander-sokurovs-faust/
I have seen some references to the move Safe House being shot with colored filters, but I have not been able to confirm with an authoritative source.


Q:

Recommend me a quick setup local http/php/mysql server for development (WIndows)

I need a quick and dirty http server to use for local application development, that supports php and mysql. Xampp will not work for me (64 bit Win 7), so Im looking for something similar.

A:

I've had good experience with The Uniform Server -- it's portable*, and it includes Apache, PHP, MySQL, and Perl in the box.  Their installation manual also says testing has been successful on 64-bit WinXP Pro.
* It's portable in the put it on your USB-stick and use it on any Windows computer sense.  They also claim to not touch the Windows registry at all.


Q:

Python, simple error handling pattern

I'm quite new to Python.
I was wondering how to achieve simple error handling without using exceptions, what sometimes (I think) is overkill.
I came up with a pattern, but I'm not sure if it is the pythonic way:
def someFunct(someArgs):
    # do stuff...
    if error:
        return False, 'error message'
    return True,None

and the caller would do something like this
success,errMsg = someFunct(myAwesomeArgs)
if success:
    # yey!
else:
    # handle error

A:

Just use exceptions - it's the standard python way: http://docs.python.org/tutorial/errors.html

A:

Using exceptions in python is not an overkill what so ever. Exceptions in python are used in several places to control the flow of your application, for example, lets imaging you have the following method using your pattern:
def some_function(*args):
    """Do stuff using a loop."""

    for i in [1, 2, 3, 4]:
        print i

    return True, None

In there, there is already an exception which is the StopIteration exception, that is, even when you tried to avoid the use of exception it is internally used. So my answer is, use exceptions, this is not Java, C# etc.. where exceptions are utterly expensive compared with the rest of the code and you are just making you code unpythonic.


Q:

Is there a countable computably saturated model of ZFC that correctly solves the halting problem?

We say that a model of ZFC $M$ correctly solves that halting problem if for every turing machine $T$, $T\text{ halts} \iff M \models T \text { halts}$.
Is there a countable computably saturated model of ZFC which correctly solves the halting problem? (See pg 3 of https://arxiv.org/pdf/1104.4450.pdf for what computably saturated means.)

A:

Sure. Any (consistent) theory (in a computable language) has computably saturated models, so just take $T$ to be (say) the theory ZFC + all true $\Pi_{17}$ statements of arithmetic. $T$ correctly decides (among other things!) whether the $e$th Turing machine halts, for each standard $e$, so any model of $T$ correctly solves the halting problem; now simply take an arbitrary computably saturated model of $T$.

Why do all appropriate theories have computably saturated models? Well, the point is that we only have to realize countably many types. Start with an arbitrary countable model $M$ of the theory, and list the computable types; at stage $s$, pass from the current model to a countable elementary extension realizing the $s$th computable type of that type is finitely consistent with the current model, and otherwise don't change the model - the union of this elementary chain will be a saturated model of the theory.


Q:

Do I earn enough skill points to unlock everything?

Possible Duplicate:
How many skill points will I have at max level?

I'd like to know if I should expect enough skill points to unlock most of the skills, or if I;m only going to get enough to specialise to the end of a few skill paths.
So, how many skill points are available in total at max level?
And, how many would I need to unlock everything available to Commander Shepard?

A:

As Johnjon notes, there are 181 skillpoints in the game.
Maxing a single skill requires 21 points.
There are enough points in the game to max out a total of 8 skills, with a few left over.
Shepard, conveniently enough, has 8 skills, plus one slot for a Bonus Power.
So, you can come very close, but you can't quite make it to maxing out all 9. You can max out 8 of them, and have 13 points remaining for the 9th, which lets you get to rank 4. You'll have 2 points left over. Alternately, you could max out 7 skills, get two to rank 5, and have 3 points left over.


Q:

What is a brief history on the idea that the Papacy is the Anti-Christ?

I am quite familiar with the Reformers opposition to the Papacy and many said the Papacy is the Anti-Christ. What confuses me is this quote from that same page:

In calling the pope the "antichrist," the early Lutherans stood in a tradition that reached back into the eleventh century. Not only dissidents and heretics but even saints had called the bishop of Rome the "antichrist" when they wished to castigate his abuse of power.

I was under the impression that the idea originated with the Reformers, however, it clearly did not. I would like a brief history of this idea up until the Reformers.

A:

This answer draws extensively from Angel Pope and Papal Antichrist, Bernard McGinn, Church History 47(2):155-173, 1978. McGinn is a Catholic and an expert on medieval mysticism.
The identification of the Pope with the Antichrist of Revelation comes essentially from Joachim of Fiore, a twelfth-century mystic who was particularly interested in the pattern of history. His theology was condemned in a synod of 1260, though it was very influential - firstly, among groups in the Church who were devoted to lives of poverty, especially the Franciscans, and secondly among various schismatic the-end-of-the-world-is-nigh sects.
For Joachim and followers, contemporary power struggles over the nature of the papacy, and questions over legitimacy during periods where there were antipopes, foreshadowed a future apocalyptic showdown between a pastor angelicus, novus dux, or orthopontifex (the good guy) and an Antichrist or pseudopontifex (the bad guy).  This was a divergence from previous Antichrist theories, which tended to think he would be a (Holy) Roman Emperor.1 Joachim himself may or may not have thought that the Antichrist would be a "proper" elected pope, as opposed to someone setting himself up in mockery of the true church. He did think that the result of the conflict would be the beginning of a new era, where all people would live a simple, monastic, contemplative life, and where there would no longer be a church or pope. 2
The next generation of Joachimites certainly did believe in the pseudopontifex. From them come the Dulcinians and other millenarian sects. By the way, if you've read Umberto Eco's The Name of the Rose, then you've met some of these people! Part of the problem for the Franciscans in that book is that everyone assumes they're Dulcinian. Both groups were influenced by Joachim, but people like William of Ockham stayed within the Church, while trying to promote poverty and simplicity in life, and did not want to get rid of the papacy. Even Ubertino of Casale, who called Boniface VIII and Benedict XI a pair of antichrists, didn't want anything more than to have a better pope take over.3
There is an influence on the Lollards, whose founder John Wycliffe (1330-1384) had similar views of the papacy. And from these "proto-Reformers" it is a hop, skip and jump to the actual Reformation, similarly animated by concern about the church being wealthy and corrupt. The big difference, roughly from Wycliffe onwards, was that now the institution of the papacy itself was seen as Antichrist - unlike the classical Joachimite view of a good and a bad pope fighting it out. For the Protestants there could not be a good pope! All popes, for them, were like mini-antichrists preparing the way for the final Antichrist of Revelation (the antichristus magnus). In a previous answer of mine you can find some references to Luther, Calvin, etc., discussing this idea.
Now, there have been other people, even before Joachim of Fiore, who used the word "antichrist" in relation to some pope. But these occurences are fairly sporadic and not influential. McGinn cites Arnulf (an archbishop of Reims), speaking at the synod where he was deposed in 991, calling John XV "Antichrist seated in the temple of God and showing himself as if he were God".4 Any stuff like this is just name-calling, and in any case is invariably about some specific individual pope, not the institution of the papacy or the hypothesized pseudopontifex.
In summary, the Pope-Antichrist link is in its purest form a creature of the Reformation, where the very institution of the papacy was held to be intrinsically evil. This built upon an earlier trend of criticizing the church for some combination of wealth, lack of zeal, or political disagreement: and where people looked forward to either a better pope, or the coming of a messianic golden age where the whole question was moot. The people associated with this view were necessarily "dissidents", and sometimes "heretics". I have not found any of them who are accounted "saints", and frankly I think it rather unlikely (unless we mean "saints" in a much more general sense).
1. See eg Hugh of Newcastle, De victoria Christi contra Antichristi (1319), or the Ludus de Antichristo, a mid-12th century play about an imperial Antichrist.
2. Antichrists and Antichrist in Joachim of Fiore, Robert E. Lerner, Speculum 60:3, 1985.
3. Arbor vitae crucifixae Jesu, Ubertino of Casale (1305) at 5.8 and 5.11 (f. 230rb-233ra, 237vb in the Venice 1485 printing).
4. Acta concilii Remensis ad Sanctum Basolum, Gerbert of Aurillac (aka, later, Pope Sylvester II), in Monumenta Germaniae Historica, Scriptores 3, 672.

A:

The roots of the doctrine in its primative form actually reaches back to the views of very early church fathers. I add this history to show the period prior to people like Joachim described in the other post. The idea stems from a very early belief by church fathers that the antichrist would be a new form of government in the Roman Empire. A powerful papacy was not existent at the time so the connection was impossible to foresee but all the seeds of the belief were sewn by them, later appropriated by those witnessing papal abuses that fit the church father expectation.
The principal idea of the church fathers is rooted in the connection of the anti-Christ with the little horn that ‘has eyes’ and ‘speaks blasphemous things’ in Daniel Chapter 7. This expected soon-to-come antichrist from some sort of mysterious sinister change within the Roman Empire (this evil horn) was considered by the Fathers to include a dreadful 'apostasy of believers' which would start a terrible history of persecution against true believers who opposed the risen new Roman power. Therefore, the prayers of the fathers was that Rome would be kept safe from any such political changes. The hope was that the dreaded horn of antichrist and massive church apostasy would be kept at bay as long as possible as it was greatly feared.
One author has already collected this history of the church fathers on this subject providing to us a convenient collection of these origins to the view adopted by nearly all early protestant reformers:
All quotes from Horae Apocalypticae; or, A commentary on the Apocalypse, critical and historical; including also an examination of the chief prophecies of Daniel (1846). page 365
Cyril, ordained Bishop of Jerusalem A.D. 350 had this view.

He, like the fathers before him, explained the four wild Beasts of Dan. 7. to be the Babylonian, Persian, Macedonian, and Roman empires, and identified the fourth Beast’s little horn with St. Paul’s Man of Sin and St. John’s Antichrist. Further he judged that the time of his coming was to be when the times of the then Roman empire were fulfilled, (ὁταν πληρωθωσιν οἱ καιροι της των Ῥωμαιων βασιλειας,) and it was dissolved into ten kingdoms, kingdoms rising up contemporaneously, but in different places:—that then Antichrist, (“some great man raised up by the devil,”) falsely calling himself the Christ, and so seducing the Jews, would by magical arts and false miracles seize on, and usurp, the power of the Roman empire, eradicate three of the ten kings, and subjugate the other seven:—that at first mild in semblance, and prudent, and the abolisher of idols, (all with a view to self-exaltation,) he would afterwards show himself as God, sitting in the Jewish temple; (“for God forbid it should be that in which we are;”) and for three years and a half persecute the Church:—finally that the apostasy, of which St. Paul spoke as Antichrist’s precursor, meant a religious apostasy, “from the right faith, from truth, and from right words.” (So Catech. Lect. xv.)

Ambrose, ordained Bishop of Milan A.D. 374 contributed this view:

The only prophetical notices on the point proposed in the genuine writings of this father, are those in his Comment on Luke 21:20; Book x. § 15–18. He there (like Cyril) explains the apostasy of St. Paul to mean an apostasy from true religion: (“à verâ religione plerique lapsi errore deseiscent:”)—that it would be the Jewish inner or mental temple in which Antichrist would sit: and that then, seizing on the kingdom, (I presume the Roman kingdom or supremacy,) he would claim for himself a throne of divine authority; “sibi divinæ vindicet solium potestatis.”
In the Comment on 2 Thess. 2. of the Pseudo-Ambrose, the hindrance to Antichrist’s manifestation is explained to be the Roman empire; its defection (αποστασια), or abolition, being the occasion of his appearance; and that he would then restore freedom to the Romans, “sub suo nomine:”—that the mystery of iniquity spoken of by St. Paul was Nero’s persecuting spirit against Christians, which still afterwards had continued to actuate succeeding Pagan emperors down to Diocletian and Julian; finally that he would, “in domo Domini, in sede sedeat Christi, et ipsum Deum se asserat.”

Chrysostom, ordained Presbyter A.D. 386 expresses the same gist:

He too (on Daniel) expounded Nebuchadnezzar’s quadripartite Image, and Daniel’s four Beasts, as the other fathers. “The days of those kings,” said of the time of the stone being cut out, he explains as the days of the Romans: and that, in smiting and destroying the Roman kingdom, it would destroy the others too, as included.—Also in his” Hom. iv. on 2 Thess. 2 he made the Roman empire to be the let or hindrance to Antichrist’s manifestation meant by St. Paul: τουτʼ εστιν ἡ αρχη ἡ Ῥωμαικη· ὁταν αρθῃ εκ μεσου τοτε εκεινος ηξει· and again: ὁταν αὑτη καταλυθῃ επιθησεται (ὁ Αντιχριστος) τῃ αναρχιᾳ, και την των ανθρωπων και την του Θεου επιχειρησει ἁρπασαι αρχην· and he explained the temple in which Antichrist would sit to be rather “the Christian Churches everywhere,” than the Jewish temple.—The mystery of iniquity he thought might be Nero, as in spirit a type of Antichrist: Νερωνα ὡσανει τυπον οντα του Αντιχριστου· και γαρ οὑτος εβουλετο νομιζεσθαι Θεος· and that Antichrist was to be αντιθεος τις; overthrowing indeed the worship of idols and other gods, but only so as to enforce the worship of himself in the place of them and of God.—The apostasy Chrysostom identifies pretty much with Antichrist himself; ὡς πολλους μελλοντα απολλυναι και αφιστᾶν. He adds that, as Rome succeeded Greece, so Rome would be succeeded by Antichrist, and Antichrist by Christ.

Jerome, ordained Presbyter A.D. 378, has again the same:

On Dan. 2. he expounds the gold, silver, brass, and iron of the symbolic Image to be the same four kingdoms as the other fathers: the stone cut out of the mountain without hands being Christ born of a virgin; whose kingdom, upon the destruction of all the other kingdoms, was finally to fill the whole earth. The breaking of the iron legs into ten toes,—part iron, part clay,—he explained of the weakness of the Roman empire at the time he wrote,—about A.D. 407....—On Dan. 7. he explains the four Beasts of the same four empires; the four heads of the third or Macedonian Beast indicating its subdivisions, on Alexander’s death, into the kingdoms of Ptolemy, Seleucus, Philip, Antigonus. On the divisions of the fourth, or Roman...—adding that this eleventh king is to be a man, with Satan’s spirit indwelling, the same as St. Paul’s man of sin: also that the Roman empire is to be finally destroyed on account of this Antichrist’s blasphemies, and with it all earthly kingdoms

Augustine notices and agrees in Jerome’s view of Daniel’s, four Beasts

As to the identity of the fourth Beast’s little horn with St. Paul’s man of sin and St. John’s Antichrist.’ He explains the apostasy in 2 Thess. 2 of a religious apostasy; indeed, (expounding the abstract of the concrete,) as the apostate Antichrist himself; “Nisi venerit refuga primùm, utique a Domino Deo:”—also as to the temple he would sit in, that it seemed to him dubious whether it might mean. Solomon’s ruined temple, or the Christian Church: that at any rate it could not be an idol’s or dæmon’s temple; because that would not be called God’s temple:—further that the let, or hindrance, in Antichrist’s way might not absurdly be taken to mean the Roman empire.

So we see that the church fathers while experiencing persecutions in Rome observed these prophecies with serious expectation that some new Roman power would rise within the churches themselves, claiming to be in some sense equal to Christ in authority over all the churches, ushering in a widespread apostasy and persecution if true believers.  It is from this ancient belief that later generations came to consider that the papacy in its previous military and religious power was that 'horn' with religious oversight represented as 'eyes' and speaking 'blasphemous things' such as the Pope's claim as being Christ's vice-regent on earth and insinuating fake authority over all believers.
It is rare a major biblical doctrine is to be entirely absent in the first few hundred years of Christianity and it should be of no surprise that this also has it roots there.

A:

A brief history on the idea that the Papacy is the AntiChrist.

What follows below is taken from Antichrist | new Advent.
The article says that when the Antichrist is understood as an individual person, a signal enemy of Christ, it excludes the contention of those who explain Antichrist as the papacy.
The article then goes on to say that

The Waldensian and Albigensian heretics, as well as Wyclif and Hus,
  called the Pope by the name of Antichrist; but the expression was only
  a metaphor in their case. It was only after the time of the
  Reformation that the name was applied to the Pope in its proper sense.
  It then passed practically into the creed of the Lutherans, and has
  been seriously defended by them as late as 1861 in the "Zeitschrift
  für lutherische Theologie".

Who are the Waldensians?

The Waldensians (also known variously as Waldenses are a Christian
  movement and religious cultural group which started in Lyon and spread
  soon to the Cottian Alps in the late 1170s. - Source: Waldensians |
  Wikipedia.

And who were the Albigenses?

A neo-Manichæan sect that flourished in southern France in the twelfth
  and thirteenth centuries. The name Albigenses, given them by the
  Council of Tours (1163) prevailed towards the end of the twelfth
  century and was for a long time applied to all the heretics of the
  south of France. They were also called Catharists (katharos, pure),
  though in reality they were only a branch of the Catharistic movement.
  The rise and spread of the new doctrine in southern France was
  favoured by various circumstances, among which may be mentioned: the
  fascination exercised by the readily-grasped dualistic principle; the
  remnant of Jewish and Mohammedan doctrinal elements; the wealth,
  leisure, and imaginative mind of the inhabitants of Languedoc; their
  contempt for the Catholic clergy, caused by the ignorance and the
  worldly, too frequently scandalous, lives of the latter; the
  protection of an overwhelming majority of the nobility, and the
  intimate local blending of national aspirations and religious
  sentiment. - Source: Albigenses | New Advent.

I have not found exactly when The Waldensian and Albigensian heretics called the Pope by the name of Antichrist.
According to the article, during some time in their life, John Wycliffe, an Englishman (c. 1330-1384) and  Jan Hus (c. 1370-1415 and born  in Bohemia), called the Pope by the name of Antichrist.

Within the Catholic Church, the way I understand it, the future wicked Pope is more identified with the false prophet than with the Antichrist.
Below are a couple of prophecies regarding the papacy:

I saw a great power rise up against the Church. It plundered, devastated, and threw into confusion and disorder the vine of the Lord, having it trampled underfoot by the people and holding it up to ridicule by all nations. Having vilified celibacy and oppressed the priesthood, it had the effrontery to confiscate the Church's property and to arrogate to itself the powers of the Holy Father, whose person and whose laws it held in contempt. - Jeanne le Royer (Sister of the Nativity,  b. 1731 and became a nun in 1755).
[...] an arrogant Pope will divide the Church. His orders will be obeyed and what is precious will be thrown out. A great spiritual confusion is on the way… the one who could have been Peter will become Judas. He will open the doors for the enemy and will make men and women of faith suffer… The church will be without Peter… a war will explode on Rome and there will be few survivors. - Pedro Regis.


Q:

How to improve working memory in adults?

Think Better on Your Feet: How to Improve Your Working Memory
in: A Man's Life, Money & Career
Brett and Kate McKay • September 20, 2016, Last updated: October 17, 2018
https://www.artofmanliness.com/articles/think-better-feet-improve-working-memory/
Training Working Memory: Why and how
Make your working memory work for you.
William R. Klemm Ph.D.
https://www.psychologytoday.com/us/blog/memory-medic/201203/training-working-memory-why-and-how
Klemm makes the claim IQ is not fixed. He claims IQ improves dramatically in the early school years in all children. Moreover, a recent study shows that both verbal and non-verbal IQ can change (for better or worse) in teenagers. The recent study is cited in the above psychology today web link.
Is it a fact or a neuromyth to claim IQ is not fixed for adults? Processing speeds slow down as we get older, and working memory steadily deteriorates/declines as we get older, too. Are we doomed to get slower and have poorer working memories as we get much older (50, 60s, 70s, 80s)?
Or can we maintain our intelligence, working memory, and processing speeds for a longer period of time if we do physical exercise, keep physically fit, and live healthy lives?

A:

IQ is not the same as working memory (either visual or non-visual). IQ is deprecated in favor of the term general intelligence (g).
Education improves g, but not by much; only about one point per year of education (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4445388/), where about 15 points are a standard deviation.
Many things affect general intelligence negatively, such as lead exposure or inadequate nutrition. However, once basic good conditions are experienced, cognitive decline is not avoidable. The good news is that while g decreases in older adults, semantic memory (knowledge) can continue increasing, such that real-world performance on many tasks need not suffer.
Beware a huge range of companies and hucksters promoting activities to slow cognitive decline: to my knowledge, none of them have much validation nor a consensus of scientists without conflicts of interest (e.g., financial).


Q:

Should I prefer to call template metafunctions through a nested typedef or inheritance?

I could write a recursive Contains metafunction either calling itself by inheritance or by a nested typedef. What is the difference (if any) with regard to the following criteria?
A: compile time and memory needed during compile time.
B: maximum recursion limit (will one allow me to work with a larger number of arguments than the other?)
C: lazy instantiation (will one allow me to elide more instantiations? This may not make a difference in the current example. Would it however if a class had nested typedef of std::conditional vs being derived from it?)
1:
template<typename T, typename... Ts>
struct Contains : std::false_type {};       //only possible if Ts is empty so does not contain
template<typename T, typename U, typename... Ts>
struct Contains<T, U, Ts...> : Contains<T, Ts...>{};
template<typename T, typename... Ts>
struct Contains<T, T, Ts...> : std::true_type{};

2:
template<typename T, typename... Ts>
struct Contains {
    typedef std::false_type Type;
};      //only possible if Ts is empty so does not contain
template<typename T, typename U, typename... Ts>
struct Contains<T, U, Ts...> {
    typedef typename Contains<T, Ts...>::Type Type;
};
template<typename T, typename... Ts>
struct Contains<T, T, Ts...>{
    typedef std::true_type Type;
};

A:

I would use inheritance, the reason being that it naturally allows for tag dispatch:
template <typename T>
void f_impl(T const & t, std::true_type derivedB) { ... }
...
template <typename T>
void f(T const & t) {
   f_impl(t, is_base_of<B,T>());
}

At the same time inheritance can be used to insert the nested information, in this case, a ::value static member that evaluates to true.


Q:

Extraneous letter "t" in output of my Zend Framework application - how best to find it?

The error I'm trying to get rid of is there is an additional letter "t" outputted before the rest of the HTML in one of my Zend Framework applications. The "t" is there only in a single action so I'm certain the problem is somewhere there.
For illustration HTML markup of the buggy controller action starts like this:
t<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

It's driving me crazy because I cannot find where this letter is being printed. Here is the entire action:
public function transactionsHistoryAction()
{
    $request = $this->getRequest();
    $transactions = $this->_getTable('Transactions');

    $finishedTransactions = $transactions->getSelect();
    $pendingWithdrawals = $transactions->getPendingWithDrawalsSelect();

    $paginator = Zend_Paginator::factory($finishedTransactions);
    $paginator->setCurrentPageNumber($request->getParam('p'));
    $paginator->setItemCountPerPage(20);

    $paginator2 = Zend_Paginator::factory($pendingWithdrawals);
    $paginator2->setCurrentPageNumber($request->getParam('p2'));
    $paginator2->setItemCountPerPage(20);

    $this->view->headTitle('Transactions - Administration panel - Website Name');
    $this->view->finishedTransactions = $paginator;
    $this->view->pendingWithdrawals = $paginator2;
}

And here is the only model I use in that action:
<?php
/**
 * transactions table
 *
 * @author Richard Knop
 */
class Transactions extends Zend_Db_Table_Abstract
{
    protected $_name = 'transactions';

    protected $_referenceMap = array(
        'User' => array(
            'columns' => array('user_id'),
            'refTableClass' => 'Users',
            'refColumns' => array('id')
        )
    );

    private function _getDb()
    {
        return Zend_Registry::get('dbAdapter');
    }

    public function getSelect()
    {
        $select = $this->select();
        $where = 'finished = 1';
        $select->where($where);
        $select->order('id DESC');
        return $select;
    }

    public function getPendingWithdrawalsSelect()
    {
        $select = $this->select();
        $where = "type = 'withdrawal' AND finished = 0";
        $select->where($where);
        $select->order('id DESC');
        return $select;
    }
}

Please help me :o
EDIT:
The layout is correct (the "t" is there only in this specific action, all other actions of the same controller output correct HTML without the "t").

A:

As TypeONeError said it is a typo in one of your php files.
A quick way to find this is to do a recursive file search (find in files in your editor).
Look for
"t<?" or "?>t"


Q:

sortedArrayUsingComparator returning incorrect results

I have an array which has a set of timestamps (as strings) and they are in sorted order. I just want to sort them again and see if the same list is returned (reason is I'll be dealing with further timestamps stored out of order and will need to sort them). Here is my dates array where timestamps are basically strings:
(
"Jun 18, 2014 12:00:00 AM",
"Jun 18, 2014 12:15:00 AM",
"Jun 18, 2014 12:30:00 AM",
"Jun 18, 2014 12:45:00 AM",
"Jun 18, 2014 1:00:00 AM",
"Jun 18, 2014 1:15:00 AM",
"Jun 18, 2014 1:30:00 AM",
"Jun 18, 2014 1:45:00 AM",
"Jun 18, 2014 2:00:00 AM",
"Jun 18, 2014 2:15:00 AM",
"Jun 18, 2014 2:30:00 AM",
"Jun 18, 2014 2:45:00 AM",
"Jun 18, 2014 3:00:00 AM",
"Jun 18, 2014 3:15:00 AM",
"Jun 18, 2014 3:30:00 AM",
"Jun 18, 2014 4:15:00 AM",
"Jun 18, 2014 4:30:00 AM",
"Jun 18, 2014 4:45:00 AM",
"Jun 18, 2014 5:15:00 AM",
"Jun 18, 2014 5:30:00 AM",
"Jun 18, 2014 5:45:00 AM",
"Jun 18, 2014 6:00:00 AM",
"Jun 18, 2014 6:15:00 AM",
"Jun 18, 2014 6:30:00 AM",
"Jun 18, 2014 6:45:00 AM",
"Jun 18, 2014 7:00:00 AM",
"Jun 18, 2014 7:15:00 AM",
"Jun 18, 2014 7:30:00 AM",
"Jun 18, 2014 7:45:00 AM",
"Jun 18, 2014 8:00:00 AM",
"Jun 18, 2014 8:15:00 AM",
"Jun 18, 2014 8:30:00 AM",
"Jun 18, 2014 8:45:00 AM",
"Jun 18, 2014 9:00:00 AM",
"Jun 18, 2014 9:15:00 AM",
"Jun 18, 2014 10:00:00 AM",
"Jun 18, 2014 10:15:00 AM",
"Jun 18, 2014 10:30:00 AM",
"Jun 18, 2014 10:45:00 AM",
"Jun 18, 2014 11:15:00 AM",
"Jun 18, 2014 11:30:00 AM",
"Jun 18, 2014 11:45:00 AM",
"Jun 18, 2014 12:00:00 PM",
"Jun 18, 2014 12:15:00 PM",
"Jun 18, 2014 12:30:00 PM",
"Jun 18, 2014 12:45:00 PM",
"Jun 18, 2014 1:00:00 PM",
"Jun 18, 2014 1:15:00 PM",
"Jun 18, 2014 1:30:00 PM",
"Jun 18, 2014 2:00:00 PM",
"Jun 18, 2014 2:15:00 PM",
"Jun 18, 2014 2:30:00 PM",
"Jun 18, 2014 2:45:00 PM",
"Jun 18, 2014 3:00:00 PM",
"Jun 18, 2014 3:15:00 PM",
"Jun 18, 2014 3:45:00 PM",
"Jun 18, 2014 4:00:00 PM",
"Jun 18, 2014 4:15:00 PM",
"Jun 18, 2014 4:45:00 PM",
"Jun 18, 2014 5:15:00 PM",
"Jun 18, 2014 5:30:00 PM",
"Jun 18, 2014 6:00:00 PM",
"Jun 18, 2014 6:15:00 PM",
"Jun 18, 2014 7:00:00 PM",
"Jun 18, 2014 7:15:00 PM",
"Jun 18, 2014 7:30:00 PM",
"Jun 18, 2014 8:00:00 PM",
"Jun 18, 2014 8:15:00 PM",
"Jun 18, 2014 8:30:00 PM",
"Jun 18, 2014 9:15:00 PM",
"Jun 18, 2014 9:30:00 PM",
"Jun 18, 2014 9:45:00 PM",
"Jun 18, 2014 10:15:00 PM",
"Jun 18, 2014 10:30:00 PM",
"Jun 18, 2014 11:15:00 PM",
"Jun 18, 2014 11:30:00 PM",
"Jun 18, 2014 11:45:00 PM"
)

The above array is in sorted timestamps. Now, if I re-sort them in ascending order, they should give me the same results I suppose BUT I am getting out of order results. I just don't understand why I am seeing such a behavior:
Here is the output I am getting:
sorted dates = (
"Jun 18, 2014 12:00:00 AM",
"Jun 18, 2014 1:00:00 AM",
"Jun 18, 2014 2:00:00 AM",
"Jun 18, 2014 3:00:00 AM",
"Jun 18, 2014 6:00:00 AM",
"Jun 18, 2014 7:00:00 AM",
"Jun 18, 2014 8:00:00 AM",
"Jun 18, 2014 9:00:00 AM",
"Jun 18, 2014 10:00:00 AM",
"Jun 18, 2014 12:15:00 AM",
"Jun 18, 2014 1:15:00 AM",
"Jun 18, 2014 2:15:00 AM",
"Jun 18, 2014 3:15:00 AM",
"Jun 18, 2014 4:15:00 AM",
"Jun 18, 2014 5:15:00 AM",
"Jun 18, 2014 6:15:00 AM",
"Jun 18, 2014 7:15:00 AM",
"Jun 18, 2014 8:15:00 AM",
"Jun 18, 2014 9:15:00 AM",
"Jun 18, 2014 10:15:00 AM",
"Jun 18, 2014 11:15:00 AM",
"Jun 18, 2014 12:30:00 AM",
"Jun 18, 2014 1:30:00 AM",
"Jun 18, 2014 2:30:00 AM",
"Jun 18, 2014 3:30:00 AM",
"Jun 18, 2014 4:30:00 AM",
"Jun 18, 2014 5:30:00 AM",
"Jun 18, 2014 6:30:00 AM",
"Jun 18, 2014 7:30:00 AM",
"Jun 18, 2014 8:30:00 AM",
"Jun 18, 2014 10:30:00 AM",
"Jun 18, 2014 11:30:00 AM",
"Jun 18, 2014 12:45:00 AM",
"Jun 18, 2014 1:45:00 AM",
"Jun 18, 2014 2:45:00 AM",
"Jun 18, 2014 4:45:00 AM",
"Jun 18, 2014 5:45:00 AM",
"Jun 18, 2014 6:45:00 AM",
"Jun 18, 2014 7:45:00 AM",
"Jun 18, 2014 8:45:00 AM",
"Jun 18, 2014 10:45:00 AM",
"Jun 18, 2014 11:45:00 AM",
"Jun 18, 2014 12:00:00 PM",
"Jun 18, 2014 1:00:00 PM",
"Jun 18, 2014 2:00:00 PM",
"Jun 18, 2014 3:00:00 PM",
"Jun 18, 2014 4:00:00 PM",
"Jun 18, 2014 6:00:00 PM",
"Jun 18, 2014 7:00:00 PM",
"Jun 18, 2014 8:00:00 PM",
"Jun 18, 2014 12:15:00 PM",
"Jun 18, 2014 1:15:00 PM",
"Jun 18, 2014 2:15:00 PM",
"Jun 18, 2014 3:15:00 PM",
"Jun 18, 2014 4:15:00 PM",
"Jun 18, 2014 5:15:00 PM",
"Jun 18, 2014 6:15:00 PM",
"Jun 18, 2014 7:15:00 PM",
"Jun 18, 2014 8:15:00 PM",
"Jun 18, 2014 9:15:00 PM",
"Jun 18, 2014 10:15:00 PM",
"Jun 18, 2014 11:15:00 PM",
"Jun 18, 2014 12:30:00 PM",
"Jun 18, 2014 1:30:00 PM",
"Jun 18, 2014 2:30:00 PM",
"Jun 18, 2014 5:30:00 PM",
"Jun 18, 2014 7:30:00 PM",
"Jun 18, 2014 8:30:00 PM",
"Jun 18, 2014 9:30:00 PM",
"Jun 18, 2014 10:30:00 PM",
"Jun 18, 2014 11:30:00 PM",
"Jun 18, 2014 12:45:00 PM",
"Jun 18, 2014 2:45:00 PM",
"Jun 18, 2014 3:45:00 PM",
"Jun 18, 2014 4:45:00 PM",
"Jun 18, 2014 9:45:00 PM",
"Jun 18, 2014 11:45:00 PM"
)

For example, why would "Jun 18, 2014 12:15:00 AM", be displayed after "Jun 18, 2014 1:00:00 AM"? I just don't get this part!!
Here is my code:
-(void)sortDates {
NSDateFormatter *dateFormatter;

dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM dd, yyyy HH:mm:ss a"];

NSLog(@"%@", xAxisDataWithDate);
NSArray *sortedTimes = [xAxisDataWithDate sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2)
{
    NSDate *date1 = [dateFormatter dateFromString:obj1];
    NSDate *date2 = [dateFormatter dateFromString:obj2];
    return [date1 compare:date2];
}];
NSLog(@"sorted dates = %@", sortedTimes);
}

I also wrote a sample program with a subset containing these dates and it seems to give me the wrong result when 1:00:00 AM is present in the array (1:00:00 AM should have been stored AFTER 12:00:00 AM):
-(void)sortDates {
NSDateFormatter *dateFormatter;

dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM dd, yyyy HH:mm:ss a"];

NSMutableArray *times = [[NSMutableArray alloc]initWithObjects:@"Jun 19, 2014 11:45:00 PM", @"Jun 18, 2014 1:00:00 AM", @"Jun 18, 2014 12:15:00 AM",@"Jun 18, 2014 12:00:00 AM", nil];
NSArray *sortedTimes = [times sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2)
{
    NSDate *date1 = [dateFormatter dateFromString:obj1];
    NSDate *date2 = [dateFormatter dateFromString:obj2];
    return [date1 compare:date2];
}];
NSLog(@"sorted dates = %@", sortedTimes);
}

Output:
sorted dates = (
"Jun 18, 2014 1:00:00 AM",
"Jun 18, 2014 12:00:00 AM",
"Jun 18, 2014 12:15:00 AM",
"Jun 19, 2014 11:45:00 PM"
)

I can't figure out why I am getting out of order results w.r.t NSMutableArray *xAxisDataWithDate and w.r.t NSMutableArray *times! Kindly help me in this regard! Appreciated.

A:

You seem to have a wrong format, the time appears to be in 12 hour format, change your format to MMM dd, yyyy hh:mm:ss a note lowercase "h"
"Jun 18, 2014 12:00:00 AM",
"Jun 18, 2014 12:15:00 AM",
"Jun 18, 2014 1:00:00 AM",
"Jun 19, 2014 11:45:00 PM"

More importantly, you should convert strings to dates prior to comparison, sortedArray… is using merged sort, therefore you will convert string to dates n log n times instead of n times


Q:

Visual Studio unable to open port to host WCF Service

I created a solution VS2010 C# with the WCF service, the library to get data, the service is working fine in a console application in the solution. No problem.
I have to use it on a VS2008 project (and probably later on a VS2005) for the older projects. Then I start VS2010 I get the "WCF Test Client". At this time in the VS2008, I tried to "Add a web reference" on the local machine... no result.
Then I tried to create a console application with Vs2010 to host it, I did this :
Uri baseAddress = new Uri("http://localhost:8080/hello");
using (ServiceHost host = new ServiceHost(typeof(SecurityAccessWCF.WCFSecurityService), baseAddress))
{
    // Enable metadata publishing.
    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
    smb.HttpGetEnabled = true;
    smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
    host.Description.Behaviors.Add(smb);

    host.Open();

    Console.WriteLine("The service is ready at {0}", baseAddress);
    Console.WriteLine("Press <Enter> to stop the service.");
    Console.ReadLine();

    // Close the ServiceHost.
    host.Close();
}

I get an error on the Open(), I get this  error "AddressAccessDeniedException - HTTP could not register URL... Your process does not have access rights" (the link provided is not clear, I'm on Win7 x64 as local admin and in a domain)

A:

Shift + Mouse Right Click on Visual Studio shortcut and select Run as administrator
This way you should be able to host it.
Alternately, you could build the project and run the resulting console application the same way under admin account.

A:

Thats a standard error meaning your application cant register the domain. Normally this is a problem on vista/windows 7 with security. Log in as administrator and run netsh http add urlacl url=http://+:80/Localhost user=DOMAIN\user
Here is a msdn article with more information


Q:

Internet Explorer not handling any event thrown by window opened with window.open

When I open a simple HTML page from the same domain (so no cross domain concerns here) in a new window/tab with window.open:
var mywindow = window.open('<html page on same domain>');

Then the following code, which according to the docs is even <IE9 compatible
if (mywindow.addEventListener) {
    mywindow.addEventListener('load', function () {
        console.log('load event fired');
    }, false);
} else if (mywindow.attachEvent) {
    mywindow.attachEvent('onload', function () {
        console.log('load event fired');
    });
}

Doesn't catch the event thrown (tested in IE11 and IE Edge). Even if I throw a custom event on the HTML page the old fashioned way:
var event = document.createEvent('Event');
event.initEvent('customEvent', true, true);
window.dispatchEvent(event);

It it not caught... Also with jQuery, no success:
$(mywindow).on("customEvent", function () {
    console.log('custom event fired');
});

Chrome and Firefox however do catch both of the events...
Is this by design? Am I missing something? Is there some way to make this work?

A:

Apparently, the page was already loaded, before I was able to attach a handler to the load event.
I managed to solve this (thanks @CBroe) by triggering a delayed custom event in a window onload handler on the page, opened with window.open.
<script>
window.onload = function() {
    setTimeout(function() {
        var event = document.createEvent('Event');
        event.initEvent('customEvent', true, true);
        window.dispatchEvent(event);
    }, 1000);
};
</script>

This way I'm sure the window has fully been loaded (it's triggered in window.onload), but is not triggered too fast for attaching a handler to this custom event.
The delay of 1 sec has been chosen arbitrarily. You might want to adjust this to your needs.


Q:

Gradle Build failing with java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

I'm building an app which fetches data from Firebase adds it into an array adapter and displays it in a list view. When I try to build the app, it fails with:

Error:Execution failed for task
  ':app:transformClassesWithInstantRunForDebug'.
   java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

My Activity:
    package app.nert;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

public class display extends AppCompatActivity {
    private AdView mAdView;
    private ArrayList<String> ttable = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        MobileAds.initialize(this, "ca-app-pub-...");
        AdView adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId("ca-app-pub-...");
        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        //Shared Preference declaration
        SharedPreferences sprefs = getSharedPreferences("nert.app", MODE_PRIVATE);
        String sid = sprefs.getString("school_id", "Not defined yet");//get schoolid
        String sch = sprefs.getString("school", "Not defined yet");//get schoolname
        String cl = sprefs.getString("class", "Not defined yet");// get classname
        String clid = sprefs.getString("class_id", "Not defined yet");//get classid
        TextView tod = findViewById(R.id.today);
        TextView tom = findViewById(R.id.tom);
        tod.setVisibility(View.VISIBLE);
        tom.setVisibility(View.VISIBLE);
    }

    protected void onStart() {
        super.onStart();
        //Begin Shared Preferences
        SharedPreferences sprefs = getSharedPreferences("nert.app", MODE_PRIVATE);
        String sid = sprefs.getString("school_id", "Not defined yet");//get schoolid
        String sch = sprefs.getString("school", "Not defined yet");//get schoolname
        String cl = sprefs.getString("class", "Not defined yet");// get classname
        String clid = sprefs.getString("class_id", "Not defined yet");//get classid
        //End Shared Preferences

        //Begin get Day
        String weekDay;
        SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.US);
        Calendar calendar = Calendar.getInstance();
        weekDay = dayFormat.format(calendar.getTime());
        String day = String.valueOf(weekDay);
        //End get Day
        ListView tday = findViewById(R.id.day);
        tday.setDividerHeight(0);

        final ArrayAdapter tdayadapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, ttable);
        tday.setAdapter(tdayadapter);
        DatabaseReference gettt = FirebaseDatabase.getInstance().getReference().child("schools").child("classes").child(sid).child(clid).child("timetable").child(day);
        gettt.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                String value = dataSnapshot.getValue(String.class);
                tdayadapter.add(value);
                tdayadapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    public void homework(View view) {
        Intent hw = new Intent(this, homework.class);
        startActivity(hw);
    }

    public void replacement(View view) {
        Intent rp = new Intent(this, replacement.class);
        startActivity(rp);
    }

    public void onBackPressed() {
    }

    public void at(View view) {
        Intent an = new Intent(this, anifrom.class);
        startActivity(an);
    }

    public void today(View view) {
        ListView lstd = findViewById(R.id.day);
        ListView lstt = findViewById(R.id.tmo);
        TextView tod = findViewById(R.id.today);
        TextView tod2 = findViewById(R.id.today2);
        TextView tom = findViewById(R.id.tom);
        TextView tom2 = findViewById(R.id.tom2);
        lstt.setVisibility(View.GONE);
        tod2.setVisibility(View.GONE);
        tom2.setVisibility(View.GONE);
        lstd.setVisibility(View.VISIBLE);
        tod.setVisibility(View.VISIBLE);
        tom.setVisibility(View.VISIBLE);
    }

    public void tom(View view) {
        ListView lstd = findViewById(R.id.day);
        ListView lstt = findViewById(R.id.tmo);
        TextView tod = findViewById(R.id.today);
        TextView tod2 = findViewById(R.id.today2);
        TextView tom = findViewById(R.id.tom);
        TextView tom2 = findViewById(R.id.tom2);
        lstd.setVisibility(View.GONE);
        tod.setVisibility(View.GONE);
        tom.setVisibility(View.GONE);
        lstt.setVisibility(View.VISIBLE);
        tod2.setVisibility(View.VISIBLE);
        tom2.setVisibility(View.VISIBLE);
    }
}

And my build.gradle
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "app.nert"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0-alpha"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }

    }
}
buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.24.4'
    }
}

dependencies {
    implementation 'com.android.support:design:26.1.0'
    compile 'com.google.firebase:firebase-database:11.8.0'
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true
    }
    compile 'com.google.firebase:firebase-core:11.8.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.google.firebase:firebase-ads:11.8.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.google.android.gms:play-services-ads:11.8.0'
}

apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'

How can I prevent the build from failing?

A:

Yeah It's Just a bug in Android Studio, try Build -> Clean Project, and after that
click Build -> Rebuild Project


Q:

Sending a POST request through Javascript on Django - failed to retrieve data

I'm trying to send a POST request to my Django view using plain javascript (I don't want any unnecessary libraries involved). The data is not sent through a form, but by using fetch. For now I just want to be able to manipulate the request.POSTin my views.py, nothing more.
Here's my code:
Javascript
let article = document.querySelector('article')
articleId = article.getAttribute('data-product-id')

# some other stuff
fetch("{% url 'shop:shoplist' 1 %}", {
              method: 'POST',
              dataType: "application/json",
              data: {'article_id': articleId},
              headers: {'X-CSRFToken': csrf_token}
              })

Python
if request.method == 'POST':
    testing = request.POST
    return JsonResponse({'test': testing})

The request is sent, the csrftoken is received correctly, but the request.POST returns just <QueryDict: {}>, instead of what I'm expecting (headers, data...).
I've searched and found a lot of similar questions, the most similar one being this one, but still I can't seem to find a solution.
Any idea?

A:

The request.POST contains only the parameters that are form encoded. Since your data type is application/json they are empty. The request.body contains the actual json data.


Q:

how to receive map& from function/class?

How to receive map<string, factory<BaseClass, ConstructorType> > from such function?
So I have
template <class BaseClass, class ConstructorType>
map<string, factory<BaseClass, ConstructorType> > get_factories (shared_library & lib) {
    type_map lib_types;
    if (!lib.call(lib_types)) {
        cerr << "Types map not found!" << endl;

    }

    map<string, factory<BaseClass, ConstructorType> >& lib_factories(lib_types.get());
    if (lib_factories.empty()) {
        cerr << "Producers not found!" << endl;

    }
    return lib_factories;

}

and I try to get its value with something like:
map<string, factory<PublicProducerPrototype, int> > producer_factories();
producer_factories = get_factories<PublicProducerPrototype, int>(simple_producer);

I try to generalize/simplify some of boost.extension methods for myself.
So how to receive map<A, B>& correctly?
How to initialize link correctly or how to return not link but real object? (sorry C++ nube)

A:

If you need a reference to a map, you should declare the function as returning a reference, not a value:
template <class BaseClass, class ConstructorType>
map<string, factory<BaseClass, ConstructorType> >& get_factories (...

Of course, this assumes that the reference returned by lib_types.get() is safe to pass out as a reference.


Q:

How can I use an environment variable in a key inside of yaml file

I have the following .env file:
# ENV
ENVIRONMENT=local
SITENAME=reo

I have the following docker-compose.yml (part of it) file:
volumes:
  ${SITENAME}-sync:
     external: true

I get the following error:
 volumes value '${SITENAME}-sync' does not match any of the regexes: u'^[a-zA-Z0-9._-]+$'

Is it possible to have a variable as a key in a Yaml file?
I noticed that: key: ${SITENAME} does work.

A:

Environment variables are not possible for keys in docker-compose.yml, only for values. See here


Q:

restriction of a map is measurable iff the map is measurable.

Suppose we have the measure space $(\Omega,F)$ and the map $T:(\Omega,F) \rightarrow (\Omega',F')$, where $A_1,A_2, \dots$ is a partition of $\Omega$ such that $A_i \in F$. The restriciton of $F$ to $A_i$ we call $F_i$ and the map restricted to $A_i$ we call $T_i$. Prove the following statement:
$T$ is $F-F'$ measurable iff $T_i$ is $F_i-F'$ measurable.
I think i proved from right to left, but the other side seem to bother me:
suppose $T_i$ is $F_i - F$ measurable, then $T_i^{-1} (F') \subset F_i \subset F$. Because this holds for all $i \in \mathbb{N}$ we see that $T^{-1}(F') \subset \cup F_i \subset F$. Hence T is measurable.
For the other implication i'm kind of stuck. Any hints on how to start?
Kees

A:

Suppose $T$ is $F-F'$ measurable. Given $A'\in F'$, $T_i^{-1}(A') = T^{-1}(A') \cap A_i$, which is in $F\cap A_i$.


Q:

Extracting an interface from an array of keys of an object to perform Pick and Omit

I'm having trouble coming up with the necessary typings for the following two functions:
const pick = (obj, ...names) =>
  names.reduce((ret, next) => {
    if (typeof obj[next] != 'undefined') ret[next] = obj[next];
    return ret;
  }, {});

const strip = (obj, ...names) =>
  pick(obj, ...Object.keys(obj).filter(key => !names.includes(key)));

I've tried something like the following:
type Picker = <T extends object, U extends (keyof T)[]>(obj: T, ...names: U) =>
  Pick<U, T>;

type Stripper = <T extends object, U extends (keyof T)[]>(obj: T, ...names: U) =>
  Omit<U, T>;

But those types require passing a type T that extends object, not array of strings. How can I construct a type from Array<keyof T> to pass into Pick and Omit?

A:

After rephrasing the question a couple of times, it occured to me that you could create a union type from an array by using the index accessor:
type Picker = <U extends object, V extends (keyof U)[]>(obj: U, ...keys: V) =>
  Pick<U, V[number]>;

type Stripper = <U extends object, V extends (keyof U)[]>(obj: U, ...keys: V) =>
  Omit<U, V[number]>;


Q:

Identity Server 4 not return error description to controller

I have an Identity server 4 project which follows the documentation on how to display the errors
Home Controller:
public class HomeController : Controller
{
    private readonly IIdentityServerInteractionService _interaction;

    public HomeController(IIdentityServerInteractionService interaction)
    {
        _interaction = interaction;
    }

    public IActionResult Index()
    {
        return View();
    }

    public async Task<IActionResult> Error(string errorId)
    {
        var vm = new ErrorViewModel();
        var message = await _interaction.GetErrorContextAsync(errorId);
        if (message != null)
            vm.Error = message;
        return View("Error", vm);
    }
}

The Identity server itself is giving some good information in the logs
fail: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Unknown client or not enabled: 3CCF1B2D-D064-4A1B-BFD4-57E0451575C7.apps.biz
{
        "SubjectId": "anonymous",
        "RequestedScopes": "",
        "Raw": {
          "client_id": "3CCF1B2D-D064-4A1B-BFD4-57E0451575C7.test.apps.biz",
          "redirect_uri": "http://localhost:4200/signin-oidc",
          "response_type": "id_token",
          "scope": "openid profile",
          "response_mode": "form_post",
          "nonce": "636589548258549622.YzMwMzRkNjAtYWU2Ni00ODlmLTg3ZWQtNmRmOThhYjcyN2JlZWFkYjk2MjEtNDAxNC00ZTQ1LWEzZTAtNTZmMWIyNDhkZjg1",
          "state": "CfDJ8FDPGFWZWNNOmnYDxcFlnVDZgaOG1kNakiXQF48y_4gnSxuIVAVQmMJ_4j9SUZz1TXGJDt4-8EKmoxLXuw3SZgyc5fy1ODzdS0Njd68T1W9dGxt8rFNrUF0njKk3XrSRTeJ45geS_uOL4w89OVupVq4UtHVbKxj3UMZLCn4W-BAXpXfo43KIT8RvxICMjbNtvPM1toEmMSlfdic6T6EZoxXpwim919xMLeQCY0S7QZdbc9DFfUfJkVYsLrofiBvQtZLfQjRQNp_7MiYFz_C4IQ7BAupErvZpcNvpBhQJWIt8BKlACVfKLHbvO6M0FKqa9A",
          "x-client-SKU": "ID_NET",
          "x-client-ver": "2.1.4.0"
        }
      }

and
 fail: IdentityServer4.Validation.AuthorizeRequestValidator[0]
  Invalid redirect_uri: http://localhost:4200/signin-oidc
{
        "ClientId": "testclient",
        "ClientName": "testclient",
        "AllowedRedirectUris": [
          "http://localhost:5002/signin-oidc"
        ],
        "SubjectId": "anonymous",
        "RequestedScopes": "",
        "Raw": {
          "client_id": "testclient",
          "redirect_uri": "http://localhost:4200/signin-oidc",
          "response_type": "code id_token",
          "scope": "openid profile",
          "response_mode": "form_post",
          "nonce": "636589567957415216.ZjYyZTU3MTEtZWRhZi00N2RhLWI1MjQtZThlZjk4NjY2NmJmZDQ4ZmUzNzQtMTI3MS00YTdiLTgzNDUtYThlMWU2NzcxMmM5",
          "state": "CfDJ8FDPGFWZWNNOmnYDxcFlnVByKSJA-wSjaBBIB2p-d1oUhuZNGBiD1gOFpnyxevmIKxNY1Hf15vlbpgLZoEVQ8O7UhyOpR1ANgUhhyl9nL4M63-2am7F1LJf9hwijkS0_WpxxJ-jYHlq4r99fS2tcaPFZjAG_UNjWYgTshD5Kps3czFvJOG04plaCn2zcKCX5AGgTVnxlG7__hi1ifn-xOipynq5nHBIasMT6doCmpjktAqx7AOK4C1D__YbVMkcRhC70qYFCfoSNhpUrROXZobP6GxYXd1y5EEbA_oXJjmePFdEL-MFQp0o5D_H_mXsU1g",
          "x-client-SKU": "ID_NET",
          "x-client-ver": "2.1.4.0"
        }
      }

However the only information isnt returned to my controller by GetErrorContextAsync so only the error name can be displayed to the user.

The description of the error isn't filled out at all.
How do i get at the very least description populated?
I am looking for a way of displaying some sensible information for the developers here.  However every error seams to return unauthorized_client so i cant tell the developer that its a problem with the redirect URI vs an invalid client id.
if (vm.Error.Error == "unauthorized_client") vm.Error.ErrorDescription = "Contact plugin developer.";

Note: Redirect URI one does appear to return a description.

A:

This is intended by design. You can't access to the reason for unathorized_client in your controller.
you can also check the source to see what's going on.
//////////////////////////////////////////////////////////
// check for valid client
//////////////////////////////////////////////////////////
var client = await _clients.FindEnabledClientByIdAsync(request.ClientId);
if (client == null)
{
    LogError("Unknown client or not enabled", request.ClientId, request);
    return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient);
}

https://github.com/IdentityServer/IdentityServer4/blob/dev/src/IdentityServer4/Validation/AuthorizeRequestValidator.cs#L150


Q:

¿Por qué decimos "por hache o por be"?

Según el diccionario:

por hache o por be

loc. adv. coloq. Por una u otra causa.

Siempre me ha resultado curiosa esta expresión, ya que me da la sensación de que la hache y la be hacen referencia a alguna otra palabra o expresión, tal vez una expresión latina cuyas iniciales fueran esas y hoy día solo la referenciáramos a través de dichas iniciales. Aunque la verdad es que la expresión parece reciente, esto es lo más antiguo que encuentro en el CORDE:

¡De manera que a ver si hay un poquito de formalidad, que ya llevan dos veces que se les llama la atención por hache o por be, y estoy viendo que todavía me van a poner ustedes en el trámite de avisar a mi marido!
Rafael Sánchez Ferlosio, "El Jarama", 1956 (España).

De hecho, la primera aparición de esta expresión en el diccionario fue en 1984 en el Academia manual, y redirige a la expresión por ce o por be. Esta nueva expresión se recoge en el diccionario desde 1817 en el DLE con una pequeña diferencia en el significado: "de un modo u otro". Y cita como ejemplo: "Por ce ó por be se salió con la suya". Nótese que no es lo mismo "de un modo u otro" que "por un motivo u otro", aunque el diccionario actual recoge las dos expresiones como sinónimas (ante lo cual discrepo: en la cita de arriba yo podría sustituir por hache o por be por por un motivo u otro, pero no por de un modo u otro). Curiosamente no logro encontrar en el CORDE ningún ejemplo de esta versión de la expresión.
Así pues, ¿significan algo esa ce y esa be de la expresión original? ¿O fue solo una expresión inventada así sin más? ¿Cómo evolucionó la ce a la actual hache? ¿Cuándo y cómo tuvo lugar ese cambio de matiz en el significado?

A:

Hay una selección de frases similares:

[decir] cesta por ballesta (1605, 1616)
por zancas o por barrancas (1770)
per fas et nafas (cc 1200 It)

por fas o por nefas (cc 1518, 1553)

a por a, y be por be (1611, 1674)

por a, be o ce (1982)
ce por ce, y be por be (1663)

ce por be (1561, 1773) (Con lujo de detalles)
be por be (1809)
por che o por be (1941)
por ce o por be (1817)

por ces o por bes (1927)
por hache o por zeta (1926)
por hache o por be (1965, 1965, 1976)
por hache o por ce
por hache o por erre (1880)

por haches o por erres (1920)
no decir haches ni erres (1886)

|| Fras. Fam. Por ce ó por be; de un modo ó de otro, por fas ó por nefas, por zancas ó por barrancas, de todos modos, etc., en cuyo sentido se dice: por ce ó por be, ya salí con la mía.

Diccionario nacional o gran diccionario clasico de la lengua ..., Volume 1 (1848)

Parece que, con el tiempo, y por la influencia de la forma de ciertas frases y las significaciones de otras, ha pasado de 'ce por be' por 'por ce o por be' hasta 'por hache o por be' con su definición actual.
Esta cita puede ser de interés:

2.3 Idiomaticidad

La idiomaticidad ha sido entendida de dos maneras diferentes. Por un lado, responde, en el sentido etimológico, a lo que es propio y peculiar de una lengua y, por otro, se puede interpretar como el rasgo semántico característico de ciertas construcciones fijas, en las que su significado no puede ser deducido a partir de los elementos que la forman, y así es como debe entenderse en el ámbito fraseolágico. Sentencia Zuluaga (1980: 123-124) que "la expresión idiomática es un signo complejo pero no. simultáneamente y desde el punto de vista funcional, un complejo de signos. Los componentes de esta no se comportan en ella como signos lingüísticos, propiamente. sino. mas bien, como componentes formales de un signo".

Por otro lado, la idiomaticidad de una unidad pluriverbal no está directamente relacionada con la cantidad de elementos idiomáticos que posea, pues si solo uno funciona idiomáticamente la unidad será idiomática. En este sentido, se considera que una palabra es idiomática cuando, por pertenecer a etapas sincrónicas previas a la actual de una lengua determinada, tiene valor únicamente dentro de la unidad fraseológica correspondiente, careciendo, por tanto, de vida léxica fuera de ella. Igualmente, se consideran idiomaticos los prestamos léxicos, así como las deformaciones fónicas, morfológicas, apócopes, pues en el seno de una expresión determinan su sentido idiomático (García-Page Sanchez, 1990: 279-290). Reflejo de ello son expresiones como mondo y lirondo, a la Chita callando, sin ton ni son, por fas o por nefás, etc.

Pese a que la idiomaticidad se ha tratado habitualmente como uno de los rasgos mas esenciales de las unidades fraseológicas, hay que tener presente que no todas ellas son idiomáticas, pues, mas Bien. «se trata de una característica potencial, no esencial. de este tipo de unidades» (Corpas Pastor, 1996: 27).

Las colocaciones y la fraseología

Hablar bien no cuesta tanto: dudas, etimologías y curiosidades de la lengua española (p335-336)

La configuración de las letras como mensaje propio, Yakov Malkiel

Eutrapelias del alfabeto español, Jacques de Bruyne (p36)

Revista de la filología española, Vol. 14 (1927)

A:

En este enlace hay tres posibles orígenes o teorías:

Una discusión acerca de cómo se escribe "uva" (te puedes equivocar, por la hache, o por la be).
Motivo de suspensos en ortografía (por hache o por be)...
La expresión bien puede venir de las formulas matemáticas relacionadas con los triángulos, donde "B" es la base y "H" la altura. Ver por ejemplo Área de un triángulo. Al parecer durante varias generaciones los libros de matemáticas tenían origen francés y se escribía "h x b" (hauteur par base), y no "a x b" (altura por base), de ahí que aún hoy conservemos dicha fórmula usando la letra H para la "Altura" y no la letra A. Esto se apunta por Javier del Hoyo en su libro "Etimologicón" (Ariel, 2013).

Por mi parte añado, citando del enlace nº 1: "Dependiendo del tipo de triángulo puedes necesitar un elemento (triángulo equilátero), dos (base y altura) o tres (siempre que no sean los tres ángulos)".


Q:

Group functions in LINQ with order by clause

I'd appreciate if someone can help me with my query:
In t-SQL:
SELECT REP_SEQ, CLASS_ID, CLASS_NAME, GROUP_ID, GROUP_NAME, CODE_ID, CODE_NAME, SUM(AMOUNT),DATE
FROM REPORTS.dbo.[table]
WHERE DATE = '2014-04-01'
GROUP BY REP_SEQ, CLASS_ID, CLASS_NAME, GROUP_ID, GROUP_NAME, CODE_ID, CODE_NAME, DATE
ORDER BY DATE, REP_SEQ, CLASS_ID, GROUP_ID, CODE_ID

I tried to write this query in LINQ:
var query = from e in context.table
                        where e.DATE == '2014-04-01'
                        group e by new { e.REP_SEQ,
                                         e.CLASS_ID,
                                         e.CLASS_NAME,
                                         e.GROUP_ID,
                                         e.GROUP_NAME,
                                         e.CODE_ID,
                                         e.CODE_NAME,
                                         e.DATE } into res
                        select new { res.Key.REP_SEQ,
                                     res.Key.CLASS_ID,
                                     res.Key.CLASS_NAME,
                                     res.Key.GROUP_ID,
                                     res.Key.GROUP_NAME,
                                     res.Key.CODE_ID,
                                     res.Key.CODE_NAME,
                                     res.Sum(e=>e.AMOUNT).Value,
                                     res.Key.DATE };

I'm not sure if it's correct. And I need to add ORDER BY clause as well.
Thanks a lot in advance

A:

If you want to get list of table you can project the results as table.
var query = context.table
.Where(t => t.DATE == '2014-04-01')
.GroupBy(e => new {e.REP_SEQ,
                   e.CLASS_ID,
                   e.CLASS_NAME,
                   e.GROUP_ID,
                   e.GROUP_NAME,
                   e.CODE_ID,
                   e.CODE_NAME,
                   e.DATE
                  })
.Select(res => new table
                  {
                     REP_SEQ = res.Key.REP_SEQ,
                     CLASS_ID = res.Key.CLASS_ID,
                     CLASS_NAME = res.Key.CLASS_NAME,
                     GROUP_ID = res.Key.GROUP_ID,
                     GROUP_NAME =res.Key.GROUP_NAME,
                     CODE_ID = res.Key.CODE_ID,
                     CODE_NAME = res.Key.CODE_NAME,
                     AMOUNT = res.Sum(e=>e.AMOUNT),
                     DATE = res.Key.DATE
                  })
.OrderBy(r = r.DATE)
.ThenBy(r => r.REP_SEQ)
.ThenBy(r => r.CLASS_ID)
.ThenBy(r => r.GROUP_ID)
.ThenBy(r => r.CODE_ID)
.ToList();


Q:

How to use link generator from javascript variable ,in symfony2

I am trying to use link generator with Javascript function.
{% for key in values %}
click!!
{%endfor %}

function bookConfirm(key) {
    if (confirm("Is it OK?")) {
    alert("OK!!");

    location.href = "{{ path('acme_member_bookLesson',{'scheKey':key})}}";
    } else {
    alert("cancel!");
    }
}

but it shows
'Variable "key" does not exist in AcmeMemberBundle:Default:show.html.twig at line 19'
How can I solve this problem? it is little bit complex to use Javascript and link generator.

A:

EDIT: The second key is not in the loop, that means that it'll always have the value of the last loop. You output the value of key as an argument to the JavaScript function. The second key value is not the key value of the javascript function, but the key value in twig. Why that is and how to fix it can be read in my original answer:
Twig is a templating engine written in PHP. That means it runs on the server side and outputs the text on in the code. Then the code is send to the browser and the browsers parses and renders/executes the HTML, CSS and JavaScript code.
So it isn't possible to execute some twig code with JavaScript.
However, you can simply fix your code using the FosJsRoutingBundle. That bundle does exactly what it says, it can handle most of the Symfony routing features on the client-side in JavaScript.
Your code would become something like:
function bookConfirm(key) {
    if (confirm("Is it OK?")) {
        alert("OK!!");

        location.href = Routing.generate('acme_member_bookLesson', { key: key });
    } else {
        alert("cancel!");
    }
}

Read more about it in their docs