Q: SailsJS: delete parameters from URL before passing to blueprint We are building an application which uses SailsJS for backend and ExtJS for frontend. ExtJS automaitcally appends these parameters to every AJAX request coming from its grid:
_dc=1421519546371&page=1&start=0&limit=25
I need to remove these parameters on the Sails side before they are passed to the blueprint actions, so that I can take advantage of the blueprint REST API. Where would be the best place to remove these parameters? I can think of my NGINX reverse proxy as one option, but I am sure there is a better place within Sails.

A: In sails the easiest place would be to remove them with a policy.
RemoveParams.js
module.exports = function(req, res, next) {
    if(req.query._dc) delete req.query._dc
    // ect ....
    next();
};

Alternate method using undocumented req.options. I have not used this, but it would seem to work and was recommended in the comments.
module.exports = function(req, res, next) {
    req.options.values.blacklist = ['_dc']
    // or req.options.values.blacklist.push('_dc') ??
    next();
};

If you so choose you could also add your own middleware to replace / remove them as well.


Q: Object Code vs. Machine Code Machine code is the Processor Specific Binary Representation of the Instructions that a program is translated into; lowest level instructions from the processor architecture's instruction set.
The operating system is the agent responsible for passing the (((Binary))) instructions to the processor through the hardware architecture.
the most abstract translation made by translators is, therefore supposed to be the Binary instructions.
The assembler takes in the Assembly code that has instructions with one-to-one correspondence to the processor's architecture instructions ( that have binary representations ), and yields the Object Code.
The yield of the linker is nothing more linked Object Files, no translation happens at this stage. The load module is Object Code. I.e.: The loaded code by OS to RAM is the Object Code (which is not the binary representation of the instructions).
Question 1: Are the binary representations saved in the OS?
Question 2: What's the translator of the object code into binary representations? is it the OS (or the language runtime installed on it, if any)? Do all languages implementations have an installed runtime to do this if it's the runtime's job? Does an earlier agent than the OS do this job?
Question 3: Is the loaded code to the RAM really the object code not the binary representation? or does the loader translate the object code to its binary representation.

A: You are misunderstanding object files. Start by taking a look at this question:
What does an object file contain?
Object files do contain binary machine language instructions for the target platform, so there is no "translator" of any kind between the binary code contained in them and what is executed on the target CPU.
I think your confusion stems from the fact that object files also contain other information, such as symbol tables and constants. It is the linker's job to collect all of this information and package it into an executable.
Side Note: This answer is assuming a C/C++ perspective. Languages like Java that execute on a virtual machine have other layers in between compiling and execution.


Q: list in reverse order python How should I fix this code in order to get a list that is in the reverse order of sequence s?
def reverse(s):
    """Return a list that is the reverse of sequence s.

    >>> reverse([1,2,3])
    [3, 2, 1]
    """
    rs = []
    for element in s:
        rs = s + rs
    return rs

A: I'd actually do something like this (I'm assuming you cant use reversed()). This uses slicing notation to reverse a list.
def reverse(s):
    return s[::-1]

I'm also assuming you need to wrap this in a function, you could just use the index notation on its own.
EDIT:
Here is a bit of an explanation of the [::-1] operation:
Slicing notation is of the format [start_point:end_point:step]
The start_point is not specified, this becomes the length of the list so the operation starts at the end.
The end_point is also not specified, this becomes -1 so the operation will end at the start.
The step is -1, so it will iterate backwards in steps of 1 (i.e. every element of the list).
This will create a shallow copy of your original list. This means the list you pass into reverse(s) will remain the same.
Example for clarification:
>>> x = [1, 2, 3]
>>> y = x[::-1]
>>> x
[1, 2, 3]
>>> y
[3, 2, 1]

A: parameter passed to function is of type list.
def reverse(s):
    return s[::-1]


Q: Playground.js Not Rendering I went through the first two tutorials on the Playground.js website, but the rectangle is not rendering the rectangle. Here is the directory structure:
index.html
scripts
---main.js
---playground.js
index.html:
<!DOCTYPE html>
<html>
    <head><title>Simple Game</title></head>

    <body>

        <script src="scripts/main.js"></script>
        <script src="scripts/playground.js"></script>
    </body>
</html>

main.js:
var app = playground({
    render: function() {
        this.layer.clear("#000088");
        this.layer.fillStyle("#ffffff");
        this.layer.fillRect(32, 32, 64, 64);
    }
});

playground.js is the downloaded file from the website.
What is going wrong, and how can I fix it?

A: Switch your main and playground script tags. The order matters:
    <script src="scripts/playground.js"></script>
    <script src="scripts/main.js"></script>


Q: Srcset not working but shows alt tag message I am building a new website, and want to use the srcset to let the browser deside what image is the best for the current viewport.
What happens is that what ever i put in the srcset the browser will just show the alt tag text "test". If i through F12 developer tools removes the srcset attribute completely, the image shows up just fine.
All images in my example exists and shows up in a browser:
Here is my image tag, can any one see what is wrong with that?
<img src="http://localhost/Medium/Alaska-2-1818.jpg" srcset="http://localhost/Large/Alaska-2-1818.jpg 500w, http://localhost/XXLarge/Alaska-2-1818.jpg 1000w" alt="test">

My problem is shown in this codepen i made:
https://codepen.io/AxelAndersen/project/editor/DxKeaV

A: In your Codepen, some URLs have an error, missing one "i".


Q: How to manage orientation in landscape and portrait using fragment I create one example in Android 3.0 and I use the fragment in it. when I change the mode landscape to portrait or viseversa it give me the error as following but when I comment the fragment calling part it works smoothly as per my changes. for this I create layout-land folder and put may xml file with changes.
does any one have a hint or solution or example for match with this?
this is my fragment:
 <fragment
            class="com.Organisemee.fragment.TaskListFragment"
            android:id="@+id/tasklistfrag"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

And this is error:
07-01 12:38:33.363: ERROR/AndroidRuntime(641): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Organisemee/com.Organisemee.OrganisemeeList}: android.view.InflateException: Binary XML file line #167: Error inflating class fragment
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1736)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1752)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3096)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.ActivityThread.access$1600(ActivityThread.java:123)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:997)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.os.Looper.loop(Looper.java:126)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.ActivityThread.main(ActivityThread.java:3997)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at java.lang.reflect.Method.invokeNative(Native Method)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at java.lang.reflect.Method.invoke(Method.java:491)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at dalvik.system.NativeStart.main(Native Method)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): Caused by: android.view.InflateException: Binary XML file line #167: Error inflating class fragment
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:688)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:724)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:727)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.view.LayoutInflater.inflate(LayoutInflater.java:391)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.view.LayoutInflater.inflate(LayoutInflater.java:347)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:224)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.Activity.setContentView(Activity.java:1777)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at com.Organisemee.OrganisemeeList.onCreate(OrganisemeeList.java:73)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     ... 12 more
07-01 12:38:33.363: ERROR/AndroidRuntime(641): Caused by: java.lang.IllegalStateException: Fragment com.Organisemee.fragment.TaskListFragment did not create a view.
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.app.Activity.onCreateView(Activity.java:4114)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:664)
07-01 12:38:33.363: ERROR/AndroidRuntime(641):     ... 22 more

A: Need to define a Fragment in XML Like This.
<RelativeLayout
android:id="@+id/main_tasklist_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@+id/main_viewmenu_layout"
android:layout_below="@+id/main_tasklist_outer">

 <fragment
        class="com.Organisemee.fragment.TaskListFragment"
        android:id="@+id/tasklistfrag"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

To Call the Fragment put this code in java file
            Fragment f = listFragment();
            FragmentTransaction ListFragft = getFragmentManager().beginTransaction();
            ListFragft.replace(R.id.main_tasklist_layout, f);
            ListFragft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ListFragft.addToBackStack(null);
            ListFragft.commit();

This Works fine in change both orientation, landscape to portrait and vice versa.


