text:
Q: RabbitMQ with mirrored queues: Failover support I am trying to set up a RabbitMQ cluster with mirrored queues (nevermind if u don't know what that is, it MIGHT NOT affect the answer). Long story short, I have N RabbitMQ instances joined together in a cluster. One of the instances is the master, the remaining are slaves  - sorry about the terminology but thats what is on the RabbitMQ docs - but they are active. However, I need to come up with a proxying solution that does the following

*

*Route ALL TCP connections to the master.

*Should the master fail, reroute all TCP connections to a new master - one of the slaves will be promoted to master in that scenario.

*No load balancing - all connections MUST go to the master (original or new).

Trouble is HAProxy seems to always work as a load balancer which is not applicable here, it is just here to provide failover support. How can I turn load balancing off but still keep failover support on?

A: Here is a solution that tackles the exact problem that you describe.


text:
Q: Hibernate criteria distinct on all columns I want to create a Hibernate Criteria that selects distinct based on all returned columns in a query.  The best that I can do is to create a ProjectionList and add each column to the list which seems very verbose compared to SQL.
pseudo-SQL
SELECT DISTINCT parent.*, child.name
  FROM parent INNER JOIN child ON parent.id = child.parent_id
 WHERE child.name = 'Chris'

Note I want to do this on the database not using a ResultTransformer.
Any suggestions?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Appium error when trying to build the AppiumServiceBuilder I am building the service correctly from what I have been reading. What is the cause of the following error and how can I fix it? I have the Selenium Standalone Server with the Java client for Appium.
My code:
AppiumServiceBuilder appiumService = new AppiumServiceBuilder()
                .usingDriverExecutable(new File("/Applications/Appium.app/Contents/Resources/node/bin/node"))
                .withAppiumJS(new File("/Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js"));
    appiumService.usingPort(4723);

    appiumService.build();

Error stack Trace:
java.lang.NoClassDefFoundError: org/apache/commons/validator/routines/InetAddressValidator
    at io.appium.java_client.service.local.AppiumServiceBuilder.createArgs(AppiumServiceBuilder.java:230)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:299)
    at com.wolff.utils.Driver.startAppium(Driver.java:53)
    at com.wolff.utils.Driver.setUp(Driver.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.validator.routines.InetAddressValidator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 28 more

java.lang.NullPointerException
    at com.wolff.utils.Driver.tearDown(Driver.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

A: it has a dependency on that jar.
 <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
            <version>1.4.1</version>
        </dependency>

Download it from here https://commons.apache.org/proper/commons-validator/download_validator.cgi
and add it to your project.


text:
Q: How can avoid having a solution specific hard coded macro in Visual Studio? Background
I have a macro AttachToRemoteProcess that I use to attach the debugger to a running process on a remote computer. The macro use hard coded names for the process and the computer. I use the macro from a toolbar button on a custom toolbar. I consider this a sub par solution and I don't really like to have such a macro in my Visual Studio environment since it only works for the specific program/environment it was hard coded for.
I am using Visual Studio 2008.
Solutions
I can imagine two solutions but I do not know if they are possible to implement.
Alternative 1
I would like to either have the macro AttachToRemoteProcess  being part of the solution (.sln) or one of the projects (.csproj) and have the toolbar appear when the solution or project has been loaded into Visual Studio. In this case it is OK to have hard coded settings such as process and computer name.
Alternative 2

*

*The macro AttachToRemoteProcess is made reusable by taking process and computer as parameters.

*The custom toolbar, button and the macro are always available in Visual Studio. This is just like my current solution, except for the parameterized macro.

*When the button is clicked the computer name and process name is looked up from somewhere in the solution or the current project.

Questions

*

*Would any of the alternative work and how can I go about doing it?

*Are there any other alternative solutions for what I want to achieve?

A: The second alternative seems to work. Instead of retrieving the parameters from the solution (perhaps using VBA and the class EnvDTE.DTE.Solution), you could display a small form to select the process and computer and use this input as parameters to your macro. The button would be displayed in a personal toolbar all the time.
I'm not sure whether you can "attach" macros to particular solutions. If that's not possible, you will have no way to implement alternative 1.


text:
Q: UsbDeviceConnection.requestWait() / UsbRequest.queue() stops communicating with device Anybody have any ideas as to why requestWait() or queue() might stop receiving information (payloads) from an external device (aggboard) after the device has been disconnected and then reconnected? If I use the bulktransfer() method (which is commented out) with otherwise the same code, the communication resumes, but bulktransfer() is dropping payloads, which is why we have tried refactoring to requestWait() and queue(). Any advice??
public class PayloadTask extends AsyncTask<Payload, Void, Payload> {

    private UsbInterface usbInterface;
    private UsbDeviceConnection usbConnection;
    private UsbEndpoint usbToAggBoard;
    private UsbEndpoint usbFromAggBoard;
    private AggBoard owner;
    private UsbRequest request = new UsbRequest();

    PayloadTask(AggBoard owner, UsbInterface intf, UsbDeviceConnection connection) {
        usbConnection = connection;
        usbInterface = intf;
        /*synchronized (intf)*/ {
            usbToAggBoard = intf.getEndpoint(1);
            usbFromAggBoard = intf.getEndpoint(0);
        }
        this.owner = owner;
    }

    @Override
    protected Payload doInBackground(Payload... payloads) {

        if (payloads != null) {
            if (payloads.length > 1) {
                Log.d("PayloadTask", "There was more than one payload. Going to have to iterate.");
                int i = 0;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (Payload payload : payloads) {
                    byte[] buffer = payload.getBytes();

                    while (AndroidUnityPlayerActivity.aggBoard == null)
                    {
                        try {
                            Log.d("PayloadTask", "Waiting for AndroidUnityPlayerActivity.aggboard to not be null");
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
                    byteBuffer.rewind();
                    try {
                        request.initialize(usbConnection, usbToAggBoard);
                        if (!request.queue(byteBuffer, buffer.length)) {
                            throw new IOException("Error queueing USB request.");
                        }
                        usbConnection.requestWait();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if(usbConnection != null) {
                            int sent = request.hashCode();
                            request.close();
                        }
                        else{
                            Log.d("PayloadTask", "Request not received by usbConnection");
                        }
                    }
//  int sent = usbConnection.bulkTransfer(usbToAggBoard, buffer, buffer.length, 1500);
                    busyWaitMicros(20);

                    if (++i % 1024 == 0) {
                        Log.e(AndroidUnityPlayerActivity.TAG, new Integer(i / 1024 * 8).toString() + "KB sent");
                    }
                    AggBoard.percentInstalled = i * 100 / payloads.length;
                   // Log.w(AndroidUnityPlayerActivity.TAG, new Float((float)i /payloads.length).toString());

                }
                Log.d("PayloadTask", "Finished iterating over the payloads.");
                // rk3188 doesn't seem to see the success/fail message.. so let's fake one :/
                if (AggBoard.encryptedBytes != null) {
                    Log.d("PayloadTask", "Aggboard.encryptedBytes was null. Creating some kind of success response payload??");
                    byte[] response = new byte [] { (byte)Payload.BOOTLOAD_STATUS,
                                                    (byte)BootloadStatusPayload.AGGREGATOR,
                                                    (byte)BootloadStatusPayload.SUCCESS,
                                                    0, 0, 0, 0,
                                                    (byte)Payload.AGGREGATOR_TAIL };
                    if (AggBoard.percentInstalled < 100) {
                        response[2] = (byte)BootloadStatusPayload.ERROR ;
                    }
                    Log.d("PayloadTask", "Creating bootload status SUCCESS task");
                    return Payload.CreatePayload(response);
                }
            } else if (payloads.length == 1 && payloads[0] != null) {
                Log.d("PayloadTask", "There was only one payload. Running it");
                byte[] buffer = payloads[0].getBytes();
                if (AndroidUnityPlayerActivity.aggBoard != null) {
                    Log.d("PayloadTask", "Only one payload, beginning bulk transfer");

                   /* if (Payload.START_SENDING_DATA == buffer[0]) {
                        AndroidUnityPlayerActivity.hasAggBoard = true;
                    }*/

                    ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
                    byteBuffer.rewind();
                    try {
                        request.initialize(usbConnection, usbToAggBoard);
                        if (!request.queue(byteBuffer, buffer.length)) {
                            throw new IOException("Error queueing USB request.");
                        }
                        usbConnection.requestWait();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if(usbConnection != null) {
                            request.close();
                        }
                        else{
                            Log.d("PayloadTask", "Request not received by usbConnection");
                        }
                    }
//  usbConnection.bulkTransfer(usbToAggBoard, buffer, buffer.length, 1000);
                }
                else{
                    Log.d("PayloadTask", "AndroidUnityPlayerActivity's aggboard was null. Can't perform bulk transfer of payload.");
                }
            }
        } else {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        byte[] response = new byte[64];
        int result = 0;
        int tries = 0;

        while (result < 1){
            if (tries > 5) {
                Log.d("PayloadTask", "PayloadTask Timed Out.");
                return null;
            } else if (isCancelled()) {
                Log.w("PayloadTask", "PayloadTask Cancelled!");
                return null;
            }

            /*synchronized (usbConnection)*/
            //if (usbConnection != null) {
                ByteBuffer byteBuffer = ByteBuffer.wrap(response);
                byteBuffer.rewind();
                try {
                    request.initialize(usbConnection, usbFromAggBoard);
                    if (!request.queue(byteBuffer, response.length)) {
                        throw new IOException("Error queueing USB request.");
                    }
                    usbConnection.requestWait();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(usbConnection != null) {
                        result = request.hashCode();
                        request.close();
                        //result += 1;
                    }
                    else{
                        Log.d("PayloadTask", "Request not received by usbConnection");
                    }
                }
//  result = usbConnection.bulkTransfer(usbFromAggBoard, response, response.length, 1000);
            tries += 1;
        }
        Log.i("PayloadTask", new Integer(response.length).toString() + " bytes received: ");
        Log.d("PayloadTask", "doInBackground returning some payload from the aggboard.");
        return Payload.CreatePayload(response);
    }

    @Override
    protected void onPostExecute(Payload payload) {
        owner.handlePayload(payload);
    }

    @Override
    protected void onCancelled() {
        Log.d("PayloadTask", "thread canceled");
        super.onCancelled();
    }

    @Override
    protected void onPreExecute() {
        Log.d("PayloadTask", "started thread");
        if (!usbConnection.claimInterface(usbInterface, true)) {
                Log.w("PayloadTask", "Failed to claim interface!");
            }
        else{
            Log.w("PayloadTask", "Claimed interface!");
        }
    }

    public static void busyWaitMicros(long micros){
        long waitUntil = System.nanoTime() + (micros * 1000);
        while(waitUntil > System.nanoTime()){

        }
    }
}


text:
Q: How can I make a consistently transparent fade, disregarding what has been drawn below? ]
In my code, I have a path that uses a custom fading that has been defined previously. It is supposed to fade the current scope's border, but, as you can see, that only happens when there is only one filling in place. When I overlay multiple fillings, their total opacity compounds and the border becomes less and less faded. How can I avoid that? I know that, in this example, the solution would be to simply change where the rectangles begin and end, but this is simply an exemplification, as I want to apply this concept to much more complicated figures, where calculating when to begin a filling to avoid this problem would be practically unfeasible. As a bonus question, how can I stop the blue filling affecting the red part and vice versa? Here's the code for the picture:
\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{fadings}

\begin{document}

    \begin{tikzfadingfrompicture}[name=my fading]
            \shade[inner color=transparent!0,outer color=transparent!100] (0.5,0.5) circle (0.5);
            \shade[inner color=transparent!0,outer color=transparent!100] (7.5,7.5) circle (0.5);
            \shade[inner color=transparent!0,outer color=transparent!100] (7.5,0.5) circle (0.5);
            \shade[inner color=transparent!0,outer color=transparent!100] (0.5,7.5) circle (0.5);
            \shade[top color=transparent!0,bottom color=transparent!100] (0.5,0.5) rectangle (7.5,0);
            \shade[right color=transparent!0,left color=transparent!100] (0.5,7.5) rectangle (0,0.5);
            \shade[bottom color=transparent!0,top color=transparent!100] (0.5,7.5) rectangle (7.5,8);
            \shade[left color=transparent!0,right color=transparent!100] (7.5,0.5) rectangle (8,7.5);
            \fill[transparent!0] (0.5,0.5) rectangle (7.5,7.5);
    \end{tikzfadingfrompicture}
    \begin{tikzpicture}

        \clip (0,0) rectangle (8,8);
        \fill (0,0) rectangle (8,8);
        \path [scope fading=my fading, fit fading=false,fading transform={shift={(current bounding box.center)}}];
        \fill[blue] (0,0) rectangle (8,8);
        \fill[blue] (0,0) rectangle (8,4);
        \fill[blue] (0,0) rectangle (8,2);
        \fill[red] (0,0) rectangle (8,1);
        \fill[blue] (0,0) rectangle (8,0.5);
        \draw[->,thick,red] (1,5) -- (0.25,4.25);
        \draw[->,thick,red] (1,3) -- (0.25,2.25);
        \draw[->,thick,red] (1,2) -- (0.25,1.25);

    \end{tikzpicture}

\end{document}

A: Welcome! Nice question! You need to put the stuff in a transparency group.
\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{fadings}

\begin{document}

    \begin{tikzfadingfrompicture}[name=my fading]
            \shade[inner color=transparent!0,outer color=transparent!100] (0.5,0.5) circle (0.5);
            \shade[inner color=transparent!0,outer color=transparent!100] (7.5,7.5) circle (0.5);
            \shade[inner color=transparent!0,outer color=transparent!100] (7.5,0.5) circle (0.5);
            \shade[inner color=transparent!0,outer color=transparent!100] (0.5,7.5) circle (0.5);
            \shade[top color=transparent!0,bottom color=transparent!100] (0.5,0.5) rectangle (7.5,0);
            \shade[right color=transparent!0,left color=transparent!100] (0.5,7.5) rectangle (0,0.5);
            \shade[bottom color=transparent!0,top color=transparent!100] (0.5,7.5) rectangle (7.5,8);
            \shade[left color=transparent!0,right color=transparent!100] (7.5,0.5) rectangle (8,7.5);
            \fill[transparent!0] (0.5,0.5) rectangle (7.5,7.5);
    \end{tikzfadingfrompicture}% <- the % removes spurious space
    \begin{tikzpicture}

        \clip (0,0) rectangle (8,8);
        \fill (0,0) rectangle (8,8);
        \path [scope fading=my fading, fit fading=false,
        fading transform={shift={(current bounding box.center)}}];
        \begin{scope}[transparency group]
         \fill[blue] (0,0) rectangle (8,8);
         \fill[blue] (0,0) rectangle (8,4);
         \fill[blue] (0,0) rectangle (8,2);
         \fill[red] (0,0) rectangle (8,1);
         \fill[blue] (0,0) rectangle (8,0.5);
         \draw[->,thick,red] (1,5) -- (0.25,4.25);
         \draw[->,thick,red] (1,3) -- (0.25,2.25);
         \draw[->,thick,red] (1,2) -- (0.25,1.25);
        \end{scope}
    \end{tikzpicture}

\end{document}


text:
Q: How do I do a milisecond delay in a .bat file I was wondering if there is a delay command in a batch file that can delay for less than a second (like 0.2 seconds). As of right now I only know of the timeout (seconds) which can only delay for a minimum of 1 second. I would appreciate any help :-)

A: As i know, there isn't a very "good" way of doing this. Some might suggest using the ping command, which is actually possible to give miliseconds of delay, but this is using the wrong tool for the wrong place.
It would be must better to write a code in C (or any other languages with this feature) and run it on batch. Try the program at the link below.
https://www.elifulkerson.com/projects/millisleep.php


text:
Q: Scalar times Point + Scalar times Point? Let $P$, $Q$ be a pair of points in the Euclidean plane and let $t_1$, $t_2$ be a pair of scalars. My textbook says that the following operations are nonsense:
$$P + Q\\
t_1 \cdot P$$
However $t_1 \cdot P + t_2 \cdot Q$ is completely valid and makes sense!
I cannot understand this at all. If you cannot multiply a scalar by a point and you cannot add points together, then how come that this expression is still valid? And how come that the result is a point?

A: $t_1P+t_2Q$ only makes sense if $t_1+t_2=1$. The important thing here is that the operation is independent of the choice of coordinate frame. If $t_1+t_2=1$, the point is just an interpolation on the line between the two points. If not, you have a leftover term that shifts the point around depending on where your coordinate origin is.
The idea here is that a point and a vector are not the same. A vector is a difference (displacement) between two points and doesn't have an anchor in the coordinate plane. You can translate it around, multiply it by any scalar and add it to any point because it's a displacement. But a point is a physical place in the plane. You can't multiply a place by a scalar (what's New York times 2?). But you can multiply a displacement (2 steps north times 2 = 4 steps north).
An interpolation is ok, because you are essentially taking $D=Q-P$, the displacement vector from P to Q. Now start at $P$ and go a fraction of this distance:
$$R=P+t_1(Q-P)=(1-t_1)P+t_1 Q$$
Notice how the sum of the coefficients is $1$.

Formally, you can imagine adding a third component (use homogeneous coordinates). A point has a form $(x,y,1)$ and a displacement is $(x,y,0)$. If your operation sets the third component to $1$, the result is a point, if it is $0$, the result is a vector, and if it's anything else, the result is neither of those things.


text:
Q: Can I access a submodule that is using the same name as an import? Consider this import:
from .scale_shape import scale_shape

https://github.com/has2k1/plotnine/blob/cbc50afaccb82e6f062034139cfc190fc49f81c5/plotnine/scales/__init__.py#L56-L59
Do I have any chance of accessing (reading and ideally, writing) the shapes variable here?
https://github.com/has2k1/plotnine/blob/cbc50afaccb82e6f062034139cfc190fc49f81c5/plotnine/scales/scale_shape.py#L11-L25
Any time I try to access plotnine.scales.scale_shape, I end up with the class, not the submodule, and while shapes is part of the submodule, it's not a member of the class. Is there another way to access .scale_shape instead of scale_shape in plotnine.shapes?


text:
Q: PHP Include Issue - Two includes don't work? I've been having issues with my PHP include function. So can anyone explain to me why this would work...
//testfile1.php
    <?php
        include 'file1.php';
    ?>

//testfile2.php
    <?php
        include 'file2.php';
    ?>

but this will NOT work..
//testfile.php
    <?php
        include 'file1.php';
        include 'file2.php';
    ?>

Is there anyway to include the second file within the main file? I'm suppose to streamline two php files into one main file and run that. (All files are on the same directory and can 'see' each other no problem.)

A: Try changing your include statements to include_once. Look for includes within your included files and change them also.
If file1.php also includes file2.php itself, and file 2 had a function declaration, you could be re-declaring a function with the same name.

A: Looks like you're overlapping include with files which are probably being included twice or not at all. In this case you need to use either
include_once() instead of include()
You can also use
require_once() instead of include() //use this option if the include is required


text:
Q: Android startActivityForResult, setResult, onActivityResult not called I started a phone call Activity requesting for result:
    Intent intentcall = new Intent();
intentcall.setAction(Intent.ACTION_CALL);
intentcall.setData(Uri.parse("tel:" + phoneNumber));
this.startActivityForResult(intentcall, REQUEST_SLIPDROP_ICON_OFF);

And then set the result in phone call listener like this:
    private class MyPhoneStateListener extends PhoneStateListener{
     public void onCallStateChanged(int state, String incomingNumber) {

         super.onCallStateChanged(state, incomingNumber);

         switch (state) {
             case TelephonyManager.CALL_STATE_IDLE:
                                   setResult(Activity.RESULT_OK);
                                   break;

Finally I want to turn off the icon in onActivityResult, but nothing happens.
    switch (requestCode) {

    case REQUEST_SLIPDROP_ICON_OFF:
        Log.d("request icon off", "request icon off");

        if (resultCode == Activity.RESULT_OK) {

            changeMenuItem(R.id.fall, R.drawable.fall);
            slipAndDropIconOn = false;

        }

        break;

Anything wrong?  Please advise!  thank you

A: I don't think this action returns a result so calling startActivityForResult is no different to calling startActivity
Note here: output = None.
http://developer.android.com/reference/android/content/Intent.html#ACTION_CALL


text:
Q: Non-linear differential equation I What is the solution to the non-linear differential equation
$$
\frac{d^2 y}{dx^{2}} = \left( \frac{2 y -1}{y^2 + 1} \right) \, \left( \frac{dy}{dx} \right)^2\ \text{ ?}
$$
I would suspect it has a connection to the inverse tangent function, but the trick of getting there seems to be elusive.

A: Let $z=dy/dx$ then we can rewrite the equation as,
$$ \frac{dz}{dx} = \frac{2y-1}{y^2+1} z^2,$$
and using the chain rule we can write $dz/dx = dy/dx \times dz/dy = z\times dz/dy$ ,
$$ z \frac{dz}{dy} = \frac{2y-1}{y^2+1} z^2,$$
$$  \int_{z_0}^z \frac{dz'}{z'} = \int_{y_0}^y \frac{2y'-1}{y'^2+1} dy'.$$
Once we have $z(y)$ from the above we can obtain $y(x)$ by integration of the equation $z=dy/dx$.


text:
Q: Spring Boot One to Many Issue in Intellij I have a problem about showing genre list when I get all values from getAllMovie function after I create a movie object.
While I can see a director's name, I cannot see any information about genres.
If the problem comes from relation mappping or anywhere , How can I fix it?
Here is the project Link : Project Link
Here is my Movie class.
public class Movie implements Serializable {

@OneToMany(mappedBy="movie",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private Set<Genre> genres = new HashSet<>();

@ManyToOne(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn
private Director director;
}

Here is Director class.
public class Director implements Serializable {

@OneToMany(mappedBy="director",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private Set<Movie> movies;

}

Here is Genre Class.
public class Genre implements Serializable {

@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn
private Movie movie;

}

Here is my updateMovie test Function
@Test
    void updateMovieById() throws ParseException {

        createMovie();

        Long id = 1L;
        Movie movie = movieService.findById(id).get();

        movie.setName("Movie B");
        movie.setRating(7.5);

        Director movieDirector = new Director();
        movieDirector.setName("Director 2");
        movie.setDirector(movieDirector);

        LocalDate now = Utils.formatDate(LocalDate.of(2019, Month.JANUARY, 1));
        movie.setCreatedAt(now);

        Genre genreFirst = new Genre();
        genreFirst.setName("Historical");
        genreFirst.setMovie(movie);

        Genre genreSecond = new Genre();
        genreSecond.setName("Horror");
        genreSecond.setMovie(movie);

        Set<Genre> genres = new HashSet<>();
        genres.add(genreFirst);
        genres.add(genreSecond);

        movie.setGenres(genres);

        Movie updatedMovie = movieService.update(id,movie);

        assertThat(updatedMovie.getId()).isGreaterThan(0);
    }

Here is my getAllMovies function.
@Test
void getAllMovies() throws ParseException {

   createMovie();

   List<Movie> movieList =  movieService.findAll();

   assertThat(movieList.size()).isGreaterThan(0);
}


text:
Q: Definitions of the operator norm of a matrix I understand that the operator norm of a matrix is induced by the vector norm, and is given by
$$
\|A\|_{\rm op} = \max_{\|x\| = 1}\|Ax\|
$$
However, in a lecture, I see the operator norm being mentioned as the following.
$$
\|A\|_{\rm op} = \max_{\|z\| = 1}|z^{\rm T}Az|
$$
Note that in the latter definition we have the absolute value (as $z^{\rm T}Az$ is a scalar).
For context, we know that $A$ is a real symmetric matrix with entries in $\{-1,1\}$. I am not able to see how these two definitions are the same. Any help would be amazing. Thanks!

A: If $A$ is real and symmetric, then $A$ is orthogonally diagonalisable with real eigenvalues. That is, there exists an orthonormal basis of eigenvectors $v_1, \ldots, v_n$, with respective eigenvalues $\lambda_1, \ldots, \lambda_n \in \Bbb{R}$. An arbitrary vector $x$ can be represented as a linear combination of this basis:
$$x = a_1 v_1 + \ldots + a_n v_n.$$
We have, using Pythagoras's theorem,
$$\|x\|^2 = \|a_1 v_1\|^2 + \ldots + \|a_n v_n\|^2 = |a_1|^2 + \ldots + |a_n|^2.$$
Applying $A$, we also get
\begin{align*}
\|Ax\|^2 &= \|a_1 Av_1 + \ldots + a_n Av_n\|^2 \\
&= \|a_1 \lambda_1 v_1 + \ldots + a_n \lambda_n v_n\|^2 \\
&= |a_1|^2 |\lambda_1|^2 + \ldots + |a_n|^2 |\lambda_n|^2.
\end{align*}
So, the problem of finding $\max_{\|x\| = 1} \|Ax\|^2$ is equivalent to maximising $|a_1|^2 |\lambda_1|^2 + \ldots + |a_n|^2 |\lambda_n|^2$, subject to $\|(a_1, \ldots, a_n)\| = 1$ (with the Euclidean norm). This quantity is maximised by biasing towards the largest value of $|\lambda_i|$, i.e. if $|\lambda_i| \ge |\lambda_j|$ for all $j$, then we get the maximum by setting $a_i = 1$ and each other $a_j = 0$.
In other words, any vector $x$ in the unit sphere which maximises $\|Ax\|^2$ is inevitably an eigenvector corresponding to one of the largest eigenvalues (in the sense that the absolute value is greatest). The actual maximum of $\|Ax\|^2$ is $|\lambda|^2$, where $\lambda$ is the largest eigenvalue. Thus, the operator norm $\|A\|$ by this definition should be $|\lambda|$.
Next, let's consider $\max_{\|x\|=1}|x^\top Ax|$. Let's keep the above linear combination for $x$ as before. Remembering that $v_1, \ldots, v_n$ is orthonormal, we get
\begin{align*}
|x^\top Ax| &= |x \cdot (Ax)| \\
&= |(a_1 v_1 + \ldots + a_n v_n) \cdot (a_1 \lambda_1 v_1 + \ldots + a_n \lambda_n v_n)| \\
&= |\lambda_1 a_1^2 + \ldots + \lambda_n a_n^2|.
\end{align*}
In similar fashion, we restrict $a_1^2 + \ldots + a_n^2 = 1$. If we have a largest eigenvalue $\lambda_i$, then
$$|\lambda_1 a_1^2 + \ldots + \lambda_n a_n^2| \le |\lambda_1| a_1^2 + \ldots + |\lambda_n| a_n^2 \le |\lambda_i|(a_1^2 + \ldots + a_n^2) = |\lambda_i|,$$
an upper bound which is again achieved when $x$ is a corresponding eigenvalue $v_i$. Again, the maximum is simply the modulus of the largest eigenvalue, which agrees with the previous definition.

A: Since by the spectral theorem every real symmetric can be diagonalized as $Q^T D Q$ with $Q$ orthogonal and $D$ a real diagonal matrix, we can write the second definition as
$$\|A\| = \max_{\|z\| = 1} ~ z^T A z = \max_{\|z\| = 1} ~z^T Q^T D A z = \max_{\|z\| = 1} ~(Qz)^T D (Qz) $$
But if we recall that every orthogonal matrix is an isometry (i.e. length-preserving and invertible), we know that $Qz$ returns a unit vector $y$ (and furthermore, for every unit vector $y$, there exists a unique $z$ such that $Qz = y$). Hence, maximizing $(Qz)^T D (Qz)$ over all unit vectors $z$ is equivalent to maximizing $y^T D y$ over all unit vectors $y$. Let the diagonal entries $d_i$ be arranged in decreasing order of absolute value, and let the $i$th entry of $y$ be $y_i$. Then we wish to maximize
$$|y^T D y| = |d_1 y_1^2 + d_2 y_2^2 + \cdots + d_n y_n^2|, ~~\text{ subject to } y_1^2 + y_2^2 + \cdots + y_n^2 = 1$$
To see when the above inequality is maximized, note that the triangle inequality says that
$$|d_1 y_1^2 + d_2 y_2^2 + \cdots + d_n y_n^2| \leq |d_1|y_1^2 + \cdots + |d_n| y_n^2 \leq |d_1| (y_1^2 + \cdots + y_n^2) = |d_1|$$
And we can observe that equality is obtained by choosing $y_1 = 1$ and the rest of the $y_i$ to be zero. In this definition, the operator norm is the the absolute value of the largest eigenvalue.
So why is the second definition the same? It's because
$$\|A x\| = \sqrt{(A x)^T (Ax)} = \sqrt{x^T (A^T A ) x} = \sqrt{x^T A^2 x}$$
since $A$ is symmetric. But as $A^2$ is a symmetric matrix, we can use what we found in the previous section to conclude that the maximum of $x^T A^2 x$ over all unit $x$ is the absolute value of the largest eigenvalue of $A^2$. But that is exactly the square of the largest eigenvalue of $A$, so in taking the square root we see that the definitions do indeed match up.


text:
Q: Changing the size of a scrollbar in tkinter(using grid layout) I'm making a Tkinter GUI that allows you to query a database and will display results in a scrollable frame. However, when you produce the results the scrollbar will not adjust to match the new size of the frame. How can I get the scrollbar to be able to display all of the results? I've put together a quick and dirty version of the code to demonstrate the problem I'm having.
import tkinter as tk

def Lookup():
    list = frame_buttons.grid_slaves()
    for l in list:
        l.destroy()
    for x in range(1000):
        tk.Label(frame_buttons, text="test", background="white").grid(row=x)

root = tk.Tk()
root.grid_rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)

frame_main = tk.Frame(root, bg="white")
frame_main.grid(row = 0,sticky='news')
frame_input = tk.Frame(frame_main, background = "white")
frame_input.grid(row=0, column=0, pady=(5, 0), sticky='nw')

tk.Button(frame_input, text="Search", fg="black", background = "grey",command=Lookup).grid(row=3, column=0,sticky='nw')

# Create a frame for the canvas with non-zero row&column weights
frame_canvas = tk.Frame(frame_main)
frame_canvas.grid(row=1, column=0, pady=(5, 0), sticky='nw')
frame_canvas.grid_rowconfigure(0, weight=1)
frame_canvas.grid_columnconfigure(0, weight=1)
# Set grid_propagate to False to allow 5-by-5 buttons resizing later
frame_canvas.grid_propagate(False)

# Add a canvas in that frame
canvas = tk.Canvas(frame_canvas, bg="gray")
canvas.grid(row=0, column=0, sticky="news")

# Link a scrollbar to the canvas
vsb = tk.Scrollbar(frame_canvas, orient="vertical", command=canvas.yview)
vsb.grid(row=0, column=1, sticky='ns')
canvas.configure(yscrollcommand=vsb.set)
frame_buttons = tk.Frame(canvas, bg="gray")
canvas.create_window((0, 0), window=frame_buttons, anchor='nw')
for x in range(15):
    tk.Label(frame_buttons, text="blah", background = "white").grid(row=x)
frame_buttons.update_idletasks()
frame_canvas.config(width=500, height=100)
canvas.config(scrollregion=canvas.bbox("all"))
root.mainloop()

this initially puts 20 labels in the scroll region, which is enough to activate the scrollbar. Then when you click search it replaces those 20 lables with 1000 test labels. But only the first 20 will be viewable.

A: You need to reset the scrollregion whenever the frame changes size and the items are redrawn.
The normal way to do that is to bind to the <Configure> event of the frame so that it happens automatically as the frame grows and shrinks.
Example:
def reset_scrollregion(event):
    canvas.config(scrollregion=canvas.bbox("all"))
...
frame_buttons.bind("<Configure>", reset_scrollregion)


text:
Q: Sum elements of a list between zeros in Python I have a list:
lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]

And I need the sum of the elements between the 0s in a new list.
I tried
lst1 = []
summ = 0
for i, elem in enumerate(lst):
    if elem != 0:
        summ = summ + elem
    else:
        lst1.append(summ)
        lst1.append(elem)
        summ = 0

but it returns [11, 0, 0, 0, 57, 0], while I expect
[11, 0, 0, 57, 0, 8]

A: Here's one way to this with itertools.groupby and a list comprehension. The grouping is done by checking if an element is zero, and if not zero, all items in the group are summed:
from itertools import groupby

lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]
f = lambda x: x==0
result = [i for k, g in groupby(lst, f) for i in (g if k else (sum(g),))]
print(result)
# [11, 0, 0, 57, 0, 8]

And of course, if items in your list are only numbers (to avoid generalising and introducing ambuigities), the lambda can be replaced with bool:
result = [i for k, g in groupby(lst, bool) for i in ((sum(g),) if k else g)]

A: you are appending extra summ when its 0, and missing 1 summ at the end
lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]
lst1 = []
summ = 0
for i, elem in enumerate(lst):
    if elem != 0:
        summ = summ + elem
    else:
        if summ:
            lst1.append(summ)
        lst1.append(elem)
        summ = 0

if summ:
    lst1.append(summ)
# lst1 = [11, 0, 0, 57, 0, 8]

A: Just add an extra lst1.append(summ)  after the loop
lst1 = []
summ = 0
for i, elem in enumerate(lst):
    if elem != 0:
        summ = summ + elem
    else:
        if summ:
            lst1.append(summ)
        lst1.append(elem)
        summ = 0
lst1.append(summ)


text:
Q: transform rotate(-90deg) change left position i have this problem with the rotation of a element.
this is what i done

12

1234

1234567

9876545

12345678910654

why the position of div change by the string lenght??

A: You can set the transform-origin in your css:

12

1234

1234567

9876545

12345678910654

MDN reference


text:
Q: loading UITableView in tab based iPhone application? i have a problem while loading a UITableView on UITabBarController, i got this error while loading table using tab
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
my code is here
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

// Return the number of sections.
return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

// Return the number of rows in the section.
return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...

return cell;
}

i tried many, it may be simple.. anyone please help me?

A: //Editing in your code, it should work.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell==nil)
    {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    return cell;
}

A: The problems is that you are using dequeueReusableCellWithIdentifier but you have no code to handle if this returns nil (i.e. when no cells have yet been created to be re-used).
For example:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];


text:
Q: How to get jar library name and version from String library name? I have many jar files in my directory:

*

*some-lib-2.0.jar

*some-lib-2.1-SNAPSHOT.jar

*some-lib-3.RELEASE.jar

*some-lib-R8.jar

*some-lib-core-1.jar

*some-lib-2.patch2.jar

*some-lib-2-alpha-4.jar

*some-lib.jar

*some-lib2-4.0.jar

How can I get library name and version from file name?
Is regex ((?:(?!-\d)\S)+)-(\S*\d\S*(?:-SNAPSHOT)?).jar$ valid for extract name and version?

A: The version number in the JAR file name is merely a convention and a default for Maven-built JARs.  It may have been overridden, and it is not always reliable reading the version number from just the file name.
A more reliable way for reading version number from JAR is to look inside the JAR file.  Here you have a couple of options depending on how the JAR was built:

*

*look at META-INF/maven/.../pom.properies and pom.xml and read the version from that - this should be present for Maven-built binaries

*sometimes version number if present in META-INF/MANIFEST.MF under Specification-Version or Implementation-Version properties

If this fails, then fall back to reading version number from the JAR name since there is no other information available.

A: Naming policy could differ across different libraries, so you aren't able to extract name/version from package name using one rule, for details you should check project docs.
In case of Maven you are able to configure the final name of built artifact with finalName pom.xml configuration option. Maven docs provide nice introduction into pom structure. Below is the example from docs:
<build>
    ...
    <finalName>${artifactId}-${version}</finalName>
    ...
</build>


text:
Q: failed to parse xml which contain html character entities in java When xml consist of html character entities, it throwing exception like this
[com.ctc.wstx.exc.WstxLazyException] com.ctc.wstx.exc.WstxParsingException: Undeclared general entity "ensp"
at [row,col {unknown-source}]: [1,66475]

Is there any way declared general entity so that I doesnot have to deal with this exception.

A: If you can edit the XML you're parsing, and the XML has a DOCTYPE declaration at the begin of the document, you need to add an entity declaration for ensp:
<!ENTITY ensp " ">

If you can edit the XML, but it hasn't a DOCTYPE declaration, you can make up a generic one such as follows:
<!DOCTYPE root [
  <!ELEMENT root ANY>
  <!ENTITY ensp "Ὸ">
]>
... content ...

where root is replaced by the document element (the root element) of the XML data you have.
If you want to have all HTML entities expanded into numeric character entities (not just ensp), have a look at https://www.w3.org/TR/html5/single-page.html#named-character-references or http://sgmljs.net/docs/html5.html#named-character-references.
If you don't have access to or can't change or don't want to change the XML (such as when you're pulling it from a network), then you might have luck by using Java's JAXP API to develop a custom EntityResolver and have your XML parsing pipeline using your custom entity resolver  (cf. https://docs.oracle.com/javase/8/docs/api/org/xml/sax/EntityResolver.html).

A: The entity "ensp" is a space character entity, you could parse the XML/HTML for that attribute then replace with something different.
        File file = new File(yourFile);
        BufferedReader bufferedReader = new BufferedReader(file);

        StringBuilder stringBuilder = new StringBuilder();
        String inputLine;

        while ((inputLine = bufferedReader.readLine()) != null) {
            stringBuilder.append(inputLine);
        }

        String content = stringBuilder.toString();
        content = content.replace("ensp;", " ");

As an example.
Edit: Sorry mistook what you asked. This probably isn't the answer you are looking for.

A: Sounds like your missing some config for Woodstox XML parser:
https://medium.com/@cowtowncoder/configuring-woodstox-xml-parser-woodstox-specific-properties-1ce5030a5173

P_TREAT_CHAR_REFS_AS_ENTS (default: false): Normally character references (like &) are simply expanded and reported as part of character data; but if this property is set to true they will instead be reported as ENTITY tokens. This may occasionally be useful when trying to fully reproduce input representation of an XML document, including choice of escaping of special characters.
  NOTE: this only works for textual content — it is not possible to support for attribute values (as there are no separate tokens; attributes are accessible via START_ELEMENT token only)

Api docs:
http://fasterxml.github.io/woodstox/javadoc/5.0/com/ctc/wstx/api/WstxInputProperties.html#P_TREAT_CHAR_REFS_AS_ENTS


text:
Q: First time using Rubber to deploy Rails app on Amazon EC2 I am planning on using Rubber to deploy a Rails app on Amazon EC2. Do I need to install Ruby, Rails, Postgres, Nginx and Unicorn on the EC2 server before running Rubber? Or does Rubber do all of these installations on EC2? Please advise. Thanks.

A: Rubber is essentially a capistrano plugin to automate deployments to amazon EC2. You don't have to manually install any of these packages. Rubber will install them for you (in the bootstrap phase), all you need to do is find the right recipe (template). You can find the list of recipes from the rubber's github page.
https://github.com/rubber/rubber/tree/master/templates
For the exact configuration that you mentioned, the following template should work.
complete_unicorn_nginx_postgresql

A: Rubber is a bunch of capistrano recipes, so based in that definition you have to configure your server before use rubber, install Ngnix, ruby, rubygems, Unicorn, etc. But you also can create your custom capistrano rubber recipes in order to configure your server, take a look at this tutorial.
http://viget.com/extend/building-an-environment-from-scratch-with-capistrano-2


text:
Q: What is the difference between a first order compartment and diffusion Biologists use Compartment models to represent the flow and storage of fluids in an animals body. In tissue (like muscle) the diffusion of blood is more accurately represented by the diffusion equation: $dB/dt = -\operatorname{Div}(\operatorname{Grad}B)$. A first order compartment model would look like $dB/dt = - k  B$ where $k$ is the reciprocal "diffusion" time.
Are these two equations equivalent and in what limiting cases?

A: $\frac{\partial B}{\partial t} =- \operatorname{div}\nabla B$ is a partial differential equation: $B$ is a function of time and space coordinates, representing the concentration of blood per volume at various parts of tissue.
$dB/dt=-kB$ is an ordinary differential equation: $B$ is a function of time only, representing the total amount of blood within a compartment at time $t$. It says that the compartment loses some percentage of amount per unit time.
These are quite different models: one pays attention to the spatial distribution of blood and studies diffusion, the other works only with the total amount, and studies inflow/outflow. There is no direct way to get one from the other.
However, if  you consider many compartments with amounts $B_1,B_2,\dots$ which exchange blood according to the above (each giving up some $kB_n$ amount to its "neighbors"), then this system of ordinary equations begins to look like a PDE when the number of compartments is large (indeed, this is a space-discretization of the diffusion PDE).


text:
Q: How to download multiple files with the same name from html page? I want to download all the files named "listings.csv.gz" which refer to US cities from http://insideairbnb.com/get-the-data.html, I can do it by writing each link but is it possible to do in a loop?
In the end I'll keep only a few columns from each file and merge them into one file.
Since the problem was solved thanks to @CodeNoob I'd like to share how it all worked out:
page <- read_html("http://insideairbnb.com/get-the-data.html")

# Get all hrefs (i.e. all links present on the website)
links <- page %>%
  html_nodes("a") %>%
  html_attr("href")

# Filter for listings.csv.gz, USA cities, data for March 2019
wanted <- grep('listings.csv.gz', links)
USA <- grep('united-states', links)
wanted.USA = wanted[wanted %in% USA]
wanted.links <- links[wanted.USA]
wanted.links = grep('2019-03', wanted.links, value = TRUE)

wanted.cols = c("host_is_superhost", "summary", "host_identity_verified", "street",
                "city", "property_type", "room_type", "bathrooms",
                "bedrooms", "beds", "price", "security_deposit", "cleaning_fee",
                "guests_included", "number_of_reviews", "instant_bookable",
                "host_response_rate", "host_neighbourhood",
                "review_scores_rating", "review_scores_accuracy","review_scores_cleanliness",
                "review_scores_checkin" ,"review_scores_communication",
                "review_scores_location", "review_scores_value", "space",
                "description", "host_id", "state", "latitude", "longitude")

read.gz.url <- function(link) {
  con <- gzcon(url(link))
  df  <- read.csv(textConnection(readLines(con)))
  close(con)
  df  <- df %>% select(wanted.cols) %>%
    mutate(source.url = link)
  df
}

all.df = list()
for (i in seq_along(wanted.links)) {
  all.df[[i]] = read.gz.url(wanted.links[i])
}

all.df = map(all.df, as_tibble)

A: You can actually extract all links, filter for the ones containing listings.csv.gz and then download these in a loop:
library(rvest)
library(dplyr)

# Get all download links

page <- read_html("http://insideairbnb.com/get-the-data.html")

# Get all hrefs (i.e. all links present on the website)
links <- page %>%
  html_nodes("a") %>%
  html_attr("href")

# Filter for listings.csv.gz
wanted <- grep('listings.csv.gz', links)
wanted.links <- links[wanted]

for (link in wanted.links) {
  con <- gzcon(url(link))
  txt <- readLines(con)
  df <- read.csv(textConnection(txt))
  # Do what you want
}

Example:  Download and combine the files
To get the result you want I would suggest to write a download function that filters for the columns you want and then combines these in a single dataframe, for example something like this:
read.gz.url <- function(url) {
  con <- gzcon(url(link))
  df  <- read.csv(textConnection(readLines(con)))
  close(con)
  df  <- df %>% select(c('calculated_host_listings_count_shared_rooms', 'cancellation_policy' )) %>% # random columns I chose
    mutate(source.url = url) # You may need to remember the origin of each row
  df
}

all.df <- do.call('rbind', lapply(head(wanted.links,2), read.gz.url))

Note I only tested this on the first two files since they are pretty large


text:
Q: What type of variable do I use to store mathematical operator? I'm trying to put buttons that have operators on them, like / * +, etc. I want to store the operator in such a way that I can use it in an expression, like 1 var 2 = 8
I would like to avoid having to use a different method for each operator, so an operator var would be my best option, I think. Objective-C for iPhone

A: The usual OO way to do this is to create a class "mathOperator" that has a method "performOp" taking two parameters, then inherit different classes from it that represent the different operations. I'm not an expert in objective-C, so my syntax is probably a bit off, but I think you'd write something like:
result = [var On:arg1 And:arg2];

for example
result = [var On:2 And:3];

would set result to 5 or 6 depending on whether var was set to add or mul. The implementation would look like (again, very roughly):
@interface Add: mathOperator
-(int)On: (int)arg1 And: (int)arg2;
@end

...

@implementation Add
-(int)On:  (int)arg1 And: (int)arg2 {
    return arg1 + arg2;
}

and of course similar for the other operators:
@implementation Mul
-(int)On:  (int)arg1 And: (int)arg2 {
    return arg1 * arg2;
}

A: Read ch 5 in Cocoa Design Patterns. The approach used is to define "Command" classes that will perform each operation defined as a class method "execute". Then you can dynamically perform the operation by obtaining the appropriate class by using the following
commandName = [NSString stringWithFormat:@"MY%@Command", [commandString capitalizedString]];
commandClass = NSClassFromString(commandName);
result = [commandClass executeWithXValue:x yValue:y];

A: The way i'd do it is to make methods for each type of arithmatic and pass the numbers into them. Then instead of all that with the variable call the function.

A: There's no such thing in C.  You'll have to use a selector which invokes a method to do what you want.


text:
Q: Azure Pipeline connect to SQL DB using service principal After my azure pipeline has create an azure sql db I'd like execute some sql.
The sql in question must be executed by an AAD authenticated user.
The service connection for the pipeline is an AAD authenticated user of the database.
If Im willing for the script to consume the service principals secret, then I can construct an OAuth call to retrieve a bearer token and use that to connect to the database.
However since the powershell script is running in the context of the service principal I have a gut feeling there is a better way to connect to the db using the service principal without relying on the secret.
Any ideas how I can do this?

A: The solution is went with was:
I added an Azure CLI task which retrieved the bearer token. I then passed this to Azure Powershell task which used the token.
$token= & az account get-access-token --resource=https://database.windows.net --query accessToken
Write-Host("##vso[task.setvariable variable=sqlToken]$token")

A: You can try below scripts in azure powershell task of your azure pipeline to get the accesstoken for Resource https://database.windows.net/
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext

$databaseAccessToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://database.windows.net/").AccessToken

$databaseAccessToken


text:
Q: jquery elements with django forms I am using jquery elements that a user can drag and drop. I post the order of the elements  to django using ajax.
Inside the django view I am able to work with the data that is posted from ajax.
Django views:
#this is the view where the jquery elements are being ordered by the user
def inside_exam(request):

    if request.method=='POST':
        form = MyForm(request.POST)
        if form.is_valid():
           #here I am able to retrieve the data from ajax and save it to a django model, code not shown here

           return redirect('exam_results')

#the view redirected to from the inside_exam view
def exam_results(request):

    #here I set the score for the exam and set the context, code not shown here

    print("all is set")
    return render(request, 'quizresults.html', context)

The print("all is set") is executed and I am able to print the html for quizresults.html in the browser. No errors are in the terminal window and this is shown in the terminal: "GET /exam_results/ HTTP/1.1" 200 8981.
But the same template is still shown, it is not showing the quizresults.html template. Any idea why the render(request, 'quizresults.html', context) is not working as expected?
By the way: when I use a django form without the jquery, everything works fine and the quizresults.html template is shown.
Since I want to show the user another template, but not update the current template, is ajax maybe not the correct way to send the jquery data in this case? If not, what would be a better way?
Edit, ajax code:
function dataToSend() {
    {% load static %}
     var node2 = document.getElementById('sortable');
     var idsInOrder = $("#sortable").sortable('toArray');
     console.log("the ids");
     console.log(idsInOrder);

     var fd = new FormData();
     for(var i=0; i<idsInOrder.length; i++) {
          j = i+1
          fd.append('a'+j, idsInOrder[i]);
     }

     $.ajax({
       type: 'POST',
       data: fd,
       cache: false,
       processData: false,
       contentType: false
     }).done(function(data) {
       //The data from the quizresults.html template is printed out here, but that template is not shown, the template in the browser is still the insidequiz.html template.
       console.log("the data");
       console.log(data);
     });
 }

 window.onload = function init() {
     function getCookie(name) {
       var cookieValue = null;
       if (document.cookie && document.cookie !== '') {
         var cookies = document.cookie.split(';');
         for (var i = 0; i < cookies.length; i++) {
           var cookie = jQuery.trim(cookies[i]);
           if (cookie.substring(0, name.length + 1) === (name + '=')) {
             cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
             break;
           }
         }
       }
       return cookieValue;
     }

     var csrftoken = getCookie('csrftoken');

     function csrfSafeMethod(method) {
         return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
     }
     $.ajaxSetup({
         beforeSend: function(xhr, settings) {
             if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
             }
         }
     });
};

A: Using redirect shortcut method in Django will return a HttpResponseRedirect object back to the AJAX, which it will be processed as a 302 Found status code, which then will make another request to the redirected resource and get the content. This does not seem to be the right way to do it, even though you get the content.
You can use the method exam_results to do the other work and return the required context, which shall be used to return the HttpResponse object using render method.
Then, with the data you get, you can replace the document with the template you receive.
Solution:
# views

#this is the view where the jquery elements are being ordered by the user
def inside_exam(request):
    if request.method=='POST':
        form = MyForm(request.POST)
        if form.is_valid():
           #here I am able to retrieve the data from ajax and save it to a django model, code not shown here

           context = exam_results(request)

           return render(request, 'quizresults.html', context)

# method to set the score for the exam
# return context from this method
def exam_results(request):

    #here I set the score for the exam and set the context, code not shown here

    # build context
    return context

 # javascript

     $.ajax({
       type: 'POST',
       data: fd,
       cache: false,
       processData: false,
       contentType: false
     }).done(function(data) {
       //The data from the quizresults.html template is printed out here, but that template is not shown, the template in the browser is still the insidequiz.html template.
       console.log("the data");
       console.log(data);

       // replace the page with the new template
       var newDoc = document.open("text/html", "replace");
       newDoc.write(data);
       newDoc.close();

       // update the url
       window.history.pushState('', 'title', "newurl");
     });

Ref: History API MDN

A: I figured that ajax makes things complicated when it comes to redirecting. What I ended up doing was to create an HTML form (that is hidden) and then post that form to a url using javascript. No need for ajax.
HTML code:
 <form id="form1" action='{% url 'inside_exam' %}' method="post" style="display:none;">
   {% csrf_token %}
 </form>

 <p> <button type='submit' style="visibility" class="button button-long button-primary" onclick="sendData(this);">Send</button></p>

javascript code:
function sendData() {
  var idsInOrder = $("#sortable").sortable('toArray');
  var form = document.getElementById('form1');
  for(var i=0; i<idsInOrder.length; i++) {
      j = i+1
      var hiddenField = document.createElement("input");
      hiddenField.setAttribute("type", "hidden");
      hiddenField.setAttribute("name", 'a'+j);
      hiddenField.setAttribute("value", idsInOrder[i]);

      form.appendChild(hiddenField);
  }
  console.log("form is:");
  console.log(form);

  form.submit();
}


text:
Q: HttpClient.PostAsJsonAsync using private members instead of public properties I have a client that is POSTing to a Web API. When the POST content is received the JSON is using the private member names for properties instead of the public properties.  (the Client app is using the Asp.Net-Web-api2 library and the Web API itself is implemented using an IHttpHandler on IIS7.5 and is not a MVC style app, also the code was working with the existing Usage class prior to a TFS mishap which caused me to recode and now the odd behavior)
//Object I am passing
[Serializable]
public class Usage
{
   private string _user;
   private string _trackingUnit;

   public string User {get {return _user;} set {_user = value;}}
   public string TrackingUnit { get{return _trackingUnit;} set { _trackingUnit = value;}}
}

I make the post using the following
Usage usage = new Usage();
usage.User = "pete";
usage.TrackingUnit = "unit of work";

HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync(url, usage);

I am receiving the POST using the following
byte[] postData = context.Request.BinaryRead(context.Request.ContentLength);
string strData = Encoding.UTF8.GetString(postData);
Usage newUsage = JsonConvert.DeserializeObject<Usage>(strData);

When I examine the strData it looks like the following, which causes the Deserialization to return an unpopulated Usage object
{"_user":"pete","_trackingUnit":"unit of work"}

I would expect
{"User":"pete","TrackingUnit":"unit of work"}

Notes:
If i new up a new Usage object and try to Serialize it inside the Web API and return the string it is formatted correctly
JsonConvert.SerializeObject(usage);

{"User":"pete","TrackingUnit":"unit of work"}

Also if I try to JsonConvert.Serialize in the client application it also works as expected

A: The reason you are seeing this is is that your framework uses json.net for JSON serialization, and somewhere in the code base the option DefaultContractResolver.IgnoreSerializableAttribute has been set to false.  When this setting, Json.NET will serialize the public and private fields of a type marked as [Serializable] -- which yours is.
To confirm where this is happening we can check the reference source.  Firstly, HttpClientExtensions.PostAsJsonAsync<T>() serializes to JSON using a freshly constructed JsonMediaTypeFormatter:
public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken)
{
    return client.PostAsync(requestUri, value, new JsonMediaTypeFormatter(), cancellationToken);
}

