text:
Q: Linear Transformation (Rotation) Let $T: \mathbb R^2 \rightarrow \mathbb R^2$ be the rotation by $π/2$ clockwise about the origin, and let $S: \mathbb R^2 \rightarrow \mathbb R^2$ be the shear along the y-axis given by $S(x, y) = (x, x + y)$. (You may assume that these are linear transformations.)
a) Write down, or compute, the standard matrix representations of T and S.
Solution:
[T] = $\begin{bmatrix} cos(π/2)&sin(π/2) \\ -sin(π/2)&cos(π/2)\end{bmatrix} = \begin{bmatrix} 0&1 \\ -1&0\end{bmatrix}$
$S(1,0) = (1,1) \implies [S(e_1)] = \begin{bmatrix} 1 \\ 1\end{bmatrix}$
$S(0,1) = (0,1) \implies [S(e_1)] = \begin{bmatrix} 0 \\ 1\end{bmatrix}$
$\implies [S] = \begin {bmatrix} 1&0 \\ 1&1 \end{bmatrix}$
b) Use (a) to find the standard matrix representations of (i) S ◦ T (T followed by S), and (ii) T ◦ S (S followed by T).
Solution:
i) S ◦ T: $\begin{bmatrix}1&0 \\ 1&1 \end{bmatrix} \begin{bmatrix} 0&1 \\ -1&0\end{bmatrix} = \begin{bmatrix} 0&1 \\ -1&1\end{bmatrix}$
ii) T ◦ S: $\begin{bmatrix} 0&1 \\ -1&0\end{bmatrix} \begin{bmatrix} 1&0 \\ 1&1\end{bmatrix} =\begin{bmatrix} 1&1 \\ -1&0\end{bmatrix}$
c) Let $C ⊆ \mathbb R^2$ be the unit square whose vertices are $(0, 0), (1, 0), (0, 1)$, and $(1, 1)$.
Draw, on separate axes, the image of C under the transformations (i) S ◦ T and (ii) T ◦ S,
clearly labelling each image. (Please draw large, clear diagrams.)
Can someone please help me with part c? And also check my solution for the first two parts?

A: Your first two parts are correct.
The point is that $S \circ T$ and $T \circ S$ are linear transformations.
Therefore, let $(x,y) \in C$. Then from what we know about $C$, we have $0 \leq x \leq 1$ and $0 \leq y \leq 1$. Observe that for any linear transformation $L$:
$$
L(x,y) = xL(1,0) + yL(0,1)
$$
Therefore,
$$
L(C) = \{xL(0,1) + yL(1,0) : x,y \in [0,1]\}
$$
From which it is easy to prove that $L(C)$ is the quadrilateral determined by the vertices $L(0,1), L(1,0), L(1,1)$ and $0$.  Calculation of these quantities for $L = S \circ T$ and $L = T \circ S$ gives you the desired conclusions.


text:
Q: How to highlight bash/shell commands in markdown? How can I highlight the Bash/shell commands in Markdown files?

For example, to highlight js, I write:
```js
function () { return "This code is highlighted as Javascript!"}
```

To highlight HTML code I use ```html.
How can we highlight Bash/shell commands?

A: I found a good description at Markdown Cheatsheet:

Code blocks are part of the Markdown spec, but syntax highlighting isn't.
However, many renderers -- like GitHub's and Markdown Here -- support syntax highlighting. Which languages are supported and how those language names should be written will vary from renderer to renderer. Markdown Here supports highlighting for dozens of languages (and not-really-languages, like diffs and HTTP headers); to see the complete list, and how to write the language names, see the highlight.js demo page.

Although I could not find any official GitHub documentation about using highlight.js, I've tested lots of languages and seemed to be working
To see list of languages I used https://github.com/highlightjs/highlight.js/blob/master/SUPPORTED_LANGUAGES.md
Some shell samples:
Shell:      console, shell
Bash:       bash, sh, zsh
PowerShell: powershell, ps
DOS:        dos, bat, cmd

Example:
```bat
cd \
copy a b
ping 192.168.0.1
```

A: If you are looking to highlight a shell session command sequence as it looks to the user (with prompts, not just as contents of a hypothetical script file), then the right identifier to use at the moment is console:
```console
foo@bar:~$ whoami
foo
```

A: It depends on the Markdown rendering engine and the Markdown flavour. There is no standard for this. If you mean GitHub flavoured Markdown for example, shell should work fine. Aliases are sh, bash or zsh. You can find the list of available syntax lexers here.

A: If I need only to highlight the first word as a command, I often use properties:
```properties
npm run build
```

I obtain something like:
npm run build

A: Bitbucket uses CodeMirror for syntax highlighting. For Bash or shell you can use sh, bash, or zsh. More information can be found at Configuring syntax highlighting for file extensions and Code mirror language modes.

A: Using the knitr package:
```{r, engine='bash', code_block_name} ...

E.g.:
```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt
```

You can also use:

*

*engine='sh' for shell

*engine='python' for Python

*engine='perl', engine='haskell' and a bunch of other C-like languages and even gawk, AWK, etc.

A: Per the documentation from GitHub regarding GFM syntax highlighted code blocks

We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.

Rendered on GitHub, console makes the lines after the console blue. bash, sh, or shell don't seem to "highlight" much ...and you can use posh for PowerShell or CMD.

A: In Obsidian, you can use sh-session
https://prismjs.com/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Attempted to call an undefined method named "renderView" of class I'm pretty new in php symfony2. I want to manage one class for sending emails.
services.yml:
   mail_helper:
      class: HelpBundle\MailSender\EmailManager
      arguments: ['@mailer','@templating']

EmailManager:
class EmailManager
{
protected $mailer;
protected $templating;

public function __construct(\Swift_Mailer $mailer,$templating)
{
    $this->mailer = $mailer;
    $this->templating = $templating;
}

public function sendEmail($fromEmail,$toEmail,$subject,$comments,$status)
{
    $message = \Swift_Message::newInstance()
        ->setSubject($subject)
        ->setFrom($fromEmail)
        ->setTo($toEmail)
        ->setBody($this->templating->renderView('HelpBundle:Emails:add-comment.html.twig', array('comments' => $comments,
            'status' => $status,
            'subject' => $subject)))
    ;
    $this->mailer->send($message);
   }
 }

In my controller I have called like this:
public newAction()
{
$mailer = $this->get('mail_helper');
    $mailer->sendEmail($fromEmail,$toEmail,$subject,$comments,$ticketStatus);
}

Error when controller action is called is next:

Attempted to call an undefined method named "renderView" of class "HelpBundle\MailSender\EmailManager".

I want to understand how I can fix this ?
Thanks a lot

A: You have to inject into your service a templating so in services.yml use:
arguments: ["@mailer", "@templating"]

and then use it in your service:
public function __construct(\Swift_Mailer $mailer, $templating)
{
    $this->mailer = $mailer;
    $this->templating = $templating;
}

public function sendEmail($fromEmail, $toEmail, $subject, $comments, $status)
{
    $message = \Swift_Message::newInstance()
        ->setSubject($subject)
        ->setFrom($fromEmail)
        ->setTo($toEmail)
        ->setBody($this->templating->render('
                 HelpBundle:Emails:add-comment.html.twig',
                 array('comments' => $comments,
                       'status' => $status,
                       'subject' => $subject
                 )
             )
        );
    $this->mailer->send($message);
}

And change renderView() to render(), because renderView() is controller shortcut


text:
Q: Python decompiler for Eclipse PyDev? Is there a way to get eclipse to read .pyc files?
I'm trying to avoid downloading an external program and I would rather not trust an on-line service.

A: There is no open-source/free decompiler for Python - just a "disassembler" (see the dis-module in the stdlib). Getting back from the Python Stack-VM-assembly (which is stored in .pyc-files) to working Python code is mostly easy, as the general structure of the code is preserved, even when using "-O".
For special case solutions (i.e., marshalling .pyc-s in the old [pre 2.3]-format), see the answer @FabioZadrozny linked, but especially when you're using Python >=2.5 to produce the .pyc-s, this will most probably not work, though, as a lot of opcodes have changed/been added.


text:
Q: Word or phrase to describe an activity that is "used to pass time" Aside from pastime, what is a word or phrase that can be used to describe an activity that is not pleasurable and used only as a diversion while letting time pass?

A: The noun "pastime" actually describes activity that is pleasurable.

pastime
an activity that someone does regularly for enjoyment rather than work; a hobby: his favorite pastimes were shooting and golf.

To describe an activity that is used only as a diversion while letting time pass, you can say you are doing something to kill time.

kill time
to do something which is not very useful or interesting while you are waiting for time to pass

Or you can just say you are idling, or, lollygagging.

lollygag
spend time aimlessly: he sends her to Arizona every January to lollygag in the sun.

Personally I don't think there is any word that describes an activity which is not pleasurable and used only as a diversion while letting time pass as when you want to kill time, you don't do things that are particularly not pleasurable, but things that have no purpose.

A: My suggestions:

Idling
Twiddling your thumbs

A: Nouns synonymous with pastime are few in number in English. Besides lollygag, the other suggestions here seem to be verbs. If you need a noun, I wonder if timekill or time-kill would work. In Indian English, time pass is a common noun.

A: A phrase I hear all the time in the software industry is a "time suck".  Especially in reference to meetings, which are also frequently referred to as "time wasters" which is essentially the same thing, time suck just sounds better.