Q: How to re-parametrize posterior function? How can I write the unnormalized posterior
$ f(p_1, p_2 | Y) = (z_1-1)*log(p_1) + (n_1-z_1-1)*log(1-p_1) + (z_2-1)*log(p_2) + (n_2-z_2-1)*log(1-p_2) $
in terms of the log odds-ratio $\alpha$ and the log odds-product $\eta$?
$\alpha = log \left(\frac{p_2/(1-p_2)}{p_1/(1-p_1}\right) $ and $\eta = log \left(\frac{p_2}{1-p_2} \times \frac{p_1}{1-p_1}\right)$?
where z_1, n_1, z_2, and n_2 are constants.

A: Note that we have
$$ \alpha = \log p_2 - \log(1-p_2) - \log p_1 + \log(1-p_1),$$
$$ \eta=\log p_2 -\log (1-p_2)+\log p_1 -\log(1-p_1).$$
Then $$\eta-\alpha = 2(\log p_1 - \log (1-p_1),$$
$$\eta +\alpha=2(\log p_2 -\log(1-p_2).$$
EDIT: previously I wrote that your unnormalized posterior couldn't be written in terms of $\alpha$ and $\eta$. However I just noticed that
$$\frac{\eta - \alpha}{2}=\log \frac{p_1}{1-p_1}$$ so that
$$p_1 = \frac{e^{(\eta-\alpha)/2}}{e^{(\eta-\alpha)/2}+1},$$
and similarly
$$\frac{\eta + \alpha}{2}=\log \frac{p_2}{1-p_2}$$ so that
$$p_2 = \frac{e^{(\eta+\alpha)/2}}{e^{(\eta+\alpha)/2}+1}.$$
Now since your unnormalized posterior is a function of $p_1$ and $p_2$, and of the constants $z_1,n_1,z_2,n_2$, you can using the above expressions write the posterior in terms of $\alpha$ and $\eta$.


Q: List contains method not working in JSF page I have two list that consist out of the same object.
I want to check if the first list containts an object of the second list
<ui:repeat var="item" value="#{userTypeController.permissionItems}">
    <c:if test="#{userTypeController.permissionItemsUserType.contains(item)}">
        <h:selectBooleanCheckbox value="#{true}"/>
        <h:outputText value="#{item.getAction()}" />
    </c:if>
    <c:if test="#{!userTypeController.permissionItemsUserType.contains(item)}">
        <h:selectBooleanCheckbox value="#{false}"/>
        <h:outputText value="#{item.getAction()}" />
    </c:if>
</ui:repeat>

but this doesn't seem to work and all I'm getting is false.
I've changed the equals and hashcode methodes but didn't help.

A: JSTL tags like <c:if> runs during view build time and the result is JSF components only. JSF components runs during view render time and the result is HTML only. They do not run in sync. JSTL tags runs from top to bottom first and then JSF components runs from top to bottom.
In your case, when JSTL tags runs, there's no means of #{item} anywhere, because it's been definied by a JSF component, so it'll for JSTL always be evaluated as if it is null. You need to use JSF components instead. In your particular case a <h:panelGroup rendered> should do it:
<ui:repeat var="item" value="#{userTypeController.permissionItems}">
    <h:panelGroup rendered="#{userTypeController.permissionItemsUserType.contains(item)}">
        <h:selectBooleanCheckbox value="#{true}"/>
        <h:outputText value="#{item.getAction()}" />
    </h:panelGroup>
    <h:panelGroup rendered="#{!userTypeController.permissionItemsUserType.contains(item)}">
        <h:selectBooleanCheckbox value="#{false}"/>
        <h:outputText value="#{item.getAction()}" />
    </h:panelGroup>
</ui:repeat>

See also:

*

*JSTL in JSF2 Facelets... makes sense?


Q: Redshift Spectrum with Very Wide Column I am using Redshift spectrum with a Glue database. I have some columns which exceed Redshift max text size (64k). Is there a way handle very large columns? Ie if I do it with a parquet does it let me go a bit bigger or is it unavailable with CSV?


Q: Discord.py How to get previous track in a queue I created a discord.py music bot with lavalink
Now I want to send and Embed with the Informations about the previous song when you use the ,previous command
i think its very improvised with the lyrics function to get the Thumbnail but thats not the problem
I just want to ask how to replace the player.queue.current_track.title with something that says it have to use the informations of the previous title
@commands.command(name="previous", aliases=["zurück"])
    async def previous_command(self, ctx, name: t.Optional[str]):
        player = self.get_player(ctx)
        name = name or player.queue.current_track.title

        async with ctx.typing():
            async with aiohttp.request("GET", LYRICS_URL + name, headers={}) as r:
                if not 200 <= r.status <= 299:
                    raise NoLyricsFound

                data = await r.json()

        if not player.queue.history:
            raise NoPreviousTracks

        player.queue.position -= 2
        await player.stop()
        embed = discord.Embed(
            title="Vorheriges Lied",
            colour=ctx.author.colour,
            timestamp=dt.datetime.utcnow(),
        )
        embed.set_thumbnail(url=data["thumbnail"]["genius"])
        embed.set_author(name=data["author"]),
        embed.set_footer(text=f"Angefordert von {ctx.author.display_name}", icon_url=ctx.author.avatar_url)
        await ctx.send(embed=embed)


Q: Reading file using Cordova File Plugin I'm using cordova file plugin - cordova file plugin
I'm actually reading the file from the textfile. Below is my code
document.addEventListener("deviceready", function () {
    window.resolveLocalFileSystemURL(cordova.file.applicationDirectory + "sameple.txt", gotFile, fail);
}, true);

function gotFile(file) {
    file.file(function (file) {
        var reader = new FileReader();
        reader.onloadend = function (evt) {
            console.log(this.result);
        }
        reader.readAsText(file);
    }, fail());
}

function fail(e) {
    console.info("FileSystem Error : " + e);
}

So whenever i run this code, i'm getting the below error
deviceready has not fired after 5 seconds.
Channel not fired: onPluginsReady
Channel not fired: onCordovaReady

Could not get Cordova FileSystem: Error: deviceready has not fired after 5 seconds.
   "Could not get Cordova FileSystem:"
   {
      [functions]: ,
      __proto__: { },
      description: "deviceready has not fired after 5 seconds.",
      message: "deviceready has not fired after 5 seconds.",
      name: "Error"
   }

{"data":"data"}

After deviceready error later i'm able to get the exact data.. How do i resolve this error? do i have to wait for the device ready execution to complete?

A: It can happen for a number of reasons, see here more details.
You should try firs @bayanAbuawad suggestion that works most of the times:

*

*Add the platforms with cordova platform add ios android

*Remove them with cordova platform remove ios android

*Add them again.
It is super weird, but it’s related to a faulty android.json and ios.json inside the platforms folder.


Q: composer installation on wamp in window 7 OS I followed the steps in this website:
http://www.wikihow.com/Install-Laravel-Framework-in-Windows
But it's not working on the instructions. Step #11
It displays like this in the command window:

The "https"//packagist.org/packages.json" file could not be downloaded: php _network_getaddresses: getaddrinfo failed: No such host is known. failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known.

I'm stuck on this, please help me on this. Thank you.

A: I never managed to get it working in WAMP server. I took my shot with XAMPP. Enormous gigantous (almost 1 GB), but heck yeah, it works!
So, try that, everything should work smoothly.
https://www.apachefriends.org/index.html

A: The solution can be found in internet connection, it is being interrupted that other components cannot be donwloaded.


Q: How can I capture a picture from webcam and send it via flask I want to send an Image object in a flask response but it gives me an error. I tried also an approach with StringIO.
image = Image.open("./static/img/test.jpg")
return send_file(image, mimetype='image/jpeg')

This is just a test case. So the major problem is to capture an image from /dev/video0 and sent it (ideally without temporary storing on disk) to the client. I use v4l2capture for that. The test picture should also work if you may have a better solution for that task.
import select
import v4l2capture
video = v4l2capture.Video_device("/dev/video0")
size_x, size_y = video.set_format(1280, 1024)
video.create_buffers(1)
video.queue_all_buffers()
video.start()
select.select((video,), (), ())
image_data = video.read()
video.close()
image = Image.fromstring("RGB", (size_x, size_y), image_data)

Thanks.
EDIT
Works now. Better solutions as v4l2capture are welcome...

A: Did it with.
image = Image.open("./static/img/test.jpg")
img_io = StringIO()
image.save(img_io, 'JPEG', quality=70)
img_io.seek(0)
return send_file(img_io, mimetype='image/jpeg')


Q: Change the Default Target Server for Entity Framework Code First Approach? I want to apply my code first migrations directly to SQL server or Azure Database instead of using the Default .sql server or Localdb/mssqllocaldb.. is there a way to do this from web.config and without editing code in context class?


Q: java graphics create an N by N board I have this question I haven't solved left in my assignment, "cmps200: introduction to java programming". This is what I wrote but it gives a blank panel:
import java.awt.*;
public class Board {
    public static void main(String[] args){
         int N= Integer.parseInt(args[0]);
        int x=0;
        int y=0;
        int m=(int)(300/5);
        DrawingPanel panel= new DrawingPanel(300, 300);
        Graphics g= panel.getGraphics();
        for (int i=1; i<=N; i++){
            for (int j=1; j<=N; j++){
                square();
                g.setColor(Color.RED);
                circle();
                g.setColor(Color.BLUE);
                circle();
                y+=m;
            }
        }
    }
    public static void square(){
        int N;
        int m= (int)(300/5);
        int x=0; int y=0;
        DrawingPanel panel= new DrawingPanel(300, 300);
        Graphics g= panel.getGraphics();
        g.setColor(Color.BLACK);
        g.drawRect(x, y, N/300, N/300);
    }
    public static void circle(){
        int x; int y; int m;
        Graphics g= panel.getGraphics();
        g.fillOval(x+y+(3/2)*m);
    }
}

A: Properly pass parameters:
public class Board {
    public static void main(String[] args){
        ...
        for (int i=1; i<=N; i++){
            for (int j=1; j<=N; j++){
                square(N);
                g.setColor(Color.RED);
                circle(x, y);
                g.setColor(Color.BLUE);
                circle(x, y);
                y+=m;
            }
        }
    }
    public static void square(int N){
        //deleted first line
        int m= (int)(300/5);
        int x=0; int y=0;
        DrawingPanel panel= new DrawingPanel(300, 300);
        Graphics g= panel.getGraphics();
        g.setColor(Color.BLACK);
        g.drawRect(x, y, N/300, N/300);
    }
    public static void circle(int x, int y){
        //deleted first line
        Graphics g= panel.getGraphics();
        g.fillOval(x+y+(3/2)*m);
    }
}


Q: How can i set mark parity? I want test my serial communication between my Arduino and my PC, i want do that because when i connect my arduino to my serial bus i didn´t receive some data.
I have connected my PC over rs232 to my Arduino mega and from the Arduino back to the PC. Now i want send a 9-bit byte to the Arduino and back to the PC, when that works i know that my serial bus is the problem.
Question:
How can i set the mark parity?
My code to test a "normal" byte(8 bit) is written in Visual C# i hope i can use them again and must only fix a bit.
Here the code:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication5
{
  class Program
{
    static void Main(string[] args)
    {

        System.IO.Ports.SerialPort port = new SerialPort("COM5", 4800);
        try
        {
            port.Open();
            while (true)
            {
                //if (port.BytesToRead > 0)
                {
                    port.Write("A");
                }

            }
        }
        catch (Exception)  // Press CTRL-C to exit.
        {
            port.Close();
            Console.WriteLine("C");
        }
        port.Close();
    }
  }
}

I hope someone can help me with friendly wishes sniffi


Q: Conditional expectation for Brownian motion
Consider two Brownian motions $(W_t)_{t\ge 0}$  with starting point $x$ and $(W'_t)_{t\ge 0}$ with starting point $y$. Define $T:=\inf\{t\ge 0:W_t=0\}$, the first time when $W_t$ is equal to $0$. Show that for every $x,y,t>0$ it holds:
$$P(W_{t\wedge T}\le y \mid \{W_0=x\})=P(|W'_t|\ge x \mid \{W'_0=y\}).$$

My attempt:
Rewrite $W'_t=B'_t+y$ for a standard Brownian motion $(B'_t)_{t\ge 0}$. Then $P(W'_0=y)=1$ and $1_{\{W'_0=y\}}=1_\Omega$, such that
\begin{align}
P(|W'_t|\ge x \mid \{W'_0=y\})&=\frac{1}{P(W'_0=y)}E\Big[1_{\{|W'_t|\ge x\}}1_{\{W'_0=y\}}\Big]=P\big(|B_t'+y|\ge x\big)
\end{align}
Rewrite $W_t=B_t+x$ for a standard Brownian motion $(B_t)_{t\ge 0}$. Then $P(W_0=x)=1$ and $1_{\{W_0=x\}}=1_\Omega$, such that
\begin{align}
P(W_{t\wedge T}\le y \mid \{W_0=x\})&=\frac{1}{P(W_0=x)}E\Big[1_{\{W_{t\wedge T}\le y\}}1_{\{W_0=x\}}\Big]=P\big(B_{t\wedge T}+x\le y\big)\\
\end{align}
Here I get stuck. Maybe I have to use $0\le B_{t\wedge T}+x$ and the reflection principle? I would really appreciate some help! Thanks in advance!

A: Perhaps we may go for the proof as follows.
First, note that
\begin{align}
&\mathbb{P}(W_{t\wedge T}\le y|W_0=x)\\
&=\mathbb{P}(W_t\le y|W_0=x,T>t)\,\mathbb{P}(T>t)\\
&+\mathbb{P}(W_T\le y|W_0=x,T\le t)\,\mathbb{P}(T\le t)\\
&=\mathbb{P}(W_t\le y|W_0=x,T>t)\,\mathbb{P}(T>t)+\mathbb{P}(T\le t)\tag{1},
\end{align}
where $\mathbb{P}(W_T\le y|W_0=x,T\le t)=1$ as $W_T=0<y$ always holds.
Second, note that
\begin{align}
\mathbb{P}(W_t\le y|W_0=x)&=\mathbb{P}(W_t\le y|W_0=x,T>t)\,\mathbb{P}(T>t)\\
&+\mathbb{P}(W_t\le y|W_0=x,T\le t)\,\mathbb{P}(T\le t).
\end{align}
Substitute this result into $(1)$, and we obtain
\begin{align}
&\mathbb{P}(W_{t\wedge T}\le y|W_0=x)\\
&=\mathbb{P}(W_t\le y|W_0=x)+\mathbb{P}(T\le t)\\
&-\mathbb{P}(W_t\le y|W_0=x,T\le t)\,\mathbb{P}(T\le t)\\
&=\mathbb{P}(W_t\le y|W_0=x)\\
&+\mathbb{P}(W_t>y|W_0=x,T\le t)\,\mathbb{P}(T\le t)\tag{2}.
\end{align}
Next, note that
$$
\mathbb{P}(W_t>y|W_0=x,T\le t)\,\mathbb{P}(T\le t)=\mathbb{P}(W_t>y,T\le t|W_0=x)
$$
denotes the probability of a Brownian motion that starts from $x$, hits $0$ at time $T$, and then goes beyond $y$ at time $t$. By the reflection principle, it follows that
$$
\mathbb{P}(W_t>y|W_0=x,T\le t)\,\mathbb{P}(T\le t)=\mathbb{P}(W_t<-y|W_0=x).
$$
Substitute this result into $(2)$, and we obtain
\begin{align}
\mathbb{P}(W_{t\wedge T}\le y|W_0=x)&=\mathbb{P}(W_t\le y|W_0=x)\\
&+\mathbb{P}(W_t<-y|W_0=x).\tag{3}
\end{align}
Thereafter, by $W_t'=W_t-x+y$, we have
\begin{align}
&\mathbb{P}(W_{t\wedge T}\le y|W_0=x)\\
&=\mathbb{P}(W_t'\le 2y-x|W_0'=y)+\mathbb{P}(W_t'<-x|W_0'=y)\\
&=\mathbb{P}(W_t'\ge x|W_0'=y)+\mathbb{P}(W_t'<-x|W_0'=y),\tag{4}
\end{align}
where $\mathbb{P}(W_t'\le 2y-x|W_0'=y)=\mathbb{P}(W_t'\ge x|W_0'=y)$ due to the fact that $2y-x$ and $x$ are symmetric with respect to $y$.
Finally, note that $x>0$, and $(4)$ is obviously the desired equality
$$
\mathbb{P}(W_{t\wedge T}\le y|W_0=x)=\mathbb{P}(\left|W_t'\right|\ge x|W_0'=y).
$$
This completes the proof.

A: Let's write the assertion in term of a standard Brownian motion $(B_t)_{t \geq 0}$.

If we set $T_{x} = \inf\{t \geq 0; B_t = -x\}$ then we need to show that
$$\mathbb{P}(x+ B_{t \wedge T_{x}} \leq y) = \mathbb{P}(|B_t+y| \geq x) \tag{1}$$
for any $x,y,t>0$.

Fix $x,y,t>0$. Since
$$B_{t \wedge T_x} = \begin{cases} -x & T_x \leq t, \\ B_t, & T_x>t \end{cases}$$
we have
$$\mathbb{P}(x+B_{t \wedge T_x} \leq y) = \mathbb{P}(T_x \leq t) + \mathbb{P}(x+B_t \leq y, T_x>t). \tag{2}$$
Since the reflection principle allows us to calculate explicitly the joint distribution $(B_t,\inf_{s \leq t} B_s)$ (see below), we get
\begin{align*}\mathbb{P}(x+B_t \leq y, T_x>t) &= \mathbb{P} \left( B_t \leq y-x, \inf_{s \leq t} B_s>-x \right) \\ &= - \frac{2}{\sqrt{2\pi t^3}} \int_{-x}^0 \int_{u \leq z \leq y-x} (2u-z) \exp \left(- \frac{(2u-z)^2}{2t} \right) \, dz \, du \\ &= \frac{2}{\sqrt{2\pi t}} \int_{-x}^0 \left[-\exp \left(- \frac{(2u-y+x)^2}{2t} \right) + \exp \left( -\frac{u^2}{2t} \right)\right] \, du.\end{align*}
Using the linearity of the integral to split the integral on the right-hand side into two parts and performing a simple change of variables we get
$$\mathbb{P}(x+B_t \leq y, T_x>t)  = \sqrt{\frac{2}{\pi t}} \int_{\mathbb{R}} \left(- \frac{1}{2} \cdot 1_{\{|u-y| \leq x\}} + 1_{[-x,0]}(u) \right) \exp \left(- \frac{u^2}{2t} \right) \, du.$$
On the other hand, the reflection principle also gives
$$\mathbb{P}(T_x \leq t) =2 \mathbb{P}(B_t' \leq -x) =\sqrt{\frac{2}{\pi t}} \int_{-\infty}^{-x} \exp \left( - \frac{u^2}{2t} \right) \, du \tag{3}$$
Adding both expressions and using that
$$\sqrt{\frac{2}{\pi t}} \int_{-\infty}^0 \exp \left(- \frac{u^2}{2t} \right) \, du = \frac{1}{\sqrt{2\pi t}} \int_{\mathbb{R}} \exp \left(- \frac{u^2}{2t} \right) \, du = 1,$$
it follows from $(2)$ that
$$\begin{align*} \mathbb{P}(x+B_{t \wedge T_x} \leq y) = 1- \frac{1}{\sqrt{2\pi t}} \int_{|z-y| \leq x} \exp \left( - \frac{u^2}{2t} \right) \, du&= \mathbb{P}(|B_t+y|>x) \\ &= \mathbb{P}(|B_t+y| \geq x) \end{align*}$$
which proves the assertion.

Some remarks on the reflection principle: The reflection principle states (...or implies, depending on the formulation...) that the running supremum $M_t := \sup_{s \leq t} B_s$ satisfies $$M_t \stackrel{d}{=} |B_t|.$$ Applying this result to the Brownian motion $(-B_t)_{t \geq 0}$ it follows immediately that $$- \inf_{s \leq t} B_s \sim |B_t|.$$ In particular, $$\mathbb{P}(T_x \leq t) = \mathbb{P} \left( \min_{s \leq t} B_s \leq x \right) = \mathbb{P}(|B_t| \leq -x) = 2 \mathbb{P}(B_t \leq x)$$ for the stopping time $$T_x := \inf\{t \geq 0; B_t = -x\}$$ from the first part of this answer. Combining the reflection principle with the strong Markov property of Brownian motion, it is possible to compute the joint density of $(B_t,M_t)$:

Let $(B_t)_{t \geq 0}$ be a Brownian motion. The joint distribution $(B_t,\sup_{s \leq t} B_s)$ equals $$\mathbb{P} \left[ B_t \in dx, \sup_{s \leq t} B_s \in dy \right] = \frac{2 (2y-x)}{\sqrt{2\pi t^3}} \exp \left(- \frac{(2y-x)^2}{2t} \right) 1_{[-\infty,y]}(x) \, dx \, dy. $$

For a proof see e.g. René Schilling/Lothar Partzsch: Brownian Motion - An Introduction to Stochastic Processes, Exercise 6.8 (there are full solutions available on the web), or this question (and differentiate in order to obtain the density function).
As before, we can use the symmetry of Brownian motion and apply the result to $(-B_t)_{t \geq 0}$ in order to get the joint distribution of $(B_t,\inf_{s \leq t} B_s)$.


Q: pgrep -f command in ssh through script gives a wrong result. how to solve this issue When I am trying to use pgrep -f <proc_name> command in ssh through script gives a wrong result. How to solve this issue? (I used RSA key for not to ask p/w)
ssh -l $UNAME $HOST bash -c "'
        pgrep -f name > p_id
        '"

A: It's hard to tell without more details, but my guess is that it's detecting the bash process. The way you're doing it, the remote ssh daemon is running bash -c '<newline>pgrep -f name > p_id<newline>', which then runspgrep -f name(with output to the file "p_id"). Note thatps -fsearches the entire command line for matches, so the "name" part of the argument tobash` is probably matching itself.
One option is to use the old trick to keep ps | grep something from matching itself: use [n]ame instead of just name. But then you need quotes around it, so the quoting gets even more complicated than it already is. It looks simpler to me to just skip the bash -c part and one layer of quoting:
ssh -l $UNAME $HOST 'pgrep -f name >p_id'

A: You didn't include any code from the script, but first look at user permissions, they may be the reason for process command returning different results. Other potential trouble spots are:
Check script permissions and verify execute options. Make sure script    user has the correct permissions for the directory where that process    runs.
You ran the command via the command prompt, is that with the    same user that is executing the script?  If not it may be    permissions.
Put the -u option in your pgrep command for the user who    owns the process you are looking for. Or try inserting an sudo    command into the script and run the pgrep as another user, one with    admin/root-like privileges.
And don't forget to read the man pages, perhaps there's an option you need.


Q: how to create web service Api in rails 4? can anyone help me how to create a web service API in rails 4. I know how create web service API in ruby 1.8.7 and rails 2.3.5 with action web service gem. When I am trying to use https://github.com/datanoise/actionwebservice gem in rails 4, I am getting deprecated errors.I want to upgrade my web service app. Please help me.

A: Rails-API looks promising, because it will be part of Rails core in Rails 5.
Rails-API
Rails-API is a subset of a normal Rails application, because API only applications don't require all functionality that a complete Rails application provides. so, it compatible well with old Rails versions. I don't know compatibility exactly, but I'm using it with Rails 3.2.x
There are another proper framework for this purpose, for example, Sinatra, Grape, but If you familiar with Rails, Rails-API will be the best choice.

A: Actionwebservice is long deprecated, in favour of REST API's. At my previous job we used a fork of actionwebservice in a rails 3 project.
Since there is no maintainer anymore for the actionwebservice gem, that fork never got merged back. If you check the fork history, a lot of people are fixing and partially updating it, but it is scattered all over the place.
Afaik none of the forks were updated to use rails 4. But using a rails 3 fork might just work.
If you really need to build a SOAP API server with Rails, imho your best option is to take a look at Wash-out, but you will have to re-write your API code.


Q: Is there any condition for groups that have subgroups of order of all divisors of its order? I want to find the condition of a group $G$ such that for all $a\big||G|$, there exists $H\leq G, |H|=a$.
For instance, If $G=C_n$, then for all $a|n$, $C_a\leq C_n$, so $C_n$ satisfies the condition.


Q: What is the point of using custom exception class in php? In some libraries it is common practice to make custom Exception classes for every error condition, like:
class FileNotFound_Exception extends Exception {}

You can handle certain type of Exception, however you cannot read all source code of all libraries to remember each Exception class, and cannot take full advantage of using custom Exceptions. Most of time I just catching them with base Exception class:
catch (Exception $e)
{
    // log and display friendly error
}

Is there other ways to have benefit of custom Exception classes, without writing long list of catch blocks?
I like Exceptions, but don't know how to use them properly. Thank you.

A: The benefit of having your own Exception class is that you, as the author of the library, can catch it and handle it.
try {
   if(somethingBadHappens) {
     throw MyCustomException('msg',0)
   }
} catch (MyCustomException $e) {
  if(IcanHandleIt) {
    handleMyCustomException($e);
  } else {
    //InvalidArgumentException is used here as an example of 'common' exception
    throw new InvalidArgumentException('I couldnt handle this!',1,$e);
  }
}

A: Well, custom exception classes lets you route your errors properly for better handling.
if you have a class
class Known_Exception extends Exception {}

and a try catch block like this:
try {
    // something known to break
} catch (Known_Exception $e) {
    // handle known exception
} catch (Exception $e) {
    // Handle unknown exception
}

Then you know that Exception $e is an unknown error situation and can handle that accordingly, and that is pretty useful to me.


Q: Rails 4: After updating an attribute post a message How do I go about posting or rendering a message after updating an attribute to reflect the changes?
(I couldn't find anything online in respect to this task)
For example: Once a user updates the ticket status there will be a message posted in the comment section reporting "Ticket has been closed". (No flash message, but a permanent one).
tickets_controller.rb
def open
   @ticket = Ticket.find(params[:ticket_id])
   @ticket.update_attributes(:ticket_status, "closed")
   redirect_to ticket_path
end

A: You can use the session for this purspose.
def open
   @ticket = Ticket.find(params[:ticket_id])
   @ticket.update_attributes(:ticket_status, "closed")
   session[:close_message] = "Ticket has been closed"
   redirect_to ticket_path
end

After that diaplay it in the view like
<%= session[:close_message] %>

but make sure to clear the session like session[:close_message] = nil after displaying the message to free the memory

A: You need to store the message in database if you want it to persist. Say for ex- There is a ticket raised (Ticket model) and someone closes it. The attribute on backend will update attribute status for ticket model.
 def update
   tkt = Ticket.where(id: 1)
   tkt.update_attributes(status: 1)
 end

If this is an ajax call, you can send a response data with message like "Ticket closed " and display it accordingly on html page in the success callback of ajax call. If it's a server call, refresh the page and use the status attribute from Ticket model to create the message.
You can use some enums like
{0 => "Ticket Open", 1 => "Ticket closed", 2 => "Ticket in progress" }

In case messages are not generic and every time some more customization is required, better to create and save the entire message as an attribute in the related model and no need to have enums.


Q: Reducing after filtering doesn't add up with jq I have the following data:
[
  {
    "name": "example-1",
    "amount": 4
  },
  {
    "name": "foo",
    "amount": 42
  },
  {
    "name": "example-2",
    "amount": 6
  }
]

I would like to filter objects with a .name containing "example" and reduce the .amount property.
This is what I tried to do:
json='[{"name":"example-1","amount":4}, {"name": "foo","amount":42}, {"name": "example-2","amount":6}]'

echo $json | jq '.[] | select(.name | contains("example")) | .amount | add'

I get this error:

jq: error (at :1): Cannot iterate over number (4)

I think that the output of .[] | select(.name | contains("example")) | .amount is a stream, and not an array, so I cannot add the values together.
But how could I do to output an array instead, after the select and the lookup?
I know there is a map function and map(.amount) | add works, but the filtering isn't here.
I can't do a select without .[] | before, and I think that's where the "stream" problem comes from...

A: As you say, add/0 expects an array as input.
Since it's a useful idiom, consider using map(select(_)):
echo "$json" | jq 'map(select(.name | contains("example")) | .amount) | add'

However, sometimes it's better to use a stream-oriented approach:
def add(s): reduce s as $x (null; . + $x);

add(.[] | select(.name | contains("example")) | .amount)


Q: Ошибка с подключением библиотеки к Vue (Nuxt) Такая проблема. Устанавливаю пакет skinwiev3d в проект. при импорте в страницу выбивает ошибку
require() of ES Module C:\Users\winve\OneDrive\Рабочий стол\***\Frontend\node_modules\skinview3d\libs\skinview3d.js from C:\Users\winve\OneDrive\Рабочий стол\Mine-Play\Frontend\node_modules\vue-server-renderer\build.dev.js not supported. Instead change the require of skinview3d.js in C:\Users\winve\OneDrive\Рабочий стол\***\Frontend\node_modules\vue-server-renderer\build.dev.js to a dynamic import() which is available in all CommonJS modules.


Q: Fetch Autosys Job status through API API is displaying all the attribute values of a job (like status, job name, instance, start time, etc).
I just want to know in post method how should i write the code so that it can fetch the status from api and display output.
url="http://some.api.com"
def get_job_status():
  try:
     response=requests.post(url)
     print(response.status_code)
     if response.status_code==200:
     // `enter code here`
     dict_data=response.json()
     print(dict_data["status'])

A: Load text into json object and fetch with keys
import requests
url = "http://some.api.com"
def get_job_status():
  response = requests.request("POST", url)
  if response.status_code == 200:
    json_data = json.loads(response.text)
    job_name = json_data["name"]
    job_status = json_data["status"]
  else:
    return "Error with Request"


Q: WWW::Netflix::API program and hiding the consumer_secret key I've written a Perl CLI program that uses the WWW::Netflix::API module. It's finished and I'd like to release it but w/o exposing my consumer_secret key. Any ideas how this can be done?

A: I think you have two options:

*

*Make the end users obtain their own Netflix key.

*Proxy all the traffic through your own server and keep your secret key on your server.

You could keep casual users away from your secret key while still distributing it with some obfuscation but you won't keep it a secret from anyone with a modicum of skill.
Proxying all the traffic would pretty much mean setting up your own web service that mimics the parts of the Netflix API that you're using. If you're only using a small slice of the Netflix API then this could be pretty easy. However, you'd have to carefully check the Netflix terms of use to make sure you're playing by the rules.
I think you'd be better off making people get their own keys and then setting up your tool to read the keys from a configuration file of some sort.


Q: PHP stops execution when calling external function When the following PHP script executes:
<?php

include "imageManager.php";
include "imageHandling/spritesheet.php";
include "updateWindow.php";
include_once "dbConnection.php";

class deleteSoftware{

    private $conn;
    private $tableName;

    public function __construct($name){

      //Database Connection
      $this->connectDatabase();

      //Delete the Icon from the image pool
      $tempFileManagerObject = new fileManager();
      $tempFileManagerObject->setSrc("../ICONS/");
      $deletedImageName = $tempFileManagerObject->getImageNameFromSoftwareName($name);
      $tempFileManagerObject->delete("../ICONS/", $deletedImageName);
      $tempFileManagerObject->deleteImageRenaming($deletedImageName);

     //Deleting the record from the database
     $prio = $tempFileManagerObject->getPriorityFromSoftwareName($name);
     $subCategory = $tempFileManagerObject->getSubCategoryFromSoftwareName($name);
     $this->tableName = $subCategory;
     $this->conn->query("delete from ".$subCategory." where priority=".$prio);
     $this->decrementPriorityInTable($prio);

     //Delete from updateWindow if exist
     $updateObject = new updateWindow();
     $updateObject->deleteUpdate($name);

      //Making sprite Sheet and moving to home directory
      echo "step-0";
      $spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../");
      echo "step-1";
      for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->copy("../ICONS/", "../Processing/", $x); }
      echo "step-3";
      $spriteSheetObject->setImagesFolder("../Processing/");
      echo "step-4";
      $spriteSheetObject->setOutPutFolder("../");
      $spriteSheetObject->processSpriteSheet();
      $spriteSheetObject->processSpriteSheetCss($this->getTotalSoftwaresCount());
      for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->delete("../Processing/",$x); }
      $tempFileManagerObject->setSrc("../Processing/");
      $tempFileManagerObject->setDes("../");
      $tempFileManagerObject->rename("tempArea", "home");
      $tempFileManagerObject->move("../Processing/", "../", "home");

    }
    public function connectDataBase(){

        $temp = new dbConnection();
        $this->conn = $temp->connectDb();

}
    public function getTheImageNameOfNewlyInsertedIcon($subCategory, $pri){

        //First of all calculate the iconName of newly inserted image
            //-Get the total number of rows for each subCategory table and add it untill we reach at the subCategory table where software to be inserted (Not add subCategory table rows count)
            //- RowCounts + maxPriority in that table + 1
                //- If there is already software for

        //Calculating the total number of rows upto subCateogryTable excluding the subCategoryTable and then add up
        $temp = false;
        $rowCount = 0;
        $this->tableName;
        $this->conn->query("use windows");

        $softwareTable = $this->conn->query("select * from software order by priority");
        foreach ( $softwareTable as $row ) {
            $categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
            foreach ( $categoryTable as $row2 ) {
                $subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
                if (!strcmp($row2["category"], $subCategory)){
                    $this->tableName = $row2["tableName"];
                    $temp = true;
                    break;
                }
         $rowCount = $subCategoryTable->rowCount() + $rowCount;
            }
            if ($temp){break;}
        }

      $rowCount = $pri + $rowCount;

      return $rowCount;//This will be the name of the image

        //Navigate to Tables
        //According to priority set the iconName
        //Record the iconName please
        //Insert the record in table
        //Execute the spritesheet
        //make css
        //finally iterate the whole database and send a string

    }
    public function decrementPriorityInTable($pri){

        $this->conn->query("use windows");

        $softwareTable = $this->conn->query("select * from ".$this->tableName." order by priority");
        foreach ( $softwareTable as $row ) {
            if($row["priority"] >= $pri+1){
                $this->conn->query("update ".$this->tableName." set priority=".($row["priority"]-1)." where priority=".$row["priority"]);
            }
        }

    }
    public function getTotalSoftwaresCount(){

        $softwareCount = 0;

        $softwareTable = $this->conn->query("select * from software order by priority");
        foreach ( $softwareTable as $row ) {
            $categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
            foreach ( $categoryTable as $row2 ) {
                $subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
                foreach ($subCategoryTable as $row3){
                   $softwareCount++;
                }

            }

        }

        $softwareCount++;
        return $softwareCount;
    }

}

?>

The line $spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../"); stops executions without any error.
The spriteSheet class comes from this library:
    <?php

    require("lib/WideImage.php");

    //All the images size must first be set to be placed on canvas
    //Depends on only 1-Image "canvasArea.jpg"
    //image processing folder is by default a "imagesToBeProcessed"
    //output folder is empty by default

    class spriteSheet{

        private $canvasWidth;
        private $canvasHeight;
        private $eachImageWidth;
        private $eachImageHeight;
        private $imagesFolder = "";
        private $outputFolder = "";
        private $imageCount = 0;
        private $maxImageInARow;

        function __construct($imgW=43,$imgH=43, $maxInRow=5, $src, $des){
            $this->imagesFolder = $src;
            $this->outputFolder = $des;
            $this->imageCounter();
            $this->eachImageWidth = $imgW;
            $this->eachImageHeight = $imgH;
            $this->canvasWidth = $imgW * $maxInRow;
            $this->canvasHeight = $imgH * ceil($this->imageCount/$maxInRow);
            $this->maxImageInARow = $maxInRow;

        }
        public function setImagesFolder($src){
            $this->imagesFolder = $src;
        }
        public function setOutPutFolder($des){
            $this->outputFolder = $des;
        }
        public function imageCounter( ){
            for ($x=1; true; $x++){
                if (!file_exists($this->imagesFolder.$x.".jpg") and !file_exists($this->imagesFolder.$x.".png") and !file_exists($this->imagesFolder.$x.".gif")){
                    $this->imageCount = $x;
                    break;
                }
            }

           $this->imageCount--;
        }
        public function setCanvasSize( ){

            $canvas = WideImage::load($this->imagesFolder."canvasArea.jpg")->resize($this->canvasWidth, $this->canvasHeight, "fill");
            $canvas->saveToFile($this->imagesFolder."tempArea.jpg");
        }
        public function resizeAllIcons( ){

            $loopEnable = true;

            for ($x=1; $loopEnable == true; $x++){
                if (file_exists($this->imagesFolder.$x.".jpg")){
                    $iconImage = WideImage::load($this->imagesFolder.$x.".jpg")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
                    $iconImage->saveToFile($this->imagesFolder.$x.".jpg");
                }
                else if (file_exists($this->imagesFolder.$x.".png")){
                    $iconImage = WideImage::load($this->imagesFolder.$x.".png")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
                    $iconImage->saveToFile($this->imagesFolder.$x.".png");
                }
                else if (file_exists($this->imagesFolder.$x.".gif")){
                    $iconImage = WideImage::load($this->imagesFolder.$x.".gif")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
                    $iconImage->saveToFile($this->imagesFolder.$x.".gif");
                }
                else{
                $loopEnable = false;
                }
            }

        }
        public function processSpriteSheet( ){

            $this->resizeAllIcons();
            $this->setCanvasSize();

            $row=0; $col=0; $tempImageCounter = 1;

            while ($tempImageCounter<=$this->imageCount){

                $icon;

                if (file_exists($this->imagesFolder.$tempImageCounter.".jpg")){
                    $icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.jpg');
                }
                else if (file_exists($this->imagesFolder.$tempImageCounter.".png")){
                    $icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.png');
                }
                else if (file_exists($this->imagesFolder.$tempImageCounter.".gif")){
                    $icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.gif');
                }
                else{
                    break;
                }

                $canvas = WideImage::load($this->imagesFolder."tempArea.jpg");
                $canvas->merge($icon, $row*$this->eachImageWidth, $col*$this->eachImageHeight, 100)->saveToFile($this->imagesFolder."tempArea.jpg");
                $tempImageCounter++;
                $row++;
                if ($row == $this->maxImageInARow){
                    $row=0;
                    $col++;
                }
            }

        }
        public function processSpriteSheetCss($maxImageCss){
            echo "maxImage:".$maxImageCss;

            $imgCommon = "img.common{
                          width: ".$this->eachImageWidth."px;
                          height: ".$this->eachImageHeight."px;
                          background-image:url(home.jpg);
                          }";

            $imgS=""; $y=0; $tempImageCounter = 1;

            for($x=0; $tempImageCounter<=$maxImageCss; $x++){
                $imgS = $imgS."img.s".$tempImageCounter."{background-position:".-1*($x*$this->eachImageWidth)."px ".-1*($y*$this->eachImageHeight)."px;}";
                if ($tempImageCounter%$this->maxImageInARow == 0){
                    $x = -1;
                    $y++;
                }
                $tempImageCounter++;
            }

            echo "SpriteSheetCSS".$imgS;
            $handle = fopen( "../css/sprite.css", "w" );
            fwrite($handle, $imgS);

        }

        public function getImageCount(){
        echo "total number of images-->".$this->imageCount;
        return $this->imageCount;
        }

    }

    ?>

My script stops execution at that line without any error.
This file works perfectly on localhost but when I put this online and execute it then this problem happens.


Q: Show login password as it is typed The keyboard on my 8 year-old laptop is becoming less reliable, often a keypress won't register first time and sometimes, if pressed too hard, will repeat. This is not a big deal except when logging into Ubuntu via the graphical login screen, because by default the login password is shown as asterisks and sometimes I enter the wrong password two or three times before having to resort to clicking on the eye to see what I have actually typed.
It would be very useful for me to have the actual keypresses shown at login, rather than asterisks, as default. Is this possible?


Q: Is there a word for the satisfaction of finding what you were looking for? Basically, Title. Is there any word for that feeling when you finally find what you've been looking for? Be it a definition for a word, or your long lost brother, or some rare bird.
Edit: To clarify, not necessarily a new discovery, but perhaps something lost, or that you know is out there, you just didn't know where until you found it. I guess it would be some variant of 'satisfaction'

A: eureka moment TFD
A moment or instance at which a sudden, revelatory idea, realization, or solution to a problem comes to mind. We'd been working on the problem in the lab for weeks, but the eureka moment came to me when I was out gardening!

A: Eureka moment is good for the really big realizations.  For more everyday use:
Aha moment

a moment of sudden realization, inspiration, insight, recognition, or comprehension The aha moment you experience when you've been trying to remember the name of a song and three hours later it hits you … —Jeffrey Kluger (Merriam-Webster)

A: Jubilation

a feeling of great happiness and triumph.

Jubilation: Google's dictionary - jubilation


Q: how to put recaptcha and submit in one line contact form 7 How to add these elements in one line:
[recaptcha] [submit "Send"]

So recaptcha will be on the left and submit button on the right
WordPress wraps each shortcode with div.

A: Give the fields class names in Contact Form 7:

[recaptcha id:recaptchaform]
[submit "Send"]

Then set your CSS to be:
.recaptchaform {float:left}
.cf7submitbtn {float:right}


Q: How Can I migrate magento 1.9 code to magento 2.3 I created a newsletter checkbox on magento 1,9 checkout and it work fine. There is the code :
app/design/frontend/default theme/default/template/persistent/ Checkout/onepage/billing.phtml
Newsletter : <input type="checkbox" name="billing[is_subscribed]" title="" value="1" id="billing:is_subscribed" class="checkbox" checked="checked" />

And finaly : app/code/core/(le nom de ton Magento)/Checkout/controllers/Onepagecontroller.php
  if (isset($data['is_subscribed'])) {
        $status = Mage::getModel('newsletter/subscriber')->subscribe($data['email']);
    }

It work like charm in magento 1.9 but I do not know how to put that in Magento 2.3 is not the same structure :/
Someone can help me ?
Best regards


Q: Magento Product View Page: Add Layout Changes Depending on Product Search or Category Browsing Using Magento 1.7.0.2 CE, I would like to try to find a way to make XML layout changes to the Product View page, depending on if the product was searched in-site or found from the category view. Reason being, the custom vertical navigation on the left bar I made for our site uses the "current_category" key in the Magento registry to display correctly.
If there is no category set, it displays our 7 major base categories. If a category is set, it displays only the sub-categories of that base category (~34 sub-cats, expands with active sub-category). So naturally, I would like to even out my sidebar space when the vertical navigation bar is small.
If a product is browsed through a category, the registry keeps the "current_category" key, so my vertical navigation fills the left bar quite well on its own. If it is searched, the navigation bar approaches about 30% of the height when compared with the right bar.
My ideal solution would be a layout update to local.xml, but I'm not sure if there is anything already built in place with Magento to do so.
So my final question is in two parts: Is there a way within Magento's XML Layout to determine if the "catalog_product_view" page was loaded via category or search?
If not: What would be the most efficient way to code in moving a couple blocks from the right bar to the left from the product view page, depending on if the product was searched or browsed?
One possible solution (for the last bit): Would anyone know how to code in a new layout tag? I was thinking of instead of just "catalog_product_view", creating "catalog_product_view_browsed" and "catalog_product_view_searched" that are applied over the default product view.
Edit: I have it working and my answer has been posted below. :)

A: In order to use custom layout handles in your local.xml file, first you have to make an observer for it. To create an observer, you start out by adding it as an extension / module. Create the following files/folders if not present (The names Yourname and Modulename can be anything, just make sure it's the same where it shows up, including upper/lower case):
Directory View
/app/etc/modules/Yourname_Modulename.xml
/app/code/local/Yourname/Modulename/etc/config.xml
/app/code/local/Yourname/Modulename/Model/Observer.php

Now that you have the file structure, let's look at the first file, Yourname_Modulename.xml tucked in the app/etc/modules/ folder:
Yourname_Modulename.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Yourname_Modulename>
            <codePool>local</codePool>
            <active>true</active>
        </Yourname_Modulename>
    <modules>
<config>

Now /app/code/local/Yourname/Modulename/etc/config.xml:
config.xml
<?xml version="1.0"?>
<config>
    <global>
        <models>
            <yournamemodulename>
                <class>Yourname_Modulename_Model</class>
            </yournamemodulename>
        </models>
    </global>
    <frontend>
        <events>
            <controller_action_layout_load_before>
                <observers>
                    <yourname_modulename_model_observer>
                        <type>singleton</type>
                        <class>Yourname_Modulename_Model_Observer</class>
                        <method>controllerActionLayoutLoadBefore</method>
                    </yourname_modulename_model_observer>
                </observers>
            </controller_action_layout_load_before>
        </events>
    </frontend>
</config>

And lastly the file /app/code/local/Yourname/Modulename/Model/Observer.php. For this one, you'll need to know what you'd like to name "your_layout_handle" and also how to determine if your layout should be loaded via PHP.
Observer.php
<?php
    class Yourname_Modulename_Model_Observer
    {
        public function controllerActionLayoutLoadBefore( Varien_Event_Observer $observer)
        {
            //Get Layout Object
            $layout = $observer->getEvent()->getLayout();

            /*
            *Begin Logic to Determine If Layout Handle Should Be Applied.
            *Below Determines If We Are On A Product View Page.
            *Here is Where You Would Modify The Code For Different Layout Handles
            */
            if( Mage::registry( 'current_product' ) ) {

                //Check if current_category is set
                if( Mage::registry( 'current_category' ) ) {

                    //Send Layout Update Handle If Product Was Browsed
                    $layout->getUpdate()->addHandle( 'your_layout_handle' );
                }
                else {

                    //Send Layout Update Handle If Product Was Linked or Searched
                    $layout->getUpdate()->addHandle( 'your_other_handle' );
                }
            }
        }
    }

I would say that is all, but of course you now need to do something with your layout handles in app/code/design/frontend/package/theme/layout/local.xml. How it behaves is up to you, but for an example here is the sections that apply in my local.xml. The names I used for my handles were "catalog_product_view_browsed" and "catalog_product_view_searched".
local.xml
<!-- Jump To Relevant Section -->

    <catalog_product_view_browsed>
        <reference name="left">
            <action method="unsetChild">
                <name>left.poll</name>
            </action>
        </reference>
        <reference name="right">
            <action method="insert">
                <blockName>left.poll</blockName>
                <siblingName>right.newsletter</siblingName>
                <after>0</after>
            </action>
        </reference>
    </catalog_product_view_browsed>

    <catalog_product_view_searched>
        <reference name="left">
            <action method="insert">
                <blockName>right.newsletter</blockName>
                <siblingName>left.vertnav</siblingName>
                <after>1</after>
            </action>
        </reference>
        <reference name="right">
            <action method="unsetChild">
                <name>right.newsletter</name>
            </action>
        </reference>
    </catalog_product_view_browsed>

<!-- End Relevant Section -->

You may need to refresh/clean your cache. That should be it.

A: There's unfortunately no way to track referring pages in Magento's layout XML, but you can tell if someone came to the product page from a search by checking $_SERVER['HTTP_REFERER'].
If a user comes to a product page from a search, the referring url will look like this: /catalogsearch/result/?q=[SEARCH TERM].


Q: Linux Terminal Characters Show Up as Symbols Rather Than As Typed On Keyboard I am using Ocaml from a Linux terminal. Sometimes it gets stuck in a weird mode where it does not respond to my keyboard as expected. For example, if I press the arrows up, down, right, and left, it generates ^[[A^[[B^[[C^[[D in input. Alternatively, sometimes if I type a letter only once it might repeat that same letter three times in a row and/or if I type the delete button it types "^H" instead.
Does anyone know what is going on here? I assume that I am inadvertently doing something to switch the mode but I don't how to switch it back or why it is switching in the first place.

A: I believe this is essentially a duplicate of this other Stack Overflow question:

Is it possible to use arrow keys in OCaml interpreter?

The stock version of the OCaml interpreter doesn't interpret special keys like arrow keys. So it will just echo their control codes (as Ben Graham points out). To get the kind of behavior you probably want (editing the input, going back to previous lines, etc.) you need to wrap the OCaml interpreter with a line editing facility. See the other question linked above for some suggestions.
This doesn't explain why you see different "modes" of behavior, but I still think this is how you want to think about your problem.

A: You should use Utop. Utop is a OCaml interpreter which offers auto-completion (like bash) and a history of command. Of course, all problems with arrow keys disappears.
You'll need to compile Zed and Lambda-Term to compile Utop.


Q: While scraping the website through scrapy in python getting the following error:
Error: UnicodeEncodeError: 'charmap' codec can't encode character
  u'\u201c' in position 0: character maps to

Code : # -- coding: utf-8 --
import scrapy

class Spider1Spider(scrapy.Spider):
    name = 'spider_1'
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = (
        'http://quotes.toscrape.com/' ,
        )

    def parse(self, response):
     x=response.xpath('//*[@class="quote"]')
     for quotes in x:
        text= x.xpath('.//*[@class="text"]/text()').extract_first()
        author= x.xpath('.//*[@class="author"]/text()').extract_first()
        Tags= x.xpath('.//*[@class="keywords"]/@content').extract_first()

        print '\ n'
        print text
        print author
        print Tags
        print '\ n'

Problm: if i use extract_first only then it's throwing the error else we use only extract. it work fines.
Could anyone please help as i am new to programming world and looking forward for positive solution.

A: You need to .encode() your Unicode strings before print:
print text.encode('utf-8')
print author.encode('utf-8')
print Tags.encode('utf-8')


Q: Mysql count columns I have a table for image gallery with four columns like:
foid | uid | pic1  | pic2  | pic3  | date     |
-----------------------------------------------
104  |  5  | 1.jpg | 2.jpg | 3.jpg | 2010-01-01
105  | 14  | 8.jpg |       |       | 2009-04-08
106  | 48  | x.jpg | y.jpg |       | 2010-08-09

Mysql query for the user's galleries looks like:
SELECT * FROM foto WHERE uid = $id order by foid DESC

The thing that I want to do is count the number of images (PIC1, PIC2, PIC3) in every of the listed galleries.
What is the best way for doing that?

A: I am assuming that each foid represents a gallery:
SELECT foid, uid, date,
       (CASE WHEN pic1 IS NULL THEN 0 ELSE 1 END +
        CASE WHEN pic2 IS NULL THEN 0 ELSE 1 END +
        CASE WHEN pic3 IS NULL THEN 0 ELSE 1 END
       ) AS pic_count
  FROM foto
 WHERE uid = $id
 ORDER BY foid DESC

Incidentally, this isn't a particularly sensible way to structure your schema. You really should split the pics out as a separate table:
foto:
foid | uid | date
-----------------------
104  |  5  | 2010-01-01
105  | 14  | 2009-04-08
106  | 48  | 2010-08-09

pic:
foid | pic
------------
104  | 1.jpg
104  | 2.jpg
104  | 3.jpg
105  | 8.jpg
106  | x.jpg
106  | y.jpg

Now, galleries can have more than three pics and querying is simpler:
SELECT foid, uid, date, COUNT(*)
  FROM foto
  JOIN pic USING (foid)
 WHERE uid = $id
 ORDER BY foid DESC
 GROUP BY foid, uid, date

EDIT: You can split an existing database thus (just guessing at stuff like column types):
CREATE TABLE picture (foid INT, pic VARCHAR(255));

INSERT INTO picture (foid, pic)
        SELECT foid, pic1 as pic FROM foto WHERE pic IS NOT NULL
        UNION
        SELECT foid, pic2 as pic FROM foto WHERE pic IS NOT NULL
        UNION
        SELECT foid, pic3 as pic FROM foto WHERE pic IS NOT NULL
    ;

ALTER TABLE foto
    DROP COLUMN pic1,
    DROP COLUMN pic2,
    DROP COLUMN pic3
    ;

Obviously, one should exercise considerable care when dropping columns, and make a backup before you start!


Q: JWT x5c token validation .net core I would like to validate a JWS token with "alg": "ES256", "x5c" header fields only.
x5c field contain 3 certificates. I'm able to load them but .net return a IDX10503 error telling me kid field is missing.
here is my code :
var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(token);

var x5cList = JsonConvert.DeserializeObject<List<string>>(jwtSecurityToken.Header.X5c);

var certs = ValidateCertificate(x5cList.ToList());
var keys = certs.Select(cert => new X509SecurityKey(cert)).ToList();

SecurityToken validatedToken;
handler.ValidateToken(jwtSecurityToken.RawData, new TokenValidationParameters
{
    ValidateLifetime = true,
    ValidateIssuer = true,
    ValidateIssuerSigningKey = true,
    IssuerSigningKeys = keys,
    TryAllIssuerSigningKeys = true,
}, out validatedToken);

Anyone know why it's not working ? I also tried to don't load keys by myself thinking that JwtSecurityTokenHandler may be able to do it by it self but it's not working as well.
When I load this token on jwt.io it says it is validated...


Q: Logistic regression with small and differing sample sizes I am relatively new to statistics and confused about the best way to proceed with this logistic regression model (and if it is the correct statistical test to use).
I ran the model in SAS and I can't make sense of the results. My first question- does it matter that the groups are quite different in size AND the sample size is small? The total sample size excluding missing values is 57, with 13 in Group 3, 18 in Group 2, 26 in Group 1.
Second question- The odds ratios are very small, ranging from  <.0001 to 0.9 with a 95%CI of seemingly infinity. Is this just a function of the sample size?
Am I missing something here that would give more accurate results, or should a different test be utilized? It seems like as it stands it is not worth moving forward with the analysis.
The independent variable is social support-- continuous and ranging from 1.10 to 4 in 0.10 increments.
The outcome variable is sleep quality that has been combined into 3 separate groups -- categorical.
Thank you in advance!


Q: Custom Apache 2.2 directory pages Like the title says, I want to take the ugly default HTML 3.2 directory page that come with Apache, and replace it with a modern, better looking page.
Anyone know how? Is it even possible? Is the page generated somewhere deep inside the source code? Tell me stuff like that, please.
P.S. I use the built in Apache server on Mac OS X 10.6.6.

A: Assuming you mean the file listing you see of a webserver directory when there is no index.html present and +Indexes is on -- All you need to do is add a html file with the style/fanciness you want and point apache at it with the
HeaderName /header.html
directive.  It'll be included at the top of every auto-generated index.
The directory lists are indeed created in the guts of apache, by mod_autoindex, which is where I found this directive: http://httpd.apache.org/docs/2.0/mod/mod_autoindex.html


Q: updating NSManagedObject doesn't call NSFetchedResultsControllerDelegate using MagicalRecord I have a model with this one to many relationShip:
Order -->> LineItem

I display LineItems in UITableViewCells:

I use UIPickerView for changing quantity of LineItems.
GOAL=> by changing picker value, subTotal be recalculated again.
the problem is here by updating lineItem, NSFetchedResultsController Delegate doesn't call (where I can reconfigure the cell again and display updated data). but when I update Order e.g set it as completed NSFetchedResultsController Delegate methods will be called.
why by updating lineItem doesn't affect delegates methods to be called?
I use magicalRecord and here is how I get NSFetchedResultsController
- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    else
    {
        _fetchedResultsController = [Order fetchAllSortedBy:@"orderDate" ascending:YES withPredicate:nil groupBy:nil delegate:self];
    }

    return _fetchedResultsController;
}

the way I setup table view:
ConfigureCellBlock configureCell = ^(OrderDetailsCell *cell, LineItem *lineItem)
{
    [cell configureForLineItem:lineItem];
};
//set fetchedresults controller delegate
Order *order = [[self.fetchedResultsController fetchedObjects] lastObject];
NSArray *lineItems = [order.lineItems allObjects];

self.ordersDataSource = [[ArrayDataSource alloc] initWithItems:lineItems cellIdentifier:@"lineItemCell" configureCellBlock:configureCell];
self.tableView.dataSource = self.ordersDataSource;

configuring cell:
- (void)configureForLineItem:(LineItem *)lineItem
{

self.menuItemName.text = lineItem.menuItemName;
self.price.text = [lineItem.unitPrice stringValue];
self.quantity.text = [lineItem.quantity stringValue];
self.totalPrice.text = [lineItem.totalPrice stringValue];

self.pickerController.model = lineItem;
self.picker.delegate = self.pickerController;
self.picker.dataSource = self.pickerController;
[self.picker setSelectedNumber:lineItem.quantity];
}

does fetching obj1 then updating obj3 cause the NSFRC delegate methods to be called?

A: The FRC will only observe changes to the objects that it is directly interested in, not any of the objects that they are related to.
You should configure your own observation, either directly with KVO or to the context being saved, and use that to trigger a UI refresh.


Q: jQuery Mobile changePage() not working in WP8.1 Hi I've spent a long time trying to get my jquery mobile (v1.4.5) and cordova (v5.3.1) app running on WP8.1. It runs fine on iOS and Android. I am aware of this SO question, and the problem I'm having is not related to this, or any others on SO.
Changepage seems to get stuck on WP8.1 because it thinks my app is still in a page transitioning state. For some reason releaseTransitionLock is not being called when it should from a previous transition.
If I comment out the if(isPageTransitioning) check in the 'change' method then it works, but I presume this has negative side-effects elsewhere.
It's a multipage app where all the pages are divs in the same html doc and I'm running jQuery v2.0.3. My changepage syntax is this, and I've tried it with transition 'none' and a variety of other options:
$.mobile.changePage("#register", { transition: "slide" });

Has anyone observed this behaviour and come up with a diagnosis or fix?

A: Use below method and it will work definitely
$.mobile.navigate("#register", {transition: "slide"});


Q: Trying to use geojson data to plot a district level choropleth I recently been interested in doing a chloropleth map of average rent prices in San Francisco over time. For example if I had a dataset like
example Dataset
data = {'district' : ['6a', '6b','7a', '7c', '5f'],
        'price' : [1000, 1500,2000 ,2500, 1750]

        }
data = pd.DataFrame(data)

GeoJson San Francisco Districts
import requests
r = requests.get('https://raw.githubusercontent.com/JimKing100/SF_Real_Estate_Live/master/data/Realtor%20Neighborhoods.geojson')
json_response = r.json()
type(json_response)

San Francisco district breakdown https://www.houseofkinoko.com/sf-district-guide/
I was wondering how I would use plotly or other data visualization tools to create a detailed 'zoomed- in' choropleth of san francisco filled by the varying prices.
Sorry if this is a bit vague but I'm a bit lossed and confused on how I should proceed with this project.


Q: how to install specific branch of git repository using yarn? I am able to install one GitHub package but not other using yarn. Please let me know what could be the issue here.
I can add https://github.com/fancyapps/fancybox#3.0
but not https://github.com/opentripplanner/otp-react-redux#result-post-processor
ravis-MacBook-Pro:gitprojects ******$ mkdir test
ravis-MacBook-Pro:gitprojects ******$ cd test
ravis-MacBook-Pro:test ***********$ yarn init
yarn init v1.6.0
question name (test):
question version (1.0.0):
question description:
question entry point (index.js):
question repository url:
question author:
question license (MIT):
question private:
success Saved package.json
✨  Done in 11.54s.

ravis-MacBook-Pro:test ******$ yarn add https://github.com/fancyapps/fancybox#3.0
yarn add v1.6.0
info No lockfile found.
[1/4]   Resolving packages...
[2/4]   Fetching packages...
[3/4]   Linking dependencies...
warning " > @fancyapps/fancybox@3.0.48" has unmet peer dependency "jquery@>=1.9.0".
[4/4]   Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ @fancyapps/fancybox@3.0.48
info All dependencies
└─ @fancyapps/fancybox@3.0.48
✨  Done in 1.35s.

ravis-MacBook-Pro:test *******$ yarn add https://github.com/opentripplanner/otp-react-redux#result-post-processor
yarn add v1.6.0
[1/4]   Resolving packages...
error Can't add "otp-react-redux": invalid package version undefined.
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
ravis-MacBook-Pro:test *******$

A: UPDATE
Please note that for Yarn 2+ you need to prefix the URL with package name:
yarn add otp-react-redux@https://github.com/opentripplanner/otp-react-redux#head=result-post-processor

A: You need use you git remote url and specify branch after hash(#).
yarn add https://github.com/opentripplanner/otp-react-redux.git#result-post-processor

installs a package from a remote git repository at specific git branch, git commit or git tag.
yarn add <git remote url>#<branch/commit/tag>


Q: Prove $K(\mathbb{Z}^n,2) = B\mathbb{T}^n$ I want to proof statement $K(\mathbb{Z}^n,2) = B\mathbb{T}^n$, how can I do that? I need to use Chern classes or something like that? Hope for your help.

A: Let $X$ be a topological space, a map $f:X\rightarrow B\mathbb{T}^n$ defines a $\mathbb{T}^n$-bundle over $X$, defined by $1$-cocycle $c\in H^1(X,\mathbb{T}^n)=H^2(X,\mathbb{Z})$. This follow from the exact sequence $0\rightarrow \mathbb{Z}^n\rightarrow\mathbb{R}^n\rightarrow \mathbb{T}^n\rightarrow 1$; since $\mathbb{R}^n$ is contractible, the long exact sequence in cohomology gives $H^n(X,\mathbb{T^n})=H^{n+1}(X,\mathbb{Z}^n)$.
Since $K(\mathbb{Z}^n,2)$ represents the $2$-singular cohomology with coefficients in $\mathbb{Z}^n$; that is the set of homotopy classes of maps $[X,K(\mathbb{Z}^n,2)]=H^2(X,\mathbb{Z}^n)$ we deduce that $B\mathbb{T}^n=K(\mathbb{Z}^n,2)$.


Q: JdbcPagingItemReader with SELECT FOR UDATE and SKIP LOCKED I have a multi instance application and each instance is multi threaded.
To make each thread only process rows not already fetched by another thread, I'm thinking of using pessimistic locks combined with skip locked.
My database is PostgreSQL11 and I use Spring batch.
For the spring batch part I use a classic chunk step (reader, processor, writer). The reader is a jdbcPagingItemReader.
However, I don't see how to use the pessimist lock (SELECT FOR UPDATE) and SKIP LOCKED with the jdbcPaginItemReader. And I can't find a tutorial on the net explaining simply how this is done.
Any help would be welcome.
Thank you

A: I have approached similar problem with a different pattern.
Please refer to
https://docs.spring.io/spring-batch/docs/current/reference/html/scalability.html#remoteChunking
Here you need to break job in two parts:

*

*Master

Master picks records to be processed from DB and sent a chunk as    message to queue task-queue. Then wait for acknowledgement on    separate queue ack-queue once it get all acknowledgements it move to next step.

*

*Slave

Slave receives the message and process it.
send acknowledgement to ack-queue.


Q: XML Schema is not validating I am working on XML and Schemas. I need help validating my schema, as when I put it in an online validator, I get an error of: S4s-elt-must-match.1: The Content Of 'sequence' Must Match (annotation?, (element | Group | Choice | Sequence | Any)*). A Problem Was Found Starting At: ComplexType.
I am using the Russian Doll design, as this seems to be the one I like the most.
catalog.xml
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<catalog xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance" xsi:noNamespaceSchemaLocation="catalog.xsd">
   <photo cid="c1749" donatedBy="John Borelli">
      <name metadata="tunis cooper property museum">Tunis R. Cooper property</name>
      <description>
      <![CDATA[
         A more recent picture of the property taken by the Borelli family.  The property is listed in the
         National and New Jersey Registers of Historic Places.
      ]]>
      </description>
      <date>circa 1950</date>
      <images>
         <img src="1749a.jpg" />
      </images>
   </photo>

   <photo cid="c1411" donatedBy="Saint Johns Catholic Church">
      <name metadata="saint johns catholic church">Saint Johns Church</name>
      <description>
      <![CDATA[
         A more recent picture of the property taken by the Borelli family.  The property is listed in the
         National and New Jersey Registers of Historic Places.
      ]]>
      </description>
      <date>1921</date>
   </photo>
</catalog>

catalog.xsd
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="catalog">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="photo"/>
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="name" type="xs:string"/>
                        <xs:element name="description" type="xs:string"/>
                        <xs:element name="data" type="xs:string"/>
                        <xs:element name="images">
                            <xs:complexType>
                                <xs:simpleContent>
                                    <xs:element name="img"/>
                                </xs:simpleContent>
                            </xs:complexType>
                        </xs:element>
                        <xs:attribue name="cid" type="xs:string"/>
                        <xs:attribue name="donatedBy" type="xs:string"/>
                        <xs:attribue name="metadata" type="xs:string"/>
                        <xs:attribue name="src" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

A: You had a couple of errors in your XSD. And one in your XML.
To remove this one error in your XML, change the namespace in the <catalog...> element from xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance" to xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance". A simple typo.
And your XSD should look like this to validate your XML:
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="catalog">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="photo" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name">
                                <xs:complexType>
                                    <xs:simpleContent>
                                        <xs:extension base="xs:string">
                                            <xs:attribute name="metadata" type="xs:string"/>
                                        </xs:extension>
                                    </xs:simpleContent>
                                </xs:complexType>
                            </xs:element>
                            <xs:element name="description" type="xs:string"/>
                            <xs:element name="date" type="xs:string"/>
                            <xs:element name="images" minOccurs="0">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="img"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                        <xs:attribute name="cid" type="xs:string"/>
                        <xs:attribute name="donatedBy" type="xs:string"/>
                        <xs:attribute name="metadata" type="xs:string"/>
                        <xs:attribute name="src" type="xs:string"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

What I changed was:

*

*The element photo occurs more than one time, so I added maxOccurs="unbounded"

*The element name can have an attribute, so I changed its definition to a complexType with simpleContent.

*The element images does not have to occur, hence I added minOccurs="0"

*I moved the attributes out of the xs:sequence into the xs:complexType
Now the XSD should validate your XML.


Q: How to remove the dots from custom menu with CSS I want to remove(hide) bullets (dots) with css code, but I can`t
Please tell me what I do wrong:
1) I give class name in my case: .no-bullets
2) I use this css code:
.no-bullets {
    list-style-type: none;
}

this is not working for me...
Then I use this css in theme stylesheet:
ul
{
    list-style-type: none !important;
}

again nothing...
Please help me with this, thank you in advance

A: here is my suggestion:
ul {
    list-style: none;}

A: the list-style properties apply to elements with display: list-item only ,make sure your list elements doesnt have any other display style.UPDATE
seeing your link your style.css file is overriding your custom style with list-style-type: disc; you have to get rid of this line.
UPDATE 2use this code in your custom css  .entry-content ul > li {
    list-style-type: none !important;
}
 this will do the job quickly.


Q: Click to drop widget using gwt-dnd library I'm using gwt-dnd library and I would like to know how to make click to drop.
That is, click the widget to move, release the mouse button, drag the widget and click to drop.
Thank you.

A: It's pretty big hacking. gwt-dnd handles mouse events by  MouseDragHandler class and it's tightly coupled with AbstractDragController, so you must provide your own implementation of this handler (just extend it) which will call onMouseDown and onMouseUp methods on your click events. But you must also override AbstractDragController, so you end up rewriting half of the library.


Q: Error in installation of Adobe Acrobat Reader - "The package is of bad quality" To install Adobe Acrobat Reader in my Ubuntu 13.04 amd64bit I downloaded the .deb installation file from the Adobe-Website and opened the file using the Software center (as suggested while downloading).
The installation failed, with the Software Center warning me that "The package is of bad quality" and giving me a long list of details starting with this
Lintian check results for /tmp/AdbeRdr9.4.2-1_i386linux_deu.deb:

E: adobereader-deu: control-file-has-bad-permissions postinst 0555 != 0755

E: adobereader-deu: control-file-has-bad-owner postinst acrorel/named != root/root

E: adobereader-deu: control-file-has-bad-permissions prerm 0555 != 0755

E: adobereader-deu: control-file-has-bad-owner prerm acrorel/named != root/root

E: adobereader-deu: maintainer-address-missing Adobe Systems, Incorporated

E: adobereader-deu: wrong-file-owner-uid-or-gid etc/ 10490/25

E: adobereader-deu: wrong-file-owner-uid-or-gid etc/bash_completion.d/ 10490/25

E: adobereader-deu: wrong-file-owner-uid-or-gid etc/bash_completion.d/acroread.sh 10490/25

E: adobereader-deu: wrong-file-owner-uid-or-gid opt/ 10490/25

E: adobereader-deu: wrong-file-owner-uid-or-gid opt/Adobe/ 10490/25

E: adobereader-deu: wrong-file-owner-uid-or-gid opt/Adobe/Reader9/ 10490/25

E: adobereader-deu: wrong-file-owner-uid-or-gid opt/Adobe/Reader9/Browser/ 10490/25

...going on with a list of details all starting with:

E: adobereader-deu: wrong-file-owner-uid-or-gid opt/Adobe/Reader9/

Now I don't know whether I can install it anyway, ignoring the warning, or how the problem can be solved. Does anyone have an idea?
Thanks!

A: If you don't actually need Adobe Reader, use Evince, which is included in Ubuntu.
Since the author of this question only needs annotation, Evince can do that, but the option is hidden. Here's how to annotate PDFs in Evince.
If you actually have a reason to need Adobe Reader, ignore how they sloppily made their package, and install it anyway.


Q: Proving an arbitrary process is Brownian motion I am new to the world of stochastic processes and Brownian motion, and am having a hard time finding easily digestible reference material (especially ones with well-worked out examples). So, in a way this question is more of a request for sources/references than a specific answer.
To give a little context to where I am approaching this from, it is specifically from the class of statistics referred to as "group sequential testing" (though there are several similar or analagous names, such as "interm analyses", "conditional power calculations", "futility analyses", etc.). I am posting this here rather than on CrossValidated simply because cursory searches reveal that people here are more familiar with the basics of stochastic processes than seems to be the case over on the stats-specific StackExchange, so I feel that I will get more helpful advice/answers here.
Anyway, the primary textbook for this field of statistical analyses is Statistical Monitoring of Clinical Trials: A Unified Approach, by Proschan, Lan, and Wittes. The basic mathematical framework for much of the book is Brownian motion; that is, the theory behind many of the group sequential tests outlined in the book is founded on the fact that standardized test statistics evaluated over time can be seen to satisfy the properties of Brownian motion. What I am trying to do is prove whether or not certain classes of non-parametric statistics (specifically the Wilcoxon rank-sum) satisfy these properties, and thus allow one to use this broader framework in that context.
So, what I am looking for are sources or references with examples of demonstrating how some arbitrary process can be shown to satisfy the properties of Brownian motion. When I search this site or Google, I can find dozens of examples, but none of them are quite that helpful, since the are generally all based on proving that some function of a Weiner process is itself a Weiner process (e.g. this question or this one). These aren't terribly illustrative to me, since the proofs all rely on the fact that some element of the process under consideration is already given to satisfy the properties of Brownian motion, rather than "starting from scratch", so to speak.
Now, I do know the basic steps for proving a process is Brownian motion (this question has them delineated rather nicely). However, I am having a difficult time finding any worked examples of these steps being applied to a process "from scratch" (which is especially critical since I am unfamiliar with a lot of the notations used in stochastic processes, which are often subtly different than those taught to us statisticians).
Can anybody point me in the direction of some nice examples or references that would be helpful, here?


Q: How to avoid repeated jobs (one per core) when I'm trying to launch different threads? I'm processing multiple big independent files (same process for each file, no communication between processes). So, I have a situation that seems  great for parallel multicore processing. And, in fact, I have access to a nice server (Scientific Linux -Red Hat Enterprise-) with multiple cores.
I'm trying to write some scripts with Perl in order to take profit of these cores. I tried both the threads module and Parallel::ForkManager. I launch the works to the server using sbatch, where I can define the number of tasks (cores) I will use (and the memory I will take, etc.). Nevertheless, when  I launched a job selecting X number of tasks, the job is not divided between cores, but always carry out repeatedly (X times, once in each core). I'm sure I'm missing something big (and basic!) but after one week going in all the directions, I don't realize what it is. What's going wrong???
Here is a sample Perl script (test.pl):
#!/usr/bin/perl -w

use strict;
use threads;
use Benchmark qw(:hireswallclock);

my $starttime = Benchmark->new;
my $finishtime;
my $timespent;
my $num_of_threads = 4;

my @threads = initThreads();
foreach(@threads){
    $_ = threads->create(\&doOperation);
}
foreach(@threads){
    $_->join();
}
$finishtime = Benchmark->new;
$timespent = timediff($finishtime,$starttime);
print "\nDone!\nSpent ". timestr($timespent);

sub initThreads{
    my @initThreads;
    for(my $i = 1;$i<=$num_of_threads;$i++){
        push(@initThreads,$i);
    }
    return @initThreads;
}
sub doOperation{
    # Get the thread id. Allows each thread to be identified.
    my $id = threads->tid();
    my $i = 0;
    while($i < 100000000){
            $i++
    }
    print "Thread $id done!\n";
    # Exit the thread
    threads->exit();
}

And here, an example of an sbatch script used to launch it:
#!/bin/bash -x
#SBATCH --job-name=prueba
#SBATCH -e slurm-%j.out
#SBATCH --ntasks=4
#SBATCH --mem=12G
srun perl -w test.pl

The output (as I said, it seems that the whole process have been repeated once in each core):
Thread 4 done!
Thread 1 done!
Thread 1 done!
Thread 4 done!
Thread 3 done!
Thread 3 done!
Thread 1 done!
Thread 3 done!
Thread 1 done!
Thread 4 done!
Thread 4 done!
Thread 3 done!
Thread 2 done!
Thread 2 done!
Thread 2 done!
Thread 2 done!

Done!
Spent 36.1026 wallclock secs (36.02 usr +  0.00 sys = 36.02 CPU)

A: With --ntasks=4, srun will launch 4 identical Perl processes. What you want is --ntasks=1 and --cpu-per-task=4 so that Slurm allocates four cores on one node for your job.


Q: How to launch console application using CreateProcess with Minimized main window I have a native c++ windows application that is launching two child processes using the following code -
if (!CreateProcess(NULL, // No module name (use command line)
    cmdLine, // szCmdline, // Command line
    NULL, // Process handle not inheritable
    NULL, // Thread handle not inheritable
    false, // Set handle inheritance to FALSE
    CREATE_DEFAULT_ERROR_MODE | NORMAL_PRIORITY_CLASS // Process Create Flags
    NULL, // Use parent's environment block
    NULL, // workingDir, // Use parent's starting directory
    &si, // Pointer to STARTUPINFO structure
    &pi) // Pointer to PROCESS_INFORMATION structure

with all parameters in STARTUPINFO block 0.  This code works fine in launching the processes.  However, I need to be able to launch the windows c++ console applications with their windows minimized.
If I add CREATE_NO_WINDOW to the Process Create Flags, I can launch the processes without any windows.  This will be unacceptable.
In my research, there does not appear to be a way force a console application to open in a minimized mode.  Is this correct?
Yes, I know that I could minimize the child application windows from within their own process, however, the other programmers on the team prefer not to do this.

A: You need to specify in the STARTUPINFO structure that you want your console window to be initially minimized:
ZeroMemory(&si);
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_MINIMIZE;


Q: UITableViewCell Not Sizing To UIImageView I was wondering if anyone knows hot to fix this issue. When I run the app, the image gets cut off instead of displayed. I have attached photos to show in detail.

A: Since you have two kind of Cells in the Table View, you have to set the height of both cells programatically inside heightForRowAtIndexPath.
Currently, you have only one cell size and I think it is default to 44.0.

A: May be you doesn't set imageview's constraints properly.
Set top, bottom, left, rignt constraint of imageview with tableviewcell frame properly. Give a aspect ratio size of the imageview.
And return UITableViewAutomaticDimension from heightForRowAtIndexPath and estimatedHeightForRowAtIndexPath delegate functions.
This will work !!


Q: Statistical videos to learn regression analysis and multivariate analysis? I'm having a tough time to understand concepts of Regression Analysis and Multivariate Analysis. I'm following the books of Johnston and Anderson, but some video lectures would help me learn it faster. Could anyone suggest me some videos of the same? Thanks.

A: You may want to take a look at the following;

*

*MIT Opencourseware Linear Algebra course (especially lectures 15 and 16)

*Coursera (especially Andrew Ng's machine learning course, there is also a specialised regression course on there too)

A: Coursera is an extremely good resource. At this point in time, there are at least three upcoming courses on regression-type topics. This one may be best suited to your needs.
One major advantage to Coursera is that you can ask any specific questions about topics not covered in the videos (like Box-Cox or other transformations) in the forums. There will be TAs or other participants who will be able to help you.

A: Where are your problems?
I have heard praise for the machine learning course on coursera, which is free:
https://class.coursera.org/ml-003/lecture
Otherwise, I would recommend a book from Andy Field (learning statistics using...) which does a good job of teaching basics.

A: I agree that the mentioned Coursera courses are worth checking add. In addtion, for regression I'll recommend week 3  of this course: http://online.stanford.edu/course/statistical-learning-winter-2014 (taught by the ultimate masters of the field :) ). In week 10 you'll find some nice multivariate techniques, although the presentation is far from exhaustive.

A: http://www.statisticshell.com/  This is andy field's website. Particularly good video lectures for when you want a lecture from a different perspective that will keep you entertained.   You might find them a bit slow/lacking in detail in some areas depending on your level. Not sure transformation is covered.
Multiple regression is here: http://www.statisticshell.com/html/woodofsuicides.html and some other multivariate methods (e.g. Manova and SEM) can be found here: http://www.statisticshell.com/html/malbowges.html


Q: C# Deserialize XML to correct class type I am using the XmlSerializer to do some serialization work. I was wondering if it is possible to "generically" deserialize from the XmlDocuement.
Concrete: If I have an XML File I would watch the tag and compare it with my DTO Model. Is this possible (better: Does .NET support this?) ? Maybe using an XSD file or something?

Example (without generic deserialization):
        XmlDocument myDocument = new XmlDocument();
        myDocument.Load(xml);

        MemoryStream stream = new MemoryStream();
        myDocument.Save(stream);

        // Here I would like to use an interface instead and load the correct type of object.
        XmlSerializer serializer = new XmlSerializer(typeof(MyClass));

        MyClass myObject;

        serializer.Serialize(stream, myObject);

A: The only way is that you pre parse the xml file so you understand the class to create.
You could also write somewhere (in the file extension? in an attribute of the first element of the doc?) the class type.
When you have the class type you can create the right class via a switch statement (converting a string to a type) or via reflection (better).