It's base class BaseJsonMediaTypeFormatter in turn has an internal IContractResolver _defaultContractResolver of type JsonContractResolver which, in its constructor, sets
// Need this setting to have [Serializable] types serialized correctly
IgnoreSerializableAttribute = false;

So that's the source of your problem.
Your options to work around this problem are as follows.
Firstly, if you are willing to add a Json.NET dependency to your models, you could mark your type with [JsonObject]
[Serializable]
[JsonObject]
public class Usage
{
    private string _user;
    private string _trackingUnit;

    public string User {get {return _user;} set {_user = value;}}
    public string TrackingUnit { get{return _trackingUnit;} set { _trackingUnit = value;}}
}

This overrides [Serializable] by resetting JsonObjectAttribute.MemberSerialization to its default value MemberSerialization.OptOut.
Secondly, you could annotate your type with data contract attributes, which Json.NET respects:
[Serializable]
[DataContract]
public class Usage
{
    private string _user;
    private string _trackingUnit;

    [DataMember]
    public string User {get {return _user;} set {_user = value;}}
    [DataMember]
    public string TrackingUnit { get{return _trackingUnit;} set { _trackingUnit = value;}}
}

Note that data contract serialization is opt-in so you will need to annotate every member to be serialized.
Thirdly, you could remove [Serializable] -- but in your question you indicate that's not an option.
Finally, you could make your own extension methods based on the reference source that replace those in HttpClientExtensions and serialize your object with IgnoreSerializableAttribute = true, e.g. (not tested):
public static class MyHttpClientExtensions
{
    static JsonMediaTypeFormatter CreateJsonMediaTypeFormatter()
    {
        var JsonMediaTypeFormatter = new JsonMediaTypeFormatter();
        // Use the provided JsonContractResolver but reset IgnoreSerializableAttribute
        ((DefaultContractResolver)JsonMediaTypeFormatter.SerializerSettings).IgnoreSerializableAttribute = true;
        return JsonMediaTypeFormatter;
    }