text:
Q: Add two json data series in one highchart I'm using highcharts time series, I need to add another data series populated from a different json file/link, is that possible?
Here is my code:
$(function () {
    $.getJSON('myfirstjson', function (data) {
        mydata = [];
        $('#tvmtgm').highcharts({
            chart: {
                zoomType: 'x'
            },
            title: {
                text: 'TVM/TGM'
            },
            xAxis: {
                type: 'datetime',

                dateTimeLabelFormats : {
                    hour: '%I %p',
                    minute: '%I:%M %p'
                }
            },
            yAxis: {
                title: {
                    text: 'Moves'
                }
            },
            legend: {
                enabled: false
            },
            plotOptions: {
                area: {
                    fillColor: {
                        linearGradient: {
                            x1: 0,
                            y1: 0,
                            x2: 0,
                            y2: 1
                        },
                        stops: [
                            [0, Highcharts.getOptions().colors[0]],
                            [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                        ]
                    },
                    marker: {
                        radius: 2
                    },
                    lineWidth: 1,
                    states: {
                        hover: {
                            lineWidth: 1
                        }
                    },
                    threshold: null
                }
            },

            series: [{
                type: 'area',
                name: 'Total vessel moves',
                data: data
            }
            ]
        });
    });
});

There are examples on the highcharts website, but they are all static data series, I need to have both data series populated from json requests

A: Yes you can. Of course, I am hoping I understood your problem.
This link shows you how you can add multiple y-axes.
As for getting the data. $.when should help you.
var data1, data2;
$.when(
    $.getJSON(onurl1, function(data) {
        data1 = data;
    }),
    $.getJSON(onurl2, function(data) {
        data2= data;
    })
).then(function() {
    //use data1 and data2
});


text:
Q: iOS Achievement: "Share on Facebook and Twitter" I want to create achievement in my iOS game, which player will reaches when he shares my game (link to app store) on Facebook and Twitter. Do you think it is ok. I'm little bit worried that this update of my game will be rejected by Apple.
Thank you


text:
Q: Can't find the relation beatween these numbers Good morning, I am developing a web app on Body Mass Index calculation. Related to the BMI calculation I want to show a counter. Inside the counter, that looks like a speedometer, there's an arrow that rotates and points to the BMI result. Like that:
Here you can find the graphic reference
The rotation of the arrow is determined by a number, that changes when the BMI changes. I can actually see the results but I can't find the formula behind the releation beatween the BMI and this number. This is the chart I have extracted:
+------+--------+
| BMI  | NUMBER |
+------+--------+
|  19  |   36   |
| 19.1 |  36.6  |
| 19.2 |  37.2  |
| 19.3 |  37.8  |
+---------------+

Considerations:
When BMI rises by 0.1, the number rises by 0.6 . I need to know, for example: given BMI 21, what equals the "number"?
Additional info:
BMI formula is: weight (kg) / (height*height) (m²)
Maybe it is easy, but I am not good at math.


text:
Q: Python 3.1 Grid Simulation Question Based on the answers from this question, I have created a grid from a 1D array, which modifies a value and its surrounding neighbours; if that value is found in another array. The main value is converted by a specific % and the surrounding elements by another.
However, how do I ensure that the changed values are not converted again during the next iteration of the samples.
Example code below. Thank you for your time!
import numpy as np

def grid(array,samples,details):

    #Sides of the square (will be using a squarable number
    Width = (len(array)) ** 0.5
    #Convert to grid
    Converted = array.reshape(Width,Width)
    #Conversion details
    Change = [details[1]] + [details[2]]
    nrows, ncols = Converted.shape

    for value in samples:

        #First instance where indexing returns it
        i,j  = np.argwhere(Converted == value)[0]

        #Prevent indexing outside the boudaries of the
        #array which would cause a "wraparound" assignment
        istart, istop = max(i-1, 0), min(i+2, nrows)
        jstart, jstop = max(j-1, 0), min(j+2, ncols)

        #Set the value within a 3x3 window to their "new_value"
        for elem in Converted[istart:istop, jstart:jstop]:

           Converted[elem] = elem + (elem * (value * ((Change[1]/100))

        #Set the main value to the new value
        Converted[i,j] = value + (value * ((Change[0])/100))

    #Convert back to 1D list
    Converted.tolist()

    return (Converted)

a = [16,2,20,4,14,6,70,8,9,100,32,15,7,14,50,20,17,10,9,20,7,17,50,2,19,20,21,22,23,24,25]
samples = [2, 7]
grid_details = [10,50,100]

result = grid(a,samples,grid_details)

A: First off, let's walk through your code section by section... There are several problems with what you have written now...
Incidentally, there's a loose convention in python to reserve Uppercase and CamelCased names for classes. (You'll often see code like foo = FooBar(baz), where foo is an instance of the class FooBar.) There's nothing wrong with calling your variable Converted instead of converted, but most code you'll see will use the latter form.
So let's start here:
import numpy as np
def grid(array,samples,details):
    ...

It appears you're passing a list in as array later on.  Because of this, you need to convert the list array to a numpy.ndarray. (Otherwise, things like array.reshape aren't going to work.)  You might also consider changing your variable name to something less generic than "array".  For the moment, though, let's keep the variable names the same. I'm also going to assume that you want floating point values, as you're multiplying by percentages later on... Let's change this to:
import numpy as np
def grid(array,samples,details):
    array = np.asarray(array, dtype=np.float)
    ...

Moving on...
    ...
    #Sides of the square (will be using a squarable number
    Width = (len(array)) ** 0.5
    #Convert to grid
    Converted = array.reshape(Width,Width)
    ...

You have a math problem there!!  A 2x2 array as 4 elements, a 3x3 array has 9, a 4x4 array will have 16, and so on... If you want to reshape a sequence into a square grid, you need to take the square root, not divide by 2!  Let's change that to:
    ...
    #Sides of the square (will be using a squareable number)
    Width = int(np.sqrt(array.size))
    #Convert to grid
    Converted = array.reshape(Width,Width)
    ...

Blame it on a lack of sleep... Clearly, x**0.5 is the same as sqrt(x), I just didn't see the second *. Sorry about that!
Next:
    ...
    Change = [details[1]] + [details[2]]
    ...

This is the same as just doing this:
Change = details[1:3]

The portion after this is fine, so let's jump on to the next problem:
    ...
    #Set the value within a 3x3 window to their "new_value"
    for elem in Converted[istart:istop, jstart:jstop]:

       Converted[elem] = elem + (elem * (value * ((Change[1]/100))

    #Set the main value to the new value
    Converted[i,j] = value + (value * ((Change[0])/100))
    ...

First off, when you iterate over it, elem is the value not the index!  You can't index the array by the values you get, otherwise you'd be trying to index it by things like 0.01, pi, or maybe even complex numbers like 5.6 + 98.44j.  Second, you're using numpy for a reason... There's no reason to iterate through each element like this.  Third, you're changing the center value twice, which is almost definitely not what you want. Instead, we can just do this:
    ...
    #--Set the value within a 3x3 window to their "new_value"
    # Save the "center" value for later use
    center = Converted[i,j]

    # Adjust the pixels around the center by a percentage
    Converted[istart:istop] *= 1 + Change[1] / 100.0

    # Adjust the center pixel by a different percentage
    Converted[i,j] = center * (1 + Change[0] / 100.0)
    ...

Finally, you have a problem with the length of the list "array"that you're passing in...
a = [16,2,20,4,14,6,70,8,9,100,32,15,7,14,50,20,17,10,9,20,7,17,50,2,19,20,21,22,23,24,25]

That's a 31 element array... There's no way to make that square without truncating or adding values.  Your current code would try to turn it into a 15x15 array, which would result in an error (a 15x15 matrix would need 255 values, (15**2)).  I'm going to assume that you wanted a 25-element, 5x5 array instead. Let's replace that with:
a = [16,2,20,4,14,6,70,8,9,100,32,15,7,14,50,20,17,10,9,20,7,17,50,2,19]

Okay, so let's put all those suggestions together into a workable piece of code:
import numpy as np

def grid(array,samples,details):
    array = np.asarray(array, dtype=np.float)

    #Sides of the square (will be using a squarable number
    Width = int(np.sqrt(array.size))
    #Convert to grid
    Converted = array.reshape(Width,Width)
    #Conversion details
    Change = details[1:3]
    nrows, ncols = Converted.shape

    for value in samples:

        #First instance where indexing returns it
        i,j  = np.argwhere(Converted == value)[0]

        #Prevent indexing outside the boudaries of the
        #array which would cause a "wraparound" assignment
        istart, istop = max(i-1, 0), min(i+2, nrows)
        jstart, jstop = max(j-1, 0), min(j+2, ncols)

        #Set the value within a 3x3 window to their "new_value"
        center_value = Converted[i,j]
        Converted[istart:istop, jstart:jstop] *= 1 + Change[1] / 100.0
        Converted[i,j] = center_value * (1 + Change[0] / 100.0)

    #Convert back to 1D list
    Converted.tolist()

    return Converted

a =  [16,2,20,4,14,6,70,8,9,100,32,15,7,14,50,20,17,10,9,20,7,17,50,2,19]
samples = [2, 7]
grid_details = [10,50,100]

result = grid(a,samples,grid_details)

print(result)

So, this transforms your original array:
[[  16.    2.   20.    4.   14.]
 [   6.   70.    8.    9.  100.]
 [  32.   15.    7.   14.   50.]
 [  20.   17.   10.    9.   20.]
 [   7.   17.   50.    2.   19.]]

Into:
[[  32.     3.    40.     4.    14. ]
 [  12.   280.    32.    18.   100. ]
 [  32.    30.    10.5   28.    50. ]
 [  20.    34.    20.    18.    20. ]
 [   7.    17.    50.     2.    19. ]]

Okay.  Now for what I think you were originally asking...  In this case, the item in the second row, second column gets modified twice... Once due to the 2 in the first row, second column, and once due to the 7 in the third row, third column.
Is this what you wanted to avoid??  If so, what do you want to happen in this case?
Do you want it to only be modified by the first match? The second match? Modified both times, but only have it modified by the sum of the percentages? You need to define what you want to happen.
At any rate, hope that helps!
Edit
If you want to avoid matching a newly-modified value, you can just find all of the matches before you start modifying things.  For example, if we change this part:
for value in samples:
    #First instance where indexing returns it
    i,j  = np.argwhere(Converted == value)[0]

To this:
locations = [np.argwhere(Converted == value)[0] for value in samples]
for i,j in locations:
    ...

It should do what you want.  Hope that's clear!


text:
Q: Converting NULL string columns from flat file source to DATETIME and INT types in destination table I am importing a flat file source to a table, all my flat file columns are string datatype. And few of my columns are NULL values, whereas in my destination tables those are Datetime and Int type. I tried to use derived column and Data conversion transformation but failed to load.
my source columns
todaysdate   yesterdaydate   batchno
NULL           NULL             NULL

The todaysdate column and yesterdaydate column in the destination table are Datetime and the Batchno column is an int type. I tried using derived and data conversion transformations but it is failing.
I need to load Null values into destination for this columns.

A: I sorted out the issue,
i have added the following expression in derived column transformation
i replaced todaysdate column in derived column transformation as
TRIM(todaysDate) =="NULL" ? (DT_STR,20,1252)NULL(DT_STR,20,1252) : todaysdate


text:
Q: How to make child elements from parent1 have a higher z-index than child elements from parent 2 (with same z-index as other parent)? I have the following HTML:
HTML

    <svg>

    </svg>

    <svg>

    </svg>

CSS
.parent {
  position: absolute;
  top: 0;
  left: 0;
  width: 1000px;
  height: 700px;
}

svg {
  overflow: hidden;
  width: 100%;
  height: 100%;
}

Abbreviations:
first parent-element: p1
second parent-element: p2
child-elements from p1: c1
child-elements from p2: c2
Background info:
Both parent-elements are positioned exactly above each other. It seems that the p2 is "a complete layer above the p1".
Problem/Question:
Currently i can NOT click on ANY c1. No chance. The p2 seems to be a complete layer above the p1. How do I manage that c2 still are above c1 BUT I am able to click on c1 if there are no c2 directly above them.

A: You could add pointer-events: none to the .parent divs and then add pointer-events:all to the .child divs.
This would mean only the actual children can be clicked. If there is no c2 then c1 should be clickable
something like this?
http://jsfiddle.net/ekL6632c/1/


text:
Q: Unable to access MS SQL running in one Docker container from an other Docker container I'm running MS SQL in Docker
I can access MS SQL from my workstation, but it does not work if I try to connect from my rails docker container:
$ docker exec -it 73  bundle exec rails c
Loading development environment (Rails 5.1.3)
[1] pry(main)> User.last
TinyTds::Error: Cannot open server 'mssql' requested by the login.
Client with IP address '109.74.176.74' is not allowed to access the server.
To enable access, use the Windows Azure Management Portal or run
sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range.  It may take up to five minutes for this change to take effect.
from /usr/local/bundle/gems/tiny_tds-2.0.0/lib/tiny_tds/client.rb:53:in `connect'

Cannot open server 'mssql' requested by the login.
Client with IP address '$MY_EXTERNAL_IP' is not allowed to access the server.
To enable access, use the Windows Azure Management Portal or
run sp_set_firewall_rule on the master database to
create a firewall rule for this IP address or address range.
It may take up to five minutes for this change to take effect.

docker-compose.yml
version: '2'

services:
  mssql:
    image: 'microsoft/mssql-server-linux:ctp2-1'
    environment:
      - ACCEPT_EULA=Y
      - SA_PASSWORD=Top-5ecret
      - PATH=$PATH:/opt/mssql-tools/bin:/opt/mssql/bin
    ports:
      - '1433:1433'

  website:
    build: .
    command: bundle exec puma --config config/puma/development.rb

    environment:
      - RACK_ENV=development
      - RAILS_ENV=development
      - DATABASE_URL=sqlserver://sa:Top-5ecret@mssql:1433/sst-staging

      - AAD_SCOPE=openid
      - AAD_REDIRECT_URI=http://localhost:3000/sst/auth/exchange
      - LOGIN_URI=http://localhost:3000/sst/login

      # Remember to export the following vars to your shell. E.g ~/.profile
      # This will add them to the container if they are present.
      - AAD_TENANT
      - AAD_CLIENT_ID

    ports:
      - '3000:3000'
    volumes:
      - '.:/numbers'
    stdin_open: true
    tty: true

A: As the error says, it's likely your Azure database has a firewall rule blocking the IP address allocated to the container, which will be different than your machine.
Find your database resource in Azure and look for a blade titled "Firewall and virtual networks."  See if there is an ip whitelist, and if your machine's ip is there.  Try to add a whitelist that will match the ip's getting assigned to your container.
As Dmitrij hinted, you could also try different values of the --network parameter to the docker run command.


text:
Q: Weighting observations and measurement uncertainty in bayes I am working on using MCMC (via STAN) to estimate model parameters for a bunch of observations with measurement uncertainty. I'm having problems with weighting each observation, and have reduced the problem to something more simple which still has the pathology I'm trying to fix -- a Pareto distribution.
Let's say I generate data in R in the following way:
rpareto = function(n,location,shape){location/runif(n)^(1/shape)}

N = 1000
std = 0.2
underlying = rpareto(N,location=10,shape=2)
logx = log(underlying) + rnorm(N,0,std)

So that I have Pareto variates (with $y>10$ and a slope of -2), with an uncertainty of 0.2 in logscale. I want to recover the location and shape.
The following STAN code will do this fine:
data {
  int<lower=0> N;
  vector[N] logx;
  real<lower=0> std;
}
parameters {
  real<lower=1,upper=4> logy_min;
  real<lower=0,upper=4> alpha;
  vector<lower=logy_min,upper=10>[N] log_xtrue;
}
model {
  exp(log_xtrue) ~ pareto(exp(logy_min), alpha);
  logx ~ wnormal(log_xtrue, std);
}

Here, I have the variates in log-space because that makes more sense in my final application (it could go either way here).
However, in my final application it makes sense to weight each observation so that higher variates are upweighted (ie. we flatten out the contribution at different scales). This can mathematically be easily done by giving each observation $x_{true}$ a weight of $w_i=x^s_{i,true}/\bar{x^s}_{true}$. In this case, the whole power-law is tilted by the scale $s$, and we need to estimate $\alpha+s$ in the model.
Conceptually, what's happening is that we're replacing every observation by $x^s_{true}$ of the same observation, as if we had data with a PDF that was proportional to $\alpha+s$. Typically I want to use $s\sim 1$.
In the case that there are no uncertainties on the observations, this works fine, that is, the following model (used on data with no uncertainties), works perfectly to give alpha=2:
functions {
  real wpareto_log(vector y,real y_min,real alpha,vector weight){
    return sum((log(alpha)+alpha*log(y_min)-(alpha+1)*log(y)) .*weight);
  }
}
data {
  int<lower=0> N;
  vector[N] logx;
  real s; //scale
}
transformed data {
  vector[N] weight;
  for (i in 1:N) weight[i] <- pow(exp(logx[i]),s);
  weight <- weight/mean(weight);
}
parameters {
  real<lower=1,upper=4> logy_min;
  real<lower=0,upper=4> alpha;
}
model {
  exp(logx) ~ wpareto(exp(logy_min),alpha+s,weight);
}

Here I had to add the weighted pareto as a new function, and calculated the weight as transformed data.
The problem comes in when using the scaling, $s$, with uncertainties as well. The obvious change that needs to be made is to weight the uncertainty distribution contribution in the same way, so that we have
functions {
  real wpareto_log(vector y,real y_min,real alpha,vector weight){
    return sum((log(alpha)+alpha*log(y_min)-(alpha+1)*log(y)) .*weight);
  }
  real wnormal_log(vector x, vector mu, real std, vector weight){
     vector[num_elements(x)] y;
     y <- x-mu;
     return sum(-y .*y .*weight ./(2*std *std));
  }
}
data {
  int<lower=0> N;
  vector[N] logx;
  real<lower=0> std;
  real s; //scale
}
transformed data {
  vector[N] weight;
  for (i in 1:N) weight[i] <- pow(exp(logx[i]),s);
  weight <- weight/mean(weight);
}
parameters {
  real<lower=1,upper=4> logy_min;
  real<lower=0,upper=4> alpha;
  vector<lower=logy_min,upper=10>[N] log_xtrue;
}
model {
  exp(log_xtrue) ~ wpareto(exp(logy_min), alpha+s,weight);
  logx ~ wnormal(log_xtrue, std,weight);
}

(so we just added the wnormal_log function, which added the weighting in).
However, this doesn't work. The mean $alpha$ is estimated as 0.09 (ie. it's just pushing against its lower boundary).
The one thing I can see that could be wrong with this model is that when replacing $x_i$ with $x_i$ copies of itself, we should perhaps be using the standard error on the mean of the $x_i$ (as computed by how many copies there are), ie. we should have $\sigma_{true} = \frac{\sigma}{\sqrt{N}}$, where $N$ here is just the weight of the variate. However, implementing this doesn't help.
Can anyone tell me what I'm doing wrong?
EDIT:
I found a bug in the stan code that I had which was causing this not to work. Working code is:
data {
  int<lower=0> N;            //Number of obs.
  vector[N] l10_x_meas;      //log10 of measurements
  vector<lower=0>[N] sd_dex; //uncertainty of measurements in dex
  real scale;
}
transformed data {
  vector[N] weight; //weighting from scale
  for (i in 1:N) weight[i] <- pow(10,l10_x_meas[i]*scale);
  weight <- weight/mean(weight);
}
parameters {
  real<lower=scale,upper=4> rate;       //slope of pareto
  real<lower=10,upper=14> l10_x_min; //lower truncation of log10(x)
  vector<lower=l10_x_min,upper=18>[N] l10_x_true; //estimates of true x
}
transformed parameters {
  vector<lower=0>[N] y;      //will be transformation of x: y log10(x/xmin)
  y <- l10_x_true-l10_x_min; //transformation
}
model {
  for (i in 1:N){
    increment_log_prob(exponential_log(y[i],(rate-scale)*log10())*weight[i]);
    increment_log_prob(normal_log(l10_x_true[i],l10_x_meas[i],sd_dex[i])*weight[i]);
  }
}

(Note that I replaced alpha+s with alpha-s). Note also that in this toy example I would not actually use the weighting, but I need it for my actual use-case. Using the weighting here reduces the accuracy of the result.

A: We have had some discussions about weights on the Stan-development Google group. Although I don't think we reached a resolution, I would say while what you are proposing is somewhat accepted in the frequentist literature, it seems difficult to reconcile it with a Bayesian approach. The weights just do not fit into Bayes' theorem very well because if the weight is greater than 1, you are conditioning on additional data that you have not actually observed (and conversely if the weight is less than 1).
I believe what you are implying is that the standard deviation of the measurement error is a decreasing function of the true measurement. If so, it should be possible to model that directly without resorting to weights.
We know that if the true value has a Pareto distribution, then its logarithm has a shifted exponential distribution. In your case, $\log{x} - \log{x_{min}} = \log{x_{true}} - \log{x_{min}} + \log{e}$ where $e$ is log-normal and $\log{x_{true}} - \log{x_{min}}$ is exponential with rate $\alpha$. So the .stan program could be something like
data {
  int<lower=1> N;
  vector[N] log_x;
}
parameters {
  real<lower=0> alpha;
  vector[N] log_e;
  real<upper=min(log_x - log_e)> log_minimum;
}
transformed parameters {
  vector[N] truth;
  truth <- exp(log_x - log_e);
}
model {
  // can ignore Jacobian warning in this case because it's a linear transformation
  log_x - log_e - log_minimum ~ exponential(alpha);
  {
    vector[N] std_dev;
    for (i in 1:N) std_dev[i] <- inv(truth[i]);
    // might want to estimate a scaling parameter on std_dev here
    log_e ~ normal(0, std_dev);
  }
  // prior on alpha
}

That said, I'm not sure if Stan would be able to sample from the posterior distribution very well due to the rapidly changing curvature of each element of log_e.


text:
Q: mysql table is not committed by commit() after delete row I am trying to delete multiple rows in mysql table, through a loop in python. There is no error message but finally the table is not being updated. My code is:
import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="1234",
    database="Share")
mycursor = mydb.cursor()

for i in range(288, 297):
    sql = "DELETE from name_list where ID = " + str(i)
    mycursor.execute(sql)
mydb.commit()

mycursor.execute("SELECT * from Share.name_list")
for row in mycursor.fetchall() :
    print(row)

Thanks

A: How about this?
for i in range(288, 297):
    sql = "DELETE from name_list where ID = %s"
    mycursor.execute(sql, (i, ))
mydb.commit()

source
this should automatically quote the variable based on the datatype and has the added benefit of sql injection protection.
In this case it doesn't matter, since the parameter is always generated by range() but concatenating variables into sql queries manually is generally bad habit.


text:
Q: How to softly update $scope and template using Angularjs? Let's say I have this array in $scope :
userList = [ {
    firstName : 'John',
    visits : 1,
    colors : { red : 1, yellow : 0 }
} ];

The template looks like :

        {{user.firstName}} - {{user.visits}}

        (red: {{user.colors.red}}; yellow: {{user.colors.yellow}})

        {{user.foo}}

Then I receive new data from the sever :
newUserList = [ {
    firstName : 'John',
    visits : 2,
    colors : { red : 5, yellow : 1 },
    foo : 'bar'
} ];

To make the updates effective I'm actually doing a simple $scope.userList = newUserList;
The problem is that doing it this way clears the whole element before setting the new values. So the template becomes

 before returning to

(...data...)

I'd like to simply update/push/add the new values. A kind of merge/extend that doesn't change things that are up to date. I guess there's a proper way to do it but couldn't find a right answer yet.

A: You can use track by to specify how the objects in the collection are associated with the DOM elements.
For example:

When using this and assigning a new array of users, as long as the tracked property of a user object is the same as previously, it will be considered the same object and Angular will update the existing DOM element instead of recreating it.
Note that the value of the property you are tracking must be unique, so obviously user.firstName would not be a good choice.


text:
Q: KeyDown and KeyUp events on a custom UserControl I have a UserControl that has inside some other controls and then a Panel that I use to paint custom shapes on mouse events. I would like to add some other functionalities but for that I would need to detect KeyDown and KeyUp while the mouse is drawing shapes on the Panel (in this situation UserControl.KeyDown/KeyUp never fire). How can be this achieved?
EDIT
Here is a minimum version for the UserControl where the problem can be seen:
public partial class UserControl1 : UserControl
{
    TextBox textBox1;
    Panel panel1;
    public UserControl1()
    {
        InitializeComponent();

        textBox1 = new System.Windows.Forms.TextBox();
        textBox1.Location = new System.Drawing.Point(0, 0);
        this.Controls.Add(this.textBox1);

        panel1 = new System.Windows.Forms.Panel();
        panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
        panel1.Location = new System.Drawing.Point(0, 25);
        panel1.Size = new System.Drawing.Size(300, 150);
        panel1.MouseEnter += new System.EventHandler(this.panel1_MouseEnter);
        this.Controls.Add(this.panel1);

        this.Size = new System.Drawing.Size(300, 200);
        this.KeyDown += UserControl1_KeyDown;
    }

    private void panel1_MouseEnter(object sender, EventArgs e)
    {
        panel1.Focus();
    }

    void UserControl1_KeyDown(object sender, KeyEventArgs e)
    {
        MessageBox.Show("Key down");
    }

}

When this control is inside a Form the "Key down" message is never displayed.

A: I took the code from Hans Passant here (great hint, many thanks!) and I modified it to suit my needs as follow:
class SelectablePanel : Panel
{
    public SelectablePanel()
    {
        this.SetStyle(ControlStyles.Selectable, true);
        this.TabStop = true;
    }
    protected override bool IsInputKey(Keys keyData)
    {
        if (keyData == Keys.Up || keyData == Keys.Down) return true;
        if (keyData == Keys.Left || keyData == Keys.Right) return true;
        return base.IsInputKey(keyData);
    }
    protected override void OnKeyDown(KeyEventArgs e)
    {
        var handler = KeyDown;
        if (handler != null) handler(this, e);
    }
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        var handler = KeyPress;
        if (handler != null) handler(this, e);
    }
    protected override void OnKeyUp(KeyEventArgs e)
    {
        var handler = KeyUp;
        if (handler != null) handler(this, e);
    }
    protected override void OnMouseEnter(EventArgs e)
    {
        this.Focus();
        base.OnMouseEnter(e);
    }
    protected override void OnEnter(EventArgs e)
    {
        this.Invalidate();
        base.OnEnter(e);
    }
    protected override void OnLeave(EventArgs e)
    {
        this.Invalidate();
        base.OnLeave(e);
    }
    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
        if (this.Focused)
        {
            var rc = this.ClientRectangle;
            rc.Inflate(-2, -2);
            ControlPaint.DrawFocusRectangle(pe.Graphics, rc);
        }
    }

    [Browsable(true)]
    public new event EventHandler<KeyEventArgs> KeyDown;
    [Browsable(true)]
    public new event EventHandler<KeyEventArgs> KeyUp;
    [Browsable(true)]
    public new event EventHandler<KeyPressEventArgs> KeyPress;
}

Finally I modified my original code like this:
public partial class UserControl1 : UserControl
{
    TextBox textBox1;
    SelectablePanel selectablePanel;
    public UserControl1()
    {
        InitializeComponent();

        textBox1 = new System.Windows.Forms.TextBox();
        textBox1.Location = new System.Drawing.Point(0, 0);
        this.Controls.Add(this.textBox1);

        selectablePanel = new SelectablePanel();
        selectablePanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
        selectablePanel.Location = new System.Drawing.Point(0, 25);
        selectablePanel.Size = new System.Drawing.Size(300, 150);
        selectablePanel.KeyDown += panel1_KeyDown;
        this.Controls.Add(this.selectablePanel);

        this.Size = new System.Drawing.Size(300, 200);
    }

    void panel1_KeyDown(object sender, KeyEventArgs e)
    {
        MessageBox.Show("Key down");
    }
}

and now it works for what I need.


text:
Q: Tool to draw a Javascript function map? i'm looking for a tool drawing a kind of function usage map (maybe there's a better name for that).
I'm working on a project with many javascript files included in pages. This project has been developped for a while and we've reached a point where this is really messy. I'd like to have a clear view of what is included where, how functions are used, etc. .
Do you know if such a tool exist ?
thanks.

A: JSLint produces a Function Report which may sort of be what you need, but in general there aren't any good static analysis tools for JavaScript.  (My current project contains a huge amount of duplicated JavaScript developed over 10+ years... we desperately need one too.)
Also see this question.


text:
Q: RBM neural network predict using sklearn I'm attempting to use RBM neural network in sklearn, but I can't find a predict function, I see how you can train it (I think) but I can't seem to figure out how to actually predict a value.
http://scikit-learn.org/stable/auto_examples/neural_networks/plot_rbm_logistic_classification.html#example-neural-networks-plot-rbm-logistic-classification-py
I'm working on a class assignment. this is the assignment:
You will then use randomized hill climbing algorithm to find good weights for a neural network.
Is it possible to do this with SKLearn? Is there a better recommended tool to be able to select different weights for NN? (The goal is to experiment with around 3 different search optimization techniques, and learn about them, not necessarily write them, nor write a NN in this case).

A: RBM's do not do prediction tasks. They are generative models. You can use the transform method to get a hidden state transformation of the input, or your gan use the gibbs method to sample from the network.

You will then use randomized hill climbing algorithm to find good weights for a neural network.

No, this is not available in scikit-learn.
It sounds like your assignment might be meant for you to implement a simpler problem from scratch rather than use another library, as hill climbing isn't normally used for training a neural network. And they probably don't want you to do hill climbing for an RBM neural network.
You should probably consult your professor for more direction on what you really should be doing.


text:
Q: ClassNotFoundException after refactoring I recently refactored my Java Project, and when performing a login task, I receive the following error (Note that it actually loads up fine) :
java.lang.ClassNotFoundException: org.chal614.model.player.Player
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:266)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:623)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1610)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1515)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1769)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at org.entice.util.Serializer.load(Serializer.java:63)
at org.entice.util.Serializer.LoadAccount(Serializer.java:124)
at org.entice.net.codec.LoginDecoder.decode(LoginDecoder.java:103)
at org.entice.net.codec.ConnectionWorker.run(ConnectionWorker.java:43)
at org.entice.net.ServerChannelHandler.messageReceived(ServerChannelHandler.java:107)
at org.jboss.netty.channel.SimpleChannelHandler.handleUpstream(SimpleChannelHandler.java:98)
at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:560)
at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:555)
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:345)
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:332)
at org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:323)
at org.jboss.netty.channel.socket.nio.NioWorker.processSelectedKeys(NioWorker.java:275)
at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:196)
at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
at org.jboss.netty.util.internal.IoWorkerRunnable.run(IoWorkerRunnable.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)

My previous packaging was org.chal614, however it is now org.entice
Naturally I have checked around, and there are no signs of chal614 references. I am now assuming this is something to do with IDE, rather than within the java code itself. Help would be appreciated.


text:
Q: winVerifyTrust is crushed when the sys time is not accurate I am developing a C# .net 3.5 application.
I am trying to verify a file signature by using WinVerifyTrust.
I also want a revocation check so I set the following parametrs of the WinTrustData.
    FdwRevocationChecks = WTD_REVOKE_WHOLECHAIN;
DwProvFlags = WTD_REVOCATION_CHECK_CHAIN;

everyting works OK except when I move the system time forward, then the method is stuck and winVerifyTrust return an answer only after a very long while.
Do you have any idea why it is happening and how can I prevent it?
Thanks

A: This might be happening since revocation information, whether CRL or OCSP has a thisUpdate field which tells when the revocation information becomes valid. The OS might have downloaded the revocation information and has to block till the time it becomes valid for use.


text:
Q: Write to File after Program Closes This might sound like a really dulled down question but I have honestly searched everywhere for it but is there a way where once the user clicks the "exit" or "stop" button to stop there program right after you click that it will write data to a file somewhere? or would that be impossible since you closesd that program? I honestly don't know, Here's my try at it Its nothing really because I don't entirely know how to do it, but I just say this
if (onExit):
    f = open('file.txt', mode='w')
    f.write (data)
    f.close

my onExit is just a Boolean and yeah I'm just not sure how to do it, I know how dumb that code looks btw I just didn't know how to show to you guys that I have tried looking for it other then if I showed you my history tab

A: Clicking an 'exit' button typically does not actually close a program immediately. Instead, the code that runs when that button is pushed also takes care of saving data.
If we are talking about a console application, which is 'closed' by ctrl-c (i.e. a KeyboardInterrupt), you can use a try-except block:
try:
    raw_input()
except KeyboardInterrupt:
    # save here
    raise

Python does support atexit handlers, but they are most likely not the right solution to your problem.

A: If you're using PyDev on Eclipse, the terminate button (red square) sends a kill message to the system, which in turn will kill your program without executing further code.
As the previous answer says, you can use the atexit module, but that only works when your program ends normally.
See also: Is it possible for Eclipse to terminate gently instead of using SIGKILL?


text:
Q: Set focus for EditText in ListView in Fragment I checked all the possible solutions to handle the focus of EditText in a ListView.
I have a ListView in a fragment. The adapter of this ListView is composed by an ImageButton, an ImageView and an EditText. I want the EditText focusable.
I tried some solutions, one of these was:
public class HomeFragment extends Fragment {
    FileAdapter adapter;
    ListView lv;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_home, container, false);

        lv = (ListView)view.findViewById(R.id.listView);
        adapter = new FileAdapter(getActivity().getApplicationContext(), list);

        lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == 1){
                    lv.setItemsCanFocus(true);

                    lv.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
                    adapter.nome.requestFocus();
                }else{
                    if (!lv.isFocused()){
                        lv.setItemsCanFocus(false);
                        lv.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
                        lv.requestFocus();
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                lv.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
            }
        });
        lv.setAdapter(adapter);

        return view;
    }
}

Then in my XML file i have android:descendantFocusability="beforeDescendants" in my ListView.
Here is my FileAdapter class:
public class FileAdapter extends ArrayAdapter<Files> {
    LayoutInflater inflater;
    EditText nome;
    private final Context context;
    private ArrayList<Files> list;

    public FileAdapter(Context context, ArrayList<Files> list) {
        super(context, R.layout.homeadapter, list);

        this.context = context;
        this.list = list;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.homeadapter, null);
        nome = (EditText) convertView.findViewById(R.id.tvNomeFile);

        return convertView;
    }
}

Obviously i put here only useful part of my code, as i said before my adapter has also other elements but useless for the question.
The solution i tried doesn't work so i'm searching another.

A: Yesterday I have the similar problem with my fragment... This is my fragment code:
public static class PlaceholderFragment_MainActivity extends Fragment implements View.OnClickListener {

    //Declaration of classes
    Floor_Adapter FloorsAdapter;
    Floor_List Floors = new Floor_List();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //Declaration of controls
        View view = inflater.inflate(R.layout.building_view, container, false);
        TextView txtvHotelName = (TextView) view.findViewById(R.id.txtvHotelName);
        ListView lvFloors = (ListView) view.findViewById(R.id.lvFloors);

        txtvHotelName.setText("Hotel");
        Floors.setFloorsArray();
        FloorsAdapter = new Floor_Adapter(getActivity(),Floors.getFloorsArray(),lvFloors);
        lvFloors.setAdapter(FloorsAdapter);

        return view;
    }

    @Override
    public void onClick(View view) {
        String A;
        TextView floor = (TextView)view.findViewById(R.id.txtvFloor);
        A = floor.getText().toString();
    }
}

And this my adapter code:
public class Floor_Adapter extends ArrayAdapter<Floor_Object>{
//Declaration of atributes
private ArrayList<Floor_Object> Floor_List;
private final Activity context;
private final  ListView lvFloors;

public Floor_Adapter(Activity context,ArrayList<Floor_Object> Floors_Array,ListView lvFloors) {
    super(context,R.layout.floor_layout,Floors_Array);

    this.context = context;
    this.Floor_List = Floors_Array;
    this.lvFloors = lvFloors;
}

public static class Floor_View{

    //Declaration of Atributes
    TextView FloorName;
    Button btnFloorRow;

    ImageView CheckImage;
    TextView NoChecks;

    ImageView BlockImage;
    TextView NoBlocks;

    ImageView DirtImage;
    TextView NoDirts;

    ImageView TroubleImage;
    TextView NoTroubles;

    ImageButton btnShowTasks;
    ImageButton btnShowRooms;
}

@Override
public View getView(int position, View ConvertView, ViewGroup parent) {

    //Declaration of Variables
    Floor_View rowView;
    LayoutInflater inflator = context.getLayoutInflater();

    if(ConvertView == null){

        rowView = new Floor_View();
        ConvertView = inflator.inflate(R.layout.floor_layout,null,true);

        rowView.FloorName = (TextView) ConvertView.findViewById(R.id.txtvFloor);
        rowView.btnFloorRow = (Button) ConvertView.findViewById(R.id.btnFlooRow);

        rowView.CheckImage = (ImageView) ConvertView.findViewById(R.id.ivCheck);
        rowView.NoChecks = (TextView) ConvertView.findViewById(R.id.txtvCheckRooms);

        rowView.BlockImage = (ImageView) ConvertView.findViewById(R.id.ivBlockRooms);
        rowView.NoBlocks = (TextView) ConvertView.findViewById(R.id.txtvBlockedRooms);

        rowView.DirtImage = (ImageView) ConvertView.findViewById(R.id.ivDirtRooms);
        rowView.NoDirts = (TextView) ConvertView.findViewById(R.id.txtvDirtRooms);

        rowView.TroubleImage = (ImageView) ConvertView.findViewById(R.id.ivTroubleRooms);
        rowView.NoTroubles = (TextView) ConvertView.findViewById(R.id.txtvTroubleRooms);

        rowView.btnShowTasks = (ImageButton) ConvertView.findViewById(R.id.btnShowTasks);
        rowView.btnShowRooms = (ImageButton) ConvertView.findViewById(R.id.btnShowRooms);

        ConvertView.setTag(rowView);
    }
    else
    {
        rowView = (Floor_View) ConvertView.getTag();
    }

    Floor_Object Floor = Floor_List.get(position);
    rowView.FloorName.setText(Floor.getFloorName());

    if(Floor.getNoChecks().equals("0")) {
        rowView.CheckImage.setVisibility(View.INVISIBLE);

        rowView.NoChecks.setVisibility(View.INVISIBLE);
    }
    else{
        rowView.CheckImage.setVisibility(View.VISIBLE);

        rowView.NoChecks.setVisibility(View.VISIBLE);
        rowView.NoChecks.setText(Floor.getNoChecks());
    }

    if(Floor.getNoBlocks().equals("0")) {
        rowView.BlockImage.setVisibility(View.INVISIBLE);

        rowView.NoBlocks.setVisibility(View.INVISIBLE);
    }
    else{
        rowView.BlockImage.setVisibility(View.VISIBLE);

        rowView.NoBlocks.setVisibility(View.VISIBLE);
        rowView.NoBlocks.setText(Floor.getNoBlocks());
    }

    if(Floor.getNoDirts().equals("0")) {
        rowView.DirtImage.setVisibility(View.INVISIBLE);

        rowView.NoDirts.setVisibility(View.INVISIBLE);
    }
    else{
        rowView.DirtImage.setVisibility(View.VISIBLE);

        rowView.NoDirts.setVisibility(View.VISIBLE);
        rowView.NoDirts.setText(Floor.getNoDirts());
    }

    if(Floor.getNoTroubles().equals("0")) {
        rowView.TroubleImage.setVisibility(View.INVISIBLE);

        rowView.NoTroubles.setVisibility(View.INVISIBLE);
    }
    else{
        rowView.TroubleImage.setVisibility(View.VISIBLE);

        rowView.NoTroubles.setVisibility(View.VISIBLE);
        rowView.NoTroubles.setText(Floor.getNoTroubles());
    }

    if(Floor.getNoBlocks().equals("0") && Floor.getNoDirts().equals("0") && Floor.getNoTroubles().equals("0")) {
        rowView.btnFloorRow.setClickable(false);

        rowView.btnShowTasks.setClickable(false);
        rowView.btnShowTasks.setImageResource(R.drawable.list_999999_50);
    }
    else{
        rowView.btnFloorRow.setClickable(true);
        rowView.btnFloorRow.setOnClickListener(OnShowTasksClickListener);

        rowView.btnShowTasks.setClickable(true);
        rowView.btnShowTasks.setOnClickListener(OnShowTasksClickListener);
        rowView.btnShowTasks.setImageResource(R.drawable.list_3a4b66_50);
    }
    rowView.btnShowRooms.setOnClickListener(OnShowRoomsClickListener);

    return ConvertView;
}

private View.OnClickListener OnShowTasksClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final int position = lvFloors.getPositionForView((View) v.getParent());
    }
};

private View.OnClickListener OnShowRoomsClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final int position = lvFloors.getPositionForView((View) v.getParent());
    }
};
}

You can see when I work with fragment it's mandatory to create control events in adapter... Just change  event of view and that it's your need, I think... I am waiting that sample helps you. If you need more info or help advice me, Good luck!
PD: I think this is your code that you need:
public class HomeFragment extends Fragment {
FileAdapter adapter;
ListView lv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_home, container, false);

    lv = (ListView)view.findViewById(R.id.listView);
    adapter = new FileAdapter(getActivity(), list);
    lv.setAdapter(adapter);

    return view;
}
}

public class FileAdapter extends ArrayAdapter<Files> {
private final Context context;
private ArrayList<Files> list;
private final ListView Lv;

public FileAdapter(Context context, ArrayList<Files> list,ListView lv) {
    super(context, R.layout.homeadapter, list);

    this.context = context;
    this.list = list;
    this.Lv = lv;
}

public static class RowView{

//Declaration of Atributes
EditText Nome;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    RowView rowView;
    LayoutInflater inflator = context.getLayoutInflater();

    if(ConvertView == null){

        rowView = new RowView();
        convertView = inflator.inflate(R.layout.homeadapter, null);

        rowView.nome = (EditText) convertView.findViewById(R.id.tvNomeFile);
    }

    rowView.nome.setOnItemSelectedListener(ItemSelecteListener);

    return convertView;
}

private View.setOnItemSelectedListener ItemSelecteListener = new View.OnClickListener() {
     @Override
        public void onItemSelected(View view) {

            final int position = lvFloors.getPositionForView((View) v.getParent());

            if (position == 1){
                lv.setItemsCanFocus(true);

                lv.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            }else{
                if (!lv.isFocused()){
                    lv.setItemsCanFocus(false);
                    lv.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
                    lv.requestFocus();
                }
            }
        }
};
}


text:
Q: How to remove a snapper config when getting error "deleting snapshot failed"? I am using snapper to take snapshots of btrfs volumes. I have one for /var as well, but decided that I want to get rid of it. It corresponds to the _var snapper config. I can't manage to do this, because when I say # snapper -v -c _var delete-config, I get the following error:
Deleting config failed (deleting snapshot failed).

All but the 'active' snapshot have been deleted, however.
I have restarted my laptop and unmounted the /var/.snapshot volume, to no avail.
When I say snapper -c _var list, I get:
 # | Type   | Pre # | Date | User | Cleanup | Description | Userdata
---+--------+-------+------+------+---------+-------------+---------
0  | single |       |      | root |         | current     |

Can anyone help me properly remove this snapper config?
(N.B.: For now, I've set all automatic snapshotting (timeline,…) off in the config.)

A: I could manage to remove a snapper config for which the .snapshots folder had been deleted by (on Debian):

*

*removing the config file from /etc/snapper/configs/

*removing the config name from /etc/default/snapper

Source: https://sobrelinux.info/questions/505676/how-do-i-reinstall-enable-snapper


text:
Q: How to handle exception with executemany (MySQL and Python) I have a python script using executemany to bulk insert rows into a MySQL table. The data is retrieved from different APIs, so every now and then there is unexpected data which leads to a row causing exception.
If I understand correctly - when calling executemany with 1,000 rows and one of them is problematic - the entire bulk is not inserted.
I want to find a way to submit 1,000 records and successfully load the ones that are not problematic. So for example - if one of a thousand is problematic it will not be loaded, but all other 999 will be loaded.
What's the best practice on that? I'm thinking of catching an exception and creating a fallback to re-submit all 1000 one by one - but it seems like there must be a better way to achieve the same outcome.
Advice?

A: Doing an "INSERT OR IGNORE" statement at the beginning of your "executemany" query will let you do exactly this - it will only add the values that don't bring an error.
The only downside is that you no longer can see what error is happening.
For example,
Original database:
('kaushik', 3)
('maria', 4)
('shreya', 38)

Query: (in python)
listofnames = [
('kaushik', 3),
('maria', 4),
('jane', 56)
]

c.executemany("INSERT OR IGNORE INTO bob (name, number) VALUES (?,?)",
listofnames)

Final db:
('kaushik', 3)
('maria', 4)
('shreya', 38)
('jane', 56)

A: When inserting, executemany batches all the data rows together and tries to insert them all with one command. As far as I know, there is no way to handle the exception raised by one failed insertion without ruining the entire batch of insertions. If one row fails, the whole command fails.
Here's what it looks like (example taken from the MySQL docs). If you tell it to do this:
data = [
  ('Jane', date(2005, 2, 12)),
  ('Joe', date(2006, 5, 23)),
  ('John', date(2010, 10, 3)),
]
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)

executemany will do this:
INSERT INTO employees (first_name, hire_date)
VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')

If you think this is going to be a rare occurrence, your idea of retrying each insertion individually will work. Something like:
try:
    cursor.executemany(stmt, data)
except ___Error:  # fill in the blank
    for datum in data:
        try:
            cursor.execute(stmt, datum)
        except ___Error:
            # handle exception, eg print warning
            ...

If you think this is going to be a frequent problem, then it will probably be more performant to forgo executemany and just do this:
for datum in data:
    try:
        cursor.execute(stmt, datum)
    except ___Error:
        # handle exception, eg print warning
        ...


text:
Q: pass Jacobian for lmfit least squares I am using the lmfit python package for non-linear optimisation (url: http://lmfit.github.io/lmfit-py/). I would like to know if it is possible to pass the Jacobian function when using the least squares fitting method ? If yes, would it be possible to provide me with a minimal example ?
Thank you!
kabrrrp
P.S.: code is as follow:
# f(t,g,p) = dg_dt(t,g,p) = R*(c^h/(c^h+K^h))-l*g
# returns rhs of an ODE (dg_dt)
def hill_1g1c(t, g_in, p_in):
    R = p_in['R'].value
    K = p_in['K'].value
    h = p_in['h'].value
    l = p_in['l'].value

    dg_dt = R*((c_int(t)**h)/((c_int(t)**h)+(K**h))) - l*g_in
    return dg_dt

# f_deriv(t,g,p)
# is intended to return the derivatives of f with respect to 4 parameter
def hill_1g1c_jac(p_in, y_in, dt, t_max, g_data, g_err):
    t=1
    R = p_in['R'].value
    K = p_in['K'].value
    h = p_in['h'].value
    l = p_in['l'].value
    dg_dR = (c_int(t)**h) / (c_int(t)**h + K**h) - l * 1
    dg_dK = (-1 * R * c_int(t)**h * h * k**(h-1)) / ((c_int(t)**h + K**h)**2) - l * 1
    dg_dh = (-1 * R * c_int(t)**h * k**h * (np.log(k) - np.log(c_int(t)))) / ((c_int(t)**h + K**h)**2) - l * 1
    dg_dl = -y_in - l * 1

    return np.array([dg_dR, dg_dK, dg_dh, dg_dl])

# y = ODE_solve(y0,p,dt, t_max) >>>> wrapper around ode.integrate, returns array of g
def ODE_solve(y0, p_in, dt, t_max):
    t = [0]
    y = [y0]
    r.set_initial_value(y0, t=0.0)
    r.set_f_params(p_in)
    while r.successful() and r.t < t_max:
         r.integrate(r.t+dt)
         t.append(r.t)
         y.append(r.y)
    return np.array(y)

# weighted least squares, objective function to be minimised
def ODE_wres(p_in, y0, dt, t_max, g_data, g_err):
    g_extended = ODE_solve(y0, p_in, dt, t_max)
    g_model = g_extended[-25:]/g_extended[-25]
    weighted_residuals = (g_data - g_model)/(g_err + 0.00000001)
    return weighted_residuals

# specs for inegrate.ode
y0 = 1
t0 = 0
r = integrate.ode(hill_1g1c).set_integrator('vode', with_jacobian=False)
t_stim = 15
t_max = t_stim + 24
t_plus = 5
dt = 1
t_extended = np.linspace(0,t_max+t_plus,t_max+t_plus+1)

# set history of all inputs to 1
c_history = [1 for val in range(t_stim)]

# data (is read in from text file)
g_data = Y_data[:,i]
# error in g
g_err = Y_error[:,i]
# input c
c_data = Y_data[:,k]
# interpolation of c, contains history (=1) and future (=endval)
c_future = [c_data[-1] for val in range(t_plus)]
c_extended = np.hstack((c_history, c_data, c_future))
c_int = interp1d(t_extended, c_extended, kind='linear')

# initial parameter vector
R_ini = random.uniform(0.01, 500.0)
K_ini = random.uniform(0.01, 20.0)
h_ini = random.uniform(-4.0, 4.0)
l_ini = random.uniform(0.07, 7.0)

p_ini = Parameters()
p_ini.add('R', value= R_ini, min=0.01, max=500)
p_ini.add('K', value= K_ini, min=0.01, max=20)
p_ini.add('h', value= h_ini, min=-4, max=4)
p_ini.add('l', value= l_ini, min=0.07, max=7.0)

res_ini = ODE_wres(p_ini, y0, dt, t_max, g_data, g_err)
chisqr_ini = np.sum(res_ini**2)

# optimise
lmsol = Minimizer(ODE_wres, p_ini, fcn_args=(y0, dt, t_max, g_data, g_err))
lmsol.leastsq(Dfun=hill_1g1c_jac, col_deriv=True)

P.P.S: I have found this valuable example at github: https://github.com/lmfit/lmfit-py/blob/master/examples/example_derivfunc.py
NOTE OF CAUTION: After managing to pass the Jacobian function to lmft.leastsq, I realized, that in my test case the optimised solution as returned by lmfit was no longer converging to the true solution. However, when using the actual scipy.optimize.leastq function (which is called by lmfit) everything worked fine, that is the returned solution converged also including the Jacobian to fit. I am not saying that lmfit.leastsq doesn't work properly when supplying it with the Jacobian function, but I recommend to treat this case with some caution. So far I have not found the time to look deeper into the cause of this.

A: You can pass in a function to compute the Jacobian as the Dfun argument to the Minimizer.leastsq method: http://lmfit.github.io/lmfit-py/fitting.html#leastsq
By default the function passed in for Dfun should return an array with the same number of rows as parameters, and each row the derivative with respect to each parameter being fitted.  Make sure to specify the parameters with a Parameters object so that the parameters are treated in the correct order.  I believe this this necessary IIRC though it might not matter.


text:
Q: Careers adverts: location not accurate On the Careers front page, after the featured jobs ads, there is a section  jobs near [your location], with a further link to More [your location] jobs.
For me, the location it's using is waaaay off by about 100 miles. I suppose this depends on how the location is being looked up, perhaps it's using my ISP's point of presence or something.
Perhaps if it were more accurate the click through rate would be higher?


text:
Q: How to compare different distribution means with reference truth value in Matlab? I have production (q) values from 4 different methods stored in the 4 matrices. Each of the 4 matrices contains q values from a different method as:
Matrix_1 = 1 row x 20 column

Matrix_2 = 100 rows x 20 columns

Matrix_3 = 100 rows x 20 columns

Matrix_4 = 100 rows x 20 columns

The number of columns indicate the number of years. 1 row would contain the production values corresponding to the 20 years. Other 99 rows for matrix 2, 3 and 4 are just the different realizations (or simulation runs). So basically the other 99 rows for matrix 2,3 and 4 are repeat cases (but not with exact values because of random numbers).
Consider Matrix_1 as the reference truth (or base case ). Now I want to compare the other 3 matrices  with Matrix_1 to see which one among those three matrices (each with 100 repeats) compares best, or closely imitates, with Matrix_1.
How can this be done in Matlab?
I know, manually, that we use confidence interval (CI) by plotting the mean of Matrix_1, and drawing each distribution of mean of Matrix_2, mean of Matrix_3 and mean of Matrix_4. The largest CI among matrix 2, 3 and 4 which contains the reference truth (or mean of Matrix_1) will be the answer.
mean of Matrix_1 = (1 row x 1 column)

mean of Matrix_2 = (100 rows x 1 column)

mean of Matrix_3 = (100 rows x 1 column)

mean of Matrix_4 = (100 rows x 1 column)

I hope the question is clear and relevant to SO. Otherwise please feel free to edit/suggest anything in question. Thanks!
EDIT: My three methods I talked about are a1, a2 and a3 respectively. Here's my result:
ci_a1 =

  1.0e+008 *

   4.084733001497999
   4.097677503988565

ci_a2 =

  1.0e+008 *

   5.424396063219890
   5.586301025525149

ci_a3 =

  1.0e+008 *

   2.429145282593182
   2.838897116739112

p_a1 =

    8.094614835195452e-130

p_a2 =

    2.824626709966993e-072

p_a3 =

    3.054667629953656e-012

h_a1 = 1; h_a2 = 1;  h_a3 = 1

None of my CI, from the three methods, includes the mean ( = 3.454992884900722e+008) inside it. So do we still consider p-value to choose the best result?

A: If I understand correctly the calculation in MATLAB is pretty strait-forward.
Steps 1-2 (mean calculation):
k1_mean = mean(k1);
k2_mean = mean(k2);
k3_mean = mean(k3);
k4_mean = mean(k4);

Step 3, use HIST to plot distribution histograms:
hist([k2_mean; k3_mean; k4_mean]')

Step 4. You can do t-test comparing your vectors 2, 3 and 4 against normal distribution with mean k1_mean and unknown variance. See TTEST for details.
[h,p,ci] = ttest(k2_mean,k1_mean);

A: EDIT : I misinterpreted your question. See the answer of Yuk and following comments. My answer is what you need if you want to compare distributions of two vectors instead of a vector against a single value. Apparently, the latter is the case here.
Regarding your t-tests, you should keep in mind that they test against a "true" mean. Given the number of values for each matrix and the confidence intervals it's not too difficult to guess the standard deviation on your results. This is a measure of the "spread" of your results. Now the error on your mean is calculated as the standard deviation of your results divided by the number of observations. And the confidence interval is calculated by multiplying that standard error with appx. 2.
This confidence interval contains the true mean in 95% of the cases. So if the true mean is exactly at the border of that interval, the p-value is 0.05 the further away the mean, the lower the p-value. This can be interpreted as the chance that the values you have in matrix 2, 3 or 4 come from a population with a mean as in matrix 1. If you see your p-values, these chances can be said to be non-existent.
So you see that when the number of values get high, the confidence interval becomes smaller and the t-test becomes very sensitive. What this tells you, is nothing more that the three matrices differ significantly from the mean. If you have to choose one, I'd take a look at the distributions anyway. Otherwise the one with the closest mean seems a good guess. If you want to get deeper into this, you could also ask on stats.stackexchange.com

Your question and your method aren't really clear :

*

*Is the distribution equal in all columns? This is important, as two distributions can have the same mean, but differ significantly :

*

*is there a reason why you don't use the Central Limit Theorem? This seems to me like a very complex way of obtaining a result that can easily be found using the fact that the distribution of a mean approaches a normal distribution where sd(mean) = sd(observations)/number of observations. Saves you quite some work -if the distributions are alike! -

Now if the question is really the comparison of distributions, you should consider looking at a qqplot for a general idea, and at a 2-sample kolmogorov-smirnov test for formal testing. But please read in on this test, as you have to understand what it does in order to interprete the results correctly.
On a sidenote : if you do this test on multiple cases, make sure you understand the problem of multiple comparisons and use the appropriate correction, eg. Bonferroni or Dunn-Sidak.


text:
Q: Creating a C++ extension for Python When I follow the instructions from Creating a C++ extension for Python I don't get any errors until I reach the section Convert the C++ project to an extension for Python.
After I go through the steps from this section and attempt to build the solution I stumble on this:
1>------ Build started: Project: CppMain, Configuration: Debug Win32 ------
1>module.cpp
1>   Creating library C:\Users\$andu\Desktop\Cpp4Py\Debug\Cpp4Py.lib and object C:\Users\$andu\Desktop\Cpp4Py\Debug\Cpp4Py.exp
1>module.obj : error LNK2019: unresolved external symbol __imp__PyFloat_FromDouble referenced in function "struct _object * __cdecl tanh(struct _object *,struct _object *)" (?tanh@@YAPAU_object@@PAU1@0@Z)
1>module.obj : error LNK2019: unresolved external symbol __imp__PyFloat_AsDouble referenced in function "struct _object * __cdecl tanh(struct _object *,struct _object *)" (?tanh@@YAPAU_object@@PAU1@0@Z)
1>module.obj : error LNK2019: unresolved external symbol __imp__PyModule_Create2 referenced in function _PyInit_Cpp4Py
1>C:\Python\Anaconda3\libs\python3.lib : warning LNK4272: library machine type 'x64' conflicts with target machine type 'x86'
1>C:\Users\$andu\Desktop\Cpp4Py\Debug\Cpp4Py.pyd : fatal error LNK1120: 3 unresolved externals
1>Done building project "CppMain.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

From the message above, I suspect that the problem comes from step 2 in that set of instructions. But I don't really know how to deal with that. Any suggestions?

I work with x64 Windows 10.

A: I'm not sure. But you can change your project's target machine type to x64 and try again. See this warning:

C:\Python\Anaconda3\libs\python3.lib : warning LNK4272: library machine type 'x64' conflicts with target machine type 'x86'


text:
Q: Pydantic model with data type field. Can't use Union, Optional, List I'm using pydantic in my project and defined a model with Type field.
from typing import Type, Union
from pydantic import BaseModel

class Item(BaseModel):
    data_type: Type

Works well with standard library types (bool, int, str etc), but when I try to create an instance using for example Union, Optional or List from typing module:
it = Item(data_type=Union[int, str])

I get an error:
File "pydantic/main.py", line 362, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for Item
data_type
  a class is expected (type=type_error.class)

How can I define data_type field for Union, Optional and List types?


text:
Q: Domain Aggregate Root with tree of Entities One property of my aggregate root Node is a tree like group of entities Task. Like
- Node
    - Name
    - Release
    - User
    - task
       - task
       - task
            - task
       - task

The tree of Task can be awfully large and therefore, not loaded completely into memory. I could implement some type of object lazy loading or dynamic queries. Furthermore I will need an easy way to add new tasks with a function like Task::addSubtask... but my intuition is telling me that those solutions are wrong in so many levels.
I am trying to take some lessons about DDD from this problem. So I would like to find a confirmation to these assumptions.

*

*Any aggregate root should always be fully loaded. Any partial load will require a subcomponent to be able to perform a query (through a repo, stored query...) which would brake many rules: single responsibility, ignorance of persistance mechanisms... (NOTE: I do not have an ORM layer providing lazy loading by default)

*The "tree shape" of tasks in memory is actually only necessary for the Outline view in the GUI. Therefore I should have a dummy composite which can perform queries to the Service Layer of my Domain Model.

*Since there is no reason to have a Task outside the context of a Node, my node repository should deal with any operation requiring the tree exploration, like:
(List*) findChildrenOfTask(Task* aTask)
(List*) findChildrenOfTask(Task* aTask, String regexInText)
(void) addChildToTask(Task* aTask)
These are my assumptions, but I would like to confirm them with someone with more experience doing DDD. The "tree only in the GUI" also seems to spur some ideas of CQRS ideas. Is this problem one example of the benefits adopting CQRS for DDD?

A: This exact example is actually addressed in Vaughn Vernon's book Implementing Domain Driven Design
That said I invite you to ponder the following:

*

*Does task need to be transactionally consistent with Node? If not it can be its own Aggregate which dramatically simplifies things. Remember that you're thinking about this from the perspective of a command ONLY.

*If the tree is only for a query why not have a DTO worry about that instead of compromising your domain model?

I will fully admit that Vernon does a MUCH better job of explaining this than I do.


text:
Q: Extra column with different conditions Hi I have SQL script and try to add extra column with different conditions but cant get it to work.
Select
PUB_Name As 'Pub Name'
,SUM(PUB_Collected) AS Collected
,Sum(PUB_Loyalty) As SumLoyalty
,(CASE WHEN SUM(PUB_Collected)>0 THEN (SUM(PUB_Loyalty)/SUM(PUB_Collected))ELSE NULL END) AS 'Percentage'
,SUM(PUB_Lodged_To_Till) As SumLodged
,Sum(PUB_Paid_Out) As SumPaidOut
,SUM(PUB_Lodged_To_Till) - Sum(PUB_Paid_Out) As 'Profit/Lose'
,SUM(PUB_Lodged_To_Till) - SUM(PUB_Paid_Out) - SUM(PUB_Loyalty) As 'Profit/Lose + Loyalty'
FROM [MattPubsDB].[dbo].[PUBRecords]
WHERE PUB_Date >= '2015-03-01'AND PUB_Date < '2015-06-01'
Group By PUB_Name

I want to get this column:
,SUM(PUB_Lodged_To_Till) - SUM(PUB_Paid_Out) - SUM(PUB_Loyalty) As 'Profit/Lose + Loyalty 2nd'

with differed WHERE:
WHERE PUB_Date >= '2015-01-01'AND PUB_Date < '2015-06-01'

I will be grateful for any help as I just start learn SQL.

A: You are going to have to use conditional aggregation, and this will affect all your aggregations.  The query will look like:
Select PUB_Name As `Pub Name`,
       SUM(CASE WHEN PUB_Date >= '2015-03-01'AND PUB_Date < '2015-06-01'  THEn PUB_Collected ELSE 0 END) AS Collected,
       . . .
       SUM(CASE WHEN PUB_Date >= '2015-01-01'AND PUB_Date < '2015-06-01'
                THEN COALESCE(PUB_Lodged_To_Till, 0) - COALESCE(PUB_Paid_Out, 0) - COALESCE(PUB_Loyalty, 0)
                ELSE 0
           END) As `Profit/Lose + Loyalty 2nd`

FROM [MattPubsDB].[dbo].[PUBRecords]
Group By PUB_Name;

I would suggest that you change the column aliases so they do not need to be escaped (no spaces, for instance).  If you don't want to change the name, then use back ticks.  Although single quotes are allowed, they tend to lead to confusion, because they are not allowed around column aliases anywhere else.


text:
Q: Load Data On Uitableview scroll I have 2000 records and i have to display only 15 records in UITableView, When User Scroll UITableView , More 15 records shold be load in table. How should I do it?

A: I think the Answer is : - (void)scrollViewDidScroll:(UIScrollView *)scrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.bounds;
    CGSize size = scrollView.contentSize;
    UIEdgeInsets inset = scrollView.contentInset;
    float y = offset.y + bounds.size.height - inset.bottom;
    float h = size.height;

    float reload_distance = 15;
    if(y > h + reload_distance)
    {
         //Call the Method to load More Data...
    }
}

Hope it will be helpful...!!!

A: You have to check the UIScrollView contentOffset for that (UITableView is built on UIScrollView). So, add this, to your UITableViewDelegate class:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    // when reaching bottom, load more

    float offs = (scrollView.contentOffset.y+scrollView.bounds.size.height);
    float val = (scrollView.contentSize.height);
    if (offs==val)
    {
     //add more data on your data array
    }
}

in order to add more cells to your table when user reaches bottom of your table view.

A: You can use two delegate methods of UIScrollView. As UITableView comes in hierachy of UIScrollView you'll get control in this delegate methods of UIScrollView.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"TableView scrolling");
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    NSLog(@"TableView Started scrolling");
}

Try above two methods. And choose the one appropriate for you. First see how NSLog are coming when you start scrolling your UITableVIew. And then write your code inside them.

A: By Default numberOfItemsToDisplay = 15;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        if (numberOfItemsToDisplay >= [self.yourArray count])
        {
            numberOfItemsToDisplay = [self.yourArray count];
            return 1;
        }
        return 2;
    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        if (section == 0)
        {
            return numberOfItemsToDisplay;
        }
        else
        {
            return 1;
        }
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (indexPath.section == 0)
        {
            static NSString *CellIdentifier = @"YourCustomCell";
            YourCustomCell *objYourCustomCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (objYourCustomCell == nil)
            {
                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"YourCustomCell" owner:self options:nil];
                for(id currentObject in topLevelObjects)
                {
                    if ([currentObject isKindOfClass:[YourCustomCell class]])
                    {
                        objYourCustomCell = (AlertsCustomCell *) currentObject;
                        break;
                    }
                }
            }
            objYourCustomCell.lbl.text = [[self.yourArray objectAtIndex:indexPath.row]valueForKey:@"vName"];
            return objYourCustomCell;
        }
        else
        {
            static NSString *CellIdentifier = @"Cell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil)
            {

                cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                [cell.contentView addSubview:[self loadMoreViewForTable:self.view]];
            }
            return cell;
        }
    }
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        [self.tblAlertsList deselectRowAtIndexPath:indexPath animated:YES];
        if (indexPath.section == 1)
        {
            numberOfItemsToDisplay =  [self loadMore:numberOfItemsToDisplay arrayTemp:self.yourArray tblView:self.tblAlertsList];
            [self.tblAlertsList endUpdates];
        }else
        {
           // action if it is not LoadMore
        }
    }

    + (NSInteger)loadMore : (NSInteger)numberOfItemsToDisplay arrayTemp:(NSMutableArray*)aryItems tblView:(UITableView*)tblList
    {
        int count =0;
        NSUInteger i, totalNumberOfItems = [aryItems count];
        NSUInteger newNumberOfItemsToDisplay = MIN(totalNumberOfItems, numberOfItemsToDisplay + kNumberOfItemsToAdd);
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        for (i=numberOfItemsToDisplay; i<newNumberOfItemsToDisplay; i++)
        {
            count++;
            [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
        }
        numberOfItemsToDisplay = newNumberOfItemsToDisplay;
        [tblList beginUpdates];
        [tblList insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];
        if (numberOfItemsToDisplay == totalNumberOfItems) {
            [tblList deleteSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationLeft];
        }
        NSIndexPath *scrollPointIndexPath;
        if (newNumberOfItemsToDisplay < totalNumberOfItems)
        {
            scrollPointIndexPath = [NSIndexPath indexPathForRow:numberOfItemsToDisplay-kNumberOfItemsToAdd inSection:0];
        }
        else
        {
            scrollPointIndexPath = [NSIndexPath indexPathForRow:i-count inSection:0];
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100000000), dispatch_get_main_queue(), ^(void){
            [tblList scrollToRowAtIndexPath:scrollPointIndexPath atScrollPosition:UITableViewScrollPositionNone  animated:YES];
        });
        return numberOfItemsToDisplay;
    }

I have to take custom cell to use this method? I have only taken UItableview

A: Try this:
http://www.cocoacontrols.com/controls/stableviewcontroller
use this two methods
//for refresh
- (void) addItemsOnTop {

     //[self getLoginFollowingUserVideosCall];
     [self refreshCompleted];
}

//for load more
- (void) addItemsOnBottom  {

     //[self getLoginFollowingUserVideosCall];
     [self loadMoreCompleted];
}

A: What you have to do is load the tableview data lazily. Like load data for the tableview cell that are current visible & not all of the data at a time.


text:
Q: asp.net gridview sum and quantity of the columns i have a small problem with summarizing of the total value of the columns. I have a shopping cart where i want to summarize  quantity and price of the item. I've done summarize of prices but when i was trying to multiply it to quantity it didn't work.
.
 Could you please give me an advice.
Here is a gridview:
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="id"  ShowFooter="true" ShowHeaderWhenEmpty="true">
    <Columns>
        <asp:BoundField DataField="item" HeaderText="Item" SortExpression="item"></asp:BoundField>
        <asp:BoundField DataField="BEE" HeaderText="Description" SortExpression="BEE"></asp:BoundField>
        <asp:BoundField DataField="count" HeaderText="Quantity" SortExpression="count"></asp:BoundField>
        <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price"></asp:BoundField>
        <asp:TemplateField>
            <FooterTemplate>
                <asp:Label ID="lbltxtTotal" runat="server" Text="Total Price" />
            </FooterTemplate>
            <FooterTemplate>
                <asp:Label ID="lblTotal" runat="server" />
             </FooterTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="id" HeaderText="id" SortExpression="id"></asp:BoundField>
        <asp:ButtonField CommandName="Delete" Text="Delete" ButtonType="Button" ShowHeader="True" HeaderText="Delete"></asp:ButtonField>

    </Columns>
    <EmptyDataTemplate>No Record Available</EmptyDataTemplate>
    <FooterStyle BackColor="White" Font-Bold="True"></FooterStyle>
    <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White"></HeaderStyle>

    <PagerStyle HorizontalAlign="Right" BackColor="White" ForeColor="Black"></PagerStyle>

    <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White"></SelectedRowStyle>

    <SortedAscendingCellStyle BackColor="#F7F7F7"></SortedAscendingCellStyle>

    <SortedAscendingHeaderStyle BackColor="#4B4B4B"></SortedAscendingHeaderStyle>

    <SortedDescendingCellStyle BackColor="#E5E5E5"></SortedDescendingCellStyle>

    <SortedDescendingHeaderStyle BackColor="#242121"></SortedDescendingHeaderStyle>
</asp:GridView>

and here is a backend:
protected void Timer1_Tick(object sender, EventArgs e)
    {
        string Username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
        string Username_new = Username.Replace("APAC\\", "");
        GridView1.DataBind();
        //live data
        String myquery = "Select * from Basket where Username='" + Username_new + "'";
        DataTable dt = new DataTable();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = myquery;
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;

        da.Fill(dt);
        GridView1.FooterRow.Cells[1].Text = "Total Amount";
        GridView1.FooterRow.Cells[2].Text = dt.Compute("Sum(price)", "").ToString();
    }

A: This is easy.
Add method to your code:
  protected void getSUM()
{
// SQL query that gets total of product sales where category id = 1
string SqlQuery = @"SELECT SUM(ProductSales) AS TotalSales
  FROM [NORTHWIND].[dbo].[Sales by Category]
  WHERE CategoryID = 1";

// Declare and open a connection to database
SqlConnection conn = new SqlConnection(
ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString);
conn.Open();

// Creates SqlCommand object
SqlCommand comm = new SqlCommand(SqlQuery, conn);

// Gets total sales
decimal TotalSales = Convert.ToDecimal(comm.ExecuteScalar());

// Close connection
conn.Close();
conn.Dispose();
comm.Dispose();

// Adds formatted output to GridView footer
GridView1.Columns[1].FooterText = String.Format("{0:c}", TotalSales);
}

In markup code, we'll define footer template and call getSUM method:
  <FooterTemplate>
  Total sales:   <%# getSUM(); %>
  </FooterTemplate>


text:
Q: DE Undetermined Coefficient Method I would like to solve the following non-homogeneous second order differential equation with constant coefficients with the method of undetermined coefficient but I have some problem with the particular solution, can someone help me? Thanks in advance!

$2y^{''}+3y^{'}+y=t^{-2}$

My problem is that I don't know how to treat the negative power. For example considering $t^{2}$, I can write $Y=At^2+Bt+C$. But in this case what I should do?

A: First, the characteristic polynomial
$$ 2r^2 + 3r + 1 = (2r+1)(r+1) = 0 \implies r = -1, -1/2 $$
So the fundamental solution is
$$ y_h(t) = c_1 e^{-t} + c_2e^{-t/2} $$

Now, you probably won't be able to use undetermined coefficients to obtain the particular solution, but variation of parameters can be of use. Let
$$ y_p(t) = u(t)e^{-t} + v(t)e^{-t/2} $$
Then
\begin{align}
e^{-t}u' + e^{-t/2}v' &= 0 \\
-e^{-t}u' - \frac12 e^{-t/2}v' &= \frac12 t^{-2}
\end{align}
$$ \implies u' = -t^{-2}e^t , \quad v' = t^{-2}e^{t/2} $$
The integrals are non-elementary, but can be expressed in terms of incomplete Gamma functions


text:
Q: Image gallery code issue I created this image gallery that an image is revealed on hovering but the revealed image is in a different place in every computer/browser i open it in but for the life of me I can't figure out why.
I just want the revealed image to appear in the middle without being on top of other images but when i get it to that setting on one computer it looks different on another.
I'm new to coding so I really hope someone helps. Here's the link to my codepen: image gallery
  [1]: http://codepen.io/zenturtle/pen/ezDGC

A: For consistent placement, you need to give the #perimeter div position: relative, so that the positioning of the large images will always be in relation to the containing div, which has a fixed width. Otherwise, the positioning is in relation to the browser/viewport, meaning that it will be different depending on the size/width of the browser.
#perimeter {position: relative;}

You will probably have to adjust all of the large image coordinates now. There are more efficient ways to do this, though. You should be able to place all of those images with one CSS rule, rather than separate ones for each image.


text:
Q: Openlayers 3: redrawing the map layer each time a segment is added to a LineString To follow up on
Dynamically adding and removing segments from a track in OpenLayers 3
I am animating the drawing of a LineString segment by segment using a setInterval loop. I end up rerendering the layer each time I loop through the function and add a segment. Is the is most efficient way to do this? The code works, although I get an
AssertionError: Assertion failed: listeners already registered

error for each loop after the first.
Relevant code below:
    function makeLineString(multipointCoords) {

        var trackStyle = new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'rgba(255,0,255,0.2)',
                width: 0.5
            })
        });

        var trackFeature = new ol.Feature({
            geometry: new ol.geom.LineString([
                ol.proj.transform(multipointCoords[0][0], 'EPSG:4326', 'EPSG:3857')
            ])
        });

        var trackLayer = new ol.layer.Vector({
            source: new ol.source.Vector({
                features: [trackFeature],
            }),
            style: trackStyle
        });

        var coordinate, i = 1,
            length = multipointCoords[0].length;
        var timeInterval = 250;
        console.log(i);

        var timer;
        timer = setInterval(function() {
            segmentConstruction(multipointCoords);
        }, timeInterval);

        function segmentConstruction(multipointCoords) {

            coordinate = ol.proj.transform(multipointCoords[0][i], 'EPSG:4326', 'EPSG:3857');

            trackFeature.getGeometry().appendCoordinate(coordinate);

            if (i === length-1) {
                clearInterval(timer);
            } else {
                i++;
                map.addLayer(trackLayer);
            };
        };
    };

A: No, don't do this. You may want something like this:
var lineString = new ol.geom.LineString([
    ol.proj.fromLonLat(multipointCoords[0][0])
]);
var trackFeature = new ol.Feature({
    geometry: lineString
});

And then your append function:
function segmentConstruction(multipointCoords) {

    coordinate = ol.proj.fromLonLat(multipointCoords[0][i]);
    lineString.appendCoordinate(coordinate);

    if (i === length-1) {
        clearInterval(timer);
    } else {
        i++;
        //map.addLayer(trackLayer); <----- remove this
    };
};

http://jsfiddle.net/jonataswalker/ots444of/


text:
Q: Meaning "I've got to know" I'd like know what is the correct meaning of this sentence: I've got to know
I don't know that sentence means like "I just understood", "I had to understand", or other...
Thanks in Advance!

A: Unfortunately, the word imperitivity isn't really a word in English, but it gets the point across, at least for me explaining the answer to your question.
As lurker pointed out, the closest relative would be must.  Though, that is a bit informal, and if not informal, it's much more demanding.

I have got to have that guitar

vs

I must have that guitar.

The first sentence suggests desire, while the second sentence suggests a need, a necessity.  Although, the first sentence can suggest the same thing, the second sentence is to the point.

In order to play that particular piece of music I must have that guitar.

vs

In order to play that [...] music I've got to have that guitar.

I believe the auxillary got is used more in America, and it is very relaxed, somewhat informal.
Here's a better example

I have got to pee / I "gotta" pee

vs

I must pee

To say that you must do something sounds a bit entitling.  It sounds very elitist.  It's almost as bad as telling someone,

I shall pee

When in doubt, and you're in the US, just use got to / gotta

A:
GOT (auxiliary verb)

*(informal) must; have got (followed by an infinitive).

The two common synonyms are must and need. You can show off by using the archaic must needs.
This is street-level, conversational English at it's best. Anytime you see something you like in a shop window, or an attractive person walks by: I've got to have it.
You can dig even deeper into the world of slang with: That is so mine.

A: Your question seems to ask possibly two different things
A) You don't know something and want to know it

I've got to know
  I need to know
  I must know

Is telling someone you are missing some sort of understanding and want to learn about the pieces you are missing.  Got gives your sentence a very strong desire.
B) You did not know something and now know it

I've gotten to know
  I've learned about
  I've become familiar with

These mean to know about something and understand what it is or how it works
Your example sentence

I just understood

could mean two different things depending on context

1) immediacy

I just understood after you explained it to me
    I just now understood after you explained it to me (this very moment)

2) limitation

I just understood the beginning of the instructions and nothing else
    I only undertook the beginning of the instructions and nothing else