How do you find a local max/min if the funciton is not differentiable there?

Question: I was reviewing some multivariable calculus and thought of a question: we can find local extrema of a function by setting the derivative to zero, but what if at the point where the local max/min actually is, the function isn't differentiable?
For example, abs(x) or something like that.
I probably just forgot how to do this, or maybe we can't calculate the local extrema this way and have to approximate it?
Thanks for the help!
Answer: This is actually a problem even when you consider smooth functions restricted to a closed set. What you do in these situations is find the local extrema the normal way (setting the derivative to zero and solving) and then also evaluating your function at the points where it fails to be differentiable. Compare the values from all these points, and you should be able to find your min/max.
Comment: Ok , thanks. I actually just found an example in my book, which is -sqrt(x^2 + y^2) which has a local and global max at (0,0) even though the partial derivatives are undefined there. Makes sense.


How to run Esoteric Language ZOMBIE

Question: Can anyone please tell me how can I compile and run a program written on ZOMBIE? For example, if I wrote the following source cord to print out "hello world" on to the screen, how can I make an .exe file out of it. Thanks!
HelloWorld is a zombie
summon
task SayHello
  say "Hello World!"
animate
animate

Comment: It runs on BRAAAAAIIINNNNNSSSSS... ;)
Answer: There doesn't seem to be a compiler for this language. Only an interpreter written in Python exists.
However, since it is written in Python, you could change Environment.__init__ from reading a file to directly embedding your source code, then generate an exe out of it.
Answer: Since you probably use Interpreter to run the program
this language, then compiled. echo file is not likely to be done

How to run Esoteric Language ZOMBIE


Image With buttons inside

Question: I have a listview with images and i need to have buttons inside the images and a label below the image, I tried with relative and absolute layouts , but dont understand how to do it.
Have some code alredy done, but the buttons do not stay in the centered in relation with the image and before image is loaded the background stays blue.
here is a example:

What have done so far:

Code:
<Grid Padding="0">
        <ListView x:Name="CoversListview" SeparatorVisibility="None" ItemsSource="{Binding Covers}" HasUnevenRows="True">
            <ListView.ItemTemplate>
                <DataTemplate>

                    <ViewCell>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="0"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <AbsoluteLayout  x:Name="ViewLayout" BindingContext="{Binding Item1}"  Padding="10,10,0,0" >
                                <StackLayout Orientation="Vertical" BackgroundColor="#01426A">
                                    <ffimageloading:CachedImage x:Name="CoverShow" Source="test.jpg" LoadingPriority="Highest" HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="160" HeightRequest="234" Aspect="AspectFill">
                                        <ffimageloading:CachedImage.GestureRecognizers>
                                            <TapGestureRecognizer Tapped="TapGestureRecognizer_OnTapped">
                                            </TapGestureRecognizer>
                                        </ffimageloading:CachedImage.GestureRecognizers>
                                    </ffimageloading:CachedImage>

                                </StackLayout>
                                <AbsoluteLayout x:Name="ViewControls" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All">
                                    <StackLayout  Orientation="Vertical" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="1,1,1,1">
                                        <Grid>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="110" />
                                            </Grid.ColumnDefinitions>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="36" />
                                                <RowDefinition Height="36" />
                                            </Grid.RowDefinitions>
                                            <customRenders:MyButton x:Name="ShowButtonFrame"  BackgroundColor="#C8DBEF" TextColor="#01426A" ConfigurationItem ="{Binding .}"  Grid.Row="1" Text="Show"  CornerRadius="16" FontSize="12" BorderWidth="0" Clicked="Button_OnClicked_ShowItem1"/>
                                            <customRenders:MyButton x:Name="DownButtonFrame"  BackgroundColor="#C8DBEF" TextColor="#01426A" ConfigurationItem ="{Binding .}"  Grid.Row="0"  Text="Download"  CornerRadius="16" FontSize="12"  BorderWidth="0" Clicked="Button_OnClicked_DownItem1"/>
                                        </Grid>
                                    </StackLayout>
                                </AbsoluteLayout>
                            </AbsoluteLayout>

                            <AbsoluteLayout  x:Name="FrameItem" Grid.Column="2" IsVisible="{Binding IsVisible}" BindingContext="{Binding Item2}" Padding="0,10,0,0"  >
                                <StackLayout Orientation="Vertical" BackgroundColor="#01426A">
                                    <ffimageloading:CachedImage x:Name="CoverShow2" Source="test.jpg" LoadingPriority="Highest" HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="160" HeightRequest="234" Aspect="AspectFill">
                                        <ffimageloading:CachedImage.GestureRecognizers>
                                            <TapGestureRecognizer Tapped="TapGestureRecognizer_OnTapped">
                                            </TapGestureRecognizer>
                                        </ffimageloading:CachedImage.GestureRecognizers>
                                    </ffimageloading:CachedImage>

                                </StackLayout>
                                <AbsoluteLayout x:Name="ViewControls2" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All">
                                    <StackLayout  Orientation="Vertical" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="1,1,1,1">
                                        <Grid>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="110" />
                                            </Grid.ColumnDefinitions>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="36" />
                                                <RowDefinition Height="36" />
                                            </Grid.RowDefinitions>
                                            <customRenders:MyButton x:Name="ShowButtonFrame3"  BackgroundColor="#C8DBEF" TextColor="#01426A" ConfigurationItem ="{Binding .}" Grid.Row="1" Text="Show" VerticalOptions="Center" CornerRadius="16" FontSize="10" BorderWidth="0" Clicked="Button_OnClicked_ShowItem2"/>
                                            <customRenders:MyButton x:Name="DownButtonFrame3"  BackgroundColor="#C8DBEF" TextColor="#01426A" ConfigurationItem ="{Binding .}" Grid.Row="0"  Text="Download"  CornerRadius="16" FontSize="10" HeightRequest="34" BorderWidth="0" Clicked="Button_OnClicked_DownItem2"/>
                                        </Grid>
                                    </StackLayout>
                                </AbsoluteLayout>

                            </AbsoluteLayout>
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>

Comment: First show us what you have tried so far.
Comment: Can Stackoverflow team open this Question please?
Answer: You should add the TapGestureRecognizer on an Image and attach a Command to it, as given below:
<Grid>
    <Image Source="myImage.png">
        <Image.GestureRecognizers>
            <TapGestureRecognizer
                Command="{Binding ImageTapCommand}"
                CommandParameter="Id or ImageName or any Parameter goes here" />
        </Image.GestureRecognizers>
    </Image>
    <Button Text="MyButton" IsVisible="{Binding ButtonVisibility, Mode=TwoWay}"  HorizontalOptions="Center" VerticalOptions="Center" />
</Grid>

In Your ViewModel or Model:
private bool _buttonVisibility;
public bool ButtonVisibility
{
    get { return _buttonVisibility; }
    set { _buttonVisibility = value; OnPropertyChanged(nameof(ButtonVisibility)); }
}

private Command<string> _ImageTapCommand;
public Command<string> ImageTapCommand
{
    get
    {
        return _ImageTapCommand ?? (_ImageTapCommand = new Command<string>((str) => ImageTapCommandExecute(str)));
    }
}

void ImageTapCommandExecute(string str)
{
    //Here str is whatever you passed with CommandParameter.
    //When your Image is tapped, button gets visible
    ButtonVisibility = true;
}

This is just a rough code I provided to you for what you want to achieve. May this help you.

Image With buttons inside


SQL Function to Search in String Values

Question: I would like to create function on sql server to check in string values .
pass to two parameters first original  '126.96.36.199.22' , second  '44.22' and return
true if parameter2 is found in original parameter
ex :
call fun1('126.96.36.199' , '23.24')  -- return false
call fun1('22.214.171.124' , '23.24') -- return false
call fun1('220.127.116.11.43.76' , '22.12') -- return false , because should be both exists
call fun1('220.127.116.11' , '22.56') -- return true
call fun1('22.214.171.124' , '21.56') -- return true
call fun1('22.214.171.124' , '34.56') -- return true
call fun1('188.8.131.52' , '34.55.35') -- return false