    public static Task<HttpResponseMessage> MyPostAsJsonAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)
    {
        return client.PostAsync(requestUri, value, CreateJsonMediaTypeFormatter(), cancellationToken);
    }

    // Replace other JSON methods as required.
}


text:
Q: After changing kernel , kernel crash is not working I have changed the kernel in Ubuntu 12.04.
After this, if I gave a kernel crash the memory configurations are getting changed and dump file is not created.. It is getting changed from 4GB to 109MB.
I am not able to find crashkernel in
cat /proc/cmdline

and /sys/kernel/kexec_crash_loaded is resetting to 0.
How to solve it ?

A: I took these hints from this recipe https://wiki.ubuntu.com/Kernel/CrashdumpRecipe

Increase the allocation by changing crashkernel= on the grub command
  line or in /boot/grub/grub.cfg (for grub2) or /boot/grub/menu.lst (for
  old grub). To avoid losing the settings when running update-grub the
  change can be made in /etc/grub.d/10_linux.


text:
Q: html tags decoded as special characters in column The html characters from UI is escaped and stored as special character in the Teradata DB.
Am looking for a function in Teradata which is similar to dbms_xmlgen.convert or UTL_I18N.UNESCAPE_REFERENCE in oracle.
SELECT UTL_I18N.UNESCAPE_REFERENCE('It' ') FROM DUAL

In oracle would give
It' .
Any Teradata equivalent function to achieve this?


text:
Q: FountainJS Angular2 installing component angular2-google-maps issue I use fountainJS Angular2 generator with Typescript and Systems.js
for scaffolding the project.
https://github.com/FountainJS/generator-fountain-angular2
But I got the issue, I can't add the component to the project.
When I put import {GOOGLE_MAPS_DIRECTIVES}
I get this error
system.src.js:1057 GET http://localhost:3000/node_modules/angular2-google-maps/core/index.js 404 (Not Found)

I went through that
https://angular-maps.com/docs/getting-started.html
'getting started' section and added some code to jspm.config.js file but I don't have angular-cli-build.js file inside my project.
My jspm.config.js
SystemJS.config({
  packageConfigPaths: [
    'npm:@*/*.json',
    'npm:*.json',
    'github:*/*.json'
  ],
  map: {
    'angular2-google-maps': 'node_modules/angular2-google-maps',
    '@angular/common': 'npm:@angular/common@2.0.0-rc.4',
    '@angular/compiler': 'npm:@angular/compiler@2.0.0-rc.4',
    '@angular/core': 'npm:@angular/core@2.0.0-rc.4',
    '@angular/http': 'npm:@angular/http@2.0.0-rc.4',
    '@angular/platform-browser': 'npm:@angular/platform-browser@2.0.0-rc.4',
    '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic@2.0.0-rc.4',
    '@angular/router': 'npm:@angular/router@3.0.0-beta.2',
    'es6-shim': 'npm:es6-shim@0.35.1',
    'os': 'github:jspm/nodelibs-os@0.2.0-alpha',
    'process': 'github:jspm/nodelibs-process@0.2.0-alpha',
    'reflect-metadata': 'npm:reflect-metadata@0.1.3',
    'rxjs': 'npm:rxjs@5.0.0-beta.6',
    'ts': 'github:frankwallis/plugin-typescript@4.0.16',
    'zone.js': 'npm:zone.js@0.6.17'
  },
  packages: {
    'angular2-google-maps/core': {
      defaultExtension: 'js',
      main: 'index.js' // you can also use core.umd.js here, if you want faster loads
    },
    'github:frankwallis/plugin-typescript@4.0.16': {
      'map': {
        'typescript': 'npm:typescript@1.8.10'
      }
    },
    'github:jspm/nodelibs-os@0.2.0-alpha': {
      'map': {
        'os-browserify': 'npm:os-browserify@0.2.1'
      }
    }
  }
});

A: You are getting node_modules/angular2-google-maps/core/index.js 404 (Not Found) because node_modules is not made available by web server used by npm run serve.
If you need node_modules to be accessible by client code, you have to add route for it in conf/browsersync.conf.js:
  routes: {
    '/node_modules': 'node_modules',

Alternatively, you could use jspm instead of npm to install angular2-google-maps:
jspm install angular2-google-maps

and jspm would modify jspm.config.js to add correct mapping for angular2-google-maps.
BUT, after 404 error is fixed, I'm getting now
system.src.js:123 Uncaught (in promise) Error: (SystemJS) core_1.NgModule is not a function
TypeError: core_1.NgModule is not a function

which probably means that the latest angular2-google-maps is incompatible with angular2-rc4 installed by generator-fountain-angular2.


text:
Q: Buy games from Blizzard by USD I from Mongolia, which is EU region by Battle.net. When I see payment options I only see RUB there. But we don't use RUB (russian currency). So problem is, since i don't have RUB visa card, I only can pay USD. But if I change my region into US, price will become 39$, almost 4 times expensive than RUB payment option.
So my question is, can I put some USD in my card and purchase game from Blizzard which is price in RUB? They convert it?
EDITED/ADDED
When I use both EU, and US sites, prices are different.
https://eu.battle.net/shop/en/product/starcraft-ii-wings-of-liberty
https://us.battle.net/shop/en/product/starcraft-ii-wings-of-liberty
On EU its 499 RUB (14$), on US its 39.99$. Why price have this much difference? Don't you think everyone buy cheaper one from eu.battle.net? Also I wonder If I buy from EU.battle.net will they give me only Russians usable client?

A: Yes, you can buy the game with your USD card even if it is priced in rubles. The fee will be based on the exchange rate for the two currencies.


text:
Q: Implementation angular plugin to nativescript-vue I am newbie with nativescipt-vue. I need to connect identity server with nativescript-vue. I found a plugin in this repo. But its developer gives only angular example. Can I use this plugin with nativescript-vue. Do you have any suggestion? Thank you in advance.

A: Good news: Most of 'things' developed on the top of NativeScript are interoperable, meaning that you can swap frameworks as desired.
Bad news: There is some problems of doing so. I've looked into the repository that you reported on the question and I saw that you have to deal with some Interfaces there.
export class AuthComponent implements OnInit { //...

Dealing with interfaces in NativeScript is a little bit confusing since you have to deal with classes in both NativeScript and Java in the same script.
The lack of documented behavior of this keyword, for example, can lead to some undesired behaviors. I am dealing with this problem right now. So, be careful.
Please provide us some parts of the code that you want to transpile to NativeScript-Vue.
Also, I highly recommend you to study how NativeScript works before understanding how NativeScript-Vue works. You are probably accessing the NS docs way more than NativeScript-Vue docs in a near future (assuming that you are already familiar with Vue).


text:
Q: Running Java Application using Popen I am running tika on my Linux server, and I want to run it using python (subprocess.Popen)
However, I have a non-root access, so I only have a local java installation. Every time I need to set the java home and path for each session :

export JAVA_HOME=/usr/java/jdk1.5.0_07/bin/java
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin

Then I can run tika from the java directory and save the output to some file out_txt.txt

curl www.vit.org/downloads/doc/tariff.doc   | java -jar
  tika-app-1.3.jar --text >out_txt.txt

So, I need to know how to use Popen to:

*

*set the java home and path using Popen

*write Tika output to the file out_txt.txt

A: 1) you could:

*

*use os.setenv('JAVA_HOME', '/usr/java/jdk1.5.0_07') before Popen, that would set the environment variable for all futre invocations. or for PATH:
os.environ['PATH'] += ":/usr/java/jdk1.5.0_07"

*pass an environment dict to Popen as env:
environ = os.environ.copy()
environ['JAVA_HOME'] = '/usr/java/jdk1.5.0_07'
environ['PATH'] += ':/usr/java/jdk1.5.0_07/bin'
subprocess.Popen(args, env=environ)

2)

*

*open the file for writing and pass it to Popen as stdout (and optionally stderr):
output = open(outfile, 'wb')
subprocess.Popen(args, stdout=output, stderr=output)

*leave it to the shell by passing shell=True to Popen:
Popen("curl www.vit.org/downloads/doc/tariff.doc | java -jar tika-app-1.3.jar --text >out_txt.txt", shell=True)


text:
Q: Automated Test Run - Python HTTPResponseNotReady() I am trying to create an automated test using python for testing a youtube API request and response and all of those happening in random quick timely manner.
What I have been getting is an unstable HTTP response from the server.
I am not using the same object for every connection as I made it in separate methods, but when testing it, I test it all in same method (i.e. call create,edit, and delete consecutively)
Here is the Error that I got.
  File "/var/lib/jenkins/shiningpanda/jobs/2a430f4f/virtualenvs/d41d8cd9/local/lib/python2.7/site-packages/oauth2client/client.py", line 490, in new_request
    redirections, connection_type)
  File "/var/lib/jenkins/shiningpanda/jobs/2a430f4f/virtualenvs/d41d8cd9/local/lib/python2.7/site-packages/httplib2/__init__.py", line 1570, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/var/lib/jenkins/shiningpanda/jobs/2a430f4f/virtualenvs/d41d8cd9/local/lib/python2.7/site-packages/httplib2/__init__.py", line 1317, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/var/lib/jenkins/shiningpanda/jobs/2a430f4f/virtualenvs/d41d8cd9/local/lib/python2.7/site-packages/httplib2/__init__.py", line 1286, in _conn_request
    response = conn.getresponse()
  File "/usr/lib/python2.7/httplib.py", line 1018, in getresponse
    raise ResponseNotReady()
