text:
Q: Did Lloyd Alexander ever discuss the relationship between his novels, The Marvelous Misadventures of Sebastian and Westmark Having read Lloyd Alexander's best known works, The Chronicles of Prydain, when I was six or seven, I sought out the rest of his then-existent oeuvre a few years later.  For whatever reason, I read the rest of his books roughly in the order in which he wrote them.  So I finished The Marvelous Misadventures of Sebastian before Westmark; and I could not help but note the high level of similarity between the two novels.  For example:

*

*The settings are both fictional worlds that are clearly based on the western European countries around the eighteenth century.

*The protagonists end up essentially as fugitives, traveling alongside the crown princesses of their respective kingdoms (although the princesses's circumstances are otherwise quite different).

*The villain, and the man responsible for each princess's predicament, is the effective regent of the kingdom.

*Along the way, the main characters join forces with liberal political activists.

*The princesses learn about the importance of reform and democratization (a theme in many of Alexander's works, also including Time Cat, and The Cat Who Wished to Be a Man).

Of course, there are important differences, as well.  The Marvelous Misadventures of Sebastian is unambiguously fantastical; the plot is resolved with the help of a magical violin.  Westmark and its sequels, on the other hand, are quite a bit more realistic.  The only fantasy element in the Westmark books are their wholly fictional setting.
However, given the strong similarities, Alexander must have been aware that he was, to a certain extent, retreading the same kind of material.  However, I have not seen that issue addressed in any of the interviews with the author that I have read or watched.  (Perhaps this is mostly because The Marvelous Misadventures of Sebastian never seemed to come up for discussion.  Despite having won a National Book Award, it seemed to remain relatively obscure compared to most of his other books.)  So, did he ever have anything to say about the similarities, and why he decided to write about the same kind of material in Westmark?


text:
Q: using STL to find all elements in a vector I have a collection of elements that I need to operate over, calling member functions on the collection:
std::vector<MyType> v;
... // vector is populated

For calling functions with no arguments it's pretty straight-forward:
std::for_each(v.begin(), v.end(), std::mem_fun(&MyType::myfunc));

A similar thing can be done if there's one argument to the function I wish to call.
My problem is that I want to call a function on elements in the vector if it meets some condition.  std::find_if returns an iterator to the first element meeting the conditions of the predicate.
std::vector<MyType>::iterator it  =
      std::find_if(v.begin(), v.end(), MyPred());

I wish to find all elements meeting the predicate and operate over them.
I've been looking at the STL algorithms for a "find_all" or "do_if" equivalent, or a way I can do this with the existing STL (such that I only need to iterate once), rather than rolling my own or simply do a standard iteration using a for loop and comparisons.

A: Is it ok to change the vector? You may want to look at the partition algorithm.

Partition algorithm
Another option would be to change your MyType::myfunc to either check the element, or to take a predicate as a parameter and use it to test the element it's operating on.

A: Boost Lambda makes this easy.
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/if.hpp>

std::for_each( v.begin(), v.end(),
               if_( MyPred() )[ std::mem_fun(&MyType::myfunc) ]
             );

You could even do away with defining MyPred(), if it is simple. This is where lambda really shines. E.g., if MyPred meant "is divisible by 2":
std::for_each( v.begin(), v.end(),
               if_( _1 % 2 == 0 )[ std::mem_fun( &MyType::myfunc ) ]
             );

Update:
Doing this with the C++0x lambda syntax is also very nice (continuing with the predicate as modulo 2):

std::for_each( v.begin(), v.end(),
               [](MyType& mt ) mutable
               {
                 if( mt % 2 == 0)
                 {
                   mt.myfunc();
                 }
               } );

At first glance this looks like a step backwards from boost::lambda syntax, however, it is better because more complex functor logic is trivial to implement with c++0x syntax... where anything very complicated in boost::lambda gets tricky quickly. Microsoft Visual Studio 2010 beta 2 currently implements this functionality.

A: I wrote a for_each_if() and a for_each_equal() which do what I think you're looking for.
for_each_if() takes a predicate functor to evaluate equality, and for_each_equal() takes a value of any type and does a direct comparison using operator ==.  In both cases, the function you pass in is called on each element that passes the equality test.
/* ---

    For each
    25.1.1

        template< class InputIterator, class Function, class T>
            Function for_each_equal(InputIterator first, InputIterator last, const T& value, Function f)

        template< class InputIterator, class Function, class Predicate >
            Function for_each_if(InputIterator first, InputIterator last, Predicate pred, Function f)

    Requires:

        T is of type EqualityComparable (20.1.1)

    Effects:

         Applies f to each dereferenced iterator i in the range [first, last) where one of the following conditions hold:

            1:  *i == value
            2:  pred(*i) != false

    Returns:

        f

    Complexity:

        At most last - first applications of f

    --- */

    template< class InputIterator, class Function, class Predicate >
    Function for_each_if(InputIterator first,
                         InputIterator last,
                         Predicate pred,
                         Function f)
    {
        for( ; first != last; ++first)
        {
            if( pred(*first) )
                f(*first);
        }
        return f;
    };

    template< class InputIterator, class Function, class T>
    Function for_each_equal(InputIterator first,
                            InputIterator last,
                            const T& value,
                            Function f)
    {
        for( ; first != last; ++first)
        {
            if( *first == value )
                f(*first);
        }
        return f;
    };

A: std::vector<int> v, matches;
std::vector<int>::iterator i = v.begin();
MyPred my_pred;
while(true) {
    i = std::find_if(i, v.end(), my_pred);
    if (i == v.end())
        break;
    matches.push_back(*i);
}

For the record, while I have seen an implementation where calling end() on a list was O(n), I haven't seen any STL implementations where calling end() on a vector was anything other than O(1) -- mainly because vectors are guaranteed to have random-access iterators.
Even so, if you are worried about an inefficient end(), you can use this code:
std::vector<int> v, matches;
std::vector<int>::iterator i = v.begin(), end = v.end();
MyPred my_pred;
while(true) {
    i = std::find_if(i, v.end(), my_pred);
    if (i == end)
        break;
    matches.push_back(*i);
}

A: For what its worth for_each_if is being considered as an eventual addition to boost. It isn't hard to implement your own.

A: Lamda functions - the idea is to do something like this
for_each(v.begin(), v.end(), [](MyType& x){ if (Check(x) DoSuff(x); })

Origial post here.

A: You can use Boost.Foreach:
BOOST_FOREACH (vector<...>& x, v)
{
    if (Check(x)
        DoStuff(x);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: $f: [a, b] \to \mathbb{R}$ be continuous. Prove that : for any $\epsilon \gt 0$ there exist points $a = x_0 \lt x_1 \lt ... \lt x_{n-1} \lt x_n = b$ Sorry for the unspecified title. There's a word limit for that and I couldn't fit it in.

Let $a \lt b$ and $f: [a, b] \to \mathbb{R}$ a continuous function. Prove the following: for any $\epsilon \gt 0$ there exist points $a = x_0 \lt x_1 \lt ... \lt x_{n-1} \lt x_n = b$ such that for any $k = 1,2,...n$ we have $$sup_{[x_{k-1},x_k]} f - inf_{[x_{k-1},x_k]} f \lt \epsilon$$

This seems faily easy but I can't set up the partition $P$ of $[a,b]$ for which this can happen. I know that $f$ being continuous on a bounded closed interval yields that it is bounded. But I can set up the sub intervals for which the criterion holds.
Please any suggestions? A little one may be of great help. I think I maybe able to solve it on my own,just need a nudge.


text:
Q: Efficient ways to gather trade items for shop quests? There are some nice items that are supposed to be unlocked by completing the shop quests for certain shops, by bringing those shops some trade items. There seem to be many sources for acquiring those items, e.g. treasure chests, but most of them seem to be limited.
What are efficient ways of farming for trade items like Buddhist prayer beads and Shrunken heads? Are there any renewable sources of those items?

A: You will find majority of the trade items in chests (the rarer items are generally found in the chests in the Followers of Romulus lairs).
The only source of "renewable" items, is the thieves/bandits that rarely attack you. Each one killed will yield a large amount of money, and one trade resource (mostly ones that you'll just sell, but sometimes quest items).

A: You get quite a variety of items by sending your brotherhood of assassins out on missions. It lists what you will receive for each mission completed so it's a very easy way to gather rare items. If your assassins are of a decent level and you have the maximum amount, you should have no problems.


text:
Q: MAAS 1.9 can't deploy OS I recently upgraded my MAAS server and found myself with MAAS 1.9.1+bzr4543-0ubuntu1. I saw that the old version of MAAS that I had been running was no longer supported, so no great loss there.
Unfortunately, every time I try and deploy Trusty to a node, it fails with the console message "DataSourceNotFoundException: Did not find any data source, searched classes: ()" on the node and the MAAS server eventually times out the deployment.
My system configuration is both very simple, and probably quite different from a common MAAS installation. In particular, I am not using the optional DNS and DHCP modules because I already have a perfectly good DNS and DHCP system. This worked great in 1.8, but I guess something has gone wrong in the new fancy network framework.
I can reproduce this easily with the following steps:

*

*apt-get install maas

*maas-region-admin createadmin ...

*Power on the node to enlist it - that works

*Commission the node - that works

*Deploy Trusty to the node - that doesn't

*Scratch head when the deployment fails

My MAAS server is 10.0.1.51/24, the nodes I am deploying are on 10.76.0.0/23, and I have a DHCP server that directs the PXE boot to fetch the PXE boot files from the MAAS server.
This all used to work fine with 1.8. Does anyone have any ideas about what might need to be poked or prodded to allow deployments to work?
Thanks

A: I have found the best way to figure out what is failing is to SSH to a node while it being commissioned and to check /var/log directory. There is a log for a cloud-init script. If that part did complete correctly then look for /var/log/juju and the logs inside it will give a you a clue on what might be failing.

A: You may expect quick and perfect answers if you post an issue in https://github.com/Ubuntu-Solutions-Engineering/openstack-installer


text:
Q: Why is 8086 control bus 4 bits? I was wondering why 8086 control bus consists of 4 lines I/O read/write and Mem read/write.
These are clearly 4 different functions that can be determined using only 2 lines. In this geeksforgeeks link we can clearly see that RD is the not operation of WR

A: It is common in hardware to use 1-hot control signals here one line for read & one line for write, instead of one encoded line for both (i.e. one line where read=0, write=1).
When signals are packed/encoded as you suggest, i.e. 2 bits represents 4 values, they generally have to be decoded into 1-hot before they can activate the intended hardware circuitry.
So, here apparently, instead of encoding and decoding, they simply expose the 4 different 1-hot lines.
Most importantly, however, two lines (one for read and one for write) allows for saying read, write, or no operation on a given bus cycle.  So, there's really three different values (or six for both I/O and memory), and these cannot even be encoded in 1 (or 2) bits (but could be in 2 (or 3 bits)).
(Yes, it also allows for dual operation read=1 and write=1, but this is understood to be bad and no one will do it.)


text:
Q: Backing Up an AG with Ola Hallengren I'm trying to understand the labyrinth that is the rules about AG backups.I've got Ola Hallengren's scripts installed on machines TST01/TST02.  02 is the preferred replica for backups. I have an AG with AdventureWorks in it and one database outside the AG - DBAutility.
I have the below in my SQL Agent job on TST01.
sqlcmd -E -S $(ESCAPE_SQUOTE(SRVR)) -d master -Q "EXECUTE [dbo].[DatabaseBackup] @Databases = 'User_Databases', @CopyOnly = 'Y',@Directory = N'C:\MyDirectory\', @BackupType = 'FULL', @Verify = 'Y', @CleanupTime = 168, @CheckSum = 'Y', @LogToTable = 'Y'" -b

When I run the job on TST01 I get a backup of DBAUtility taken from TST01 and written to that machine.  I get no backup of AdventureWorks.  I'm taking this approach from a post from Brent Ozar.
Brent on Ola H and AG Backups
I know Ola has other parameters for AG backups, but I couldn't seem to get that to work as expected either.

A: I do this a lot with my Availability Group backups (using Ola's scripts). Since you have @CopyOnly = 'Y', and you have a Secondary server set as your preferred replica for backups, Ola's script will ignore this backup on your Primary and use the Secondary server for the FULL_COPY_ONLY backups (if the script is run there).
If you were to do away with the @CopyOnly = 'Y' parameter, the scripts would take a FULL backup on your Primary server (FULLs and DIFFs are not allowed on Secondaries).
Ola's scripts are smart when it comes to Availability Groups.  If you have a preferred secondary specified, his scripts will try to use it for any backups that don't HAVE to be done on the Primary.  Because of this, I wound up creating identical backup jobs across my Primary and Secondary servers, and each one runs whichever backups are appropriate based on the current status of each server.


text:
Q: SQL to powerBI expression? How to write this expression in PowerBI
select distinct([date]),Temperature from Device47A8F where Temperature>25

Totally new to PowerBI. Is there any tool that can change the query from sql to PowerBI expression?
I have tried so many type of different type of expressions but getting error, Most of the time I am getting this:
The expression refers to multiple columns. Multiple columns cannot be converted to a scalar value.

Need help, Thanks.

A: After I posted my answer, wondered if your expected result is get only one date by temperature, In other words, without repeated dates in your result set.
A side note: select distinct([date]),Temperature from Device47A8F where Temperature>25 returns repeated dates since DISTINCT keyword evaluate distinct columns values specified in the SELECT statement, it doesn't return distinct values in a specific column even if you surround it with parenthesis.
Now what brings us here. What I can see in your error is that you are trying to use a table-valued (produces a table with multiple columns) expression in a measure which only accepts scalar-valued (calculate only one value).
Supposing you have a table like this:

Running your SQL query you will get the highlighted in yellow rows:

You can see 01/09/2016 date is repeated. If you want to create a measure you have to define what calculation you want to show for temperature. i.e, average, max or min etc.
In the below expression is being calculated the maximum temperature greater than 25 per date:
MaxTempGreaterThan25 =
CALCULATE ( MAX ( Device47A8F[Temperature] ), Device47A8F[Temperature] > 25 )

In this case the measure MaxTempGreaterThan25 is calculated per date.

If you don't want to produce a measure but a table. In the Power BI Tool bar select Modeling tab and click New Table icon.

Use this expression:
MyTemperatureTable =
FILTER ( Device47A8F, Device47A8F[Temperature] > 25 )

It should produce a new table named MyTemperatureTable like this:

I recommend you learn some basics about DAX, it is pretty different from SQL / T-SQL and there are things you can't do depending on your model and data.
Let me know if this helps.

A: You probably don't need to write any code if your objective is to show the result in a Power BI visual e.g. a table.  Power BI naturally aggregates data if the datatype is numeric (e.g. Temperature).
I would just add a Table visual on a Report page and add the Date and Temperature columns to it. Then in Visualizations / Fields / Values I would click the little down-arrow on the Temperature field and set the Aggregation e.g. Maximum.  Then in Visualizations / Fields / Filters I would click the little down-arrow on the Temperature field and set the Filter e.g. is greater than: 25
Hard-coded solutions are unlikely to survive the next question from your users e.g. "but what if I want to see Temperature > 24? Or 20? Or 30?"


text:
Q: Centering plus/minus toggle element inside a circle I have 2 elements that represent +/- signs, When the two elements are visible they represent +, On clicking the vertical element disappears and it becomes -.
Both + and - signs are inside a circle, I want to center both vertical and horizontal elements inside that circle.
Here is a fiddle: http://jsfiddle.net/9ek3gt7o/10
The HTML:

The CSS:
.plusminussign{
    position: relative;
    display:inline-block;
    height: 24px;
    width: 24px;
    vertical-align: bottom;
    opacity: .7;
    background: green;
    border-radius: 50%;
    color: #fff;
    margin: 10px auto;
    cursor: pointer;
}

.circle .horizontal {
  position: absolute;
    background-color: #fff;
    width: 15px;
    height: 2.5px;
    left: 50%;
    top: 50%;
}

.circle .vertical {
  position: absolute;
    background-color: #fff;
    width: 2.5px;
    height: 15px;
    left: 50%;
    top: 50%;
}

.closed .horizontal {
  transition: all 0.5s ease-in-out;
  transform: rotate(-90deg);
  opacity: 1;
}

.closed .vertical {
  transition: all 0.5s ease-in-out;
  transform: rotate(-90deg);
}

.opened {
  opacity: 1;
}

.opened .horizontal {
  transition: all 0.5s ease-in-out;
  transform: rotate(90deg);
  opacity: 0;
}

.opened .vertical {
  transition: all 0.5s ease-in-out;
  transform: rotate(90deg);
}

On clicking, The class opened will be added to the container .plusminussign .
jQuery:
$('.plusminussign').on('click', function(){
    $(this).toggleClass('opened');
});

I want a x-browser compatible responsive solution, So that I won't lose the positioning if the screen gets smaller.
How to center both horizontal and vertical elements inside the circle?

A: To center something you have a few solutions:
Negative margins
Works in older browsers and newer browsers, but you have to hardcode with height / width
.circle{
    position: relative;
    height: 100px;
    width: 100%;
    border-radius: 50%
}

.plus-vert{
    height: 50px;
    width: 2px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -25px 0 0 -1px;
}

.plus-horiz{
    height: 2px;
    width: 50px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -1px 0 0 -25px;
}

Top/left values puts the top left  corner of your line in the center of the circle. The negative margin shifts the line back halfway on each access which centers the item. This works in older browsers, but is less than ideal since you have to hardcode height/width.
CSS3 Transform
This is mostly similar to the previous method, except you use transform to shift it back halfway instead of negative margins.
.circle{
    position: relative;
    height: 100px;
    width: 100%;
    border-radius: 50%
}

.plus-vert{
    height: 50px;
    width: 2px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

.plus-horiz{
    height: 2px;
    width: 50px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

This is only compatible with CSS3 enabled browsers and has the benefit of not caring what the height/width are since it's in %'s.
Flex Box
This uses the flex box layout to center things
.circle{
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100px;
        width: 100%;
        border-radius: 50%
    }
.plus-vert{
    height: 50px;
    width: 2px;
    background-color: #fff;
}

.plus-horiz{
    height: 2px;
    width: 50px;
    background-color: #fff;
}

This has the benefit of the taking all the layout logic from the  children and putting it on the parent.
They should all be good, just depends on what browsers you want to support.


text:
Q: Why my VTK display nothing? I used VTK for several years, And I found a problem today that is very strange, the code is as follows:
#include <vtkSmartPointer.h>
#include <vtkImageData.h>

#include "vtkBoxWidget.h"
#include "vtkCamera.h"
#include "vtkCommand.h"
#include "vtkColorTransferFunction.h"
#include "vtkPiecewiseFunction.h"
#include "vtkPlanes.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkVolume.h"
#include "vtkVolumeProperty.h"
#include "vtkFixedPointVolumeRayCastMapper.h"
#include "vtkInteractorStyleTrackballCamera.h"

#include <vtkAutoInit.h>
VTK_MODULE_INIT(vtkRenderingOpenGL2);
VTK_MODULE_INIT(vtkRenderingVolumeOpenGL2)
VTK_MODULE_INIT(vtkInteractionStyle)

#include <limits>
#include <string>

int main(int argc, char *argv[])
{
/************************************************************************/
/* Generate a RGBA volume                                               */
/************************************************************************/
vtkSmartPointer<vtkImageData> image = vtkSmartPointer<vtkImageData>::New();
int dim[3] = { 10, 10, 10 };
double spacing[3] = { 1.0, 1.0, 1.0 };
double origin[3] = { 0.0, 0.0, 0.0 };
image->SetDimensions(dim);
image->SetSpacing(spacing);
image->SetOrigin(origin);
image->AllocateScalars(VTK_UNSIGNED_CHAR, 4);

unsigned char* ptr = static_cast<unsigned char*>(image->GetScalarPointer());
int idx = 0;
for (int z = 0; z < 10; z++){
    for (int y = 0; y < 10; y++){
        for (int x = 0; x < 10; x++){
            if (z > 6){
                ptr[idx] = 255;
                ptr[idx + 1] = 0;
                ptr[idx + 2] = 0;
                ptr[idx + 3] = 255;
            }
            else{
                ptr[idx] = 0;
                ptr[idx + 1] = 0;
                ptr[idx + 2] = 0;
                ptr[idx + 3] = 0;
            }

            idx += 4;
        }
    }
}

/************************************************************************/
/* Rendering                                                            */
/************************************************************************/
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();
renWin->AddRenderer(renderer);

vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetRenderWindow(renWin);
iren->SetDesiredUpdateRate(10.0);
iren->GetInteractorStyle()->SetDefaultRenderer(renderer);

// Create our volume and mapper
vtkSmartPointer<vtkVolume> volume = vtkSmartPointer<vtkVolume>::New();
vtkSmartPointer<vtkFixedPointVolumeRayCastMapper> mapper = vtkSmartPointer<vtkFixedPointVolumeRayCastMapper>::New();
mapper->SetInputData(image);
mapper->SetBlendModeToComposite();
mapper->SetSampleDistance(0.1);

vtkSmartPointer<vtkPiecewiseFunction> opacityFun = vtkSmartPointer<vtkPiecewiseFunction>::New();
opacityFun->AddPoint(0, 0.0);
opacityFun->AddPoint(255, 1.0);

// Create the property and attach the transfer functions
vtkSmartPointer<vtkVolumeProperty> property = vtkSmartPointer<vtkVolumeProperty>::New();
property->SetScalarOpacity(opacityFun);
property->IndependentComponentsOff();
//property->SetInterpolationTypeToLinear();

// connect up the volume to the property and the mapper
volume->SetProperty(property);
volume->SetMapper(mapper);

// Set the default window size
renWin->SetSize(400, 400);
renWin->Render();

// Add the volume to the scene
renderer->AddVolume(volume);
renderer->ResetCamera();

// interact with data
renWin->Render();
iren->Start();

return 1;
}

I am generate a 10*10*10 RGBA volume and display it, but I get nothing in my screen. In line 46, if I change (z > 6) to (z < 2), it display correct box as I expected, also if I change (z > 6) to (z > 6 || z < 2), it also display 2 correct boxes.
Then why (z > 6) display nothing? what should I do to make it run correctly?

A: This look like a bug to me. If you set opacity to 1 instead of 0 for z<=6, you can circumvent your problem, that only seems to occur when opacity is equal to 0.


text:
Q: Understanding cellular homology: degree of attaching map of a two cell I am working towards an understanding of cellular homology as explained here on Wikipedia.
To help me I am calculating a simple example:

I have two problems: good mathematical notation and actual correctness of what I'm doing.
First, let me show what work I did:
For notation I use $\partial$ to denote the boundary of a cell. Also, if $e_1$ is any $1$-cell, I let $\partial e_1 = \{a,b\}$ where $a$ is the label for the positive end and $b$ the label for the boundary point with negative orientation.
Then I calculated the attaching maps as follows:
$$\begin{array}{cc}
f_2: \partial e_2 \to e_1^2 \sqcup e_1^1 & e^{i\theta}\mapsto e^{i\theta} \\
f_{11}: \partial e_1^1 \to e_0^1 \sqcup e_0^2 & a \mapsto e_0^2, b\mapsto e_0^1 \\
f_{12}: \partial e_1^2 \to e_0^1 \sqcup e_0^2 & a \mapsto e_0^2, b\mapsto e_0^1
\end{array}$$
Using these attaching maps and the definition of degree for attaching maps in dimension $0$ I calculated the following degrees for these maps:
$$ \deg (f_{11} \text{ at } e_0^1) = 1, \deg (f_{11} \text{ at } e_0^2) = -1$$
$$ \deg (f_{12} \text{ at } e_0^1) = 1, \deg (f_{12} \text{ at } e_0^2) = -1$$
For $f_2$ I have:
$$ \deg (f_2 \text{ at } X_1/(X_1 - e_1^1)) = -1$$
$$ \deg (f_2 \text{ at } X_1/(X_1 - e_1^2)) = 1$$
My justification for the degrees of $f_2$ is that $X_1/(X_1 - e_1^1)$ looks like this:

And this maps $S^1$ one time CCW around the origin. The space $X_1/(X_1 - e_1^2)$ looks like this:

And this maps $S^1$ one time around the origin clockwise so the degree is $-1$ by definition.
My questions are:

(1) Is the notation $\partial e_1^1 \to e_0^1 \sqcup e_0^2$ for the
  domain and codomain of the attaching maps correct? I could not find a
  worked out example anywhere and this is my own notation.
(2) Similarly I am unsure whether it is good to write $a \mapsto
> e_0^2, b\mapsto e_0^1$ for the attaching maps. Is this how it is
  usually written down?
(3) Is my argument for the degrees of the map $f_2$ correct? I did
  calculate the homology groups and they turned out correct but of
  course this doesn't mean that everything I did here was correct.

Basically, this question boils down to checking whether I completely understand the definition of cellular homology.

A: First, a remark: it's common to denote the dimension of a cell (or anything, really) as an exponent, not a subscript. So for example $e^2$ is usually used for a cell of dimension $2$, not $e_2$. That's not a huge problem though.
As for your questions:
#1: This notation is correct, but only for the map attaching a 1-cell to the 0-skeleton. In general the n-skeleton is not the disjoint union $\sqcup$ of the cells. In particular you wrote $\partial e_2 \to e_1^2 \sqcup e_1^1$: this looks like the $1$-cells are not attached, which is not the case.
If you want to use a more common notation, I suggest calling your CW complex something like $X$, and the $k$-skeletons $X^{(k)}$. Then the attaching map is $\partial e_{k+1} \to X^{(k)}$, for any dimension $k$.
#2: This one is OK, in my opinion. I'm a bit more unsure about $e^{i \theta} \mapsto e^{i \theta}$, but it's clear from the context what that means. But really, in practice you don't write down the attaching map explicitly like that, a picture is generally enough (though props to you for wanting to understand what's going on behind the picture).
#3: This looks OK to me.


text:
Q: Как проиграть OGG файл внутри программы? Нашёл способ проигрывать файл через библиотеку os:
import os
os.startfile ("имяфайла.ogg")

Но в таком случае он открывает установленный на компьютере VLC плеер и открывает файл через него. Как сделать так, чтобы не открывалось никаких дополнительных программ на компьютере, а просто запускался звуковой файл?


text:
Q: Страница настроек приложения, как в ОС Видел в некоторых приложениях, например, model document viewer, страницу с настройками с точно таким же видом, как и в самой ОС Андроид. Каким образом добиться такого же виде страницы? Или они просто вручную компируют, что вряд ли.
Пример:

A: Есть специальная PreferenceActivity. Суть проста - в xml файле описываете, какие нужны настройки (их названия, подсказки, типы, значения по умолчанию и так далее), а сама система берет на себя создание, отображение и сохранение настроек.


text:
Q: how to get row id which just added My c# button adding some data in one table. how can i get id of this row? does anybody have idea?
  private static void InsertIntoTransportation(string ZednadebNumber, DateTime DateTime, int SellerID, int BuyerID, string TransStart, string TransEnd, decimal Quantity, string LoadType, string LoadName, int DriverID, decimal Cost, decimal FuelUsed, decimal salary)
    {
        try
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO Transportation (DriverID, ClientIDAsSeller, ClientIDAsBuyer, ZednadebNumber, LoadName, TransStart, TransEnd, LoadType, Quantity, Cost, FuelUsed, DateTime) VALUES (@DriverID, @ClientIDAsSeller, @ClientIDAsBuyer, @ZednadebNumber, @LoadName, @TransStart, @TransEnd, @LoadType, @Quantity, @Cost, @FuelUsed, @DateTime)", new SqlConnection(Program.ConnectionString)))
            {
                cmd.Parameters.AddWithValue("@DriverID", DriverID);
                cmd.Parameters.AddWithValue("@ClientIDAsSeller", SellerID);
                cmd.Parameters.AddWithValue("@ClientIDAsBuyer", BuyerID);
                cmd.Parameters.AddWithValue("@ZednadebNumber", ZednadebNumber);
                cmd.Parameters.AddWithValue("@LoadName", LoadName);
                cmd.Parameters.AddWithValue("@TransStart", TransStart);
                cmd.Parameters.AddWithValue("@TransEnd", TransEnd);
                cmd.Parameters.AddWithValue("@LoadType", LoadType);
                cmd.Parameters.AddWithValue("@Quantity", Quantity);
                cmd.Parameters.AddWithValue("@Cost", Cost);
                cmd.Parameters.AddWithValue("@FuelUsed", FuelUsed);
                cmd.Parameters.AddWithValue("@DateTime", DateTime);
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                SqlCommand cmd1 = new SqlCommand("INSERT INTO Salary (DriverID, TransportationID, Salary) VALUES (@DID, @@IDENTITY, @Salary)", new SqlConnection(Program.ConnectionString));
                cmd1.Parameters.AddWithValue("@DID", DriverID);
                cmd1.Parameters.AddWithValue("@Salary", salary);
                cmd1.Connection.Open();
                cmd1.ExecuteNonQuery();
                cmd1.Connection.Close();
                cmd.Connection.Close();
            }
        }
        catch (Exception)
        {

            MessageBox.Show("ვერ ვახერხებ მონაცემთა ბაზასთან კავშირს, დაწრმუნდით თქვენი კომპიუტერის ინტერნეტთან კავშირის გამართულობაში.", "შეცდომა !!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

A:
My c# button adding some data in one
  table. how can i get id of this row?
  does anybody have idea?

Your code example provided inserts two rows.
Either way, simply alter the statement to included "; SELECT SCOPE_IDENTITY()" at the end, and get a scalar result from the command.
Assuming your row ID is a standard integer field (rather than a bigint)
// Edit your command text to have "; SELECT SCOPE_IDENTITY()" at the end.
int? insertedId = cmd.ExecuteScalar() as int?;
if (insertedId.HasValue)
 {
    //  success!
 }

Note that if your row isn't using auto incrementing integer/big-int, then this won't work.
In addition, I would strongly suggest that you consider moving your statements to stored procedures, if this is for anything other than test/sample code.
Separating your SQL code out of your C# means that you can re-use common statements (think of them as Methods). Alternatively, consider using an ORM solution.

A: On an MS SQL Server, My preference is for the output clause. You wouldn't be executing a non-query, it would be a reader (even though it's technically an insert) - the resultset from your insert will then contain one row with the field(s) you choose. This is useful if you have a ROWVERSION (TIMESTAMP) column that you also need for updates that might follow (prevents you from doing another read).
Edit - Just use OUTPUT, not OUTPUT INTO (which is more useful for SQL Server side code than C#).
This works well with sprocs and triggers too, as opposed to scope_identity (which, when using instead-of triggers is in a different scope and so returns null), or @@identity and all of it's issues.

A: Some of my co-worker developers will perfrom a query after the insert to return the identity value.  As a DBA there are other ways to get it as indicated by Alexander.  While the query will produce extra IO on the network at least it should still be in cache and not cause any more Disk IO.


text:
Q: Energy balance of closed timelike curves in Gödel's universe I recently read Palle Yourgrau's book "A World Without Time" about Gödel's contribution to the nature of time in general relativity.
Gödel published his discovery of closed timelike curves in 1949. Many years later (in 1961), S. Chandrasekhar and James P. Wright pointed out in "The geodesic in Gödel's universe" that these curves are not geodesics, and hence Gödel's philosophical conclusions might be questionable. Again some years later, the philosopher Howard Stein pointed out that Gödel never claimed that these curves are geodesics, which Gödel confirmed immediately. Again much later other physicists have computed that these closed timelike curve must be so strongly accelerated that the energy for a particle with a finite rest mass required to run through such a curve is many times its rest mass. (I admit that I may have misunderstood/misinterpreted this last part.)
Questions

*

*This makes me wonder whether any particle (with finite rest mass) actually traveling on a closed timelike curve wouldn't violate the conservation of energy principle. (As pointed out in the comments, I made a hidden assumption here. I implicitly assumed that the particle traverses the closed timelike curve not only once or only a finite number of times, but "forever". I put "forever" in quotes, because the meaning of "forever" seems to depend on the notion of time.)

*I vaguely remember that light will always travel on a geodesic. Is this correct? Is this a special case of a principle that any particle in the absence of external forces (excluding gravity) will always travel on a geodesic?

*Is it possible for a particle to be susceptible to external forces and still have zero rest mass?

*Is it possible that Chandrasekhar and Wright were actually right in suggesting that Gödel's philosophical conclusions are questionable, and that they hit the nail on the head by focusing on the geodesics in the Gödel's universe?

A: I have not really studied Godel's metric, so I will only address questions 2 and 3 in a general metric (without specifically referring to Godel's metric).
Yes, light (in vacuum) will always travel on a null geodesics. Yes, particles remain on geodesics in absence of a net external force. Momentum means different things in the massive and mass-less case, since massive particles move on geodesics with timelike tangent vectors and mass-less move on null tangent vectors. 4-force is equal to the covariant derivative of 4-momentum along the tangent vector to its worldline. I will elaborate:
Let us assume a world in which quantum mechanics is bogus and all particles have a 'kick' (momentum) associated with them. A particle of light has a definite momentum associated with it. So its 'kick' can be redirected and/or diminished. Particles with mass also have this 'kick' and can also have it redirected and/or diminished. The 'kick' is redirected when 'kick' makes contact with the force applier i.e. they would be deviated from their geodesic motion.
Now, in particles with non-zero mass this kick is directly proportional to the 4-velocity. So applying a force on the particles changes its 4-velocity and deviates it from timelike geodesic motion.
However, for mass-less particles the 4-velocity does not exist (as proper time in their frame is 0). Applying force on the particle would also deviate it from null geodesic motion, but the tangent vector of it's motion would remain a null vector, so their net speed would still remain c in your local frame throughout the application of force.
Back to reality. In classical GR, we don't have any forces for these mass-less particles, but have forces (Electromagnetic forces) for massive particles. So we treat mass-less particles purely as waves with energy and momentum (that can't be changed by applying classical force). Note, in classical GR, in vacuum the speed of the EM wave can be reduced in dielectric media, but the fastest speed possible in the dielectric frame will still remain a null vector (speed of light).
In the above discussion, I treat gravitation as the structure of space-time and not as a force.
In Quantum Field Theory, observation is discontinuous and particles change in number and type between 2 successive measurements. There is a symmetry in these changes which leave net Energy and momentum invariant. So here force is irrelevant here and we treat photons as particles again.
Questions 1 and 4:
First of all there is no global conservation of energy in general relativity. There is only local conservation of energy. There are other methods used to get globally conserved quantities (like Killing vectors fields).
CTC's are looked upon as pathological entities. A whole lot of concepts in classical GR have to be revisited if if we accept CTC's in the acceptable causal structure of realistic spacetimes.
A lot of ideas we take for granted are thrown to the winds in such extreme spacetime. Let me give you a very crude and rough analogy:
-There is an astral chicken that lays an egg and dies, the egg hatches and the chick eats the egg and its parent, lays an egg, dies and so on..... Thus, the astral chicken's wordline is a CTC.
-Let's say you (moving along a normal geodesic) are at the event P (hatching of egg) and stay with the chicken till event Q (dying of chicken), the chicken will vanish suddenly after Q. Can you imagine the chicken vanishing?
-The egg also appeared suddenly in your past at P. Kind of like Marty in Back To the Future who appears and disappears suddenly. The egg-mass appears, turns into a chick and disappears, obviously from your viewpoint, energy is not conserved at all not even locally.
This is the best I can do without referring using math. Causal Structure is a very elementary theory, you will be able to understand it. This would help you better understand CTC's, which are not elementary at all. I recommend Wald's book on GR. In addition, here is a pdf by Thorne on some implications of CTCs. It is a moderately advanced paper, but very interesting.http://www.its.caltech.edu/~kip/scripts/ClosedTimelikeCurves-II121.pdf

A: Light will not travel on a geodesic in the background spacetime, as light is an electromagnetic field and has stress-energy and so itself warps the spacetime around it.  However if the light induced curvature is small compared to the curvature already there, then it won't change things much, so will go on an approximately geodesic route.
Same for you spaceship and all it's fuel.  But again, as long as the ship induced curvature is not large compare to the curvature without the ship the changes are not large. And again, the comparison is ship-induced curvature compare to the curvature without the ship, it has nothing to do with the fueled up energy versus empty ship energy, well as long as the fueled up ship is the one that doesn't change the curvature much.
OK, let's get to that fuel required.  Imagine two ships. The Space Valdez and the Space Chicken.  One time in Camp Music, in the past, the Space Valdez is manufactured at Music Camp.  It harvests fuel at Music Camp, way more fuel than it personally needs and plans to transport some fuel to Camp Parts Unknown, which is far away.  So far away that the Space Valdez carries factories capable of manufacturing and assembling replacement spaceship parts.  The occupants of Music Camp wish to be good galactic occupants so instruct the Space Valdez to respond with overwhelming kindness to distress broadcasts even if it uses up much fuel and resources.  Who knows maybe there is a default way to program fuel transports to react so that others can recognize that it isn't a giant missile and maybe making it respond to any request to fuel or manufacture is a way to do that.  Not saying that it is smart, but say it happened, even just once, in the history of the universe.  So the Space Valdez sets off on its maiden voyage, fueled up, with manufacturing and communications capability and full of goodwill. Aims towards Camp Parts Unknown and goes.
So the Space Valdez is transporting a huge amount of fuel taking a nice geodesic through spacetime when it encounters a distress broadcast from a decrepit and low fuel ship called the Space Chicken. The Space Valdez accelerates to join and matches the accelerating trajectory of the Space Chicken and exchanges vast data back and forth at extremely close range.  This encounter is considered productive and the Space Valdez uploads a datastore from the Space Chicken that describes an earlier state of the Space Chicken in a surprising similar looking region of spacetime.  It repairs, refuels and wholesale rebuilds the Space Chicken as needed.  Including resetting the whole datastore of the Space Chicken. Then they bid farewell and the Space Valdez heads back out to Camp Unknown.
Meanwhile the rejuvinated Space Chicken is in bootup mode and runs on autopilot mode which includes accelerating hard to test activate the rockets.  It saves a checkpoint in the datastore (that includes instructions about how to build and repair the Space Chicken) as part of bootup process.  It then uses the newly acquired fuel and polished craft to hurtle around the cylinder on an accelerated trajectory. And it made the log of it's current state shortly after losing communication distance with the Space Valdez. Eventually battered and low on fuel the Space Chicken, so very damaged but having always maintained a good record (at cost to degredation of the rest of the ship and using up of fuel) of it's earlier state and keeping the communication system good and full of data of the kind that strangers might find beneficial to have, the Space Chicken starts to broadcast a distress broadcast.  This transmission is picked up by the recently manufactured Space Valdez on its first voyage.
OK, so we have the complete picture.  All the fuel that is shot out of the Space Chicken's engines can be traced back as having come from the Space Valdez and then originally from Camp Music.  Same with all the wear and tear energy that inevitable happened as the Space Valdez fixed up the Space Chicken.  The information about how to manufacture, repair, build, program, and reboot the Space Chicken are a type of Djinn, with no ultimate source, but merely flow from one region of spacetime to another.  In every local region, the physics is normal.  Parts wear out, systems are used to maintain redundancy, material is used to protect the integrity of data, energy and momentum are shot out one way to accelerate the other way sop fuels goes down except when being refueled in flight by a fuel transport vessel.  Nothing weird at all.  Particularly no violations of conservation of energy, because that is a local law so we just need small coordinate patches and in each patch the energy changes by exactly how much flowed in.  This scenario solves that fine.  We could write a chapter book about each region of spacetime over an small bit of space and a small bit of time and the story looks perfectly ordinary.
As for entropy. In a sense the same thing happens, at each point entropy is already there and as time goes on the local entropy goes down by an amount less than the entropy that flows out.  The Space Chicken uses fuel to do things and emits waste heat during the whole trip.  With local stores of entropy, it is again a local law.
With no quantum, there is no problem.  And no violation of laws of energy or thermodynamics. Other answers that mention things vanishing and appearing are wrong.  General Relativity is a local theory, just break it up into small pieces where nothing weird happens, if you can't do that then you've done it wrong.  If when you glue it all together you look at it and you don't like it, that's your problem if each local piece followed the rules just fine.  And you don't ever even need to bring up words like forever.  Just break it into pieces and describe each piece in a totally normal way and make it clear how the pieces line up.
I hope I did that for you in this example, and if you break it into pieces there is never a need for the word forever, and breaking it into pieces each of which looks fine, and sewing them together is what General Relativity is all about.
For your other questions:
Is it possible for a particle to be susceptible to external forces and still have zero rest mass?
A zero mass particle can still have its momentum changed by an external agent/interaction, and that can make it deviate from a geodesic, but unlike for a massive particle it need not, it could just increase its energy without changing direction so could continue the same direction.
Is it possible that Chandrasekhar and Wright were actually right in suggesting that Gödel's philosophical conclusions are questionable, and that they hit the nail on the head by focusing on the geodesics in the Gödel's universe?
The focus on geodesics is a red herring and a wild goose chase.  Nothing travels on a geodesic unless it has no energy, no stress, no momentum and no spin.  Plus you can refuel so there is no issue whatsoever.  There are problems with Closed Timelike Curves, but they are more about quantum effects or stability issues.


text:
Q: How to using Akka Futures asynchronously in Java I'm making a call in a Java service layer that looks like this;
Future<Object> future = Patterns.ask(myActor, message, timeout);

Response res = (Response) Await.result(future, timeout.duration());

I've read the Akka documentation and realize blocking like this is not recommended. I need to return the response object to the calling method. Is it possible do this asynchronously with Akka from my Java service? I tried to do this using the future.onSuccess method however the onSuccess method does not allow a return value so I can't return the value.

A: The akka way of passing data between threads, which is essentially what you are doing by blocking above is to compose futures or to send a message to an Actor.
The following example has been taken from the Akka documentation.
final ExecutionContext ec = system.dispatcher();

Future<String> f1 = future(new Callable<String>() {
    public String call() {
        return "Hello" + "World";
    }
}, ec);

Future<Integer> f2 = f1.map(new Mapper<String, Integer>() {
    public Integer apply(String s) {
        return s.length();
    }
}, ec);

f2.onSuccess(new PrintResult<Integer>(), system.dispatcher());

Notice that in this example data is being 'returned', or more precisely it is being handed off to another unit of work without a thread having to block and wait for a result.
This is why onSuccess returns void, it is to be used at the end of a chain of composed futures.  If it was to return a value, it would be like map and it would return another Future.  Which would leave you with the same requirement of blocking.
Thus to answer your question, no.  There is no way to 'return' a value from an asynchronous future without blocking.  Instead you should review why you need Response to be returned like that, and see if instead you can move the handling of Response into either onSuccess or map.  A minor alternative is to return Future[Response] and let the caller worry about chaining the futures.  The case that you have hit usually happens when mixing paradigms, and it is best avoided.


text:
Q: Game center display with wrong orientation I'm trying to integrate gamecenter into my application.
It works fine on iPad, but on iPhone, the game center view is partially displayed, with a wrong orientation. See : http://cl.ly/image/2b241H210T3E
Here is how I call the view:
    GKLeaderboardViewController *lb = [[GKLeaderboardViewController alloc] init];
if (lb != nil) {
    lb.category = [NSString stringWithFormat:@"%@_overall", [AppSettings appleGameCenterId]];
    lb.leaderboardDelegate = self;
    [self presentModalViewController:lb animated:YES];
}
[lb release];

I also tried to sub class GKLeaderboardViewController like this:
.h:
 @interface ITGKLeaderboardViewController : GKLeaderboardViewController
 @end

.m:
@interface ITGKLeaderboardViewController ()

@end

@implementation ITGKLeaderboardViewController

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

@end

But it's still the same result.
Any idea ?
Thanks for your help !

A: Finally fond how to fix it.
self.modalPresentationStyle = UIModalPresentationCurrentContext;

I had the exact same problem with MFMailComposeViewController, and the same line resolved the issue.


text:
Q: Pre-populate redux-form causes double rendering I have created Simple form following the guide in redux-form documentation which prepopulate data from a reducer called staticData.
SandBox Code can be seen here
The reducer is initialized with the state required for the prepopulation and there is no actioמ that calls it. (see the code below).
Bottom Line: Is it possible to pre-populate redux-form with only 1 render?


text:
Q: OpenCV - training LatentSVMDetector models in OpenCV (algorithm from Pedro Felzenszwalb ) Why is there no module to train latent SVM in OpenCV?
There is only the detector: http://docs.opencv.org/modules/objdetect/doc/latent_svm.html

A: That's right. You should use the Matlab package to train new models.
However, unfortunately, there is no updated code that I know of for transforming the Matlab models to xml's to use in OpenCV.


text:
Q: Severe GAE performance degradation all of sudden We've seen calls start to take 10x to 100x longer as of a specific point in time (right about 2012-02-18 04:00:00).  For example, our longest call that normally can take up to 5 seconds, is now timing out at a minute. I'm pretty sure it's not a result of a code or configuration change made on our part.  All of our API calls seem to be impacted.  Using AppStats, there seems to be no glaring culprit.  (Unfortunately, I don't have a saved graph before Friday to compare to.)  We do many gets/fetches, and some writing, against the high-replication datastore -- both seem impacted.
Any insight?

A: Best to file a production issue so it can be investigated.


text:
Q: How pointer chasing is working in this benchmark Trying to understand how pointer chasing is working (basically the access pattern) in the following benchmark:
https://github.com/google/multichase/blob/master/multichase.c
For the simple chase:
static void chase_simple(per_thread_t *t) {
  void *p = t->x.cycle[0]; ----> here p is pointing to initial address

  do {
    x200(p = *(void **)p;) ----> didn't get this statement, is x200 some compiler built-in ?
  } while (__sync_add_and_fetch(&t->x.count, 200));

  // we never actually reach here, but the compiler doesn't know that
  t->x.dummy = (uintptr_t)p;
}

where and how  in the code, access pattern is made somewhat unpredictable so that H/W prefetcher doesn't guess it properly?

A: I'd assume x200 is a CPP macro that repeats its operand 200 times, for loop unrolling.  Read x200 as "times 200".  Possible implementation:
#define x5(x)  x x x x x
...
#define x200(x)  x100(x) x100(x)

That would make sense to amortize the cost of the atomic RMW to increment t->x.count.
You can check by looking at C preprocessor output, e.g. gcc -E, or search for the macro definition in the included files.

The actual statement being repeated,
p = *(void **)p;, is just dereferencing a pointer to get another pointer.  Often you'd have p = p->next; if you had struct foo *p, but with just a void* you need a cast to keep the compiler happy and get an assembly instruction like mov rax, [rax].
Without a struct that can contain a memory that's a pointer to the same struct type, dereferencing a pointer is going to change the type.  C doesn't have a way to declare an infinitely-indirect pointer that just produces the same type when you deref it.

where and how in the code, access pattern is made somewhat unpredictable so that H/W prefetcher doesn't guess it properly?

Nowhere in this function; it's just iterating through an existing linked list.
Look for the code that allocates space and stores pointers into it.  Probably allocated as one large array, so it has control over the layout, unlike if it did many small mallocs.  A random shuffling of the integers 0..n-1 could be mapped transformed to an array of pointers to pointers.  Or something like that; perhaps you need to invert that mapping to make sure there aren't short cycles.  Or maybe there's some simpler way to generate a linked list that covers all slots in a random order, with the last element pointing to the first so it's a closed loop that can be iterated as many times as you want.


text:
Q: Siddhi join events with data from DB I want to understand the "dos" and "dont dos" in siddhi. I saw DB connectors and possibilities to enrich stream events with data from DB (lets say the cassandra connector).
Example:
@primaryKey('id')
@store(type = 'rdbms', datasource = 'WSO2_TEST_DB')
define table BuyerInfoTable (id string, name string, address string, email string);

@info(name = 'EnrichBuyerInformation')
from ShipmentInfoStream as s join BuyerInfoTable as b
    on s.buyerId == b.id
select s.orderId, b.name, b.address, b.email, s.shipmentType
insert into ShipmentAndBuyerInfoStream;

Do I understand right, that this approach would mean that there is a select query made to the db on each incoming Event on the ShipmentInfoStream ?
In case yes - this sounds like a "dont do" for me - especially if we are talking about 100k events / sec.
Or am I understanding the architecture in a wrong way?

A: Yes, you are correct. As per the above query, when there is an event arrived in ShipmentInfoStream then there will be a DB query, get the output and process further.
But, this operation could be improved in various ways.

*

*If the DB table only contains limited values (and not changed by external users) then you could pre-load those events, keep in the in-memory event store and process them.

*You could use a cache to improve the performance. Check the "Caching In Memory" section in https://siddhi.io/en/next/docs/query-guide/#store ...


text:
Q: Convergence of $\int_{-\infty}^{\infty} \sin p(x)\,dx$ where $p$ is a polynomial with $\deg p>1$ I thought about this problem today, and tried to solve it. Let $ax^n$ be the leading term of $p$.
I can prove that $\displaystyle\int_{-\infty}^{\infty}\sin ax^n\,dx$ converges (below), and I argued that since $p(x)\sim ax^n$ for sufficiently large $x$, we have $\sin p(x)\sim \sin ax^n$, and so the convergence of $\displaystyle\int_{-\infty}^{\infty}\sin p(x)\,dx$ is determined by that of $\displaystyle \int_{-\infty}^{\infty}\sin ax^n\,dx$.
I am not sure whether this is correct though, and would appreciate some help if it is not. Many thanks!

$n>1$ throughout.
Call $ax^n$ the leading term of $p$. For sufficiently large $x,\;p(x)\sim ax^n$, and thus $\sin p(x)\sim \sin ax^n$
Without loss of generality, assume $a>0$ and restrict ourselves to $\mathbb{R}^+$. It is sufficient to consider:
$$\int_{0}^{\infty} \sin ax^n\,dx$$
For this, let $t=ax^n:$
$$ \int_0^{\infty} \sin x^n\,dx=\frac{1}{\sqrt[n]{a}n}\int_0^{ \infty} t^{\frac{1}{n}-1}\sin t\,dt$$
Now, break up the real line into segments of length $\pi,$ and let $t=w+k\pi:$
$$\sum_{k\geq 0} \frac{1}{\sqrt[n]{a}n} \int_{k\pi}^{(k+1)\pi} t^{\frac{1}{n}-1}\sin t\,dt=\sum_{k\geq 0} \frac{(-1)^k}{\sqrt[n]{a}n}\underbrace{\int_0^{\pi}\frac{\sin w}{(w+k\pi)^{ 1-\frac{1}{n}}}\,dw}_{s_k}$$
We now work our way towards the Leibniz test:
$$0<s_k<\int_0^{\pi}\frac{dw}{(w+k\pi)^{1-\frac{1}{n}}}=n\sqrt[n]{\pi}\Big((k+1)^{\frac{1}{n}}-k^{\frac{1}{n}}\Big)\to 0\;\;\text{as}\;k\to \infty$$
And of course, since $\sin w>0$ for $w\in (0,\pi):$
$$\Big(w+(k+1)\pi\Big)^{\frac{1}{n}-1}<\Big(w+k\pi\Big)^{\frac{1}{n}-1}\Rightarrow s_{k+1}<s_k$$
Thus $s_k$ is a null sequence and is monotonically decreasing hence $ \displaystyle\sum_{k\geq 0} (-1)^k s_k$ converges, and it follows that the integral in question converges also.

A: Suppose that $f(x)$ is a function where $\lim_{x \to \infty}f(x)=\infty$ and $f'(x)$ is increasing and positive on $[N, \infty)$, for some $N>0$. Note that a polynomial of degree $>1$ with positive leading coefficient satisfies this condition. Suppose that $x_1>N$ such that $f(x_0)=2 k \pi$ for some $k \in \mathbb{N}$. We wish to find a condition so that
$$
\int_{x_0}^{\infty} \sin \left(f(x)\right) dx
$$
converges. First, note that $f$ is strictly increasing to $\infty$, so for each $m \in \mathbb{N}$, there is an unique $x_m$ such that
$$
f(x_m)= (2k+m)\pi.
$$
If $x$ is between $x_m$ and $x_{m+1}$, then $\int_{x_0}^x \sin(f(t))dt$ is between $\int_{x_0}^{x_m} \sin(f(t))dt$ and $\int_{x_0}^{x_{m+1}} \sin(f(t))dt$. As such, it suffices to show that the following series converges:
$$
\sum_{m=1}^{\infty} \int_{x_m}^{x_{m+1}} \sin(f(t))dt.
$$
By our defintion of $x_m$, this series is alternating in sign. Using the substition $u=f(t)$ yields
$$\int_{x_m}^{x_{m+1}} \sin(f(t))dt = \int_{(2k+m)\pi}^{(2k+m+1)\pi} \frac{\sin(u)}{f'(f^{-1}(u))} du.$$
Note that the conditions on $f$ force that the function $f'(f^{-1}(u))$ is increasing. Hence
$$
|\int_{x_m}^{x_{m+1}} \sin(f(t))dt | > |\int_{x_{m+1}}^{x_{m+2}} \sin(f(t))dt|
$$
for each $m$. The last condition we need for convergence is only
$$
\lim_{m\to\infty} \int_{(2k+m)\pi}^{(2k+m+1)\pi} \frac{\sin(u)}{f'(f^{-1}(u))} du =0,
$$
so the last condition we would want is that $f'(x)\to \infty$, which is satisfied by our polynomial.

A: Select an $N$ such that $p'(x) \neq 0$ for $|x| > N$. It suffices to show that $\int_N^{\infty} \sin p(x)\,dx$ and $\int_{-\infty}^{-N} \sin p(x)\,dx$ are convergent. We do the first integral as the second is done the same way. For $M > N$ write
$$\int_N^M \sin p(x)\,dx = \int_N^M p'(x)\sin p(x) {1 \over p'(x)}\,dx$$
Integrate by parts, integrating $p'(x)\sin p(x)$ to $-\cos p(x)$ and differentiating ${1 \over p'(x)}$.  we get
$$\int_N^M p'(x)\sin p(x) {1 \over p'(x)}\,dx = -{\cos p(M) \over p'(M)} + {\cos p(N) \over p'(N)} - \int_N^M \cos p(x){p''(x) \over p'(x)^2}\,dx$$
Now let $M \rightarrow \infty$. Since $|\cos(p(M))| \leq 1$ and $p'(M) \rightarrow \infty$ as $M \rightarrow \infty$, the first term goes to zero. Also, the degree of the denominator of
${\displaystyle {p''(x) \over p'(x)^2}}$ exceeds the degree of the numerator by the degree of $p(x)$, which is at least $2$, so the integral converges absolutely, using that $|\cos p(x)| \leq 1$. So the integral converges. In particular, we have
$$\int_N^{\infty} \sin p(x) \,dx =  {\cos p(N) \over p'(N)} - \int_N^{\infty} \cos p(x){p''(x) \over p'(x)^2}\,dx$$
Here the right-hand integral converges absolutely.


text:
Q: How to instantiate an association to a service class based on the contract hierarchy? I want to instantiate an association to a service class based on the contract hierarchy. Consider following code:
public interface IServiceBase
{
    void DoSomething();
}

public interface IService : IServiceBase
{
    void DoSomeOtherthing();
}

public interface IOtherService : IServiceBase
{
    void DoAnotherthing();
}
public class ServiceBase : IServiceBase
{
    public virtual void DoSomething()
    {
        Console.WriteLine("Base service implementation");
    }
}
public class Service : ServiceBase, IService
{
    public void DoSomeOtherthing()
    {
        Console.WriteLine("New service implementation");
    }

    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("Child service implementation");
    }
}
public class OtherService : ServiceBase, IOtherService
    {
        public void DoAnotherthing()
        {
            Console.WriteLine("Another child service implementation");
        }
    }
public abstract class ClientBase
{
    public IServiceBase Service { get; set; }
}

public class Client : ClientBase
{
    public IService Service { get; set; }
}

public class OtherClient : ClientBase
{
    public IOtherService Service { get; set; }
}

If an IoC container try to inject Service property of ClientBase, it will find two types that are registered as IServiceBase: IService and IOtherService.
How IoC can decide to use which type is proper for instatiation? This decision depends on Client concrete class: Client or OtherClient which they know to which inherited interface they actually depend on: IService or IOtherService corresponds to Service or OtherService type.

A: Usually IoC/DI containers configure a concrete service interface. They don't automatically handle an injection of IService even if you've already configured IOtherService when that last interface implements IService too. That is, it can only inject a direct implementation of IOtherService.
For example, in Castle Windsor you register an implementation for more than one service at once as follows:
container.Register
(
     // OtherService implements these interfaces, right?
     Component.For<IServiceBase, IService, IOtherService>()
              .ImplementedBy<OtherService>()
);

That is, once OtherService gets injected in a component on which the type is IServiceBase, IService or IOtherService, the container will be able to resolve OtherService.

A: Finally I ended up to a solution which encapsulates composition logic in a Resolver(Composer) class; accompanied by some contract on property definition for services.
We define Lazy properties which T is type of service interface. As I fixed up following code:
public interface IServiceBase
{
    void DoSomething();
}

public interface IService : IServiceBase
{
    void DoSomeOtherthing();
}

public interface IOtherService : IServiceBase
{
    void DoAnotherthing();
}
public class ServiceBase : IServiceBase
{
    public virtual void DoSomething()
    {
        Console.WriteLine("Base service implementation");
    }
}
public class Service : ServiceBase, IService
{
    public void DoSomeOtherthing()
    {
        Console.WriteLine("New service implementation");
    }

    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("Child service implementation");
    }
}
public class OtherService : ServiceBase, IOtherService
    {
        public void DoAnotherthing()
        {
            Console.WriteLine("Another child service implementation");
        }
    }
public abstract class ClientBase
{
    private IServiceResolver _serviceResolver;
    public ClientBase()
    {
        _serviceResolver = new ServiceResolver();
        _serviceResolver.Resolve(this);
    }
    [Resolve(isParentContract:true)]
    public Lazy<IServiceBase> Service { get; set; }
}

public class Client : ClientBase
{
    [Resolve]
    public Lazy<IService> Service { get; }
}

public class OtherClient : ClientBase
{
    [Resolve]
    public Lazy<IOtherService> Service { get; }
}

The ServiceResolver responsibility is to find all Lazy properties which marked by Resolve attribute and create a Lazy instance of the true contract which is infer-able by matching contracts to parent service contract. This way the property which is marked by ResolveAttribute as isParentContract:true will be instantiated by the key of type a property which is defined in inherited client class and it's interface type is inherited from type of property defined in parent client.


text:
Q: Diminuir tamanho do Campo Editar bom dia.
Sou iniciante, estou tentando diminuir o tamanho da coluna do editar e não estou conseguindo conforme a imagem abaixo.
Alguém pode me ajudar?

        @*Campo Nome*@

            @Html.DisplayNameFor(model => model.Nome)

         Editar

Atenciosamente,
Thiago Corrêa.

A: Primeira pergunta: por que está usando table para alinhar os elementos?
Isso é conceitualmente errado. Use tabela para dados tabulares apenas.
O Bootstrap fornece o row, que permite o alinhamento de elementos por meio de um grid.
Assim:

<link  rel="stylesheet"  href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">

    Editar
    <input type="text" class="form-control">

    <button class="btn btn-default">
      Editar
    </button>

A: Casa vc não possa mudar a estrutura de table para div como o amigo Wallace sugeriu aqui tem um modelo de table apenas com as classes default do Bootstrap.
veja que definindo o tamanho de col- da primeira th a segunda nem th assumi uma largura implícita.

<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

   nome
   editar

   nome
   <button class="btn btn-primary">X</button>

   nome
   <button class="btn btn-primary">X</button>

   nome
   <button class="btn btn-primary">X</button>

w-100
Agora se vc quiser fazer com algum CSS customizado vc pode simplesmente determinar uma largura de 100% pra primeira TH, assim ela ocupa todo o espaço e a segunda TH só ocupa o tamanho dela mesma.
Nesse exemplo eu criei uma classe .w-100 que corresponde a width:100% e coloquei na primeira TH, apenas isso...

.w-100 {
  width: 100%;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

        nome
        editar

        nome
        <button class="btn btn-primary">X</button>

        nome
        <button class="btn btn-primary">X</button>

        nome
        <button class="btn btn-primary">X</button>


text:
Q: commutators in upper triangular matrices Consider the group $T_p(n)$ of all non-singular upper triangular matrices with entries in $\mathbb{F}_p.$ Its commutator subgroup is $U_p(n)$ (all elements in $T_p(n)$ with $1$s on the main diagonal). The question is: is every element in $U_p$ a commutator of matrices in $T_p?$

A: Too long for a comment and only a partial answer for $n>2$. A note on commutators in the group of infinite triangular matrices over a ring, by Agnieszka Bier and Waldemar Holubowski, Linear and Multilinear Algebra 63  (2015) no. 11, 2301-2310; seems relevant. It includes results on finite matrices, despite the title.
Let $R$ be an associative ring with $1$, and let ${U}(R)$ be its group of invertible elements. $T(n,R)$ denotes the group of upper triangular $n\times n$ matrices; $UT(n,R)$ the set of upper unitriangular matrices ($1$s in the diagonal), $UT(n,m,R)$ the subgroup containing exactly all those matrices which have zero entries on the first $m$ super diagonals; and the basic commutators $c_k(x_1,\ldots,x_k)$ are defined inductively by $c_1(x_1)=x_1$, $c_{i+1}(x_1,\ldots,x_{i+1}) = [c_i(x_1,\ldots,x_i),x_{i+1}]$; let $\gamma_k(G)=G$ be the $k$th term of the lower central series of $G$. Finally, the Engel words $e_k(x,y)$ are given by $e_2(x,y)=[x,y]$, $e_{m+1}(x,y) = [e_m(x,y),y]$.
The authors prove:

Theorem 1.5 Let $R$ be an associative ring with $1$ such that $U(R)$ is commutative. Then:

*

*$\gamma_k(UT(n,R))=UT(n,k,R)$ and every element of $\gamma_k(UT(n,R))$ is a value of the basic commutator $c_k$.

*Every element of $\gamma_k(UT(n,R))$ is a value of the Engel word $e_k$.

  Moreover, if $1$ is a sum of two invertible elements, then

*$[T(n,R),T(n,R)] = UT(n,R)$ whenever $n\geq 2$.

*Every element of $\gamma_2(T(2,R)) = UT(2,R)$ is a commutator.

*Every element of $\gamma_2(T(n,R)) = UT(n,R)$ with $n>2$ is a product of at most two commutators.

In particular, for $R=\mathbb{F}_p$ with $p>2$, then the answer is "yes" for $n=2$ by point 4; but for $n>2$ they only show every element is a product of at most two commutators.
Perhaps this was already known for the special case of matrices over commutative rings/fields?


text:
Q: OpenXML Remove text from template I have a number of .docx templates that customers download, but certain words need to be changed or removed from the document for different customers. I can't find anything on how to remove text:-
using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
{
  foreach (Text element in doc.MainDocumentPart.Document.Body.Descendants<Text>())
  {
   //This is fine
   element.Text = element.Text.Replace("DocumentDate", wordReferenceTemplatesMV.DocumentDate)

   //Need help on how to remove text
   element.Text = element.Text.Remove???("TextToRemove")
}

A: Why not just replace it with an empty string?
element.Text = element.Text.Replace("TextToRemove", string.Empty);

A: If you don't want the element any more then you can delete the whole element:
using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
{
    foreach (Text element in doc.MainDocumentPart.Document.Body.Descendants<Text>())
    {
        if (element.Text == "TextToRemove")
            element.Remove();
    }
}

Edit
If you're left with an empty line the chances are you have a Paragraph that contained the Text. In that case you want to remove the Paragraph instead in which case you can do:
if (element.Text == "TextToRemove")
    element.Parent.Remove();

A: Most text values are in Run element. Basically you can run through all the Run elements and check its text. it should be something like:
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
foreach (Run r in body.Descendants<Run>())
{
    string sText = r.InnerText ;
    //...compare the text with the value
    //note sometime, you could see the text be broken into two runs, you need to find a way based on your requirements and connect them.    }

if you want to delete the text, you can just delete the run.
call the run's remove() method.
r.Remove();

More details about Runs and text object,
If you use the file as template, usually I will set some special properties on the Run element, so later, I can find them with more accuracy.
for example, inside the run loop, before checking its text, you can check the color first.
if( r.RunProperties.Highlight.Val == DocumentFormat.OpenXml.Wordprocessing.HighlightColorValues.Yellow )
{
    string sText = r.InnerText ;
    ....
}

Hope it helps.

A: I don't think it's the paragraph element causing the empty line when removed.
Clients send over a template with an address block as:-
[address1]
[address2]
[city]
[town]
[state]
[zip]
The fields are populated from the database with the replace function, but if an address doesn't contain an [address2] value, that's what I need removing. If I remove the text, I'm still left with an empty line between [address1] and [city]. The [address2] field isn't in it's own paragraph.


text:
Q: Plotting the graph of $\operatorname{Re}(z)<2$ $$\operatorname{Re}(z)<2$$
My idea was that, in the complex plane, the graph looks like a ray starting at the origin and extending up to $2$, but not including that point. Then there would have to be a little comment or some way to indicate that this applies to every angle $\theta$ around the origin, so long as the radius, $R$, is less than $2$.
However, Wolfram plots it like this. Which one of us is more correct? I don't understand why Wolfram plots this in the $x$-$y$ axis.

A: Neither is correct.
With $z = x+iy$, the inequality is just $x < 2$, representing a half-plane to the left of the  vertical line $x = 2$:


text:
Q: Why would BIOS count 3 GB and Vista show 4 GB RAM? I upgraded my Vista computer from 2GB to 4GB of RAM.
However, upon boot up, it shows only 3.072 GB of memory.
Yet Vista says I have 4.00 GB of memory.
In addition, the computer doesn't seem "twice as fast" at all (Eclipse still takes 20 seconds to open, Vista Explorer lags and spins the hour glass just as often, etc.).
(1) Is there something I have to do to make my computer faster after it has this extra memory, and (2) is it alright that the boot up screen only seems to recognize 3 GB?

A: The reason that Windows reports 4GB of RAM is because Vista is lying to you.
Remember that when Vista was released, purchasing 4GB of RAM was becoming much more cost-effective for the average user. Saying that the OS only reported 3GB of RAM when you knew your machine had 4 GB installed probably caused all kinds of support calls and support costs for Microsoft. The cheapest and simplest solution was to just change what Vista reported to the user, regardless of how much memory was addressable. My guess is that any amount of RAM greater than or equal to 3GB triggers x86 Vista reporting 4GB installed.
Vista SP1 Notable Changes

With SP1, Windows Vista will report
  the amount of system memory installed
  rather than report the amount of
  system memory available to the OS.
  Therefore 32-bit systems equipped with
  4GB of RAM will report all 4GB in many
  places throughout the OS, such as the
  System Control Panel. However, this
  behavior is dependent on having a
  compatible BIOS, so not all users may
  notice this change.

A: Do you maybe have an onboard graphics card that uses 1GB of system mem?
And regarding your loading times, unfortunately more RAM probably won't make much of a difference unless your system is already using it all and having to swap out virtual memory. A faster hard-drive and disk defrag might help loading times more.
The extra RAM will be more handy at not slowing down your system once you have opened up some large Photoshop docs, and have opened up loads of Firefox tabs etc.

A: Best explained by Jeff - Where's my RAM ?

A: I don't know why Windows would report 4Gb whereas the BIOS is reporting 3Gb - possibly a bug in the BIOS reporting since if the BIOS can really only see 3Gb than Windows should only see 3Gb - you could try updating the BIOS.
(...and see answer to this question).
Also, on a 32bit system you're only actually going from 2Gb to 3Gb of usable memory as the system can't use the 4th Gb since the memory addresses are reserved for system use - see this Dan's Data article for explanation.
You're much more likely to notice a speed increase moving from 1 to 2Gb than from 2 to 4Gb (2Gb is pretty much plenty for a Celeron system). If you're on Vista or Windows 7, have a look at the System Rating (Windows Experience Index) to see where the bottleneck lies - I suspect it will be the processor rather than the RAM.

A: There is a 3GB ram address space limit in 32bit operating systems. The last GB is used for other uses on the system. The way this was displayed was changed in Vista and "fixed" in SP1.
If you want more than 3GB, you need to use a 64bit version of windows.
There are more details here http://www.dansdata.com/askdan00015.htm and this microsoft support KB article

If you are running Windows Vista or if
  you have upgraded Windows XP to
  Windows XP Service Pack 2 (SP2) or a
  later version, the memory that is
  reported in the System Properties
  dialog box or by the System
  Information tool (Msinfo32.exe) has
  changed. This symptom occurs if the
  following conditions are true:
  - The computer has 4 or more gigabytes (GB) of RAM.
  - The computer is using Physical Address Extension (PAE) mode.
For example, before you upgrade to
  Windows XP SP2, the System Properties
  dialog box may report approximately
  3.87 GB of RAM.
The System Information tool may report that the total
  physical memory is approximately
  3,540.00 megabytes (MB). After you
  upgrade to Windows XP SP2, the System
  Properties dialog box may report
  approximately 3.12 GB of RAM, and the
  System Information tool may report
  that the total physical memory is
  approximately 2,770.00 MB.
This issue occurs because of a design
  change in Windows XP SP2 that is also
  included in Windows Vista. The changes
  were made to PAE mode behavior to
  improve driver compatibility.
To reduce driver compatibility issues,
  Windows Vista and Windows XP Service
  Pack 2 or a later version include
  hardware abstraction layer (HAL)
  changes that mimic the 32-bit HAL DMA
  behavior. The modified HAL grants
  unlimited map registers when the
  computer is running in PAE mode.
Additionally, the kernel memory
  manager ignores any physical address
  that is more than 4 GB. Any system RAM
  that is more than the 4 GB barrier
  would be made unaddressable by Windows
  and be unusable in the system. By
  limiting the address space to 4 GB,
  devices with 32-bit DMA bus master
  capability will not see a transaction
  with an address that is more than the
  4 GB barrier. Because these changes
  remove the need to double-buffer the
  transactions, they avoid a class of
  bugs in some drivers that is related
  to the correct implementation of
  double buffering support.

Also application launch times are more about disk IO speed than the amount of RAM you have, hence why eclipse is no faster to load.

A: The reason for the discrepancy is as mentioned above how Vista reports memory size.
The solution however when running a 64-bit OS is to enable a BIOS feature called memory remap. This is by default disabled in the BIOS because it breaks compatibility with 32-bit OS:s.
What the feature does is that instead of mapping your gfx card/io cards and such below the 4GB boundry it moves everything above the 4GB boundry. The result is that it does not steal the address space and you can therefore use all 4GB of memory. It will also report the correct size at the BIOS screen.


text:
Q: geom_mark_ellipse runs forever I'm trying to plot the graph using geom_mark_ellipse.
I don't know why it runs forever without any error message.
First, I plot the normal scatter plot graph.
It runs successfully.
dailyActivity %>%
  ggplot(aes(Calories,TotalSteps)) +
  geom_point()

But when I add geom_mark_ellipse as below, it runs forever.
any suggestion, please
dailyActivity %>%
  ggplot(aes(Calories,TotalSteps)) +
  geom_point() +
  geom_mark_ellipse(fill=UserType, label=UserType)

I did try to move fill and label inside aes(), still runs forever
dailyActivity %>%
  ggplot(aes(Calories,TotalSteps)) +
  geom_mark_ellipse(aes(fill=UserType, label=UserType)) +
  geom_point()

Here is the sample data enter image description here

A: thanks so much for great help.
Step to solve:

*

*move fill and label inside aes()

*install.packages('Rcpp') and library(Rcpp)


text:
Q: Maximum power test Question:
In a count that was held a year ago in a reserve , there were 15 tigers counted. 7 females and 8 males, which were marked with numbers from 1 to 15.
a. By recent reports, there was fear that the number of tigers in the reserve had dropped under 15. In order to check that, it was decided upon going out and recording the numbers of 4 tigers in the reserve, which will appear randomly. If the maximum number of these 4 records is k or lesser, then the conclusion is that the number of tigers really decreased.

*

*if the count was done with return. what is the value of K, if the required p-value is 0.1?

*If the count was done without return , calculate the p value of the test when k=9.

b. In a random sample of 4 tigers, without return , there was 1 male and 3 females found. Now we need to check if the first count (a year ago) had a mistake, and actually there are 15 tigers in the reserve but among them 8 females and only 7 males.
1. find a maximum power test based on X - the number of females in a 4 tiger sample.
2. find the p-value of that test, and make a conclusion for a=0.1
3. find the probability of a type II error, and the power of the test.
My thoughts
I did part a, and wasn't sure about it.
about part b- didn't really know how to do it- is doing the ratio of likelihood functions a good way to start? I don't know what is the parameter for that though...
in A.1. i said that $X_i\sim U(1,15), S(X)=max(X_i)$. $P(S(x)\le k)=0.1$ so $0.1=\frac {k-1+1}{15-1+1}=\frac k{15}$ so $k=1.5$ -> $k=1 $(k has to be a whole number)
A.2. $P(S(x)\le9)=P(X_1\le9)P(X_2\le8)P(X_3\le7)P(X_4\le6)=\frac 6{65}$


text:
Q: Find an alternative FPTAS for knapsack There is a famous algorithm using, the recusive integer data problem on:
w(j,p) = min weight set of items of profit=p when we have j items
Now I was wondering if there was an alternative solution using:
p(j,w) = max profit set of items of weight=k when we have j items
The recursion can be found without so much difficulty; $p(j,w) = max(p(j-1,w), p(j-1,w-w_j)+p_j$)
$p(.,0)=0\\
p(.,w<0)=-\infty\\
p(0,w>0) = -\infty$
Thank you for your help or if you can redirect me to a paper dealing with it :).


text:
Q: blur the side of the site blure side site
[1]: https://i.stack.imgur.com/giurR.jpg
how to blur the side of a website
: https://i.stack.imgur.com/bIgfz.png
#main-style {
position: relative;
}
#main-style::after {
content: "";
width: 100%;
height: 135%;
position: absolute;
top: -30px;
left: 0;
overflow: hidden;
filter: blur(5px);
}

this code don't work

A: Just replace the code where you wrote: filter: blur(5px); with backdrop-filter: blur(5px)
Explanation:
The code you wrote earlier works by taking a snapshot of the element and display the snapshot with blurred effect at the place of the element.
backdrop-filter, instead blurs the background of the element.
Note:
As of now, backdrop-filter does not work with Firefox Browsers.


text:
Q: How can we still see the CMB? May seem stupid but i cant wrap my head around it. if a star explodes we eventually see it when the light gets here. but once its got here we see the event and the star is now gone, we cant see it anymore because its not there anymore. so how can we still see the CMB if all the light has reached us, why can we continue to see it ?

A: The CMB happened everywhere in the universe. As time goes on we see it from further and further away.


text:
Q: how to create a txt file with specific information in c++ my goal is to create a .txt file like this:

598.1       # temperature in Kelvin
3.49       # pressure in atm
H_g        # list of species allowed in the system
H2_ref

but, the first 2 values should be 2 double values, which i am using in my program
i'am using c++
If anyone has got a solution or hints for me?
That would be awesome!
Thank you in advance!
best regards
schwing

A: This should write your double to a text file. For more information read http://www.cplusplus.com/doc/tutorial/files/
// basic file operations
#include <iostream>
#include <fstream>

void writeFile() {
    double myTempInK = 0;
    double myPresInAtm = 0;

    ofstream myfile;
    myfile.open ("example.txt");
    myfile << myTempInK << "# temperature in Kelvin\n";
    myfile << myPresInAtm << "# pressure in atm\n";
    myfile << "H_g # list of species allowed in the system\n";
    myfile << "H2_ref \n";
    myfile.close();
}

A: To insert data and create the file use std::ifstream f; and open it then write to it using f.write(...);

A: @FreshD and Graham Best:
thanks a lot...now it is working properly with this code:
std::ofstream myfile;
myfile.open("C:/Users/schwing/temp/example.txt");
myfile << p << "\n " << T << "asdf";
myfile.close();

just one question is left:
i had to specify the exact file directory. Where is the program puting the file, if i'm not using C:/Users/schwing.... and is there a possibility to use "relative" paths?
i have to mention, that i am generating a dll, and running the program in another program!
thanks in advance!


text:
Q: ¿cual es el porque de este error en tiempo de ejecución? Estoy aprendiendo a programar por mi cuenta a través de manuales pdf, mi pregunta es por que me sale un error y no me devuelve el numero máximo cuando ingreso números con decimales este es el código y el error también lo coloco aquí por que no se que quiere decir
package byJoel;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
    // write your code here

        //crea un objeto Scanner para introducir datos desde la ventana de comandos
        Scanner entrada = new Scanner(System.in);

        //pide y recibe como entrada tres valores de punto flotante
        System.out.print("Escriba tres valores de punto flotante, separados por espacios: ");
        double numero1 = entrada.nextDouble();
        double numero2 = entrada.nextDouble();
        double numero3 = entrada.nextDouble();

        //determina el valor maximo
       // double resultado = Maximo(numero1,numero2,numero3);

        //Imprime el valor Maximo
        System.out.println("El maximo de los tres es: "+ Maximo(numero1, numero2, numero3));
    }

    //creamos un método que devuelve el máximo de sus tres parametros double
    public static double Maximo(double x, double y, double z)
    {
        double ValorMax = x; // asume que x es el mayor para empezar"

        if (y > ValorMax)
            ValorMax = y;
        if (z > ValorMax)
            ValorMax = z;

        return ValorMax;
    }
}

ERROR QUE ME SALE AL INGRESAR NUMERO DE PUNTO FLOTANTE
Escriba tres valores de punto flotante, separados por espacios: 5.22 12.4 8.32

Exception in thread "main" java.util.InputMismatchException
  at java.util.Scanner.throwFor(Scanner.java:864)
  at java.util.Scanner.next(Scanner.java:1485)
  at java.util.Scanner.nextDouble(Scanner.java:2413)
  at byJoel.Main.main(Main.java:15)

A: Debes especificar una configuración regional para tu objeto Scanner de la siguiente forma:
Scanner entrada = new Scanner(System.in).useLocale(Locale.US);

Según la documentación :

An instance of this class is capable of scanning numbers in the
  standard formats as well as in the formats of the scanner's locale. A
  scanner's initial locale is the value returned by the
  Locale.getDefault() method; it may be changed via the
  useLocale(java.util.Locale) method
  The localized formats are defined in terms of the following
  parameters, which for a particular locale are taken from that locale's
  DecimalFormat object, df, and its and DecimalFormatSymbols object,
  dfs.

Traducción:

Una instancia de esta clase es capaz de escanear números en
  formatos estándar, así como en los formatos de la configuración regional del escáner. Un
  escenario inicial del escáner es el valor devuelto por el
  método Locale.getDefault (); Puede cambiarse a través del
  método useLocale(java.util.Locale)
  Los formatos localizados se definen en términos de los siguientes
  parámetros, que para una localidad particular se toman de la configuración regional
  del objeto DecimalFormat, df, y su objeto DecimalFormatSymbols,
  Dfs.

Por lo tanto, tu configuración regional predeterminada utiliza un DecimalFormat que espera una coma como un delimitador decimal en lugar de un punto.
Respuesta extraída de SO en inglés


text:
Q: cygcares-2.dll - missing from cURL library in cygwin install Hi I am wondering about cygcares-2.dll which is missing from my curl install in cygwin.
First I went in and installed with apt-cyg, then I reinstalled using the cygwin setup/install exe.
I was missing a few other dll's but I am still missing cygcares-2.dll and cannot find a version of it anywhere.
Output from the console when I do a cygcheck:

cygcheck: tack_down: could not find cygcares-2.dll

Does anybody know where I might be able to find cygcares-2.dll?


text:
Q: how to declare a variable in html for primary key and use it in an 'if' statement I need to run a segment of a code when the primary key of the object is 1,4,7...etc.
Basically, I need to run a if statement for a certain block of code.
            {% with i = ev.pk %}
                {% if i%3 == 1 %}

                {% endif %}
            {% endwith %}

{{ ev.event_title }}

{{ event.event_details }}
{{ ev.date }}{{ ev.venue }}

        {% endfor %}```

The above code doesn't work, I need:
1. Declare a variable (i)
2. assign it ev.pk
3. run an if statement {% if i%3 == 1%}

I am open for suggestions if there is a better way to code this.

A: Probably this will work (using divisibleby):
{% with ev.pk as i %}
       {% if i|divisibleby:3 %}

       {% endif %}
{% endwith %}


text:
Q: Move a Character on a Terrain DirectX9 I have created a terrain using a raw file and I want a character to move on the terrain.
How do i Check for collisions with the terrain ?

A: Simple way is to check sphere vs world collision. There is a lot of information about how to check sphere vs trianle collision. There is a lot in search: https://stackoverflow.com/search?q=sphere+world+collision


text:
Q: How to convert MongoDB archive file to JSON format? If I dump a database like so:
mongodump --archive=out.mdb

Is there some way to convert out.mdb to a flat JSON file? If so, how? (for example, if I just wanted to restore a single document)

A: mongoexport
I believe the only way is from the database, using mongoexport:
mongoexport --db yourdb -c yourCollection --out yourCollection.json

warning from mongo
Just take notice of the following (from their website):

WARNING
Avoid using mongoimport and mongoexport for full instance
  production backups. They do not reliably preserve all rich BSON data
  types, because JSON can only represent a subset of the types supported
  by BSON. Use mongodump and mongorestore as described in MongoDB Backup
  Methods for this kind of functionality.

A: Command for export :
mongoexport --db <dbname> --collection <collectionname> --out collection.json

Once exported, if there are BSON data is there, we can follow the below methods
Official MongoDB Java Driver comes with utility methods for parsing JSON to BSON and serializing BSON to JSON.
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
DBObject dbObj = ... ;
String json = JSON.serialize( dbObj );
DBObject bson = ( DBObject ) JSON.parse( json );

The driver can be found here: https://mongodb.github.io/mongo-java-driver/
In this way, if we take, we can convert easily.


text:
Q: How to retrieve the newest record from a Firebase Application and pass to a python variable? I need to update the variables from a FirebaseApplication object up in real-time.
But a FirebaseApplication is like a static dictionary object and the values can only be obtained by specifying the 'key' by get() method. How can I update the FirebaseApplication all the time? If each value of the firebase object is a dictionary with date/time as keys, how can I retrieve the newest values?
from firebase import firebase
url = "https://dw-1d-cc5-grp08.firebaseio.com/" # this is a test url
token = "yurddml214RsOPi9Ua0OhuDgeuzxm2Q7v7V6T6ZZ" #this is a test token
firebase = firebase.FirebaseApplication(url,token)
output_data = firebase.get('/humidity')
print(output_data)

A: In addition to accessing data by key, you can order and filter data by one of its child properties. For example:
https://yourdb.firebaseio.com/users.json?orderBy="name"&equalTo="Yannis"

This URL will give you all users whose name property is equal to "Rahul".
See the Firebase documentation on ordering and filtering for more examples.

A: You can use Firebase functions to get it done.


text:
Q: $T$, $S$ are lineary dependent $\Leftrightarrow$ $[T]_B$, $[S]_B$ are lineary dependent. EDIT: I see in the comments that my question is not clear enough so I will explain:
if I want to check whether $T$, $S$ are linearly independent or not, I will just pick an  easy to work with, basis for $V$ and then check if $[T]_B$, $[S]_B$ are linearly independent. so the real question is can I do that? and why?

A: Every vector space $V$, such that dim$(V)=n$ is isomorphic to $\mathbb{F}_n$ (column vectors with $n$ components), but even more than this, the isomorphism is a linear isomorphism, that is it preserves the structure of the vector space. To prove that this is indeed so you have to prove that the function $\phi$ mapping each vector of $V$ to its coordinate vector, is:

*

*functional

*injective and surjective

*preserves scalar multiplication and vector addition (this is where you add the extra conditions of preserving the structure of the vector space)

It is a quite straightforward direct proof, and most linear algebra books have it.
I hope this helps.


text:
Q: Rails, oauth vs oauth2 I want to know the difference between oauth and oauth2 gems available in ruby and which one can be used to connect with various sites like facebook, twitter, salesforce etc (There are many plug-ins available for this but can we create a single APIs for connecting all oauth provider).
~N a R e N

A: These two gems differ by the version of OAuth standard they implement, respectively 1 and 2.
The choice depends on the OAuth providers you want to work with and what versions they support. For example, Facebook supports only OAuth 2, but some older systems might support OAuth 1 only.


text:
Q: How many items can I draw without replacement so that I don't hit any bad items with certain probability? I have a set of $n$ objects, and $k$ of them are bad (but we don't know which ones until we inspect them). Our goal is to locate the $k$ bad items, and to simplify the problem, I thought about blindly discarding some items, since $k$ is typically much smaller than $n$ (i.e., say 5% of the items are bad).
To start, if we blindly remove a single item, the probability that it is safe to remove is $\dfrac{n-k}{n}$ (i.e., there are $n-k$ safe-to-remove items, and a total of $n$ items). I think I can work out the probability of the next removal being safe etc., and then taking a product of these I can derive the probability of making a number of consecutive safe removals.
More generally, I'd like to compute "how many removals can I make (say uniformly at random) so that the probability of all of them being safe is at least $p$?" The hypergeometric distribution looks relevant, but I'm not sure if it is exactly what I need. (It has been ages since I took probability, so many of the terms I see on Wikipedia are familiar, but have fallen out of my head).

A: Suppose I have $n+k$ objects of which $n$ are "normal" and $k$ are "defective." If I make $r$ random draws uniformly without replacement, then the probability that none of my $r$ draws will be defective can be calculated as follows:
$$p(r) = \frac{{n \choose r}}{ {n+k \choose r}} = \frac{\frac{n!}{r!(n-r)!}}{\frac{(n+k)!}{r!(n+k-r)!}} = \frac{n!(n+k-r)!}{(n-r)!(n+k)!}$$
Given $n$ and $k$, you can calculate $p(r)$ for $r=1, 2,\dots, n$ to determine the threshold value of $r$ below which $p(r)$ is at least as large as some desired value $\underline{p}$.