Thanks.
Comment: call fun1('184.108.40.206' , '23.24')  -- return false
call fun1('188.8.131.52.43.76' , '22.12')  -- return  false , because should be both exists
call fun1('184.108.40.206' , '22.56')  -- return  true
call fun1('220.127.116.11' , '21.56')  -- return true
call fun1('18.104.22.168' , '34.56')  -- return true
call fun1('126.96.36.199' , '34.55.35')  -- return false
Comment: Which version of SQL Server?
Comment: sql server 2008
Comment: Welcome as a new user to SO. Please take the [Tour](http://stackoverflow.com/tour) and also read [Help-Center/asking](http://stackoverflow.com/help/on-topic). Instead of using comments for code you should edit your question to enhance the information.
Answer: Based on the updated question, this isn't the answer. You're looking to confirm that all values in string of delimited values exists in another string of delimited values, in this case the delimiter is '.'
select
  case when charindex('44.22','184.108.40.206.22')>0 then 'true'
    else 'false'
    end

Update: if the search string is always in that format, this will work:
create function dbo.func1 (@StringToFind nvarchar(128), @StringToSearch nvarchar(128))
returns nvarchar(5) as
begin
  return case
          when charindex(left(@StringToFind,charindex('.',@StringToFind)-1),@StringToSearch)>0
           and charindex(right(@StringToFind,charindex('.',reverse(@StringToFind))-1),@StringToSearch)>0
          then 'true'
          else 'false'
          end;
end
go

select dbo.func1('44.22','18.104.22.168.22')

Comment: @Bas fair enough but you didn't state this in the original question. You should edit that and provide more details, like are their any limitations to the second expression? Can it be 188.8.131.5299.23 etc....
Comment: in this case should be return true because 44.22 is already exitis in (220.127.116.11.22)
Comment: if i pass one parameter  like select dbo.func1('44','126.96.36.199.22')
I have error
Comment: both parameter is dynamic
Comment: this was assuming the search strings would always be that format 'xx.xx', 'xx.xx.xx....' for something more dynamic you can adapt and use @Shnugo's answer
Answer: Declare @YourTable table (TheString varchar(100), FindString varchar(100));
Insert Into @YourTable values
 ('184.108.40.206','23.24')       -- return false
,('188.8.131.52.43.76','22.12') -- return false , because should be both exists
,('22.214.171.124','22.56')       -- return true
,('188.8.131.52','21.56')       -- return true
,('126.96.36.199','34.56')       -- return true
,('126.96.36.199','34.55.35');

Select *
      ,InString = [dbo].[udf_InString](TheString,FindString)
From @YourTable

Returns
TheString           FindString  InString
126.96.36.199         23.24       false
184.108.40.206.43.76   22.12       false
184.108.40.206         22.56       true
184.108.40.206         21.56       true
188.8.131.52         34.56       true
184.108.40.206         34.55.35    false

The UDF
CREATE FUNCTION [dbo].[udf_InString](@String varchar(max),@Search varchar(max))
Returns varchar(25)
Begin
    Declare @RetVal varchar(25)
    ;with cte as (
        Select RetSeq = Row_Number() over (Order By (Select null))
              ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
        From (Select x = Cast('<x>'+ Replace(@String,'.','</x><x>')+'</x>' as xml).query('.')) as A
        Cross Apply x.nodes('x') AS B(i)
    )
    Select @RetVal = case when count(*)>0 then 'true' else 'false' end
     From  cte A
     Join  cte B on (A.RetSeq+1=B.RetSeq or A.RetSeq+2=B.RetSeq)
     Where A.RetVal+'.'+B.RetVal = @Search
    Return @RetVal
End

Answer: You might try it like this:
I use an XML-trick first to split both delimited strings into their parts (get a derived table). An INNER JOIN reduces them to the parts included in both sides. The rest is counting: If the count of common elements equals the total count on side 2, all elements are common:
Attention: Any row, where no common elements exist, is ommitted. You might use a LEFT JOIN against a DISTINCT list of all existing IDs to inlcude rows without value crossings...
It should be easy to create a function from this. Just hand in the two strings as parameters and replace TheString and CheckString with them (and delete FROM @dummyTbl). In this case an empty result is false.
DECLARE @dummyTbl TABLE(ID INT IDENTITY,TheString VARCHAR(100), CheckString VARCHAR(100));
INSERT INTO @dummyTbl VALUES
 ('126.96.36.199','23.24')  -- return false
,('184.108.40.206.43.76','22.12') -- return false , because should be both exists
,('18.104.22.168','22.56') -- return true
,('188.8.131.52','21.56') -- return true
,('126.96.36.199','34.56') -- return true
,('18.104.22.168','34.55.35');

WITH casted AS
(
    SELECT ID
          ,CAST('<x>' + REPLACE(TheString,'.','</x><x>') + '</x>' AS XML) AS s1
          ,CAST('<x>' + REPLACE(CheckString,'.','</x><x>') + '</x>' AS XML) AS s2
    FROM @dummyTbl
)
,s1Tbl AS
(
    SELECT ID,x.value('.','int') Val
    FROM casted
    CROSS APPLY s1.nodes('/x') AS A(x)
)
,s2Tbl AS
(
    SELECT ID,x.value('.','int') Val
    FROM casted
    CROSS APPLY s2.nodes('/x') AS A(x)
)
SELECT s1Tbl.ID
      ,CASE WHEN COUNT(s1Tbl.ID)=(SELECT COUNT(x.ID) FROM s2Tbl AS x WHERE x.ID=s1Tbl.ID) THEN 'true' else 'false' END AS FullyIncluded
FROM s1Tbl
INNER JOIN s2Tbl ON s1Tbl.Val=s2Tbl.Val AND s1Tbl.ID=s2Tbl.ID
GROUP BY s1Tbl.ID

Answer: Here is a function that uses XML to spit the strings and an anti-join to see if everything matches.  Then you can simply call it as a cross apply like below.
CREATE FUNCTION dbo.FindStringsInString(
    @String VARCHAR(MAX)
    ,@SearchString VARCHAR(MAX)
)
RETURNS BIt
AS
BEGIN
    IF (COALESCE(LEN(@String),0) = 0 OR COALESCE(LEN(@SearchString),0) = 0)
    BEGIN
       --either the String or the SearchString is Null or Empty
       RETURN 0
    END

    DECLARE @XMLString XML = CAST('<X>' + REPLACE(@String,'.','</X><X>') + '</X>' AS XML)
    DECLARE @XMLSearchString XML = CAST('<X>' + REPLACE(@SearchString,'.','</X><X>') + '</X>' AS XML)

    IF NOT EXISTS (
       SELECT 1
       FROM
          (
          SELECT
             n.value('.', 'varchar(MAX)') as S
          FROM
             @XMLSearchString.nodes('X') as t(n)) searchstring
          LEFT JOIN (
          SELECT
             n.value('.', 'varchar(MAX)') as S
          FROM
             @XMLString.nodes('X') as t(n)) string
          ON searchstring.S = string.S
       WHERE
          string.S IS NULL
    )
    BEGIN
       --All of the values in the Search StringMatch a Value in the String
       RETURN 1
    END

    --default if it hasn't returned by now it is false
    RETURN 0

END
GO

Test Data, I added NULL and '' cases and Select from function:
DECLARE @Table AS TABLE (String VARCHAR(100), SearchString VARCHAR(100))
INSERT INTO @Table VALUES
('18.104.22.168' , '23.24')  -- return false
,('22.214.171.124' , '23.24') -- return false
,('188.8.131.52.43.76' , '22.12') -- return false , because should be both exists
,('184.108.40.206' , '22.56') -- return true
,('184.108.40.206' , '21.56') -- return true
,('220.127.116.11' , '34.56') -- return true
,('184.108.40.206' , '34.55.35') -- return false
,('126.96.36.199' , NULL) -- return false
,('184.108.40.206' , '') -- return false
,(NULL , '34.55.35') -- return false
,('' , '34.55.35') -- return false

SELECT *
FROM
    @Table t
    CROSS APPLY (SELECT
       dbo.FindStringsInString(t.String, t.SearchString)) s(Match)

SQL Function to Search in String Values


How would this nonchord tone be labeled? Is it a retardation?

Question:
I'm working on an analysis of a song, and there is a section where the phrase starts off on this E-natural note over a B-flat major triad. This is the first note of the melody line.
Since it isn't approached by anything, would it make sense to call this a 4-5 retardation? Is it better to call it a free tone?
I know nonchord tone criteria doesn't always work, but I wanted to see if there is a good way to label this note. Thanks in advance!
Comment: Looks to me like a blue note - flat 5. So, a chromatic approach to the P5. Retardation is usually what is called sus2.
Answer: It's an accented lower neighbor.


Markov Model for gating probabilities

Question: A Markov model is used to describe the stochastic gating of particles through channels. A channel is permeable exactly when four gates are open in it - this can be represented by the following Markov diagram.
$$n_0 \overset{4 \alpha}{\underset{\beta}{\rightleftharpoons}} n_1 \overset{3 \alpha}{\underset{2 \beta}{\rightleftharpoons}} n_2 \overset{2 \alpha}{\underset{3 \beta}{\rightleftharpoons}} n_3 \overset{ \alpha}{\underset{4 \beta}{\rightleftharpoons}} n_4 $$
where $\alpha, \beta$ are transition rates.
and NOW: I read the following:" Exact or Markov methods model
channel noise as continuous time Markov processes to iterate
through the transition-probability matrix of state change to
infer the exact number of ion channels opened during each
time step"
let us consider we are at time $t$ - how can i calculate the population of open channels at $t + \delta t$ .. i do not really understand the description above.
Answer: Let $X(t)$ be the number of open channels at time $t$ i.e. $X(t)=i$ when the processs is in state $n_i$ at time $t$. Then $\{X(t):t\geqslant 0\}$ is a continuous-time Markov chain with infinitesimal generator
$$
Q = \left(
\begin{array}{ccccc}
 -4 \alpha  & 4 \alpha  & 0 & 0 & 0 \\
 \beta  & -3 \alpha -\beta  & 3 \alpha  & 0 & 0 \\
 0 & 2 \beta  & -2 (\alpha +\beta ) & 2 \alpha  & 0 \\
 0 & 0 & 3 \beta  & -\alpha -3 \beta  & \alpha  \\
 0 & 0 & 0 & 4 \beta  & -4 \beta  \\
\end{array}
\right).
$$
The non-diagonal entries of $Q$ denote the "rate" at which the process is moving its current state to a different state; more precisely, conditioned on $\{X(t)=i\}$, the    time to the next transition
$$
\inf\{s>t:X(s)\ne X(t)\}-t
$$
is exponentially distributed with intensity
$$
\sum_{j=0}^4 Q_{ij}\cdot\mathsf 1_{\{Q_{ij}>0\}}.
$$
(This follows from the minimum of finitely many independent exponential random variables having intensity the sum of said intensities.)  Given some initial distribution $\gamma$ of $X(0)$, the sequence of states $\{T_n: n=0,1,2,\ldots\}$ the process visits defines an embedded discrete-time Markov chain $\{Y_n: n=0,1,2,\ldots\}$, with probability transistion matrix
$$
R = \left(
\begin{array}{ccccc}
 0 & 1 & 0 & 0 & 0 \\
 \frac{\beta }{3 \alpha +\beta } & 0 & \frac{3 \alpha }{3 \alpha +\beta } & 0 & 0 \\
 0 & \frac{\beta }{\alpha +\beta } & 0 & \frac{\alpha }{\alpha +\beta } & 0 \\
 0 & 0 & \frac{3 \beta }{\alpha +3 \beta } & 0 & \frac{\alpha }{\alpha +3 \beta } \\
 0 & 0 & 0 & 1 & 0 \\
\end{array}
\right).
$$
(Recall that if $\{Z_i : i \in\{1,\ldots,n\}$ is a finite collection of independent exponentially distributed random variables with respective intensities $\lambda_i$, for each $i$ the probability of $\left\{\bigwedge_{j=1}^n Z_j=Z_i\right\} = \frac{\lambda_i}{\sum_{j=1}^n\lambda_j}$.
For each $t>0$, there is similarly a transition matrix $P(t)$ where $P(t)_{ij} = \mathbb P(X(t)=j\mid X(0)=i\}$. These matrices satisfy the backward Kolmogorov differential equations $P'(t) = QP(t)$ with initial condition $P(0)=I$ (the identity matrix), which has the unique solution $e^{Qt}$ where
$$
e^{Qt} := \sum_{n=0}^\infty \frac{(Qt)^n}{n!}.
$$
The rows of $Q$ sum to zero, and hence for any $t>0$ and nonnegative integer $n$ we have $$\max_i\left\{\sum_j \left|\left(I - \frac{Qt}n \right)^n_{ij}\right| \right\}<1.$$ It follows then that the matrix exponential $e^{Qt}$ converges for any $t$, and so we may compute the derivative of $Q(t)$ term-by-term:
$$
Q'(t) = \frac{\mathsf d}{\mathsf dt} \left[\sum_{n=0}^\infty \frac{(Qt)^n}{n!}\right]\\
=\sum_{n=0}^\infty \frac{\mathsf d}{\mathsf dt} \left[\frac{(Qt)^n}{n!}\right]  = Qe^{tQ},
$$
thus verifying that $Q'(t)=QP(t)$.
Comment: Thank you! this is a fantastic answer!

Markov Model for gating probabilities


Solving recurrence relation with 2 variables

Question: If I have a recurrence relation like $$T(n,k)=\frac{T(n-1,k)+T(n,k-1)}{2}$$ with initial values $\forall n \quad T(n,0)=T_0$ and $\forall k \quad T(0,k)=0$. How can I solve it? By the way this came up when I was solving a physics problem
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: @JeanMarie's answer points out we also need $T_{0,\,p}$ for $p>0$. My guess is you want these to be $0$. But whether I'm right or not, your question should address this boundary too.
Comment: $T_{0,p}$ is $0$ @J.G.
Comment: @spitfire In that case, you might want to work out a recursion relation in a sequence $p_n$ of polynomial functions of $k$ satisfying $T(n,\,k)=T_0p_n(k)/2^{n+k-1}$.
Comment: @J.G. but what is $p_n$? Polynomial functions of $k$? Sorry but I didn't get what are these. I'm not a mathematician I'm a physicist
Comment: @JoséCarlosSantos I edited my question and there's no doubts  I think
Comment: @spitfire:  Here's a different approach...  There's a simple book that explains a lot about these types of recurrence relations called "generatingfunctionology".  You can get a free copy of the book at https://www.math.upenn.edu/~wilf/DownldGF.html  In particular, check out section 1.4, which expains two-term functions.  I hope that this may help.
Comment: Follow approach from here https://math.stackexchange.com/questions/2065067/solving-two-dimensional-recurrence-relation-a-i-j-a-i-j-1-a-i/2065193#2065193. Also warning, you will need to get your definitions straight. As currently written, it is unclear what is $T(0,0)$, is it $T_0$ or $0$?
Answer: Here is a graphical representation of your recurrence relationship :

(which, now that you have settled correctly your initial data, isn't compulsory, but is interesting by itself because it shows its similarity with the ¨Pascal's triangle" (see below).
Some numerical computations on the first values of $T_{n,k}$ in the case of $T_0=1$ give the following first numerical results with denominators $2^{n+k-1}$.
(please note the diagonal values equal to $1/2$) :

Out of this array, we can build a simplified one by turning it $135°$clockwise in the "Pascal's triangle' manner and keeping only the numerators where the right diagonal, instead of being filled by "ones", is filled by successive powers of $2$ :
$$\begin{array}{ccccccccc}
&&&&&1&&&&\\
&&&&\color{blue}{1}&&\color{red}{2}&&&&&\\
&&&\color{blue}{1}&&3&&\color{red}{4}&&&&&&&&\\
&&\color{blue}{1}&&4&&7&&\color{red}{8}&&&\\
&\color{blue}{1}&&5&&11&&15&&\color{red}{16}&&&\\
\color{blue}{1}&&6&&16&&26&&31&&\color{red}{32}
\end{array}\tag{1}$$
We have simplified the problem because in this way only integers are managed, and (thanks to an indication by the OP) this is known in the litterature under the name "Bernoulli triangle" yielding the explicit formula for the coefficients in the previous "Pascal's like" array (1) (it is why we write $T'$ instead of $T$):
$$\displaystyle T'_{n,k}=\frac{1}{2^{n}}\sum _{p=0}^{k}{\binom {n}{p}} \ \ \text{for} \ \ k=0,1,\cdots n$$
Comment: And all the $T(n,0)$ is not equal to $0$ it's equal to $T_0$
Comment: I find solution to this problem : https://cdn.discordapp.com/attachments/719928959256625232/724081817828851758/potd_193.pdf
Comment: I'm sorry for not writing it in my question @Jean Marie
Comment: I'm sorry but this wasn't clear to me. So why do we need that graphical represantation? how can we solve  the recurrence relation?
Comment: I get what you wrote there, but how can I find $T_{n,k}$ in terms of  $n$,$k$,$T_0$.I've searched about wave propagation with damping but i didn't find anything. So can you explain more? by the way what you mean numerical value for $T_{0,q}$ they are all zeros
Comment: I have improved the approach by reducing the issue to a pure integer question (In the case $T_0=1$). But I still doubt there is a closed form expression for the general term.
Comment: Therfore the keyword for what I had found is "Bernoulli triangle", with a formula for $T_{n,k}$ that still contains a "\Sigma"..


Centered div all the time

Question: I have something like this:

.center_position_div{
    width:100%;
    background-color:green;
    display: flex;
    flex-wrap: wrap;
}

.show_running_exam
{
    width: 22%;
    background-color:aliceblue;
    margin-left: 1%;
    margin-right: 1%;
    margin-bottom: 5px;
    margin-top: 6px;
    overflow: hidden;
}

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

How can I center divs on the middle parent div? I assume that in the parent div can exist many divs. I could use "padding-left" in parent div, but this is not a universal solution. I tried use "marging: 0 auto;" - still not working. What can I do?
Answer: I believe you're looking to set the content justification. Applying justify-content: center; to the parent container should do the trick.

.center_position_div {
  width: 100%;
  background-color: green;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.show_running_exam {
  width: 22%;
  background-color: aliceblue;
  margin-left: 1%;
  margin-right: 1%;
  margin-bottom: 5px;
  margin-top: 6px;
  overflow: hidden;
}

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd sfdsfdsfsdfd sfdsfsd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

Comment: Ohh thanks! Its working. I'm going to remember there is exist something like   justify-content.
Answer: Is this what you were looking for?

.center_position_div{
        width:100%;
        background-color:green;
        display: flex;
        flex-wrap: wrap;
        flex-direction: column;
        align-items: center;
    }

    .show_running_exam
    {
        width: 22%;
        background-color:aliceblue;
        margin-left: 1%;
        margin-right: 1%;
        margin-bottom: 5px;
        margin-top: 6px;
        overflow: hidden;
    }

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

saddsdsadsdsdf dsfsdfd sfdsfdsfsdfd sfdsfsd

Comment: I've tested this solution, but not working. But I deleted flex-direction: column; and this gives me a good result.

Centered div all the time


Static member functions not acting as expected

Question: I have the following code that is not compiling as expected.  I have a class which has a static member function, and another class which includes its header trying to use it.  It does not seem to be working.
static bool validLocation(int _x) // within class A
{
    return false;
};

Class B includes class A, and has the following call in one of its functions:
if (!(A::validLocation(180)))
    continue;

Obviously these are simplified for reading purposes, but why is this not acceptable?
Sorry for the vagueness.  As for the error message:
  "A::validLocation(int)", referenced from: B::functionThatCallsThis() in B.o

Symbols not found.
Collect2: ld returned 1 exit status

The static function is public, as declared in the header file.
Comment: What's missing is the compiler error message ;)
Comment: Wow, thanks for that.  Half asleep.  I will update
Comment: have you tried escaping from all namespaces (leading `::`) and then qualifying the namespace of your classes explicitly? Perhaps `class B` sees A, but not the right one?! To rule that out you could make B a `friend` of A temporarily (then we're sure it's not about hidden member functions or so).
Comment: When you say "within class A" do you mean it's totally inside the header file?
Answer: From the error message you gave, I'm going to assume you aren't linking the objects together or you declared validLocation() as a free function since I don't see a A:: before its definition.  Hard to tell given the amount of information here.
Edit:
Now the error message is a bit more clear, and it looks like you aren't including the correct object files to the linker.
Answer: EDIT: Did you remember to link both A.o and B.o together to create your binary? It sounds like A.o isn't getting included and the compiler didn't inline the static function.
Also you have a ; at the end of your function that's definitely not needed and may be invalid (I can't recall)
Comment: Nope.  It's definitely public.  Strange.  Sorry, I just realized how vague the rest of my message was though.  I'll clear it up
Comment: The stray semicolon is not invalid. It's simply an empty expression. Tools like PCLINT will point it out, though.
Comment: If that function is indeed defined inside class A, it must be implicitly inlined, right? No need to include the object file then. No need for that object file to even exist.
Answer: when you define your function validLocation(), are you defining in a separate file, .cpp perhaps? If so, you need to put A:: before the function name, like so:
static bool A::validLocation(int _x) // within class A
{
    return false;
};


How can you cause a combobox to loose focus?

Question: I am developing a windows forms project in vb.net. I have added a comboBox to my form. the form automatically focuses on the comboBox. Nothing I click on causes the comboBox to loose focus. I do not want the form to focus on the comboBox because I do not want users to change the selected text in the comboBox by accidentally moving the scroll wheel.
I have tried:
comboBox1.CanFocus = False
comboBox1.Focus = false

These properties are not write-able.
InvokeLostFocus(ComboBox1, New EventArgs)

This does not throw a compiler error but it does not seem to do anything either (focus stays).
I am really stuck and can not find anything on SE or google. Any help is much appreciated.
Thanks!
Answer: You need to focus another control. Note that the form itself cannot be focused.
Something like:
label1.Focus()

If this doesn't work for you, you can try this:
Private Sub Form1_Load(sender As Object, e As EventArgs)
    Me.ActiveControl = label1;
End Sub

You can even try to disable and enable the ComboBox.
Comment: Thanks! the second option works perfect. The focus on the combobox is lost. I tried to vote up but I do not have enough rep :(
Comment: I tried that and it does not work. I am not sure if labels can be focused on or not so I also tried: TextBox1.Focus(). This does not work either.


Montar uma unica string com varias strings de uma ArrayList em Java

Question: Como posso pegar de forma simplificada várias Strings de uma ArrayList e unir em apenas uma váriavel do tipo String? Sou novo no Java e estou com dificuldade para concluir essa alteração de forma simplificada, evitando linhas de códigos longos e sem necessidade.
 List<String> fields_list = new ArrayList<String>();

 Saída: ["Campo1, Campo2, Campo3"]

Deverá ficar dessa forma a minha variável do tipo String:
String fields = "Campo1 Campo2 Campo3";

Answer: Use o método join() da classe String:
String fields = String.join(" ", fields_list);

Nota: Necessita JAVA 8
Comment: Se ele estiver usando java 8 tudo bem. Caso contrário não vai funcionar. Você poderia incluir este detalhe na sua resposta :)
Comment: @EdgarMunizBerlinck Sim, estava agora a editar para colocar link para a documentação. Vou no entanto deixar isso mais claro.
Comment: Não estava usando Java 8 Support, acabei de implementar no meu Eclipse: http://download.eclipse.org/eclipse/updates/4.3-P-builds/.
Comment: @ramaral quer incorporar minha resposta na sua e eu apago?
Comment: @MaiconCarraro Apagar porquê? A sua resposta é válida(votei nela), acho que deve mantê-la.
Comment: @ramaral Porque o autor já marcou a sua como correta, então se você incorpora a minha na sua fica uma resposta válida pra qualquer pessoa com o mesmo problema :)
Comment: @MaiconCarraro O AP marcou a minha como a resposta aceite, a que melhor servia para ele, não quer dizer com isso que só ela está correcta ou que é a melhor. Outra pessoa que não esteja a usar JAVA 8 irá ler a sua resposta e será a sua que lhe servirá e por certo votará nela. Se eu incorporar a sua resposta na minha passarei eu a receber todos os créditos o que não seria justo. O que melhor indica se uma resposta é boa ou não é o número de votos que recebeu e não a marca de aceite.
Answer: Utilize um StringBuilder para agrupar seus valores e o for para iterar sobre a lista, exemplo:
StringBuilder sb = new StringBuilder();
for (String s : fields_list)
{
    sb.append(s);
    sb.append(" ");
}

System.out.println(sb.toString().trim());

Não concatene as strings dessa forma s1 + s2
Desse jeito pra cada concatenada o compilador gera uma nova instância do StringBuilder de forma implícita, então a melhor maneira é utilizando apenas 1 conforme o exemplo.
Answer: Ou você pode fazer um loop:
String listString;
for (String s : list)
{
    listString += s + " ";
}

Ou você pode usar o StringUtils, que fica no commons-lag
listString = StringUtils.join(list, " ");

Comment: Em concatenaçõs dentro de loops deve-se usar StringBuilder ou StringBuffer


Calculating the 'deviance' in an Analysis of Deviance table for generalized linear models

Question: The issue concerns question 3(b) of this paper.
Specifically, I am trying to fill in the missing values for the 'Deviance' column of the ANOVA table. Using R, I find the missing corresponding to 'Day' to be 0.2733. However, when I try to verify this by direct calculation with
$$2[\ell_{\mathrm{proposed}}-\ell_{\mathrm{null}}]=2\left[\sum_{i,j,k}n_{ijk}Y_{ijk}\alpha_{i}+n_{ijk}\log\left(\frac{1+\exp(\mu)}{1+\exp(\mu+\alpha_i)}\right)\right]$$
Note that here I've assumed the model $n_{ijk}Y_{ijk}\sim B(n_{ijk},p_{ijk})$ where $\mathrm{logit} p_{ijk} = \mu + \alpha_i$ for day $i=1,2,3$, species $j = 1,2,3$ and observation $k = 1,\ldots, K_{ij}$. I cannot seem to obtain the correct answer when observations from the table are plugged into the above (also, here $n_{ijk}$ denotes values from the  'total' columns). Could someone please give a model solution to this question?
Answer: I don't know if this is considered an acceptable answer or not, but the lazy way to solve this exam question is to note this line in the summary() output:
Null deviance: 33.631 on 22 degrees of freedom

and these lines in the deviance table:
      Df Deviance Resid. Df Resid. Dev P(>|Chi|)
NULL
Day   xx xx       20        33.358     0.8723

Since the null deviance is 33.631 and the residual deviance (Resid Dev) is 33.358, the difference in deviance between the null model and the model with Day  only (which is what's listed in the Deviance column) is 33.631-33.358 = 0.273.
You can get the difference in degrees of freedom (Df) similarly (null [22] - residual [20] = 2), or by explaining that Day is a categorical predictor with 3 levels and thus requires 3-1 = 2 additional parameters over the null (intercept-only) model.
Comment: Thank you! I had a feeling I was overthinking it. I'd worked out everything else in a similar fashion to this and completely overlooked the null deviance!


If $f(x) = x$ if $x \in \mathbb{Q}$ and $f(x) = 0$ otherwise, is $f$ Riemann integrable?

Question:
Let $f$ be defined as:
$$
f(x) = \begin{cases}
  x & \text{ if } x\in\mathbb{Q}; \\\\
  0 & \text{ if }x\notin\mathbb{Q}. \end{cases}
$$
  Is $f$ Riemann integrable on $[0,1]$? Prove it.

We know that the upper sum $U = x$ and lower sum $L=0$.
Since $\lim U\neq \lim L$, $f(x)$ is not Riemann integrable.
Is this sufficient for the proof?
Comment: What does it mean that the upper sum is $x?$ Which is the partition?
Answer: Start from the basic. Divide the interval [0,1] into $n$ sub-intervals, each of length $\frac{1}{n}$, i.e. $[0,\frac{1}{n}], [\frac{1}{n}, \frac{2}{n}], \cdots, [\frac{n-1}{n}, 1]$, Note that, at each sub-interval of the form $[\frac{i}{n}, \frac{i+1}{n}]$, maximum value of the function = $\frac{i+1}{n}$ and minimum value is 0, as each sub-interval has at-least one rational and one irrational number. Then show that Lower integral converges to 0, but upper integral does not which will show that the function is not Riemann Integrable.


How can I tell which filesystem Worklight's  is referring to?

Question: We are using Worklight's automated  ANT task to deploy a Worklight application. Unfortunately, it's currently failing with this error message:
BUILD FAILED
/deployment/jenkins/jobs/UAT-uat2-Deploy/workspace/co.uk.homebase.strategic-app/Homebase/ciBuild/buildAndDeployAnt.xml:171: The following error occurred while executing this line:
/deployment/jenkins/jobs/UAT-uat2-Deploy/workspace/co.uk.homebase.strategic-app/Homebase/ciBuild/buildAndDeployAnt.xml:186: app-deployer failed:SEVERE:Bad Request; Error 400: java.lang.RuntimeException: java.io.IOException: There is not enough space in the file system.

Unfortunately, the error message isn't precise about which filesystem is out of space. On this system, there are several filesystem which might be relevant, including /tmp, the Liberty server install filesystem (our Worklight server is running on WebSphere Liberty), and a separate filesystem for the Worklight logs.
Is there any way we can discover which filesystem is being referred to? None of them appear to be significantly low on space, although the /tmp filesystem is quite small, so that's my suspicion. If that's the case, is there a way to configure  to use a different filesystem for temporary files?
Comment: Setting a different temp folder in your operating system does not sound like something Worklight (nor ANT) needs to handle...
Comment: @IdanAdar, I agree. Do you know which filesystem it's referring to though? The system we are running the ANT task on? The one we are deploying to?
Answer: In our case, we discovered that the filesystem that was out-of-space was on the target system where we were trying to deploy a .wlapp file. Doubling the size of /tmp (this was an AIX box) fixed the issue.


Comando para criar varias colunas em um data.frame condicionado a outras 2 colunas

Question: Se tenho um data.frame formado pelos vetores:
V1<-c("A","B","C","D","B")
V2<-c("C","D","C","B","B")
V3<-c("D","D","C","A","A")
V4<-c("C","B","C","A","C")
G1<-c("C","C","A","A","B")
G2<-c("D","B","D","C","A")
G3<-c("A","B","B","C","A")
G4<-c("C","C","B","A","D")

dd<-data.frame(V1,V2,V3,V4,G1,G2,G3,G4)

 V1 V2 V3 V4 G1 G2 G3 G4
  A  B  B  A  A  D  B  C
  B  C  A  C  B  C  A  C
  B  D  D  C  D  A  D  D
  C  C  B  C  D  A  D  C
  C  B  C  D  B  B  C  A

Queria criar 4 novas colunas com nomes R1,R2,R3,R4 que vejam se V1=G1, V2=G2 e assim sucessivamente, e levem a informação 1 para verdadeiro e 0 para falso
Tinha conseguido assim, mas queria um comando para fazer todos de uma só vez.
dd$R1<-ifelse(dd$V1 == dd$G1, 1,0)

Tentei usar for mas não estava funcionando.
Answer: Uma solução R base.
# primeiro determinar as colunas "V" com
# os mesmos números das colunas "G"
v <- grep("^V", names(dd))
g <- match(sub("^V", "", names(dd)[v]), sub("^G", "", names(dd)))

# agora quais têm valores iguais
# +(...) transforma valores lógicos em 0/1
R <- +(dd[v] == dd[g])

# e juntar tudo
colnames(R) <- paste0("R", v)
dd2 <- cbind(dd, R)
dd2
#  V1 V2 V3 V4 G1 G2 G3 G4 R1 R2 R3 R4
#1  A  C  D  C  C  D  A  C  0  0  0  1
#2  B  D  D  B  C  B  B  C  0  0  0  0
#3  C  C  C  C  A  D  B  B  0  0  0  0
#4  D  B  A  A  A  C  C  A  0  0  0  1
#5  B  B  A  C  B  A  A  D  1  0  1  0

Answer: Pode fazer a comparação diretamente entre o conjunto de colunas "G*" e "V*":
dd[grep("V", names(dd))] == dd[grep("G", names(dd))]
#>         V1    V2    V3    V4
#> [1,] FALSE FALSE FALSE  TRUE
#> [2,] FALSE FALSE FALSE FALSE
#> [3,] FALSE FALSE FALSE FALSE
#> [4,] FALSE FALSE FALSE  TRUE
#> [5,]  TRUE FALSE  TRUE FALSE

Como o R codifica VERDADEIRO como 1 e FALSO como 0, para ter o resultado como números pode aplicar as.integer às colunas:
apply(dd[grep("V", names(dd))] == dd[grep("G", names(dd))], 2, as.integer)
#>      V1 V2 V3 V4
#> [1,]  0  0  0  1
#> [2,]  0  0  0  0
#> [3,]  0  0  0  0
#> [4,]  0  0  0  1
#> [5,]  1  0  1  0

Ou, se preferir usar ifelse:
ifelse(dd[grep("V", names(dd))] == dd[grep("G", names(dd))], 1,0)

Note que assume-se que as colunas estejam na ordem correta (1, 2, 3,...). Se não estiverem, ordene-as primeiro:
dd <- dd[sort(names(dd))]


mail relay from web application / tool

Question: What is the best way to send mail notification from web application?
I have domain that uses google apps for the mail service.
I want my application to be able to send mail to the users and I tried to use SmtpClient of asp.net to perform the job.
Google block my sender user since i'm sending more than 50 mails.
What is the best way to perform this task? should i install my own mail server? does google offer such service?
Thanks,
Lior
Answer: Upgrade to Google Apps for Business and you'll have a higher per day quota. :)
Also, there's a class of applications known as email delivery services.  They take care of emailing for you, so you don't have to run a mail server as part of your development.  I recommend SendGrid.
Answer:
What is the best way to send mail notification from web application?

There are four options, only one of which is very good (in my opinion) ;)

depricated option Set SPF records on your webservers IP address and send mails directly from there. Thats very high maintenance as most Email providers have whitelists with IPs from which they accept emails. This has been a thing many years ago, but isn't anymore.

very high volume option Use an API like mailchimp to send mails via API calls. Thats a good solution unless the API is down, then your webapp needs to be able to do error handling for that. Also its rather pricey while you can get a normal SMTP address for free. If you have a very high volume of mails, maybe go with something like mailchimp. In any case, if you send out newsletters or so, you need a provider thats build for that, or you need to adjust the limits in the providers settings. Otherwise you might get rate limited.

webapp has SMTP credentials option If you import a library in your webapp to talk SMTP, and you give this library your SMTP credentials make sure it can do error handling and will not just log something to error and then drop the mail. Thats a good way to "loose emails".

imho best solution: local mailrelay Use a local mailrelay using Postfix or OpenSMTPD, where you setup SMTP authentication credentials of the SMTP account(s) that you want your webapp to send mails with. From your webapps perspective all you have to do is set the correct sender (MAIL FROM) address and then give the mail to 127.0.0.1:25. The mailrelay will do the rest. If you get rate limited the mailrelay will keep the mails in its queue and try again periodically.

Personally I think using a Mailrelay is the the best approach. You can do this with Postfix, but the config is rather annoying for such a small task. Postfix is more suited to larger Mail environments (incoming and outgoing for many mail users) and just to complex to setup and debug for a simple mailrelay. I have recently switched to OpenSMTPD and am very happy with it.
There are many tutorials on how to setup a SMTP mailrelay for webservers with this one being the most detailed and easy to follow one I have found so far.

What is the best way to perform this task? should i install my own mail server?

Running your own mailserver is possible with solutions like mail in a box or similar FOSS tools. I personally wouldn't recommend that though, as often times large mail providers have whitelists (I'm looking at you microsoft) that will just block your mails, and then you have to maintain that mailserver and do things to get your IP unblocked. Many smaller email providers also fell for dubious blocklist schemes, where you have to pay the blocklist provider to unblock your IP (NEVER do that - a good blocklist like spamhouse will unblock you automatically after a period of time).

mail relay from web application / tool


GLib-GObject-CRITICAL warnings

Question: I'm confused by these two warnings. Can anyone explain how I might have come about triggering them, and how they would be able to be debugged in gdb?

(gtkworkbook:24668): GLib-GObject-CRITICAL **: g_cclosure_new: assertion `callback_func != NULL' failed
(gtkworkbook:24668): GLib-GObject-CRITICAL **: g_signal_connect_closure_by_id: assertion `closure != NULL' failed
Comment: I get these all the time... quite annoying.
Comment: What usually was the cause of the problem?
Answer: One thing you can try is pass in --g-fatal-warnings to Gtk::Main, this will cause warnings to assert.  You can attach with gdb and maybe figure out some more detail about where this is failing.
Answer: I found the problem.
This code was ported from an original implementation in C, and I had a requirement before to use an array of function pointers to call the functions inside of a shared library. Although this [seemed] to work at the time once I actually started using them it was not the case. I am a little stumped on why its not working, but I was able to centralized the problem to the following piece of code.

gtk_signal_connect (GTK_OBJECT (plugin()->workbook()->gtk_workbook), "switch-page",
 (GtkSignalFunc)this->signals[NOTEBOOK_SWITCHPAGE], plugin->workbook());

Was changed to the following:

gtk_signal_connect (GTK_OBJECT (plugin()->workbook()->gtk_workbook), "switch-page",
 (GtkSignalFunc)signal_gtknotebook_switchpage, plugin->workbook());

Now, the code compiles and I am not getting any nasty errors. I think this is the answer!

GLib-GObject-CRITICAL warnings


What dependencies do I need to run Apache CXF with Spring Boot on Java 11?

Question: This is driving me nuts. We are trying to use Java 11 with Spring Boot (to self host) and Apache CXF (for code-first SOAP development).
Is this combination just not possible?
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
        <version>3.3.2</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <version>2.3.2</version>
        <type>pom</type>
        <exclusions>
            <exclusion>
                <groupId>javax.activation</groupId>
                <artifactId>*</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0</version>
    </dependency>
</dependencies>

Results in:
[ERROR] module java.xml.bind reads package javax.activation from both jakarta.activation and java.activation
[ERROR] module java.xml.soap reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module java.xml.ws reads package javax.activation from both java.activation and jakarta.activation
[ERROR] the unnamed module reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module spring.context reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module spring.boot.autoconfigure reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module spring.boot reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module java.annotation reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module java.activation reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module jakarta.activation reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module org.apache.cxf.core reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module org.apache.cxf.frontend.jaxws reads package javax.activation from both java.activation and jakarta.activation
[ERROR] module spring.beans reads package javax.activation from both java.activation and jakarta.activation

I have been adding and removing dependencies all week. Either I end up with a class not found error, a module not found error (for my own module), or the above. If I exclude the jakarta.activation module, I get compilation errors because another module depends on it.
Any ideas on the set of dependencies I can use to get this junk working?
Comment: I am not very familiar with how  Spring Boot handle runtime dependencies but can you try setting `jakarata` dependency as provided?
Answer: We are using Spring Boot, CXF, and Java 11 in one of our projects also. We had some problems because the current version of CXF still requires some sun and javax dependencies.
This are our working dependencies:
<dependency>
        <groupId>jakarta.xml.ws</groupId>
        <artifactId>jakarta.xml.ws-api</artifactId>
        <version>${jakarta.version}</version>
    </dependency>
    <dependency>
        <groupId>jakarta.xml.bind</groupId>
        <artifactId>jakarta.xml.bind-api</artifactId>
        <version>${jakarta.version}</version>
    </dependency>
    <dependency>
        <groupId>jakarta.jws</groupId>
        <artifactId>jakarta.jws-api</artifactId>
        <version>${jakarta.version}</version>
    </dependency>
    <dependency>
        <groupId>jakarta.activation</groupId>
        <artifactId>jakarta.activation-api</artifactId>
        <version>2.0.0</version>
    </dependency>
    <dependency>
        <groupId>jakarta.xml.soap</groupId>
        <artifactId>jakarta.xml.soap-api</artifactId>
        <version>2.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.messaging.saaj</groupId>
        <artifactId>saaj-impl</artifactId>
        <version>2.0.0</version>
    </dependency>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.4.0-b180830.0359</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <version>3.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
        <version>3.4.2</version>
    </dependency>
    <dependency>
        <groupId>javax.xml.ws</groupId>
        <artifactId>jaxws-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>javax.jws</groupId>
        <artifactId>javax.jws-api</artifactId>
        <version>1.1</version>
    </dependency>

and some of the properties:
<properties>
    ...
    <java.version>11</java.version>
    <springfox.swagger.version>3.0.0</springfox.swagger.version>
    <apache.cxf.version>3.3.0</apache.cxf.version>
    <jakarta.version>3.0.0</jakarta.version>
    ...
</properties>

Answer:     <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <version>2.3.2</version>
        <type>pom</type>
    </dependency>

Comment: Please provide more information than just a code snippet.


There exists an deleted neighborhood around $0$ so thag a non-zero analytic function is no-where $0$

Question: This is obvious if we use Identity theorem. But I can't use that since it is real analysis exercise. All I can use there exists series expansion for the function around $0$.
Since non-zero analytic function not all coefficient is $0$. So we need to find $r$ so that $0<|z| \leq r$ such that $\sum a_n z^n$ is never zero. We need to prove only using the techniques of sequence and series. How to proceed? Any help please?
Comment: The intuition should be that, as $z\rightarrow0$, the term $a_{n_0}z^{n_0}$ with the smallest $n_0$ s.t. $a_{n_0}\neq0$ should asymptotically dominate the series (compare the graphs to get a feel for this). Indeed, you can show that $|\sum a_nz^n|>|a_{n_0}z^{n_0}|/2$ for $z$ sufficiently small by computing the limit of the quotient.
Comment: identity theorem holds for real analytic functions too, but if you want another alternative assume there is $r_n \to 0, f(r_n)=0$ and wlog assume $r_n >0$ decreasing, so by Rolle you find $s_n \to 0, f'(s_n)=0$ with $s_n$ positive decreasing and use induction to find such for all derivatives; this implies $f^{(n)}(0)=0, n \ge 1$ so $f$ constant
Comment: But there is no such assumption that $f(0) =0$. And it is exercise given in sequence and series chapter so can't use continuity and differentiability.
Answer: I will assume that the Taylor series of $f$ centered at $0$ is not the null series; otherwise, the statement is trivially false.
If $f(0)\ne0$, it follows from the continuity of $f$ that there is a neighborhood of $0$ at which there are no zeros of $f$. If you want to avoid assuming that $f$ is continuous, you can do it as follows: near $0$, you have\begin{align}f(x)-f(0)&=\left(\sum_{n=0}^\infty a_nx^n\right)-a_0\\&=\sum_{n=1}^\infty a_nx^n\\&=x\sum_{n=0}^\infty a_{n+1}x^n.\end{align}Now, let $\rho$ be the radius of convergence of the series $\sum_{n=0}^\infty a_nx^n$ and take $r\in(0,\rho)$. If $|x|<r$, it follows from what was done above that$$\bigl|f(x)-f(0)\bigr|<|x|\sum_{n=0}^\infty|a_{n+1}|r^n,$$and so, if$$|x|<\frac{|f(0)|}{\sum_{n=0}^\infty|a_{n+1}|r^n},$$then $\bigl|f(x)-f(0)\bigr|<\bigl|f(0)\bigr|$, and therefore $f(x)\in\bigl(0,2f(0)\bigr)$; in particular, $f(x)\ne0$.
And if $f(0)=0$, then let $k$ be the smallest natural number such that $a_k\ne0$. Then$$f(x)=a_kx^k\left(1+\frac{a_{k+1}}{a_k}x+\frac{a_{k+2}}{a_k}x^2+\cdots\right).$$If$$g(x)=1+\frac{a_{k+1}}{a_k}x+\frac{a_{k+2}}{a_k}x^2+\cdots,$$then $g(0)=1\ne0$ and therefore $g$ has no zeros near $0$ (as above) And, of course, $a_kx^k=0\iff x=0$. So, near $0$, the only zero of $f$ is $f$ itself.
Comment: It's done.${}{}$
Comment: Is it possible to prove without using continuity?
Comment: Yes, but since being analytic is *much* stronger than being continuous, why do you want to do that?
Comment: It is a exercise in sequence and series. That is why.
Comment: Thank you so much


Ansible filter using ad-hoc command

Question: How can I filter the nocache block or free block using ad-hoc command? I tried ansible centos1 -m setup -a 'filter=ansible_memory_mb.nocache' but doesn't filter it out.
ansible centos1 -m setup -a 'filter=ansible_memory_mb'
centos1 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 11808,
                "used": 926
            },
            "real": {
                "free": 10686,
                "total": 12734,
                "used": 2048
            },
            "swap": {
                "cached": 0,
                "free": 4096,
                "total": 4096,
                "used": 0
            }
        },
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

Answer: You can't. As the documentation for setup says, "The filter option filters only the first level subkey below ansible_facts."
Answer: this is a bit messy, but you can..
I am running my ansible against my localhost, so you will have to modify the path a bit, and replace localhost
ANSIBLE_LOAD_CALLBACK_PLUGINS=true ANSIBLE_STDOUT_CALLBACK=json ansible localhost -m setup | jq .plays[].tasks[].hosts.localhost.ansible_facts.ansible_memory_mb.nocache

output:
{
  "free": 11987,
  "used": 703
}

Comment: Right, after one has the output in JSON format, it will be possible to filter afterwards via [`jq`](https://stedolan.github.io/jq/) (JSON query, like sed for JSON data).

Ansible filter using ad-hoc command


JSON com valor - Lista do App Nulo

Question: Estou criando um App, onde ele apresentará algumas informações de um banco de dados externo utilizando um arquivo JSON para que eu consiga apresentar essas informações no App.
Porem quando eu executo o código, a lista em meu app retorna nula e sem nenhum resultado. Gostaria de saber onde estou falhando na construção de meu Código.
public class PontosActivity extends AppCompatActivity {

private String TAG = PontosActivity.class.getSimpleName();

private ListView lstPontos;

private static String url = "http://mpeprojeto.com/pontos";

ArrayList<HashMap<String, String>> pontosList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pontos);

    pontosList = new ArrayList<>();

    lstPontos = (ListView) findViewById(R.id.listPontos);

    new GetPontos().execute();

}

private class GetPontos extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeHttpHandler(url);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray pontos = jsonObj.getJSONArray("pontos");

                // looping through All Contacts
                for (int i = 0; i < pontos.length(); i++) {
                    JSONObject c = pontos.getJSONObject(i);

                    String data = c.getString("datar");
                    String hora = c.getString("horar");
                    String lat = c.getString("latr");
                    String longt = c.getString("longtr");

                    // tmp hash map for single contact
                    HashMap<String, String> ponto = new HashMap<>();

                    // adding each child node to HashMap key => value
                    ponto.put("datar", data);
                    ponto.put("horar", hora);
                    ponto.put("latr", lat);
                    ponto.put("longtr", longt);

                    // adding contact to contact list
                    pontosList.add(ponto);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error1: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error2: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Avalie novamente seus ultimos pontos, pois não foi encontrado nenhum!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if(result!=null) {
            ListAdapter adapter = new SimpleAdapter(
                    PontosActivity.this, pontosList,
                    R.layout.activity_listpontos, new String[]{"Data:", "Hora:",
                    "Latitude:", "Longitude:"}, new int[]{R.id.dataPonto,
                    R.id.horaPonto, R.id.latitudePonto, R.id.longitudePonto});
            adapter.notifyAll();
            lstPontos.setAdapter(adapter);
        }
        else
        {
            Toast.makeText(getApplicationContext(), "Nenhum Ponto Registrado", Toast.LENGTH_LONG).show();
        }
    }

}