ResponseNotReady

I was thinking that I should have a time.delay() between each HTTP request?
What do you guys think and suggest me to do on this case, since I am still learning on this matter?
Thank you for all the sugesstion and help ;)
Basic Idea of the Code I am using :
yt_service = gdata.youtube.service.YouTubeService()
yt_service.email = 'exampple@gmail.com'
yt_service.password = 'password'

def GetAndPrintUserUploads(username):
    yt_service = gdata.youtube.service.YouTubeService()
    uri = 'http://gdata.youtube.com/feeds/api/users/%s/uploads' % username
    PrintVideoFeed(yt_service.GetYouTubeVideoFeed(uri))

and for testing it I authenticate the user and print user upload a few time after that consecutively


text:
Q: Get source file path of a running python script from process id I have a process running in the background, a python one, with ps -ef I can see filename from running command : UID PID PPID ... python ./filename.py
How can I know where the file is located

A: pwdx < PID > gives full directory the process is running from.
So, the full script would be
ps -ef | grep 'your process' | awk '{print $2}' | xargs pwdx

Though, you can simplify this into
pgrep 'your process' | awk '{print $1}' | xargs pwdx


text:
Q: AzCopy Ignoring or recreating Checksum I'm using the Azure tool AzCopy to export data from table storage, modify the exported data, and then import the data into another table storage table.  I'm using the following command to export:
AzCopy /Source:https://MYSERVER/MYTABLE/ /SourceKey:SOURCEKEY /Dest:C:\migration /Manifest:MYTABLE

Since you cannot add a filter for the export, I'm filtering the data post-export, remove data from the JSON as necessary.  I'm then using the following command to import this data to another server:
AzCopy/Source:C:\export /Dest:https://MYOTHERSERVER/MYTABLE /DestType:Table /DestKey:DESTKEY /Manifest:MYTABLE EntityOperation:InsertOrReplace

These operations work fine when I do not manipulate the JSON file.  When I do, however, the contents of the file are, of course, changed and the checksum in the manifest file no longer matches.  When I go to do the import, I get a "file is corrupt" message.
Here is what the manifest file looks like:
"Version":2,"PayloadFormat":"Json","Checksum":5500917691400439101,"AccountName":"SERVER","TableName":"MYTABLE","Timestamp":"2017-08-25T14:10:53.7489755Z","SplitSize":0,"TotalDataFiles":1}

How can I get AzCopy to either not validate the checksum or replace the checksum?
I've tried the following code to recreate the checksum, but when I do on the original JSON, it does not match:
var md5Hash = getFileHash(file);
var checksum = convertHash(md5Hash);

private byte[] getFileHash(string filePath)
{
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(filePath))
        {
            return md5.ComputeHash(stream);
        }
    }
}

private string convertHash(byte[] data)
{
    var algorithm = MD5.Create();
    var result = BitConverter.ToUInt64(data,0);
    return result.ToString();
}