Arquivo JSON:
{
"pontos": [
    {
            "datar": "14/11/2016",
            "horar": "20:37:001",
            "latr": "-22.778899",
            "longtr": "-47.554477"
    },
    {

        "datar": "14/11/2016",
            "horar": "20:39:001",
            "latr": "-22.748596",
            "longtr": "-47.858532"

     }
    ]
    }

HttpHandler:
public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public String makeHttpHandler(String reqUrl){
    String resposta = null;

    try{
        URL url = new URL(reqUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream is = new BufferedInputStream(connection.getInputStream());
        resposta = convertStreamToString(is);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return resposta;
}

XML:
<TextView
    android:id="@+id/dataPonto"
    android:layout_width="67dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="5dp"
    android:text="" />

<TextView
    android:id="@+id/horaPonto"
    android:layout_width="67dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:text=""
    android:layout_alignParentTop="true" />

<TextView
    android:id="@+id/latitudePonto"
    android:layout_width="67dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="5dp"
    android:text="" />

<TextView
    android:id="@+id/longitudePonto"
    android:layout_width="67dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:text=""/>

Answer: Gabriel,
Revisei seu código e não encontrei nada muito óbvio de erro. Então, vou sugerir para você testar algumas coisas:
1) O json está vindo corretamente ? Na classe HttpHandler coloca um Log.d da resposta antes de dar o return para ter certeza que o json está correto.
2) Você está rodando o AsyncTask de dentro do onCreate (main thread), o que não é recomendado.
Tenta assim:
new Thread() {
    @Override
    public void run() {
        new GetPontos().execute();
    }
}.start();