This returns 4500814390503865422.

A: AzCopy doesn't support skipping checksum validation during table import for now. BTW, the checksum recorded in manifest file is actually CRC rather than MD5, and it's calculated by aggregating CRC of all exported files rather than the single manifest file.


text:
Q: Can't locate Switch.pm in @INC in Ubuntu 16.04 LTS Here is one problem shown when I tried to make my android 2.3.7 OS sytem by typing make -j8 under the directory:
/home/paultsai/android/aosp-2.3.x/

Can't locate Switch.pm in @INC (you may need to install the Switch module) (@INC contains: external/webkit/WebCore/bindings/scripts /etc/perl /usr/local/lib/x86_64-linux-gnu/perl/5.22.1 /usr/local/share/perl/5.22.1 /usr/lib/x86_64-linux-gnu/perl5/5.22 /usr/share/perl5 /usr/lib/x86_64-linux-gnu/perl/5.22 /usr/share/perl/5.22 /usr/local/lib/site_perl /usr/lib/x86_64-linux-gnu/perl-base .) at external/webkit/WebCore/dom/make_names.pl line 38.
BEGIN failed--compilation aborted at external/webkit/WebCore/dom/make_names.pl line 38.
make: *** [out/target/product/generic/obj/STATIC_LIBRARIES/libwebcore_intermediates/WebCore/HTMLNames.h] Error 2
make: *** Waiting for unfinished jobs....
Can't locate Switch.pm in @INC (you may need to install the Switch module) (@INC contains: external/webkit/WebCore/bindings/scripts /etc/perl /usr/local/lib/x86_64-linux-gnu/perl/5.22.1 /usr/local/share/perl/5.22.1 /usr/lib/x86_64-linux-gnu/perl5/5.22 /usr/share/perl5 /usr/lib/x86_64-linux-gnu/perl/5.22 /usr/share/perl/5.22 /usr/local/lib/site_perl /usr/lib/x86_64-linux-gnu/perl-base .) at external/webkit/WebCore/dom/make_names.pl line 38.
BEGIN failed--compilation aborted at external/webkit/WebCore/dom/make_names.pl line 38.
make: *** [out/target/product/generic/obj/STATIC_LIBRARIES/libwebcore_intermediates/WebCore/HTMLElementFactory.h] Error 2
Can't locate Switch.pm in @INC (you may need to install the Switch module) (@INC contains: external/webkit/WebCore/bindings/scripts /etc/perl /usr/local/lib/x86_64-linux-gnu/perl/5.22.1 /usr/local/share/perl/5.22.1 /usr/lib/x86_64-linux-gnu/perl5/5.22 /usr/share/perl5 /usr/lib/x86_64-linux-gnu/perl/5.22 /usr/share/perl/5.22 /usr/local/lib/site_perl /usr/lib/x86_64-linux-gnu/perl-base .) at external/webkit/WebCore/dom/make_names.pl line 38.
BEGIN failed--compilation aborted at external/webkit/WebCore/dom/make_names.pl line 38.
make: *** [out/target/product/generic/obj/STATIC_LIBRARIES/libwebcore_intermediates/WebCore/V8HTMLElementWrapperFactory.h] Error 2
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Can anyone tell me how to fix these problems ?

A: Open a terminal (Ctrl-Alt-t) and then:
 sudo apt-get install libswitch-perl

or using cpan:
cpan

At the prompt cpan[1]>, type
install Switch


text:
Q: CSS3 Animation | Simple issue I have the following CSS code :
@keyframes hvr_shadow
{
    from
    {
        box-shadow: 0px 0px 4px rgba(60, 60, 60, 0.5);
    }

    to
    {
        box-shadow: 0px 0px 6px rgba(60, 60, 60, 0.8);
    }
}

@-moz-keyframes hvr_shadow /* Firefox */
{
    from
    {
        -moz-box-shadow: 0px 0px 4px rgba(60, 60, 60, 0.5);
    }

    to
    {
        -moz-box-shadow: 0px 0px 6px rgba(60, 60, 60, 0.8);
    }
}

@-webkit-keyframes hvr_shadow /* Safari and Chrome */
{
    from
    {
        -webkit-box-shadow: 0px 0px 4px rgba(60, 60, 60, 0.5);
    }

    to
    {
        -webkit-box-shadow: 0px 0px 6px rgba(60, 60, 60, 0.8);
    }
}

#gallery .fancybox
{
    border: 1px solid #333;
    display: block;
    padding: 0;
    margin: 0;
    height: 138px;
    -moz-box-shadow: 0px 0px 4px rgba(60, 60, 60, 0.5);
    -webkit-box-shadow: 0px 0px 0px rgba(60, 60, 60, 0.5);
box-shadow: 0px 0px 4px rgba(60, 60, 60, 0.5);
}

#gallery .fancybox:hover
{
    animation: hvr_shadow 700ms;
    -moz-animation: hvr_shadow 700ms; /* Firefox */
    -webkit-animation: hvr_shadow 700ms; /* Safari and Chrome */
    -o-animation: hvr_shadow 700ms; /* Opera */
}

While the animation is working, after a while the shadow auto return to primary settings.
How can I keep the settings of the animation while the mouse is still hovering the image ?
Here you can find a Fiddle demo : http://jsfiddle.net/haX8j/

A: This will solve your problem:
-webkit-animation: hvr_shadow  700ms .1s 1 ease-in-out normal forwards;
-moz-animation: hvr_shadow  700ms .1s 1 ease-in-out normal forwards;
-o-animation: hvr_shadow  700ms .1s 1 ease-in-out normal forwards;
animation: hvr_shadow  700ms .1s 1 ease-in-out normal forwards;

JS Fiddle: http://jsfiddle.net/haX8j/1/

A: Actually I think you are better off using a transition.  It's far simpler, it works with Firefox and it will fade out correctly when moving off the link:
.link
{
    -moz-box-shadow: 0px 0px 4px rgba(60, 60, 60, 0.5);
    -webkit-box-shadow: 0px 0px 4px rgba(60, 60, 60, 0.5);
    box-shadow: 0px 0px 4px rgba(60, 60, 60, 0.5);

    -moz-transition: all 0.7s;
    -webkit-transition: all 0.7s;
    -o-transition: all 0.7s;
    transition: all 0.7s;
}
.link:hover
{
    -moz-box-shadow: 0px 0px 6px rgba(60, 60, 60, 0.8);
    -webkit-box-shadow: 0px 0px 6px rgba(60, 60, 60, 0.8);
    box-shadow: 0px 0px 6px rgba(60, 60, 60, 0.8);
}

Here is a fiddle example.  I've made the shadow much bigger so you can see the effect more clearly: http://jsfiddle.net/DYdZs/


text:
Q: imagej always shows black images for an assignment I have to display an image using imagej in java. So I used the following code:
    FloatProcessor abc=new FloatProcessor(imageSizeX,imageSizeY);
        for (int i=0;i<imageSizeX;i++){
              for(int j=0;j<imageSizeY;j++){
              abc.putPixel(i, j, 100);
              }
        }
        ImagePlus im=new ImagePlus("test",abc);
        im.show();

but the Image I get is always completely black. Can you tell me what the mistake is?
It should at least be white if the value was 0 shouldn't it?
(FYI: imageSizeX=imageSizeY=256)

A: .putPixel uses the conversion Float.intBitsToFloat.
If you want a direct access to the pixels, you can use setf(int x, int y, float value).
Moreover, if you already have the pixels into an array, you can use the constructors to immediately set the pixel values FloatProcessor(int width, int height, int[] pixels).