Sobre isso tem uma pergunta semelhante no link abaixo:
https://stackoverflow.com/questions/31874990/async-task-android-execute
Comment: Tentei fazer o que me disse, mas continua vindo nulo, porem não sei o motivo de continuar nulo a resposta do meu arquivo Json..
Comment: Deve ser o teu método convertStreamToString(is) ... coloca o source dele aqui pra eu ver ...

JSON com valor - Lista do App Nulo


How do I make an iterator over a 2-dimensional table in Lua?

Question: I've got a lua table made of tables, so it's two-dimensional: root -> child -> grandchild.
None of the levels of this hierarchy is guaranteed to be "array-like". The first level has integers with "nil gaps", and second one is not even indexed by integers (but by tables).
The table in question is a private structure inside a lib. I want to provide a way for the library user to parse its grandchildren. I don't care much about the order in which the they are parsed, as long as all of them are.
The first thing I thought about was using a function accepting a callback:
-- this scope has access to root
function eachGrandChild(callback)
  for _,child in pairs(root) do
    for index,grandChild in pairs(child)
      callback(index, grandChild)
    end
  end
end

Usage:
-- no access to root, only to eachGrandChild
eachGrandChild(function(index, grandChild) print(index, grandChild) end)

This much is understood.
My question is: could I provide a similar functionality using an iterator instead?
I'm talking about something that would allow me to do this:
for index,grandChild in iterator() do
  print(index, grandChild)