text:
Q: Is it possible to set config settings on Firefox from a Addon I'm looking for a way to print from web without prompting the print dialog (I just made the question).
I found This method for Firefox and it seems to work, but it obviously will affect all websites. So I'm thinking of developing a Firefox Addon that makes this configuration to affect only specific websites.
I don't know nothing about building Firefox addons, but if it's possible to change settings this way I will learn how to do it.
So my question is.. Is it possible to set config settings on Firefox from a Addon and for specific websites?
Thanks a lot.

A: If you are going to develop a Firefox addon you could "easily" replace the print button and delegate to the standard print action on normal websites. For a list of URLs, i.e. your web site, you temporarily set print.always_print_silent to true and be done with it.
For modifying a preference in an addon you would something like this:
// Get the "accessibility." branch
var prefs = Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefService).getBranch("accessibility.");

// prefs is an nsIPrefBranch.
// Look in the above section for examples of getting one.
var value = prefs.getBoolPref("typeaheadfind");

// get a pref (accessibility.typeaheadfind)
prefs.setBoolPref("typeaheadfind", !value); // set a pref (accessibility.typeaheadfind)

(taken from this snippet).

A: One way is to provide your own implementation of the printing prompt service. You could then inspect the window being printed and turn on silent printing if you want to bypass the print dialog. You might need to retrieve the original service to handle the cases that you don't want to. I couldn't find much documentation but there's some related documentation here.


text:
Q: Browserify requires vendor module built with Browserify I'm having problem with Browserify requiring a vendor library.
The vendor library I'm using is better-dom, which is also built with Browserify. I installed it from bower and when I'm trying to built, I got:
Error: Cannot find module './utils' from '<...>/bower_components/better-dom/dist'

Apparently Browserify is trying to parse and process the requires statements in the pre-built library. I tried browserify-shim and modulify with no luck, other attempts are also included below. Any help is appreciated, thanks in advance.
My configuration:
package.json:
...
"browser": {
  "DOMLegacy": "./bower_components/better-dom/dist/better-dom-legacy.js",
  "DOM": "./bower_components/better-dom/dist/better-dom.js"
},
...

Gulpfile.js:
gulp.task('scripts', function() {
  var bundle = browserify({
    noparse: ["<...>bower_components/better-dom/dist/better-dom.js"]
  });

  bundle.add('./js/all.js');

  // bundle.external("./bower_components/better-dom/dist/better-dom-legacy.js");
  // bundle.external("./bower_components/better-dom/dist/better-dom.js");

  // bundle.transform({ modulify: {
  //   "./bower_components/better-dom/dist/better-dom-legacy.js": "DOMLegacy",
  //   "./bower_components/better-dom/dist/better-dom.js": "DOM"
  // }});

  // bundle.require(
  //   "./bower_components/better-dom/dist/better-dom-legacy.js",
  //   { expose: "DOMLegacy" });
  // bundle.require(
  //   "./bower_components/better-dom/dist/better-dom.js",
  //   { expose: "DOM" }
  // );

  return bundle.bundle()
    .on('error', function(e) {
      console.log(e.toString());
      this.emit('end');
    })
    .pipe(source('all.js'))
    .pipe(gulp.dest(paths.assets));
});

A: I just found out there is a bug in browserify 5 with the noparse option.
Workaround: use the old name of this option: noParse (still working in browserify 5)
var bundle = browserify({
    noParse: ["<...>bower_components/better-dom/dist/better-dom.js"]
});

It should fix your build.


text:
Q: Using rdb$get_context as default value for a column In a Firebird database, I need to create a DOMAIN with default value taken from the context variable.
It should be something like
CREATE DOMAIN USER_ID AS INTEGER
  DEFAULT RDB$GET_CONTEXT('USER_SESSION','UID') NOT NULL;

When I execute this, I am getting the following error

Invalid token.
  Dynamic SQL Error.
  SQL error code = -104.
  Token unknown - line 2, column 13.
  RDB$GET_CONTEXT.

How can this be done, maybe there is another way than the DEFAULT clause?

A: Just create a BEFORE INSERT trigger:
CREATE TRIGGER your_trigger_name FOR your_table
  BEFORE INSERT
  POSITION 0
AS
BEGIN
  IF (NEW.your_field IS NULL) THEN
    NEW.your_field = RDB$GET_CONTEXT('USER_SESSION','UID');
END


text:
Q: How do I call a procedure of another schema from the trigger of a different schema I am trying to create a trigger that logs all the ddl changes of a particular schema (Schema DS) and updates those changes in another schema (Schema SD).
CREATE OR REPLACE TRIGGER audit_ddl_trg AFTER DDL ON SCHEMA DECLARE
    sql_text   ora_name_list_t;
    v_stmt     VARCHAR2(2000);
    n          PLS_INTEGER;
BEGIN
    n := ora_sql_txt(sql_text);
    FOR i IN 1..n LOOP v_stmt := v_stmt || sql_text(i);
    END LOOP;

    v_stmt := regexp_replace(v_stmt, 'rename[[:space:]]+.*[[:space:]]+to[[:space:]]+([a-z0-9_]+)', '\1', 1, 1,
               'i');
    IF ( ora_sysevent = 'TRUNCATE' ) THEN
        NULL;
    ELSE
        INSERT INTO audit_ddl (
            d,
            osuser,
            current_user,
            host,
            terminal,
            owner,
            type,
            name,
            sysevent,
            statements
        ) VALUES (
            sysdate,
            sys_context('USERENV', 'OS_USER'),
            sys_context('USERENV', 'CURRENT_USER'),
            sys_context('USERENV', 'HOST'),
            sys_context('USERENV', 'TERMINAL'),
            ora_dict_obj_owner,
            ora_dict_obj_type,
            ora_dict_obj_name,
            ora_sysevent,
            v_stmt
        );

        sd.insert_log(sql_text);
    END IF;

END;
/

However, it does not seem to recognize the procedure. I tried creating a database link. But that doesn't work too. Is there anyway to get around this?

A: I suspect that you've got the trigger in one schema and the table in another, but I don't know which is which. Let's assume that AUDIT_DDL_TRIG is in schema DS and table AUDIT_DDL is in schema SD. In that case, you need to qualify the name of the table with the schema that it's in, i.e. INSERT INTO SD.AUDIT_DDL(...whatever...). In addition, schema DS is going to need to have an appropriate GRANT so it can store data into that table, as in GRANT INSERT INTO SD.AUDIT_DLL TO DS.
EDIT
If the problem is the call to SD.INSERT_LOG at the end of the procedure, you may need to grant execute permission to schema DS:
GRANT EXECUTE ON SD.INSERT_LOG TO DS;


text:
Q: Why this "interpolation" is correct? Why does the interpolation in this image make any sense?
Why won't I take $N(6.3) - N(6.1)$ or $N(6.2) - N(6.1)$? It is not linear at all.

A: It is not linear but it's constantly growing, $dN/dx >0$, and the values given are very close so interpolating linearly makes a good approximation.
This is vry used (or was before computers), in tables of data giving number for logrithms, or in statistical tables of distribution functions, like the area from $-\infty$ to $x$ in the gaussian function.

A: Linear interpolation means that you draw the line through two known points, and use the values on the line to estimate unknown points.
To find the value of $N(0.6278)$, you draw the line through $(0.62, N(0.62))$ and $(0.63, N(0.63))$. Letting $f(x)$ denote the function this line determines, then we expect $f(0.6278) \sim N(0.6278)$.
The particular expression they use to calculate this value is easy to remember once you're used to it -- but for the time being, since you're not yet used to it, you should go through the whole calculation of working out the equation defining the line.
You could use $x=0.63$ and $x=0.61$ for the known points. But your estimate is likely to be less accurate, because $0.61$ is further away from the point of interest than $0.62$.
For a similar reason, using $x=0.61$ and $x=0.62$ is less likely to be accurate. And it would be called linear extrapolation rather than linear interpolation. Extrapolation is ill-behaved more often than interpolation is.

A: Note that $N(0.64)-N(0.63)=0.0033$ and $N(0.63)-N(0.62)=0.0033$, so the slope of $N(x)$ in these ranges is probably close enough to constant that linear interpolation is "good enough."
Linear interpolation is most often used because it is simplest and provides results that are "good enough" for the purpose at hand. As the other answerer notes, this is a less common technique in the computer era, but it is worth knowing.
Basically, we are using the mean value theorem: $$N(x+\Delta x) -N(x) = N(x) + (\Delta x)N'(x_0)$$ for some $x_0\in [x,x+\Delta x]$, and the fact that for $$N'(x_0)\approx N'(x)\approx \frac{N(x+0.01)-N(x)}{0.01}$$
Thus, this linear interpolation is only as good a this estimation for $N'(x_0)$.

A: To answer the question of "Why won't I take $N(0.63)−N(0.61)$ or $N(0.62)−N(0.61)$?":
You know the value of $N$ at $0.62$ and at $0.63$, and you want to approximate its value at points between the two. The formula given is the linear approximation that passes through $N(0.62)$ at $0.62$ and through $N(0.63)$ at $0.63$. If you replaced the slope $N(0.63)-N(0.62)$ with something else, then the value you got for, say, $N(0.62999)$ would not be close to the known value $N(0.63)$. Hopefully you can see why that's bad.


text:
Q: iPhone and iPad, take screenshot with video playing My app need to take some screenshot when a video is being played on the screen. The video is played by AVPlayer and AVPlayerLayer. The problem when I try to use old methods, such as:
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
else
    UIGraphicsBeginImageContext(rect.size);

CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;

It returns an image of the screen and a black area (which the video should be there). I can take a screenshot successfully with UIGetScreenImage() but it is a private API so I am not sure if I can use it or not

A: From what I have read, many published apps have been using UIGetScreenImage(). It seems like Apple is quite lenient with its usage. Perhaps you could take a chance...

A: Although a lot of time has passed - I would like to note this is now possible on iOS 7 using the snapshot command on a UIView:
https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instm/UIView/snapshotViewAfterScreenUpdates:


text:
Q: python package healthcare.ai load error I successfully installed the healthcare.ai python package, but could not load it. Here is the error message. Has anyone else experienced this before?
File "/Users/mshen/.virtualenvs/test/lib/python2.7/site-packages/healthcareai/common/model_eval.py", line 142
    return {'accuracy': accuracy, **roc, **pr}
                                   ^
SyntaxError: invalid syntax

A: Someone suggested that I should use Python 3 to install the package.
That indeed solved the problem (thanks & sorry I didn't get to accept your answer before it somehow disappeared).
Here's what I did.

*

*install python 3
brew install python3

*create a python 3 virtual environment
python3 -m venv test3

*activate python 3 virtual environment
source ./test3/bin/activate