end

I've been thinking about this for a while but I'm not able to crack it. All the examples I've seen use numbers to easily "manage the state of the iterator" on each iteration. Since I don't have numbers, I'm a bit stuck.
Answer: Coroutines make it easy to write this kind of iterator. A coroutine is a function whose execution can be suspended and resumed, conceptually like a thread. A coroutine can contain deeply nested loops, yield a value from the inner most loop, then continue right where it left off when resumed. When it yields, the caller who resumed it can receive yielded values.
In your case, convert eachGrandChild into a generator function which yields grandchildren.
function eachGrandChild(root)
  for _,child in pairs(root) do
    for index,grandChild in pairs(child) do
      coroutine.yield(index, grandChild)
    end
  end
end

Then use coroutine.wrap to create a function that will create a coroutine for your generator and resume it each time the function is called.
function grandChildren(t)
    return coroutine.wrap(function() eachGrandChild(t) end)
end

Now you have your iterator:
for key, val in grandChildren(root) do
    print(key, val)
end

There's a chapter on this in Programming in Lua.
Comment: @kikito: Your direct callback method is definitely going to be more efficient, in part because of the reduced function call overhead (resume, yield). But it's not as bad as you might think (Lua's coroutines are [very well written](http://stackoverflow.com/questions/13300682/how-do-i-make-an-iterator-over-a-2-dimensional-table-in-lua)).  For instance, if you benchmark the coroutine implementation vs prapin's implementation, I suspect you'll find the coroutine to be faster.
Comment: Awesome answer. The "managing the state of a function" part I said was practically yelling "coroutines!" to me, but I didn't connect the dots. I'm a bit concerned about execution speed (this parsing loop will be executed many times per frame so it has to be reasonably fast) but I'll do some tests.
Comment: you were right in everything. Even when creating a new anonymous function each time, the callback code is the fastest one. Coroutines take around 200% time to do the same job, and the next-based solution takes around 220%. So I guess I'll stick to callbacks. This has been a good learning experience nonetheless! :)
Comment: Just keep in mind, [premature optimization is the root of all evil](http://c2.com/cgi/wiki?PrematureOptimization). Yes, 200% may sound awful, but we're talking about a differences a few *microseconds*. Are you calling this thousands of times per frame?
Comment: "Premature evil is the root of all optimizations" :D I know the quote. And yes, this is going to be called thousands of times per frame - It'll be at the heart of a collision library (`root` is actually a spacial index)
Answer: I agree with Mud that coroutines are the best approach to the problem.
For the record, I have written an iterator without coroutines for the sake of comparison.
The first function eachGrandChild is called for each element. It uses a state variable, the containing the two indices (the top and second level).
function eachGrandChild(state)
  while state.childIndex ~= nil do
    local child           = root[state.childIndex]
    state.grandChildIndex = next(child, state.grandChildIndex)
    if state.grandChildIndex == nil then
      state.childIndex = next(root, state.childIndex)
    else
      return state.grandChildIndex, child[state.grandChildIndex]
    end
  end
end

The iterator is initialized with the helper function:
function grandChildren(root)
  return eachGrandChild, {childIndex = next(root)}
end

Now the iterator can be used normally:
for key, val in grandChildren(root) do
    print(key, val)
end

Compared to the coroutine based version, eachGrandChild has more lines of code and is more difficult to read.
Comment: Thanks for your answer. I will try both approaches nevertheless - yours might be more efficient, if slightly longer. I would declare both answers as correct if possible. You definitively deserve a +1
Comment: I've taken the liberty of refactorizing the iterator code a bit - names instead of magic numbers, a while instead of a repeat-until, and a simplified "run out of grandchildren" condition. I also removed `root` from the state, since it's assumed to be available on the scope. I hope you don't mind if I edit your answer.
Comment: @kikito Thanks for the code editing. This is more readable now.


Total Change vs Average Total Change

Question: Someone help me get a grasp of this. Feel like am missing some math principles:
If I have
<code>     2018 2019
      1     2
      3     4
      5     6
      7     8
Total 16    20
</code>
The percentage change in totals for $2019$ is $\left[\dfrac{20}{16}-1\right]$% $= 25$%
Shouldn't this give the same result as calculating the individual change for each row and averaging the sum of these?
That is: $\dfrac{(100 + 33.3 + 20 + 14.3)}4 ?$
Comment: @The Demonix _ Hermit it's MathJaX not $\LaTeX$
Answer: No. What is equivalent is if you express each change in terms of the average of the 2018 values. ${1+3+5+7\over 4}={16\over 4}$ So the change is $25\%+25\%+25\%+25\%= 100\%$ of their average. which when averaged is $25\%$
Comment: This does not answer why the two are different. I don't understand. Why is total change different than average change.

Total Change vs Average Total Change


PHP imagick converting image from CMYK to RGB inverts image

Question: I have an image being rejected by the eBay API because of this:
 <ShortMessage>Source picture uses an unsupported colorspace.</ShortMessage>
    <LongMessage>Pictures with a CMYK colorspace are not supported; source pictures must use a RGB colorspace compatible with all web browsers supported by eBay. Submit pictures created using a camera or scanner set to save images with RGB color.</LongMessage>

Well, I had no idea it was a CMYK nor am I even sure how to tell.  I then used the following code to attempt a convert:
$image= "$img.jpg";
$i = new Imagick($image);
$i->setImageColorspace(Imagick::COLORSPACE_SRGB);
$i->writeImage($image);
$i->destroy();

It converts (and is now accepted by eBay), but it also inverts the colors of the picture. Why would it do this and is there another COLORSPACE I should be using?
Thanks.
Answer: The setImageColorSpace method is not meant to be used for existing images - it's only for new images (e.g. $imagick->newPseudoImage(100, 100, "xc:gray");)
The transformImageColorSpace method is the right one to use for changing an existing images colorspace.
$image= "$img.jpg";
$i = new Imagick($image);
$i->transformImageColorspace(Imagick::COLORSPACE_SRGB);
$i->writeImage($image);
$i->destroy();

Comment: Great help! And more info here http://www.phpimagick.com/Imagick/transformImageColorspace


Abrir, editar e salvar um arquivo binário no Python3

Question: É possível abrir um arquivo binário e ler seus bits no Python3, editar e salvar um novo binário. Se for possível, como?
Answer: Sim, é possível. Considere um arquivo binário chamado teste.bin de exemplo com o seguinte conteúdo (bytes em hexadecimal):
 A0 B0 C0 D0 E0 F0

O seguinte código lê esses bytes e altera o conteúdo do byte na posição 2 (que inicialmente tem o valor C0) para FF:
with open('teste.bin', 'r+b') as file:
    byte = file.read(1)
    while byte != b'':
        print(byte)
        byte = file.read(1)

    file.seek(2, 0)
    file.write(b'\xFF')

Resultado da execução:
b'\xa0'
b'\xb0'
b'\xc0'
b'\xd0'
b'\xe0'
b'\xf0'

Bytes no arquivo após a execução:
A0 B0 FF D0 E0 F0

P.S.: Esse exemplo "edita" o mesmo arquivo. Se você desejar criar um
  segundo arquivo com as alterações, basta abri-lo com um outro nome de
  variável. Por exemplo, ao invés e usar o with open, você pode fazer
  assim:
srcFile = open('teste.bin', 'rb')
tgtFile = open('teste2.bin', 'wb')
. . .
srcFile.read ...
tgtFile.write ...
. . .
srcFile.close()
tgtFile.close()

Note que no exemplo inicial eu usei 'r+b' para abrir o arquivo. O
  r e o + indicam que o arquivo vai ser aberto para leitura e para
  atualização, e o b indica que ele deve ser aberto como binário ao
  invés de texto. Nesse segundo exemplo, eu já abro cada arquivo em um
  modo distinto: o arquivo de origem (srcFile) eu abro apenas como
  leitura (e por isso uso 'rb') e o de destino (tgtFile) eu abro
  apenas como gravação (e por isso uso 'wb'). O uso do w na abertura
  do arquivo de destino faz com que ele seja sempre truncado (se quiser
  manter o conteúdo existente você deve abrir com o r+).
Answer: Para abrir um arquivo em modo binário basta usar o modo b na funcão open:
open("arquivo", "r+b") # Abre arquivo em modo binário para edição

A partir daí, todas as funções normais de leitura, escrita e navegação de arquivos estão valendo:
with open("arquivo", "r+b") as arquivo:
    byte = arquivo.read(1)
    # altera byte
    arquivo.write(byte)

Lembrando que, como o arquivo foi aberto em modo binário, todas as funções vão aceitar e retornar objetos byte.


R data.table - new column with ':=' and keep existing column

Question: Is it possible to create a new column and keep (few) existing columns in the statement ? e.g. creation of "x" column and then keeping "x" and "mpg" column
dt <- data.table(mtcars)

dt[,x:=mpg]

dt[,.(x,mpg)]

Comment: Do you need to modify the original object as it can be dangerous if not being careful
Comment: I totally agree. It is not advisable to update the original object. I have a situation where minor savings in processing time will add value.
Answer: If we need it in a single step, instead of doing the := to modify the original dataset, specify it with = inside list or .(
dt[,.(x = mpg, mpg)]

Or if it necessary to create the column in original dataset, it can be piped
dt[, x := mpg][, .(x, mpg)]

If we want to update the columns in the original object, another option is set
set(dt[, x:= mpg], i = NULL, j = names(dt)[!names(dt) %in% c('x', 'mpg')], value = NULL)

Comment: Which option would be more efficient from the performance perspective? I am assuming that option#1 will require to assign output back to original data table. right? dt <- dt[,.(x = mpg, mpg)]
Comment: @R007 `:=` is faster, but then you are also subsetting.  Can you please check on a bigger dataset with `microbenchmark`
Answer: If you want to do the replacement by reference, using := then you can do
dt[, x:=mpg][, setdiff(colnames(dt), c('x', 'mpg')) := NULL]


Groups with Functions as operators

Question: I just couldn't let go of this. A Group operator is typically defined to be a single operator like a '+' or as a composition operator like in a Permutation group. However, we fail to precisely define an operator - more generally!
For e.g. Let the group $G \subset \mathbb{Z}$ be a subset with the following properties.

Operator : The '+' operator could be defined to be $f(x,y)=x+y, f:\mathbb{Z^{2}} \to \mathbb{Z}$ being the group operator.
Closure: $\forall (x,y) \in G,  f(x,y) = z \vert z \in G$
Identity: $ \exists i \in G \vert f(x,i) = i $ $\forall x \in G$
Inverse: $ \exists (y,i) \in G \vert f(x,y) = i$ $\forall x \in G$
Commutative: $\forall (x,y) \in G, f(x,y) = f(y,x)$
Associativity: $\forall (x,y) \in G, f(z, f(x,y)) = f(f(z,x),y)$

I think then this captures the idea the generalized version of the operators could be some function $f$ instead of some specific operation that is very narrow or more specific to the problem in hand. This could be extended to include infinite and finite sets and discrete or continuous. $f: \mathbb{R}^{n}\to \mathbb{R},$$f: \mathbb{C}^{n}\to \mathbb{C}$ which is about how general we can get.This can be then generalized more to include the search for such operator functions and the corresponding $G$ that satisfies the aforesaid conditions. The "Well known" discrete groups such as $S_{n}$ is merely a specific Group with some "fixed" operator and identity. I guess we could cover it to include Lie groups as well. Instead of searching for Groups that contain specific fixed operators  we should instead focus on fixed Groups/subsets with  search for these operator functions that generate that Groups/subsets and may be relations between such Groups/subsets.
Here is an example, consider a set of points in the $(+,+)$ and $(-,-)$ quadrants of a circle at center (0,0). Call it P and Q. Now under the function
$f(x,y) =x +y$. Such that $x \in  P$ and $y \in Q$. We can assemble a set of points from each of these quadrants such that we can form a 'Structure'. The inverse of course exists with $(0,0)$ being the identity.
Now, my question is why restrict it to one such function $x+y$. There must be other functions, in general, that apply to these points that also generate a similar structure. All I'm trying to say is shouldn't the concept of group be studied under this general concept instead of fixing the '+' or other operations
Just wondering what you guys think and would appreciate more info!
Comment: Note: $\Bbb Z\ast\Bbb Z$ means the *free product of $\Bbb Z$ with itself*, **not** the *direct product $\Bbb Z\times\Bbb Z$ of $\Bbb Z$ with itself*.
Comment: [Somehow I think this is related.](https://math.stackexchange.com/q/2725786/104041)
Comment: I'm no that's sure what you've written is somehow different from the definition of a group (excluding commutativity of course)
Comment: By allowing the operator $f(x,y)$ to be defined as a function we can introduce for e.g  $f(x,y) = e^{x+y}$  is my point. Which we wouldn't ordinarily consider to be an operator
Answer: I'm not sure I understand your question but here's a collection of thoughts on the opening post.

The closure axiom in group theory is often omitted by some authors as it is implied by, in a model of the theory (i.e., a group $(G, \circ)$), the binary operation being just that: a binary operation defined by
\begin{align}
\circ: G\times G&\to G \\
(g_1, g_2) &\mapsto g_1\circ g_2,
\end{align}
so that $g_1\circ g_2\in G$.
Nonetheless, yes, one has to check closure from time to time to see if a candidate group is indeed a group, but such cases are usually subgroups of some group or even a semigroup. I think there are some esoteric exercises or lemmas - even theorems - that start with the assumption of some closure properties that end up showing the resulting structure is a group.
One such exercise is as follows.

Consider a semigroup $S$. Show that $S$ is a group if and only if $aS=S=Sa$ for every $a\in S$.$^\dagger$

Also Exercise 39 of the supplementary exercises for chapters 1-4 of Gallian's "Contemporary Abstract Algebra" is a 1995 Putnam question. You might be interested in it. It explores closedness without explicit use of group theory.

$\dagger$ Here $aS:=\{as\mid s\in S\}$ and $Sa$ is defined dually. Reference for exercise: Howie's "Fundamentals of Semigroup Theory", somewhere near the beginning.

Groups with Functions as operators


How create form elements in form theme hook

Question: I have a custom module with a from, form submit handler and for theme hook
In some case I need to create multiple form elements (textfields for example with name like "user_input_1"-"user_input_n")
What I did is change $form array in form theme hook and render new elements. But these elements are missing in the post and form submit processing form (even if shown on a page). I realize what it might be not appropriate way of creating new form elements in theme hook OR maybe there is something(function) what will allow me to properly prepare new form elements in theme hook on a fly.
Or maybe there is another way as I know how many elements do I need in submit processing function which rebuild the form and doing something like $form_state['storage']['wizard_step'] = 'step3' (multi-step form). But I don't know drupal very well, just started..
Stuck and spend few hours trying to find appropriate way of solving this. Any help appreciated.
Thanks
Answer: Answer is simple: form alter hook allows to manage form content on a fly
Comment: Hello, and welcome on Drupal Answers. May you expand your answer? As it is, it is not much helpful for future readers.


Modifying HPE Proliant thermal settings

Question: HPE states that from iLO 4 version 2.76 user can view and modify system thermal configuration settings using iLO interfaces. Finally! This is great feature for example those who have HPE incompatible drives. More details about this issue can be read from here
However, they haven't documented feature and I can't figure out how settings should be modified. Any tips where to look?
Comment: You should use compatible disks. There's no reason not to.

But can you provide better information on the specific platform and hardware you're describing.
Comment: There is lot of reasons. This is my homelab and compatibe disk are quite expensive. Anyway, I have 6 HPE Proliant DL360p gen8 servers. Currently I have 15 unused Seagate Barracuda 2TB hard drives. I'd like to utilize those but because they messing with temperature sensor I can't.
Answer: Please refer to pages 180 and 185 in the iLO 4 User Guide
Link to guide

Modifying HPE Proliant thermal settings


Passing const char* to function from external library that takes a char*

Question: Consider I have the following function in a dynamic external library libExternal.dylib:
void print(char* str)
{
    // Changes the first char to 'a' and prints the string
    *str = 'a';
    printf("%s\n", str);
}

Next, I have an executable that loads this external library and calls the function (error checking omitted):
int main(int argc, const char * argv[])
{
    void* hLib = dlopen("libExternal.dylib", RTLD_LAZY | RTLD_LOCAL);

    typedef void(*printFunc)(const char*);
    printFunc func = (printFunc)dlsym(hLib, "print");

    std::string test = "hello";
    func(test.c_str());

    dlclose(hLib);

    return 0;
}

As you can see, the function defined in the library takes a char* as parameter. When using dlsym, I made it get a function that takes a const char*. And it works!
My question is, how is this possible? The dynamic loader ignores const types? I really couldn't find an answer anywhere, so please help me! :)
EDIT:
I know this code is wrong, I'm just trying to understand how is this possible.
Comment: Please pay attention to the "Question preview" window and use proper code formatting (fixed it for you this time).
Answer: It works but it doesn't mean it's correct.
It doesn't ignore const types, you're casting the external function to a function which accepts const types:
typedef void(*printFunc)(const char*);
                         ^^^^^^^^^^^

printFunc func = (printFunc)dlsym(hLib, "print");
                 ^^^^^^^^^^^

And try to use right function signature to avoid undefined behavior due to modifying a const value.
Comment: @LuísMendes it's a fluke that it's working. The dynamic storage of `std::string` is actually a non-`const` array so it appears to work fine. You're crossing a dynamic library boundary and using an incorrect function type; the compiler can't detect this mistake.
Comment: That's correct, I'm casting it, but casting a const char* to char* is wrong. I don't understand how this code runs without crashing.
Comment: @Simple: `test` as a `std::string` is non-const, but the return value of `test.c_str()` is const.
Comment: @MM. right but that doesn't mean that the array `c_str` points to is actually `const`.
Comment: You can also take a pointer to an int, substract 5, set that and it doesn't crash. Doesn't mean that this is correct and will never crash. It's just a matter of luck.
Comment: @Simple: Yes.. but I think it's still an undefined behavior. In this case he's lucky but in general it can be a access violation.
Comment: Thanks for the feedback guys! I know this code is wrong, I was just trying to understand how it was possible. Your contributions were really helpful.
Comment: @MM. it is undefined behaviour you're right. Was just pointing out one of the reasons it appears to work (the biggest problem is the incorrect function type).
Answer: Passing const char * to foo(char *str) is undefined behavior (UB).
It could work, it might not.  It certainly will not work on systems that prevent writing to const memory.  Other systems are lenient and subsequent operations may / may not work as expected.
C11 draft 6.7.3. 6
Comment: @Giorgi Yes - it is still UB.  Think of a system where `const` and non-`const` pointers had some attribute attached to their pointer value.  And that system had no means to convert a `const` to non-`const` pointers.
Comment: @Giorgi Perhaps C11dr §22.214.171.124 8 "... If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined."
Comment: @Giorgi Yes passing non-`const` to `const if fine.
Comment: @Giorgi "compatible" is not the same as "allow-ability"  `A` may be a subset of `B` even if `B` is not a subset of `A`.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/84510/discussion-between-chux-and-giorgi).
Answer: Consider this code:
#include <stdio.h>
int
main(int argc, char **argv)
{
        char a[] = "foo";
        const char *b = a;
        char *c = (char *)b;
        *c = 'a';
        printf("%s\n", b);
        return 0;
}

That's on a high level equivalent to what you're doing internally. Theoretically char *c = (char *)b; *c = 'a'; is illegal, but in practice it happens to work in this particular case.
See const as a kind of contract between the writer of the API and the user of that API rather than something that is strictly enforced by the compiler and runtime. A secondary reason for const to exist is that it allows string literals to be put into read-only segments in programs opening up for many useful optimizations (like deduplication of strings), but I'd argue that primarily const is a just reminder for the programmer.
This is why in large projects I've seen adding const to function arguments is sometimes called "const poisoning". You poison some string or struct that is being passed around many different layers of APIs to make a promise that it isn't modified anywhere through the layers. The act of adding const by itself is very valuable to discover where unintended modifications happen. You can always get rid of the const quite easily and break the contract, but by not doing that you make it easier to read and debug your program. I've even done some experiments and compilers don't do optimizations that would be reasonable to do if the compiler expected const to be respected.
Sometimes it's even necessary to cast away const for completely legitimate reasons. For example when you have something like this:
struct foo {
    const char *string;
    int dynamic;
};
void
foo_dynamic(struct foo *f, int x)
{
    f->dynamic = 1;
    f->string = malloc(16);
    snprintf(&s->string, 16, "%d", x);
}
void
foo_static(struct foo *f, const char *x)
{
    f->dynamic = 0;
    f->string = x;
}
void
foo_free(struct foo *f)
{
    if (f->dynamic)
        free((void *)f->string);
    free(f);
}

In this case we make the promise in our API that we won't change the contents of what foo->string points to during the life time of foo, but we still need to be able to free it if we allocated it ourselves. A language fundamentalistlawyer might say that this is undefined behavior (it is) and there are solutions to achieve the same thing (there are), but this is pretty common in practice.


Joining query results into one

Question: This is my table to track down the employees off days. This example is only for one person.
ID   PID     Year       OffDays       DayTypeNumber
------------------------------------------
1     1      2011       10            1
2     1      2011       5             2
3     1      2012       20            1
4     1      2012       3             2

I would like to write such a query that should only show one result for each year with additional column
Year       OffDays(1)    OffDays(2)
------------------------------------------
2011       10            5
2012       20            3

Answer: You can use the PIVOT function for this:
select year,
  [1] [OffDays(1)],
  [2] [OffDays(2)]
from
(
  select year, offdays, daytypenumber
  from yourtable
) src
pivot
(
  sum(offdays)
  for daytypenumber in([1], [2])
) piv

See SQL Fiddle with Demo
Result:
| YEAR | OFFDAYS(1) | OFFDAYS(2) |
----------------------------------
| 2011 |         10 |          5 |
| 2012 |         20 |          3 |

Or you can use an aggregate function with a CASE statement:
select year,
  sum(case when daytypenumber = 1 then offdays end) [OffDays(1)],
  sum(case when daytypenumber = 2 then offdays end) [OffDays(2)]
from yourtable
group by year

See SQL Fiddle with Demo
If you only have two types that you are comparing, then you can use subqueries:
select t1.year,
  [OffDays(1)],
  [OffDays(2)]
from
(
  select sum(offdays) [OffDays(1)], year
  from yourtable
  where daytypenumber = 1
  group by year
) t1
left join
(
  select sum(offdays) [OffDays(2)], year
  from yourtable
  where daytypenumber = 2
  group by year
) t2
  on t1.year = t2.year

See SQL Fiddle with Demo
The above answers will work great, if you have a known number of values for DayTypeNumber, but if those are unknown then you can use dynamic SQL to generate the PIVOT:
DECLARE @cols AS NVARCHAR(MAX),
    @colNames AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(DayTypeNumber)
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

select @colNames = STUFF((SELECT distinct ', ' + QUOTENAME(DayTypeNumber)
                      +' as [OffDays('+cast(DayTypeNumber as varchar(10))+')]'
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT year,' + @colNames + ' from
             (
                select year, offdays, daytypenumber
                from yourtable
            ) x
            pivot
            (
                sum(offdays)
                for daytypenumber in (' + @cols + ')
            ) p '

execute(@query)

See SQL Fiddle with Demo
All of these will produce the same results:
| YEAR | OFFDAYS(1) | OFFDAYS(2) |
----------------------------------
| 2011 |         10 |          5 |
| 2012 |         20 |          3 |

Comment: @Kaf - That's the artifice of SQLFiddle and the knowledge of [bluefeet](http://stackoverflow.com/users/426671/bluefeet?tab=answers&sort=votes). :)
Comment: I know (and hope) you will give the dynamic query in some time [like this one](http://dba.stackexchange.com/a/27669/9332)
Comment: dude, what did you do in here!
you are genious! thank you very much!

Joining query results into one


EICRA - External interrupt control register "A"?

Question: while learning about the external interrupts, I have gone through the document of atmega328p.
came across EICRA, why is that it is necessary to explicitly mention as A, when there isn't anything called EICRB(using ctrl+f, I have searched for EICRB in the document).
Answer: Because other models may have more external interrupt capable pins and may need more control registers. This naming approach provides forward compatibility (to some extend) with more capable products.
For example, take a look at ATmega2560 datasheet. You will notice that it has EICRB, as well as more bits in EICRA compared to ATmega328P.