access integer array using DataBinding

Question: I am trying to create RecyclerView with use of DataBinding for Integer data, i have already tried with String data by declaring string-array in string.xml, here is answer from where i have taken reference.
Now i am trying to implement it with integer-array but not able to access it from xml.
Here is my integer.xml
<integer-array name="hours">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
    <item>11</item>
    <item>12</item>
</integer-array>

here is my xml file
<android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:entries="@{@integerArray/hours}">

and my custom binding adapter
@BindingAdapter("entries")
public static void entries(RecyclerView recyclerView, Integer[] array) {
    recyclerView.setAdapter(new SimpleArrayAdapter(array));
}

But it is showing me error line 1:0 token recognition error at: '@integerArray/'
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Identifiers must have user defined types from the XML file. hours is missing

Answer: Found solution from document itself, i was doing silly mistake. It should be intArray instead of integerArray, and in BindingAdapter it should be int[]
app:entries="@{@intArray/hours}"

and adapter should be
@BindingAdapter("entries")
public static void entries(RecyclerView recyclerView, int[] array) {
    recyclerView.setAdapter(new SimpleArrayAdapter(array));
}

Answer: Thanks for the answer. Here I want to share the similar solution for binding image from integer-array Drawable resource.
My integer-array resource of Drawable:
<resources>
    <integer-array name="platform_images">
        <item>@drawable/android</item>
        <item>@drawable/iphone</item>
        <item>@drawable/windows</item>
    </integer-array>

</resources>

My BindingAdapter function:
object DataBindingUtil {
    @BindingAdapter("imageIndex", "images")
    @JvmStatic
    fun setImageResource(imageView: ImageView, imageIndex: Int, images: TypedArray) {
        imageView.setImageResource(images.getResourceId(imageIndex, 0))
    }
}

My ImageView:
<ImageView
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:src="@drawable/android"
    app:imageIndex="@{2}"
    app:images="@{@typedArray/platform_images}" />

access integer array using DataBinding


Find nth occurrence of a symbol and replace using regular expression

Question: I have a file with more than 20K lines and in each line we have exactly 151 '@' symbols as a delimiter. I need to replace value between 104th, 105th and 105th and 106th occurrence of '@' symbol. I tried with Excel but having issues with date fields and felt replacing in Notepad++ is easy. Could anyone provide inputs on the regex? I tried with replacing with nth occurrence of the symbol but it didn't work.
Sample Line

9007;624;@0@0@1@Company & Co. "XYZ" ;Comp & Co. HG;@@@Ger;Ger;@@@@0@0@@@@@@@@@uid=XYZ@@@@@Gery;@0@@@@@0@@@@@@@T@@@@@0@0@0@0@0@0@0@0@0@0@0@@@@@@@@@@@@@@@@1@1@1@1@1@@@@@@@@@@@@@@@@@@@@@@@@@@08.007.001.001 Bs;08.007.001.004 Zahlungen;üüüüüüü;äääää;@Sct;2006;Mar;da das Haus;@@@$S0et7xV0@568;536871132;36108;536871497;536871712;536871449;536907021;148000;@THA@@@uid=Compa@03/03/2016;12:41:00:00@doc@096@@0@@1@@@OHG | 0624 | Ger | 9007 | Ger;@@2005;1953;@B48D3B01257184408AF2F2D69BAC1DEF000000000000@268471076@@@@@@@0@@@@@@07/24/2012;07:39:00:00@@@@@@@@@@@@$S0et7xV0@0@email@example.com

Highlighted in bold needs to be replaced. Appreciate anyone's insights on this.
Thanks!
Comment: What do you want to replace it by?
Comment: Replace with a pre-defined text.
Comment: So two texts? You keep the @ separator between them? Can you edit your question and show what you have tried and what is holding you back in doing this?
Comment: What is the expected output?
Answer: You could use the following replacement instruction (press Ctrl+H to open Find/Replace dialog):
Find what: ^((?:[^@]*@){104})[^@]*@[^@]*
Replace with: \1Hello@World
Search mode:
⦿ Regular expression
Replace All
Here the two texts are replaced by "Hello" and "World". Adapt as needed.
Break down of the regex:

^ matches the start of a line
[^@]*@ matches a sequence of non-@ characters, followed by one @.
(?:   ){104}: repeats 104 times the pattern enclosed within (?: )
(     ): captures the matched text in a capture group that can be referenced with \1.
Comment: Thanks much for the answer. However, I tried with above regex but it did not work. As I said in my question, I will have line with @ as delimiter and need to replace the value in between 104th, 105th and 105th, 106th occurrence of @ with predefined text.

For ex:

Actual Line -> A@B@C@D@E@F@G@H@I@@J (Consider @ before D is the 104th occurrence in a line for ex)
Expected Output -> A@B@C@TEST@STRING@F@G@H@I@@J (D & E are replaced with TEST and STRING)
Comment: I tested this with the input you gave in the question, and this worked for me. The "Actual Line" you give here does not have 105 @ characters, so it won't work with that. Your question didn't specify what the expected output is for the given example, so I had to use dummy text. Would be better to complete your question and provide the expected output literally. I just did the operation again, and it works as you describe in this comment.
Comment: Thanks for the note. I checked again and see that there are 151 occurrences of '@' symbol in the given input. Please note that value may or may not be there between delimiter.
Comment: Yes, all that is taken into account. Like I said it works for me: I pasted the example input in Notepad++ with several other lines of text, applied the Find/replace operation, and it replaced the text you marked in bold with "Hello" and "World". If it doesn't work for you then I cannot help you. It works for me (using Notepad++ v8.4.8)
Comment: See it run also on [regex101](https://regex101.com/r/EstXhI/1)
Comment: Yes, even for me it worked in regex101. Strangely it doesn't work in my notepad++ v5.9.2. May be I need to upgrade and check once. Thanks much for your time and providing the solution.
Comment: The issue is with Notepad version. I tried in 6.9 and it works. Thanks!
Comment: Hmmm, version v5.9.2 is indeed an old relic. According to [this page](https://notepad-plus-plus.org/news/v623-end-of-world-edition/), version v6.2.3 dates from 2012, so you had a version that was more than a decade old!


If a convex function is divided by a linear function, what will it be?

Question: I have a convex function $f(x)$ and a linear function $g(x)$. Is $\frac{f(x)}{g(x)}$ still convex? If it is not, can I use the techniques in convex optimization to optimize $\frac{f(x)}{g(x)}$?
Comment: Have you at least tried an example like $f(x) = e^x$ and $g(x) = x$?
Answer: $f(x)=x^4$ is a convex function, and $g(x)=x$ is linear, but $\frac{f(x)}{g(x)} = x^3$ which is not convex
Comment: Thank you very much. So if I have a fractional function that may not be convex, can I add some constraints or do something else to make it able to solve with convex optimization?


$x(e^x - e^{-x})-e^x = 0$ has two reals solutions but am I supposed to use the intermediate value theorem?

Question: Recently I've stumbled across a problem asking how many real solutions there was to $x(e^x-e^{-x})-e^x = 0 $, the answer is at least two, and it's easy to verify when plotting the function. However, in exams conditions, I would not have the opportunity to plot and was wondering if there is an "easy" way to find it?
Personally, I did use the intermediate values theorem. But here's the problem. I found that there was a $x_0 \in \mathbb{R}$ where $f(x_0)$ was negative and two values such as $ a < x_0 < b$ where $f(a) > 0$ and $f(b) > 0$
I think it's okay but I would be glad if there was a better way, not relying on roughly knowing how much $e^2$, etc is equal to. In this case it was fairly easy to find the values but it's always stressing me out to think I could've not think of a specific value.
Comment: It could be a good idea to divide the equality by $e^x$ first. This can be done, since $e^x$ cannot be $0$
Comment: Yeah that's a nice idea to simplify it at first thanks you
Answer: Your problem is equivalent than showing that $$f(x):=x(1-e^{-2x})=1,$$
has several solutions. It's rather clear that  $f(0)=0$ and $f(x)\to +\infty$ whenever $x\to \pm \infty $. So, oblviously, $f(x)=1$ has at least two solutions. It's also quite clear that $f(x)=1$ has exactly two solutions since $f'(x)<0$ whenever $x<0$ and $f(x)>0$ whenever $x>0$.
Comment: Way more clear that way thanks you, I didn't not thought of making the function easier to visualize !


How can I add cookies to Seaside responses without redirecting?

Question: I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output?
I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie.
Is there another way that already exist to add a cookie that will go out on the next response?
Answer: There is currently no built-in way to add cookies during the action/callback phase of request processing. This is most likely a defect and is noted in this issue: http://code.google.com/p/seaside/issues/detail?id=48
This is currently slated to be fixed for Seaside 2.9 but I don't know if it will even be backported to 2.8 or not.
Keep in mind that there is already (by default) a redirection between the action and rendering phases to prevent a Refresh from re-triggering the callbacks, so in the grand scheme of things, one more redirect in this case isn't so bad.
If you still want to dig further, have a look at WARenderContinuation>>handleRequest:. That's where callback processing is triggered and the redirect or rendering phase begun.
Edited to add:
The issue has now been fixed and (in the latest development code) you can now properly add cookies to the current response at any time. Simply access the response object in the current request context and add the cookie. For example, you might do something like:
<code>self requestContext response addCookie: aCookie
</code>
This is unlikely to be backported to Seaside 2.8 as it required a fairly major shift in the way responses are handled.
Comment: I'm not so worried about the redirections as the flow of control in the code. Thanks, :)
Answer: I've just looked into this in depth, and the answer seems to be no.  Specifically, there's no way to get at the response from the WARenderCanvas or anything it can access (it holds onto the WARenderingContext, which holds onto the WAHtmlStreamDocument, which holds onto the response's stream but not the response itself).  I think it would be reasonable to give the context access to the current response, precisely to be able to set headers on it, but you asked if there was already a way, so: no.
That said, Seaside does a lot of extra redirecting, and it doesn't seem to have much impact on the user experience, so maybe the thing to do is to stop worrying about it seeming kludgey and go with the flow of the API that's already there :)
Comment: I was trying to figure out how one component could handle the request then render a different component. Having to redirect first then render the other component adds an extra step in the design of the code. Oh well, I'm still learning.  Thanks, :)


Arquivo com caracteres estranhas

Question: Eu tenho uma string que recebe um valor de entrada pelo teclado e um arquivo que contem uma string. O que preciso fazer é comparar a string digitada com a string do arquivo e conferir se são iguais, mas fui ver que tipo de string do arquivo estava tirando e tava vindo com caracteres estranhos (botão de play, '@' e seta pra baixo). O código em tese parece funcionar, contudo gostaria de saber porque a string que estou trazendo pra comparar com a digitada pelo usuário está vindo com esses caracteres.
<code>#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>

main()
{

setlocale(LC_ALL,"portuguese");

FILE *arquivo;
char frase[6];
char frase2[6];
int i;

if(arquivo = fopen("teste.txt", "r") == NULL)
{
    puts("ERRO! IMPOSSÍVEL ABRIR O ARQUIVO");
}
else
{
    printf("Digite a frase: \n");
    gets(frase);

    fgets(frase2, 6, arquivo);
    puts(frase2);

    if(i = strcmp(frase, frase2) == 0)
    {
        puts("Encontrado");
    }
    else
    {
        puts("Não encontrado");
    }

}

fclose(arquivo);
getch();
return 0;
}
</code>
Comment: O que tem no arquivo?
Comment: O arquivo possui o nome "Lucas", ou seja, quando o usuário digitar string no teclado, é para fazer uma comparação. Contudo, quando eu puxo essa string do arquivo para ver o que está acontecendo sai umas caracteres todas estranhas. Ai então o programa sempre diz "Não Encontrado". Já verifiquei e o arquivo tá com texto ANSI e mesmo assim não adiantou.
Answer: <code>#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>

main(){

    setlocale(LC_ALL,"portuguese");

    FILE *arquivo;
    char frase[6];
    char frase2[6];
    int i;

    if(arquivo = fopen("teste.txt", "r") == NULL)//Uma estrutura
    //condicional só aceita valores boleanos e você está atribuindo
    //então coloque assim

    //arquivo = fopen("teste.txt", "r");

    //if(arquivo == NULL)
   {
        puts("ERRO! IMPOSSÍVEL ABRIR O ARQUIVO");
   }else{
        printf("Digite a frase: \n");
        gets(frase);//não é recomendável usar gets() pois não terá uma
        //controle sobre o tamanho da string que o usuário digitar

        fgets(frase2, 6, arquivo);
        puts(frase2);

        if(i = strcmp(frase, frase2) == 0)//como disse antes sem atribuição em
        //estruturas condicionais, tire o 'i' e como ele não irá servir para nada
        //no código apague ele lá no ínicio

        //if(strcmp(frase, frase2)){
            puts("Encontrado");
        }else{
            puts("Não encontrado");
        }

    }

    fclose(arquivo);
    getch();//getchar();

    return 0;
}
</code>
Acho que não tem mais erros.
Comment: Muitíssimo obrigado! Esse daqui me deu uma dor de cabeça!

Arquivo com caracteres estranhas


Why is Rubygems still installing docs when I told it not to?

Question: I have this in my ~/.gemrc file:
---
:backtrace: false
:benchmark: false
:bulk_threshold: 1000
:sources:
- http://gems.github.com
- https://rubygems.org
- https://rails-assets.org
:update_sources: true
:verbose: true
:gem: --no-document

It took literally about 8 minutes to install sinatra, because of the ri documentation.  (I have the clock time in my prompt, so I'm not just taking a wild guess.)  How can I fix this so that it actually obeys my ~/.gemrc file?
Answer: Remove the leading : from :gem:.
Comment: Removing the leading `:` turns the key from a symbol to a string after YAML parses the file. Unfortunately gem isn't consistent with the naming of the variables; Some are symbols and some are strings. http://guides.rubygems.org/command-reference/


Getting a specific part of a value out of a dictionary value

Question: Here is my dictionary:
article_names = {'AppliedEthics': (14, ['Ngaiklin', 'ip:pD950754B.dip.t-dialin.net']),
'Anarchism': (406, ['Bobdobbs1723', 'Brion_VIBBER', 'DanKeshet', 'David_depaoli',
'Eclecticology', 'Graft', 'Lee_Daniel_Crocker', 'Peter_Winnberg', 'Quercusrobur',
'The_Cunctator', 'Tzartzam', 'ip:18.104.22.168', 'ip:220.127.116.11', 'ip:18.104.22.168',
'ip:220.127.116.11']), 'AmericanSamoa': (14, ['Ngaiklin', 'ip:office.bomis.com']),
'AccessibleComputing': (14, ['Ngaiklin', 'RoseParks'])}

As you see it's in the format of article_names[name]:([number of edits], [n users who edited it])
I want to take the second part of the value for each dictionary key (Aka the part in brackets after the number), and turn it into a count of users before depositing them back into a different dictionary. I have been stumped on this for a while now, and I didn't sleep last night so I'm sure it's easy but I'm beat.
Example of what I'm trying to process it into:

Anarchism                             [15] (number of users who edited the article)
AppliedEthics                         [2]
AmericanSamoa                         [2]
AccessibleComputing                   [2]

I have this function that works fine for my other data sets, because they're not dicts and I can't for the life of me convert this thing to something easier to work with... I feel stupid.
def formatter(sorted, type, edit_var, ID): #ID is just to identify if it's that god forsaken dict
    count = 0
    print()
    for line in sorted:
        count+=1
    print("Printing the top {} {} in regards to {}:\n ".format(count, type, edit_var))
    print("{:37} {:4}".format(37*"-", 4*"-"))
    for line in sorted:
        print("{:37} {}".format(line[0], line[1]))

Answer: You can do this with tuple unpacking:
for k, (num, users) in article_names.items():
    print k, len(users)

article_names.items() turns it into a list of tuples:
article_names.items()
# [('AppliedEthics', (14, ['Ngaiklin', 'ip:pD950754B.dip.t-dialin.net'])), ('Anarchism', (406, ['Bobdobbs1723', 'Brion_VIBBER', 'DanKeshet', 'David_depaoli', 'Eclecticology', 'Graft', 'Lee_Daniel_Crocker', 'Peter_Winnberg', 'Quercusrobur', 'The_Cunctator', 'Tzartzam', 'ip:18.104.22.168', 'ip:22.214.171.124', 'ip:126.96.36.199', 'ip:220.127.116.11'])), ('AmericanSamoa', (14, ['Ngaiklin', 'ip:office.bomis.com'])), ('AccessibleComputing', (14, ['Ngaiklin', 'RoseParks']))]

which means each item will look something like:
('AppliedEthics', (14, ['Ngaiklin', 'ip:pD950754B.dip.t-dialin.net']))

and k, (n, users) parses out those three parts into three variables.
Answer: Ok, so you effectively want to return the length of that list of editors. You can do this with a dictionary comprehension:
>>> from pprint import pprint
>>> edits = {k: [len(edits)] for k, (num, edits) in article_names.items()}
>>> pprint(edits)
{'AccessibleComputing': [2],
 'AmericanSamoa': [2],
 'Anarchism': [15],
 'AppliedEthics': [2]}

A nice easy one-liner; and it seems to be the desired output that you specified in your question. This works because each value is a tuple, and the list of editors is the second item of that tuple.
Answer: to return the number of editor you need to get the length of the list of editors inside a tuple inside a dictionary and it is done like this example:
I am using the same dict you suggested:
mydict = {'AppliedEthics': (14, ['Ngaiklin', 'ip:pD950754B.dip.t-dialin.net']),'Anarchism': (406, ['Bobdobbs1723', 'Brion_VIBBER', 'DanKeshet', 'David_depaoli', 'Eclecticology', 'Graft', 'Lee_Daniel_Crocker', 'Peter_Winnberg', 'Quercusrobur', 'The_Cunctator', 'Tzartzam', 'ip:188.8.131.52', 'ip:220.127.116.11', 'ip:220.127.116.11','ip:22.214.171.124']), 'AmericanSamoa': (14, ['Ngaiklin', 'ip:office.bomis.com']),'AccessibleComputing': (14, ['Ngaiklin', 'RoseParks'])}
for key in mydict:
    print key, [len(mydict[key][1])]

you will get as an output:
AppliedEthics [2]
Anarchism [15]
AmericanSamoa [2]
AccessibleComputing [2]

Comment: With this, I get "length = [(key,len(mydict[key][1])) for key in mydict]
TypeError: 'int' object is not subscriptable" thrown at me. I'm on python 3.3.3 so I did my best to adjust for that too. I assume somewhere else in my program something is being made an int and it's messing things up?
Comment: I tested my code on python 2.7.2, no idea where does this error come from. here is an online python interpreter: http://repl.it/languages/Python
Comment: I'm required to use 3.3.3 :( I don't doubt that it works! It's similar to the things I've been trying but unfortunately the differences between 2.x and 3.x have been ruining my efforts in this regard
Comment: here is a reference for python 3.3, len(s) check it out: http://docs.python.org/3.3/library/functions.html#len
Comment: I tested it on python 3.3.2 and it works fine just by adding ( ) to the print function. that's as far as i can help :) good luck.
Comment: It turns out I had code that resulted in the dict being formatted partially BEFORE it got to the format function because when I print it at the beginning of it it looks like:
    article_names: {'AccessibleComputing': 2, 'AppliedEthics': 2, 'Anarchism': 15, 'AmericanSamoa': 2}

still, trying to print("{:31} {}".format(key, mydict[key][1])) still raises a "typeError: 'int' object is not subscriptable" :(
Comment: Update: I figured it out thanks to you :) Thank you! I had some weird redundant code that was messing things up
Answer: If you want to store the result in a list of tuples:
[(i,len(d[i][1])) for i in d]

and in a dictionary:
{i:len(d[i][1]) for i in d}


How do i prove f(0) = 0 (Calculus problem)

Question: I need some help to get started with this question.
$$f(x) + \ln(1+f(x)) = \frac{\sin x}{1+x}$$
Show $f(0) = 0$ and use that to find $f'(0)$.
Where do i start to show $f(0) = 0$? $f(x)$ inside $\ln(1+f(x))$ is confusing me a a lot.
Comment: The right side is $0$ for $x=0$, so you have $f(0)+\ln(1+f(0))=0$. Now, show that $r+\ln(1+r)=0$ has only the solution $r=0$ in the reals.
Answer: For $x=0$, you get
$$f(0)+\ln(1+f(0))=0$$
so $f(0)$ is solution of the equation $y+\ln(1+y)=0$. Now, the function $g : y \mapsto y +\ln(1+y)$ is strictly increasing on its domain, so it is injective. Moreover, $g(0)=0$, so $0$ is the only solution to $g(0)=0$. So
$$f(0)=0$$


What does views_ensure_table() do?

Question: I see it often, $this->ensure_my_table() and I'm not sure what it does and why it is important when building Views handlers.
Answer: Taken from the API page:
views_handler::ensure_my_table

Ensure the main table for this handler is in the query. This is used a
  lot.

It's just to make sure that the base table (node or user for example) that your handler needs is referenced in the query/actually exists.

What does views_ensure_table() do?


C# XML Serialization array and multiple class

Question: Ihave problem with serialization XML and dont know how to bite it..
My xml file should look like this:
<?xml version="1.0" encoding="utf-8"?>
<ItemBag>
     <Bag>
         <BagConfig Name="txt" ZenDrop="0" ItemRate = "100" ExcRate="100" AncientRate="0" SocketRate="0"/>
     </Bag>
     <Default>
         <DefaultConfig cat="1" id="1" minlv="0" maxlv="15" skill="1" luck="1" addopt="0" exc= "0" anc="0" sock="0" />
     </Default>
     <Items>
         <Item cat="1" id="1" minlv="0" maxlv="15" skill="1" luck="1" addopt="0" exc="0" anc="0" sock="0" />
         <Item cat="7" id="21" minlv="7" maxlv="7" skill="0" luck="0" addopt="0" exc="1" anc="0" sock="0" />
         <Item cat="8" id="21" minlv="7" maxlv="7" skill="0" luck="0" addopt="0" exc="1" anc="0" sock="0" />
         <Item cat="9" id="21" minlv="7" maxlv="7" skill="0" luck="0" addopt="0" exc="1" anc="0" sock="0" />
     </Items>
</ItemBag>

Here is my Serializable class:
[System.SerializableAttribute()]
        [System.Xml.Serialization.XmlTypeAttribute()]
        [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
        public partial class ItemBag
        {
            public ItemBagBag Bag;

            public ItemBagDefault Default;

            [System.Xml.Serialization.XmlArrayItemAttribute("Item", IsNullable = true)]
            public ItemBagItem[] Items;
        }

        [System.SerializableAttribute()]
        [System.Xml.Serialization.XmlTypeAttribute()]
        public partial class ItemBagBag
        {

            public ItemBagBagBagConfig BagConfig;
        }

        [System.SerializableAttribute()]
        [System.Xml.Serialization.XmlTypeAttribute()]
        public partial class ItemBagBagBagConfig
        {

            [System.Xml.Serialization.XmlAttributeAttribute()]
            public string Name;

            [System.Xml.Serialization.XmlAttributeAttribute()]
            public sbyte ZenDrop;
            //.......ETC
        }

        [System.SerializableAttribute()]
        [System.Xml.Serialization.XmlTypeAttribute()]
        public partial class ItemBagDefault
        {

            public ItemBagDefaultDefaultConfig DefaultConfig;
        }

        [System.SerializableAttribute()]
        [System.Xml.Serialization.XmlTypeAttribute()]
        public partial class ItemBagDefaultDefaultConfig
        {
            [System.Xml.Serialization.XmlAttributeAttribute()]
            public sbyte cat;

            [System.Xml.Serialization.XmlAttributeAttribute()]
            public sbyte id;
         //........ETC
        }

        [System.SerializableAttribute()]
        [System.Xml.Serialization.XmlTypeAttribute()]
        public partial class ItemBagItem
        {

            [System.Xml.Serialization.XmlAttributeAttribute()]
            public sbyte cat;

            [System.Xml.Serialization.XmlAttributeAttribute()]
            public sbyte id;
       //.......ETC
        }

Here is Serializable method
    static void SerializationToXml()
    {

        XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
        namespaces.Add(string.Empty, string.Empty);

        ItemBag item = new ItemBag()

        {
            Bag = new ItemBagBag
            {
                BagConfig = new ItemBagBagBagConfig
                { AncientRate = 1, ZenDrop = 1, ExcRate = 1, ItemRate = 1, Name = "ss", SocketRate = 1 }
            },
            Default = new ItemBagDefault
            {
                DefaultConfig = new ItemBagDefaultDefaultConfig
                { addopt = 1, anc = 1, cat = 1, exc = 1, id = 1, luck = 1, maxlv = 1, minlv = 1, skill = 1, sock = 1, Value = "1" }
            },
            Items = new ItemBagItem[]
            {
                //doesent work :(
            }

        };
  TextWriter writer = new StreamWriter(@"c:\test.xml");
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ItemBag));
                serializer.Serialize(writer, item, namespaces);
                writer.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
        }

I don't know how to make working an Array of Items (Bag and Default parsing OK)
I count for Your help
Comment: Also you can look at http://stackoverflow.com/questions/1212742/xml-serialize-generic-list-of-serializable-objects
Answer: Did you a favor and tidied things up... working nice too.
Code here:
internal class Program
    {
        private static void Main(string[] args)
        {
            ItemBag item = new ItemBag()
            {
                Bag = new Bag
                {
                    BagConfig = new BagConfig { AncientRate = 1, ZenDrop = 1, ExcRate = 1, ItemRate = 1, Name = "ss", SocketRate = 1 }
                },
                Default = new Default
                {
                    DefaultConfig = new DefaultConfig { Addopt = 1, Anc = 1, Category = 1, Exc = 1, ID = 1, Luck = 1, MaxLevel = 1, MinLevel = 1, Skill = 1, Sock = 1 }
                },
                Items = new List<Item>()
                {
                    { new Item { Addopt = 1, Anc = 1, Category = 1, Exc = 1, ID = 1, Luck = 1, MaxLevel = 1, MinLevel = 1, Skill = 1, Sock = 1 }}
                }
            };

            string serialized = item.XmlSerialize();

            Console.WriteLine(serialized);
            Console.ReadLine();
        }
    }

    [XmlRoot]
    public class ItemBag
    {
        public Bag Bag { get; set; }

        public Default Default { get; set; }

        [XmlArray("Items")]
        [XmlArrayItem("Item")]
        public List<Item> Items { get; set; }

        public ItemBag()
        {
            Bag = new Bag();
            Default = new Default();
            Items = new List<Item>();
        }
    }

    public class Bag
    {
        public BagConfig BagConfig { get; set; }

        public Bag()
        {
            BagConfig = new BagConfig();
        }
    }

    public class BagConfig
    {
        [XmlAttribute]
        public string Name { get; set; }

        [XmlAttribute]
        public int ZenDrop { get; set; }

        [XmlAttribute]
        public int ItemRate { get; set; }

        [XmlAttribute]
        public int ExcRate { get; set; }

        [XmlAttribute]
        public int AncientRate { get; set; }

        [XmlAttribute]
        public int SocketRate { get; set; }
    }

    public class Default
    {
        public DefaultConfig DefaultConfig { get; set; }

        public Default()
        {
            DefaultConfig = new DefaultConfig();
        }
    }

    public class DefaultConfig
    {
        [XmlAttribute("cat")]
        public int Category { get; set; }

        [XmlAttribute("id")]
        public int ID { get; set; }

        [XmlAttribute("minlv")]
        public int MinLevel { get; set; }

        [XmlAttribute("maxlv")]
        public int MaxLevel { get; set; }

        [XmlAttribute("skill")]
        public int Skill { get; set; }

        [XmlAttribute("luck")]
        public int Luck { get; set; }

        [XmlAttribute("addopt")]
        public int Addopt { get; set; }

        [XmlAttribute("exc")]
        public int Exc { get; set; }

        [XmlAttribute("anc")]
        public int Anc { get; set; }

        [XmlAttribute("sock")]
        public int Sock { get; set; }
    }

    public class Item
    {
        [XmlAttribute("cat")]
        public int Category { get; set; }

        [XmlAttribute("id")]
        public int ID { get; set; }

        [XmlAttribute("minlv")]
        public int MinLevel { get; set; }

        [XmlAttribute("maxlv")]
        public int MaxLevel { get; set; }

        [XmlAttribute("skill")]
        public int Skill { get; set; }

        [XmlAttribute("luck")]
        public int Luck { get; set; }

        [XmlAttribute("addopt")]
        public int Addopt { get; set; }

        [XmlAttribute("exc")]
        public int Exc { get; set; }

        [XmlAttribute("anc")]
        public int Anc { get; set; }

        [XmlAttribute("sock")]
        public int Sock { get; set; }
    }

And you can use this extension method:
///
        /// Serializes the specified System.Object and returns the serialized XML
        ///
        /// <typeparam name="T">This item's type</typeparam>
        /// <param name="item">This item</param>
        /// <param name="removeNamespaces">
        ///     <para>Specify whether to remove xml namespaces.</para>para>
        ///     <para>If your object has any XmlInclude attributes, then set this to false</para>
        /// </param>
        /// <returns>Serialized XML for specified System.Object</returns>
        public static string XmlSerialize<T>(this T item, bool removeNamespaces = true)
        {
            object locker = new object();

            XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
            xmlns.Add(string.Empty, string.Empty);

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            lock (locker)
            {
                StringBuilder stringBuilder = new StringBuilder();
                using (StringWriter stringWriter = new StringWriter(stringBuilder))
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
                    {
                        if (removeNamespaces)
                        {
                            xmlSerializer.Serialize(xmlWriter, item, xmlns);
                        }
                        else { xmlSerializer.Serialize(xmlWriter, item); }

                        return stringBuilder.ToString();
                    }
                }
            }
        }

put the extension method into a static class somewhere..
Comment: Thank You for Cleaning my code... Now i am able to understand what i've done wrong :) . Thanks again for tips and help !


Qual o equivalente do mysql_result no mysqli?

Question: Como posso fazer um FOR em php usando mysqli?
Pois eu sempre consegui fazer isso:
for($i=0; $i < $qtde; $i++){
   $pet_id = **mysql_result**($dadosPets, $i, 'animal_id');
}

Como eu faço o mesmo, porém, com mysqli?
Comment: @GustavoSevero mysql_* ou mysqli_*? Este Warning mostra mysql_*, E mysqli_result não existe nas funções mysqli_*,  veja pela qual ela foi substituída [neste link](http://php.net/manual/en/function.mysql-result.php)
Comment: GustavoSevero o link que o @coringa indicou está sim correto, veja que tem um trecho escrito `mysqli_data_seek() in conjunction with mysqli_field_seek() and mysqli_fetch_field()`, este é o exemplo correto, a função `data_seek`. Criei uma resposta.
Comment: Você pode pesquisar em sites do PHP sobre a documentação do mySQLi, pelo que saiba, mySQLi (my SQL improved) é uma versão aprimorada do SQL, então seus métodos e funções serão as mesmas, correto? Tente fazer isso com o mySQLi normal que deve funcionar.
Comment: Desculpe te informar @CypherPotato, mas isso não procede, pois já tentei e dá erro.
"Warning: mysql_result() expects parameter 1 to be resource, object given in /home/petsm976/public_html/php/default.php on line 164
"
Comment: @Coringa, eu estou usando mysql_, mas quero mudar para mysqli_
Comment: @Coringa, já olhei nesse link que vc indicou, mas não tem nenhum exemplo com FOR, todos são com WHILE.
Answer: O próprio link da documentação pode lhe ajudar http://php.net/manual/en/ (recomendo em inglês, pois as vezes a versão em portugues contem erros :/ )
Terá que usar:
http://php.net/manual/en/mysqli-result.data-seek.php
Um exemplo completo:
<?php
//Conecta
$mysqli = new mysqli("localhost", "usuario", "senha", "banco");

if (mysqli_connect_errno()) {
    printf("Erro de conexão: %s\n", mysqli_connect_error());
    exit;
}

$query = 'SELECT ...'; //Sua select

if ($result = $mysqli->query($query)) {
    for($i = 0; $i < $qtde; $i++) {
        if ($result->data_seek($i)) {
            $row = $result->fetch_assoc();

            //ID do pet
            $pet_id = $row['pet_id'];

        }
    }
    $result->close();
}

$mysqli->close();

Estilo procedural:
<?php
//Conecta
$link = mysqli_connect("localhost", "usuario", "senha", "banco");

if (!$link) {
    printf("Erro de conexão: %s\n", mysqli_connect_error());
    exit;
}

$query = 'SELECT ...'; //Sua select

if ($result = mysqli_query($link, $query)) {
    for($i = 0; $i < $qtde; $i++) {
        if (mysqli_data_seek($result, $i)) {
            $row = mysqli_fetch_assoc($result);

            //ID do pet
            $pet_id = $row['pet_id'];
        }
    }

    mysqli_free_result($result);
}

mysqli_close($link);

Comment: Vou tentar isso @GuilhermeNascimento, obrigado.
Comment: fui no link que vc passou, http://php.net/manual/en/mysqli-result.data-seek.php, e tentei usar o mesmo código, porém, procedural... Só não entendi como eu coloco o for... Pode me ajudar?
Comment: Valeu @GuilhermeNascimento, coloquei esse código procedural e apareceu a seguinte mensagem:
"Warning: mysqli_data_seek(): Couldn't fetch mysqli_result in /home/petsm976/public_html/php/default.php on line 167"
Comment: @GustavoSevero atualizei a resposta, veja que mudei duas linhas do código, teste de novo por favor.
Comment: Valeu @GuilhermeNscimento, nenhum erro aparece mais.
Só tento dar um echo na variável e ela não aparece hehehe
Comment: Sim, @GuilhermeNascimento, coloquei $pet_id = $row['pet_id'];, mas var_dump($data)? Que $data? hehehehe
Comment: Dei um var_dump($result), mas o resultado foi:

object(mysqli_result)#4 (5) { ["current_field"]=> int(0) ["field_count"]=> int(14) ["lengths"]=> array(14) { [0]=> int(1) [1]=> int(1) [2]=> int(4) [3]=> int(1) [4]=> int(1) [5]=> int(10) [6]=> int(1) [7]=> int(0) [8]=> int(1) [9]=> int(1) [10]=> int(1) [11]=> int(2) [12]=> int(12) [13]=> int(9) } ["num_rows"]=> int(4) ["type"]=> int(0) } object(mysqli_result)#4 (5) { ["current_field"]=> int(0) ["field_count"]=> int(14) ["lengths"]=> array(14) { [0]=> int(1) [1]=> int(1)...
Comment: Dei um var_dump($row) e apareceu isso:

array(14) { [0]=> string(1) "9" [1]=> string(1) "5" [2]=> string(4) "Tuti" [3]=> string(1) "2" [4]=> string(1) "1" [5]=> string(10) "2013-06-11" [6]=> string(1) "2" [7]=> string(0) "" [8]=> string(1) "2" [9]=> string(1) "1" [10]=> string(1) "1" [11]=> string(2) "RS" [12]=> string(12) "Porto Alegre" [13]=> string(9) "cruza 50%" } array(14) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> ...

Cara, esse var_dump com $row, apareceram, melhor, os dados.
Comment: @GustavoSevero eu editei o código da resposta, o correto é `mysqli_fetch_assoc` e não `mysqli_fetch_row`, foi engano meu.
Comment: Valeu @GuilhermeNascimento, agora os dados aparecem.
Answer: prefiro esse exemplo
notação Orientado à Objeto
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

notação procedural
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Comment: Olá Danley. Prefere porque esse meio? Apesar do exemplo citado na minha resposta mostrar mysqli_data_seek, não quer dizer que é útil usa-lo comparado "LIMIT", o mysqli_data_seek pode ser usado com intervalos, por exemplo: 1, 3, 5, 7 ou até intervalos aleatórios, 2, 7, 15, 17, 18, 24, controle dele é para "navegar" baseado pelo indice da forma que a pessoa desejar. De qualquer forma concordo que para o simples, o LIMIT é o que resolve ;)
Comment: Opa Guilherme, eu concordo que o seu exemplo permite mais lógicas e, consequentemente, atender a mais requisitos; eu prefiro o exemplo dessa resposta, porque facilita para casos em que você queira pegar todos os dados com mais facilidade. Mas, principalmente, porque é mais legível para quem tá iniciando com PHP. Só mais uma forma disponível para ajudar os iniciantes.


How to extract standard error from ARIMA output in R?

Question: After I run the arima function in R, I get an output that gives me the coefficients and the standard errors of the coefficients.  Pulling the coefficients is easy, you just do arima$coef.
How do I pull out the standard errors in the output of arima?
Answer: The help file suggests coef( ) to access the coefficients and vcov( ) to access the variance matrix. The standard errors of the coefficients would then be sqrt(diag(vcov( )).

coef: a vector of AR, MA and regression coefficients, which can be
  extracted by the coef method.
var.coef: the estimated variance matrix
  of the coefficients coef, which can be extracted by the vcov method.

Note that questions like this, which are solely about coding and not at all about statistics, are a better fit on stackoverflow.com than here on CrossValidated.  You're also more likely to get good help if you demonstrate that you've read the help files before posting.
Comment: ok i didn't know i had to sqrt diag the varcoef term
Comment: Wouldn't `sqrt(diag(vcov())` give you the standard deviation, not the standard error? If you want the standard error of the mean, you would still need to divide by the square root of the sample size.
Comment: @Elyce There are several problems with that, because the data in an ARIMA model are explicitly not independent.  As Aaron explains in this answer, `var.coef` estimates the variance matrix of the (estimated) coefficients: by definition, its diagonal elements are the *sampling variances* of the coefficient estimates; that is, they are the squares of the standard errors.


What does dx = dy mean formally?

Question: I have a circle with circumference $X$ and charge density $\lambda$ and have to find a potential at distance $a$ from the center. I understand how to do that, the physics way is to write $E_x = \dfrac{K\lambda a l}{(a^2+x^2)^{\dfrac{3}{2}}},$
and then say that this implies $\mathbb d E_x = \dfrac{K\lambda a}{(a^2+x^2)^{\dfrac{3}{2}}}\mathbb d l,$  and then integrate with respect to $\mathbb d l$ from $0$ to $2 \pi x$.
But what does $\mathbb dE = ... \mathbb d l$? mean mathematically
I tried to approach it with taking the total derivative of $E_x$ which would work only if I viewed $E_x$ as function of only $l$, because then I get
$\mathbb dE = \dfrac{\partial}{\partial l} (\dfrac{K\lambda a l}{(a^2+x^2)^{\dfrac{3}{2}}}) \mathbb d l = \dfrac{K\lambda a}{(a^2+x^2)^{\dfrac{3}{2}}} \mathbb d l .$
If I would take this approach (which I doubt works every time), then I have no idea how to integrate total differentials.
Am I on the right track at least? Or is there some part of math I am missing?
Comment: Your title is not clear.
Comment: It means they increase/decrease with the same rate (talking about $dx=dy$).
Comment: "$\mathbb dE = ... \mathbb d l$" signifies the electric field(dE) due to the small element of charge(dl).
Comment: Well I understand that, but I am trying to find a rigorous mathematical way how to perceive it. Like what theory is behind saying that if $\Delta E = f(x) \Delta x$, then $ \mathbb d E = f(x) \mathbb d x$.
Comment: You are basically right... You consider $E_x$ as a function of $l$ and you derive it. As you can see, the result contains again $x$.
Comment: @LukášMoudrý you'll find physicists are a little loose and fast with formality. In the end, every measurement is a rational number so considering everything an approximation more or less works.
Comment: @CyclotomicField I understand and know that. But usually there is some formal way behind what they do – and that is what I am trying to do.
Comment: You have to apply the operation to a function: $\dfrac {d}{dy}f(y)$ and $f(y)$ is a certain symbolic expression containing (among others) $y$.
Comment: @LukášMoudrý How do you define $dE$ formally?
Comment: @MauroALLEGRANZA Oh okay, that makes sense. But when I now take this to the disk I have something like $\Delta E = \frac {Ka \sigma \pi x^2 \Delta x}{(x^2+a^2)^{3/2}}$ and then doing $\frac{\mathbb d}{\mathbb d x} E$ results in something nasty. But doing it the physics way, you just differentiate $x^2$ to $2x \mathbb d x$, which still makes me confused from the math point of view.
Comment: @CyclotomicField Well that is something I am trying to find out, if there is any formal explanation.
Comment: It's the same as saying that the area of the annular disk of radius $r$ and width $\delta r$ is $ 2\pi r \delta r$. Integrating this expression in $r$ between $0$ and $R$ you get the area of the disk of radius $R$.
Comment: @LukášMoudrý I'm not sure there is a meaningful way to do this without appealing to the integral in the first place. I would note that Newton did all of his physics without understanding what he was doing and Euler built a mountain of analysis informally as well. Sometimes you can just go for it.
Comment: It means that the differential 1-forms $$\mathrm{d}E_x \qquad\text{and}\qquad \frac{K\lambda a}{(a^2+x^2)^{\frac{3}{2}}}\,\mathrm{d}l, $$ when they are restricted onto the submanifold $$M=\left\{(E_x,l)\in\mathbb{R}^2: E_x = \frac{K\lambda a l}{(a^2+x^2)^{\frac{3}{2}}} \right\}, $$ are identical. More intuitively, when $E_x$ and $l$ are restricted to the surface defined by the relation $E_x = (K\lambda a l)/(a^2+x^2)^{3/2}$ (with all the other variables frozen), they induce the same 'rates of change'.
Comment: This also means that, if you consider different relations or allow some other variables to vary, then they induce different submanifolds and hence the restrictions of the above 1-forms onto them can be no longer identical.
Comment: @SangchulLee Amazing! Thx! So to grasp the math behind it on deeper level, I have to go to manifolds and forms?
Comment: That's correct :) However, besides that the language of differential manifolds provides a rigorous justification of differential, I see no harm to leave this technicality as a 'black box' and proceed. The key idea is to know which relations you are working with, which will in turn determine the relations between the differentials. (In particular, seemingly the same notation may actually refer to different things if they came from unrelated or incompatible relations.)
Comment: @SangchulLee Well, yes, I could leave it as a blackbox, but my brain just wanna know :D Thx a lot again
Answer: I'm not 100% familiar with your example so I will answer with an equally valid example. Say you want to compute the area of the disk of radius $R$ and you only know the formula for the length of a circle of radius $R$ ($2\pi R$) and calculus.
One way is to draw the annulus between the disk of radius $r+\delta r$ and $r$ and compute its area. Here $\delta r$ is just a small quantity. I will be more precise later.
The area of this annulus is approximately given by
$$
\delta A = 2 \pi r \delta r .
$$
Note that strictly speaking the formula is wrong, and in fact it is only valid up to linear order in $\delta r$. To be more precise we should write
$$
\delta A = 2 \pi r \delta r + O(\delta r^2) .
$$
which tells us that the error of the first formula is of order $\delta r^2$. If we knew already the formula for the area of the disk we could write
$$
\delta A = \pi \big[ (r +\delta r)^2 -r^2 \big] = \pi (2r \delta r +\delta r^2 ),
$$
but we don't.
Now to find the area of the disk of radius $R$ you can simply integrate $ \delta A$ from $0$ to $R$. To be more precise what we are doing here is really evaluating the integral as a limit of Riemann sums.
$$
A(R) = \int_0^R dr 2 \pi r = \lim_{\delta r\to 0} \sum_j  2\pi r_j \delta r
$$
In this form it does not matter whether we use the first or second expression (or third) for $\delta A$ because the term $O(\delta r^2)$ contributes zero to the sum in the limit $\delta r\to 0$. (If you want to be explicit you can choose $\delta r = R/N$, $r_j= j \delta r$, $j=0,1,\ldots,N-1$.
Now we learn that the area is
$$
A(R) = \pi R^2
$$
You can indeed differentiate and  obtain
$$
\frac{dA}{dr} (r) = 2 \pi r
$$
which you can "interpret" as
$$
dA = 2\pi r dr.
$$
This very powerful interpretation, is allowed because, after Leibniz, we write the derivative as the limit of the incremental ratio.
In this context this is more than sufficient. In differential geometry one can say that $dr$ (and $dA$) are 1-forms but I would say this is beyond the scope of the question (one needs a definition of forms in the first place).
Answer: In the way you used it, it seems like $df = g\,dl$ means $\frac{\partial f}{\partial l} = g$. If $f$ is a function of more than one variable, this is not equivalent to the interpretation of $df$ as a one form.

What does dx = dy mean formally?


4th order differential equations with Bessel Function solutions

Question: I am working on a a 4th order linear PDE coming from the modified wave equation of a stiff material. I have radial symmetry which has lead me to a 4th order ODE in $r$:
$r^3 R''''(r) + 2r^2 R'''(r) - rR''(r)+R'(r) = m^4 r^3 R$
where $m^4$ is a constant. This ODE is subject to boundary conditions:
$|R(0)|<\infty$, $|R'(0)|<\infty$, $R''(R)=0$, $R'''(R)=0$,
where $R$ is the radius of my circle. I know that the solution should be in terms of Bessel functions as is typical of problems of this type. Mathematica gives solutions in terms of Bessel functions and Meijer G functions. Looking at the basic formulation (from wikipedia) of the Meijer G functions I do not see how this is obviously a solution (not implying it is obvious, I am implying that I do not see how it fits).
My first question is if someone can help me get to the Meijer G formulation or present to me useful information on how this DE relates to Meijer G functions. Secondly, is there anyway to rewrite this to get it in terms of Bessel functions (I do not think this is the case because they fulfill second order ODEs). Is the analytic solution of this easy (easy in terms of doable at a beginning graduate level) or is it very convoluted?
EDIT: I went back to the original formulation of the problem and found:
$\left( \frac{1}{r}\frac{d}{dr} \left\{ r \frac{d}{dr} \right\} \right) R(r) = m^4 R(r)$.
Now, instead of expanding, I found that I can consider this as two PDEs:
$\left( \frac{1}{r}\frac{d}{dr} \left\{ r \frac{d}{dr} \right\} \right) R(r) = k^2 R(r)$
and
$\left( \frac{1}{r}\frac{d}{dr} \left\{ r \frac{d}{dr} \right\} \right) R(r) = -k^2 R(r)$.
From this standpoint the solution becomes much easier to understand in terms of Bessel Functions. I will be posting a solution below.
Answer: Doraemonpaul's answer above is perfectly valid given the ODE originally suggested. However, a simpler method presents itself given the reformulation I have provided in the answers. For anyone interested, this is what I find.
We know that
$\left( \frac{1}{r}\frac{d}{dr} \left\{ r \frac{d}{dr} \right\} \right) R(r) = -k^2 R(r)$
has Bessel function solutions of the first and second kind, i.e. a linear combo of $J_0(kr)$ and $Y_0(kr)$ satisfies the above ODE. Because $n$ is an integer in the Bessel ODE we require both $J_0$ and $Y_0$ for a linearly independent solution. Next, note that
$\left( \frac{1}{r}\frac{d}{dr} \left\{ r \frac{d}{dr} \right\} \right) R(r) = k^2 R(r)$
is solved by a linear combo of $I_0(kr)$ and $K_0(kr)$, modified Bessel functions of the first and second kind. So, to solve
$\left( \frac{1}{r}\frac{d}{dr} \left\{ r \frac{d}{dr} \right\} \right) R(r) = m^4 R(r)$
we simply take a linear combination of all four. The general solution is given by
$R(r) = a_1 J_0(kr) + a_2 Y_0(kr) + a_3 I_0(kr) + a_4K_0(kr)$.
Then, we can apply boundary conditions. Noting that $Y_0(0)\rightarrow -\infty$ at the same rate as $K_0(0)\rightarrow \infty$ and that $J_0(0)=I_0(0)$, we require $a_2 = a_4$. The derivative yields
$R'(r) = -ka_1 J_1(kr) - ka_2 Y_1(kr) + ka_3 I_1(kr) - ka_2 K_1(kr)$.
Noting that $Y_1(0)$ and $K_1(0) \rightarrow \infty$ at the same rate, we find that $a_2 = a_4 \equiv 0$.
I will stop here, the other boundary conditions are easy to apply. You then get a second order system
$\left[\begin{array}{c c}
J_0(kR) - J_2(kR) & I_0(kR) + I_2(kR)\\
3J_1(kr) - J_3(kR) & 3I_1(kR) + I_3(kR) \\ \end{array} \right]$
$\left[\begin{array}{c}
a_1\\
a_3\end{array}\right]$
$=\left[\begin{array}{c}
0\\
0\end{array}\right]$
which can be solved numerically (unless anyone knows how to solve a coupled system of Bessel functions analytically? Or more specifically just the determinant. I would love to hear about it) to find allowable $kR$ values.
Answer: Perhaps the most direct approach should use the Frobenius method:
Let $R(r)=\sum\limits_{n=0}^\infty a_nr^{n+k}$ ,
Then $R'(r)=\sum\limits_{n=0}^\infty(n+k)a_nr^{n+k-1}$
$R''(r)=\sum\limits_{n=0}^\infty(n+k)(n+k-1)a_nr^{n+k-2}$
$R'''(r)=\sum\limits_{n=0}^\infty(n+k)(n+k-1)(n+k-2)a_nr^{n+k-3}$
$R''''(r)=\sum\limits_{n=0}^\infty(n+k)(n+k-1)(n+k-2)(n+k-3)a_nr^{n+k-4}$
$\therefore r^3\sum\limits_{n=0}^\infty(n+k)(n+k-1)(n+k-2)(n+k-3)a_nr^{n+k-4}+2r^2\sum\limits_{n=0}^\infty(n+k)(n+k-1)(n+k-2)a_nr^{n+k-3}-r\sum\limits_{n=0}^\infty(n+k)(n+k-1)a_nr^{n+k-2}+\sum\limits_{n=0}^\infty(n+k)a_nr^{n+k-1}=m^4r^3\sum\limits_{n=0}^\infty a_nr^{n+k}$
$\sum\limits_{n=0}^\infty(n+k)(n+k-1)(n+k-2)(n+k-3)a_nr^{n+k-1}+\sum\limits_{n=0}^\infty2(n+k)(n+k-1)(n+k-2)a_nr^{n+k-1}-\sum\limits_{n=0}^\infty(n+k)(n+k-1)a_nr^{n+k-1}+\sum\limits_{n=0}^\infty(n+k)a_nr^{n+k-1}-\sum\limits_{n=0}^\infty m^4a_nr^{n+k+3}=0$
$\sum\limits_{n=0}^\infty(n+k)(n+k-1)^2(n+k-2)a_nr^{n+k-1}-\sum\limits_{n=0}^\infty(n+k)(n+k-2)a_nr^{n+k-1}-\sum\limits_{n=0}^\infty m^4a_nr^{n+k+3}=0$
$\sum\limits_{n=0}^\infty(n+k)((n+k-1)^2-1)(n+k-2)a_nr^{n+k-1}-\sum\limits_{n=0}^\infty m^4a_nr^{n+k+3}=0$
$\sum\limits_{n=0}^\infty(n+k)^2(n+k-2)^2a_nr^{n+k-1}-\sum\limits_{n=4}^\infty m^4a_{n-4}r^{n+k-1}=0$
$k^2(k-2)^2a_0r^{k-1}+(k+1)^2(k-1)^2a_1r^k+(k+2)^2k^2a_2r^{k+1}+(k+3)^2(k+1)^2a_3r^{k+2}\sum\limits_{n=4}^\infty((n+k)^2(n+k-2)^2a_n-m^4a_{n-4})r^{n+k-1}=0$
$\therefore k^2(k-2)^2=0$
$k=0,2$
Can you take it from here?
Comment: Thank you so much @doraemonpaul, I had never been introduced to this powerful method before this! My only question is here I get two recurrence relations. I haven't gone through it yet, but I assume they are consistent in the series representation.


Are Delphi FireDAC shared connections thread safe

Question: I'm using Delphi 10.2.3 w/ FireDAC on a Firebird DB.  I have an event history table that gets updated asynchronously with external device events.  If the device count is high and the events frequent, there can be concurrent calls to the method that updates the DB with the event.  I'd like to wrap the update in a thread using a shared connection to accommodate the potential for these collisions.  I just want to confirm that FireDAC shared connections are thread-safe?
Comment: No. https://docwiki.embarcadero.com/RADStudio/Sydney/en/Multithreading_(FireDAC)
Comment: OK, thanks.  I'll switch to pooled connections.
Comment: I cannot get pooled connections to work - if I set Pooled=True, it throws an exception about extra parameters, including in the connection def editor in the IDE.  Is this a limitation of Firebird?
Comment: Found the problem: the connection definition had a `Driver=FB` line.  Removing that and letting the FireDAC code set the driver type allowed the connection.
Answer: No. An excerpt from the Delphi 10 online help topic Multithreading (FireDAC):

after a thread opens a query and until its processing is finished, the
application cannot use this query and the connection objects in
another thread. Similarly, after a thread starts a transaction and
until the transaction is finished, the application cannot use this
transaction and the connection objects in another thread.


Install specific git commit with pip

Question: I'm developing a django app and I'm using pip to manage my requirements. How can I do to install a specific git's commit?
In my case I need to install this commit:
https://github.com/aladagemre/django-notification/commit/2927346f4c513a217ac8ad076e494dd1adbf70e1
Answer: You can specify commit hash, branch name, tag.
For the branch name and the tag, you can also install a compressed distribution. This is faster and more efficient, as it does not require cloning the entire repository. GitHub creates those bundles automatically.
hash:
$ pip install git+https://github.com/aladagemre/django-notification.git@2927346f4c513a217ac8ad076e494dd1adbf70e1

branch-name
With git
$ pip install git+https://github.com/aladagemre/django-notification.git@cool-feature-branch

or from source bundle
$ pip install https://github.com/aladagemre/django-notification/archive/cool-feature-branch.tar.gz

tag
with git
$ pip install git+https://firstname.lastname@example.com

or from source bundle
$ pip install https://github.com/aladagemre/django-notification/archive/v2.1.0.tar.gz

It is a not well-documented feature, but you can find more information at https://pip.pypa.io/en/latest/topics/vcs-support/
Comment: It will add this fun message: `Could not find a tag or branch '2927346f4c513a217ac8ad076e494dd1adbf70e1', assuming commit.`
Comment: @vlad-ardelean any idea on how to tell pip IT IS a commit? This is getting outputed on my deploy script and I don't want to suppress all stderr.
Comment: In addition I would mention a HTTPS version of `git+` command: `pip install git+https://github.com/gpoore/codebraid@011464539bfb09b8611c8aef0d543532cea958bf`. It may be important for people behind corporate http proxies.
Comment: @ScottStafford You should not have a branch / tag which is called like a commit message. That would be ... strange.
Comment: @LeonardoArroyo that warning is no longer printed as long as you use the full 40 character hash with recent versions of pip. See: https://github.com/pypa/pip/pull/4674
Comment: The git+git://... version of this answer no longer works for GitHub effective today. Please see https://github.blog/2021-09-01-improving-git-protocol-security-github/
Comment: If you do not specify anything, what is the behavior?
Comment: You might not need the 'v' at the beginning of the tag name… If you see the `Could not find a tag or branch` consider removing the 'v' and trying again.
Answer: It's possible to automatically install a python package using the requirements.txt file on you project just by adding the following line:
package-name -e git+https://github.com/owner/repository.git@branch_or_commit#egg={package-name}
and run the command line:
$ pip install -r requirements.txt
Comment: For me (pip 9.0.1 in python3.5 virtualenv ) it didn't work : `pip install -r requirements.txt` raised 'Could not detect requirement name, please specify one with #egg='. But it worked with the format '-e git+https://github.com/owner/repository.git#egg=branch_or_commit'
Comment: I got it working but this is unclear.  Need to have "package_name -e ..." and not just "-e ..." at the start of the line.
Comment: The `package -e url` syntax was not working for me. I'm guessing this was meant to signify an editable build but, well, it was not installing from Github when I tried this. Merely specifying the actual `git+https://github.com/...` URL like in the accepted answer worked for me with pip 19.2.3 on Python 3.8.2
Comment: You need to use this format inside the requirements.txt file. Did you do that?
Comment: A working example, from a line in my requirements.txt:

`python-openid -e git+https://github.com/openid/python-openid.git@d093a0919198eb53826ae5753e517af10ad95d5b#egg={python-openid}`
Answer: An extra comment to @hugo-tavares's answer:
If it's a private GitHub repository, you'll need to use:
pip install git+ssh://email@example.com/....

In your case:
pip install git+ssh://email@example.com/aladagemre/django-notification.git@2927346f4c513a217ac8ad076e494dd1adbf70e1

Answer: If you want to create an egg package, you can still use the same @branch_or_commit appendage: pip install git+ssh://firstname.lastname@example.com/myrepo.git@mybranch#egg=myeggscript

Install specific git commit with pip


Fact that affine transformations carries convex sets to convex sets

Question: My question is: it is usually told us that affine transformations have that property but cuuouldnt this be generalized for all linear transformations? While proving that affine transformations have images of set convex sets convex we do the folliwing;
$$T(ap+(1-a)p)=aT(p)+(1-a)T(p)$$
If $o<a<1$ then image is also convex. Didn't I use the property of linear transformations while proving? Why it is stated that affine transformations carry convex sets to convex sets instead of saying linear transformations?
Comment: Saying that it holds for affine transformations is more general than saying it holds for linear transformations
Answer: That linear transformations preserve convexity is not a generalization of the fact that affine transformations do.  It's really the other way around.  You do use the property that linear transformations map convex sets to convex sets, and then combine this with the fact that an affine transformation is a just a linear transformation plus a translation.
First things first I'm a little confused about your notation; I think you're using $p$ as a double meaning and it causes your expression to simplify to an arithmetic tautology $T(p) = T(p)$ independent of any properties of $T$.
To be precise in why a linear transformation $T$ preserves convexity, I would argue as follows: pick two points $u,v$, in the image of $T$, and write them as $T(x), T(y)$ for $x, y$ in the domain of $T$.  Then convexity of the domain implies that $ax + (1-a)y \in Domain$ for all $a \in [0,1]$, and linearity implies the image of the line $ax + (1-a)y$ under $T$ is a line, $au + (1-a)v$, connecting $u$ and $v$ in the image.
Now an affine transformation is a slight generalization of a linear transformation.  It has to map linear objects to linear objects (lines go to lines, planes to planes...), like a linear transformation, but it doesn't have to respect subspaces (in particular we don't require $A(0) = 0$ for an affine transformation $A$).  So the important quality $T(ax + by) = aT(x) + bT(Y)$ doesn't hold for most affine transformations.  Indeed the simplest affine transformations are pure translation, $A(x) = c$, for which you can see linearity very much fails. But since you know that linear transformation preserve convexity and it's intuitive that translation should preserve convexity, you'd expect an affine map to still also preserve convexity.
When you replace $T$ with $A(x) = T(x) + c$ in the above, nothing much changes, but you will notice that there's formally a little bit more going on (some cancellation happens).  The points $u,v$ that we choose in the image have preimages under $A$ of $x,y$, i.e. $T(x) + c = u$, $T(y) + c = v$.  Then
$$A(ax + (1-a)y) = T(ax + (1-a)y) + c $$
$$= aT(x) + (1-a)T(y) + c = a(u-c) + (1-a)(v-c) + c$$
$$=au + (1-a)v$$.
So again, since the affine transformation $A$ maps lines to lines we are able to find a line between any two points of the image of $A$.


Derivative of $\log|...|$

Question: Can anyone help me in this: I'm trying to find the derivative with respect to $x$, where $x$ is real, for the following function
$$\log\left|1-\frac{x}{w}\right|$$
where $w$ is a nonreal number (complex number)?
Answer: Let $w=u+\imath\ v$, with $v\neq 0$.
Note that your $\log$ is the usual real logarithm, for its argument is a positive real number.
Hence, all you have to do is to compute the derivative (w.r.t. $x$ of course) of the real function:
$$f(x):=\log \sqrt{\frac{(u-x)^2+v^2}{u^2+v^2}} =\frac{1}{2}\ \log \Big( (u-x)^2+v^2\Big) - \frac{1}{2}\ \log \Big( u^2+v^2\Big)\; ,$$
which can be done using the usual chain rule.
Answer: Note that $$\left| 1 - \frac{x}{w} \right| = \sqrt{ \left(1- \frac{x}{w} \right) \left(1- \frac{x}{w^*} \right) }.$$
Thus, we have  (as we take the derivative later, we do not have to worry about the branches) $$\log \left| 1 - \frac{x}{w} \right| =
\frac12 \left[ \log\left(1- \frac{x}{w} \right) + \log\left(1- \frac{x}{w^*} \right) \right].  $$
Thus, the derivative is given by
$$ \frac{d}{dx}\log \left| 1 - \frac{x}{w} \right| = \frac{1}{2} \left[
\frac{w}{w-x} + \frac{w^*}{w^*-x} \right] = \frac{ \mathop{\rm Re} (w)  \,x - |w|^2}{ |w-x|^2}.$$

Derivative of $\log|...|$


Chords in MIDI?

Question: I'm looking for a way to represent chords in a MIDI file.
Note that I'm not looking to represent chord voicings.  That can be trivially done with multiple note-on messages.  But if I do that, then I have to do some sort of note-on to chord analysis every time I read the MIDI file back in, and that's a major nuisance especially since I already know the chord structures when I write the file.
Rather, I'm looking for something more akin to guitar tablature or fake books.  That is, I want to record "C" or "Cm" or "I" or "iii7" at a particular point in time.
So my questions...
Is there a standard way to do this?  (I'm not finding one, but I don't know the current spec thoroughly.)
Is there a non-standard way of doing this?
I'm considering using the "tag" facility of the lyric/display meta event.  It appears as though I can invent {@chord=Cm} and that should be transparent to any reader, past, present, or future, who doesn't understand this usage.  Am I reading the standard right?  Would this be a reasonable, essentially private, non-standard extension?
Answer: yeah, you're on the right track.  that should way should do fine.
all you need is the time, root, chord quality.  (maybe /bass)
although midi is a standard format, it's a really loose standard.
there's no standard way of storing fingering, for example.
so pick the best text event you can (which ya did).
other midi sequencers don't store chords exactly the same way, either.  which, i mean, really is pretty dumb.  you'ld think by now they could agree on a standard.  midi has been around since the 80s shoish.
Answer: The text event in a midi file does not contain absolute position of the text. It just contains text. Squeezing them between note events could work or you  could also mark the position of the start of the chord with the text event each time you have a chord change, but that is going well out of the way for this format. Midi strong suit is that it's lightweight and compact. The basic information about the instrument used, each note, the duration, and velocity are all at the core of midi. Any extra (meta) info is outside of the scope of what midi is for. Even key and time signature which are important for notation doesn't have an affect on the midi events themselves. Notation programs typically use them to display the midi events in a way that makes sense to musicians.
There are other file formats out there that may work better for you depending on what your goal is. If you just want to notate this then there are plenty of notation softwares out there that can do chord symbols fine in time like Finale, Sibelius, Musescore, and Lilypond. If you really just want a file format to hold this information for a project, MusicXML has a much better representation for chord symbols.
Comment: not sure what you mean by absolute position, but it has time for the event, and that's all ya need for a chord event, really

Chords in MIDI?


What's the difference between access a file and opening a file

Question: I have this doubt: ¿Wich are the differences between: open a file and access a file?
I'm working with fanotify, and I'm only interested on FAN_ACCESS events. I start my program and when I try to edit some file, the program does what it has to do.
Said that, I have wrote some tests, and some of test cases uses code like this:
filesystem::ofstream acces_to_file;
acces_to_file.open('/tmp/test_file.txt');
acces_to_file <<  "Some text" << endl;
acces_to_file.close();

but surprisingly, this access is no detected by my program. I access the same file from nano (even without restart the so mentioned program) and all works again.
Thats why I think it has to be some difference between access and open a file.
The program is always executed by root user.
I set the flags as following:
fanotify_mark(fd, FAN_MARK_ADD, FAN_ACCESS | FAN_EVENT_ON_CHILD, AT_FDCWD, MONITOR_ROOT_PATH);

Answer: In general, opening a file tells the OS you want to operate with the file.
In general, file access is how you operate with the file:  read only, write only, read & write.  Some access permission also include sequential or random.
Comment: So when I'm  writing to a file, I'm accessing an already opened file? It's that what you mean? Of course that's what you mean, What i'm thinking?? ;p
Comment: And [this](http://www.xypron.de/projects/fanotify-manpages/man2/fanotify_mark.2.html) says that `FAN_ACCESS` means the file was read from (which your example doesn't do)
Answer: What exactly are you asking? If you are asking about being able to Access the text file which you want to write to, where are you storing the text file? If you are storing the text file in a location that is read only, then writing to the text file will fail. It may still open the file and close it, but no writing will take place. For example, if your text file is located in the program file of your PC, you only have Read Access to items stored there. If you want Read/Write access to the file, store it in C:\Users\Default\AppData
Comment: Really? Why are you putting negative scores to my posts? I am trying to be helpful.


Generate and stream compressed file with Flask

Question: I am able to generate and stream text on the fly, but unable to generate and stream a compressed file on the fly.
from flask import Flask, request, Response,stream_with_context
import zlib
import gzip

app = Flask(__name__)

def generate_text():
    for x in range(10000):
        yield f"this is my line: {x}\n".encode()

@app.route('/stream_text')
def stream_text():
    response = Response(stream_with_context(generate_text()))
    return response

def generate_zip():
    for x in range(10000):
        yield zlib.compress(f"this is my line: {x}\n".encode())

@app.route('/stream_zip')
def stream_zip():
    response = Response(stream_with_context(generate_zip()), mimetype='application/zip')
    response.headers['Content-Disposition'] = 'attachment; filename=data.gz'
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)

Than using curl and gunzip:
curl http://127.0.0.1:8000/stream_zip > data.gz

gunzip data.gz
gunzip: data.gz: not in gzip format

I don't care if it is zip, gzip, or any other type of compression.
generate_text in my real code generates over 4 GB of data so I would like to compress on the fly.
Saving text to file, zipping, returning zip file, and than deleting is not the solution I'm after.
I need to be in a loop generating some text -> compress that text -> streaming compressed data until I'm done.
zip/gzip ... anything is fine as long as it works.
Answer: You are yielding a series of compressed documents, not a single compressed stream. Don't use zlib.compress(), it includes the header and forms a single document.
You need to create a zlib.compressobj() object instead, and use the Compress.compress() method on that object to produce a stream of data (followed by a final call to Compress.flush()):
def generate_zip():
    compressor = zlib.compressobj()
    for x in range(10000):
        chunk = compressor.compress(f"this is my line: {x}\n".encode())
        if chunk:
            yield chunk
    yield compressor.flush()

The compressor can produce empty blocks when there is not enough data yet to produce a full compressed-data chunk, the above only yields if there is actually anything to send. Because your input data is so highly repetitive and thus the data can be efficiently compressed, this yields only 3 times (once with 2-byte header, once with about 21kb of compressed data covering the first 8288 iterations over range(), and finally with the remaining 4kb for the rest of the loop).
In aggregate, this produces the same data as a single zlib.compress() call with all inputs concatenated. The correct mime-type for this data format is application/zlib, not application/zip.
This format is not readily decompressible with gzip however, not without some trickery. That's because the above doesn't yet produce a GZIP file, it just produces a raw zlib-compressed stream. To make it GZIP compatible, you need to configure the compression correctly, send a header first, and add a CRC checksum and data length value at the end:
import zlib
import struct
import time

def generate_gzip():
    # Yield a gzip file header first.
    yield bytes([
        0x1F, 0x8B, 0x08, 0x00,  # Gzip file, deflate, no filename
        *struct.pack('<L', int(time.time())),  # compression start time
        0x02, 0xFF,  # maximum compression, no OS specified
    ])

    # bookkeeping: the compression state, running CRC and total length
    compressor = zlib.compressobj(
        9, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0)
    crc = zlib.crc32(b"")
    length = 0

    for x in range(10000):
        data = f"this is my line: {x}\n".encode()
        chunk = compressor.compress(data)
        if chunk:
            yield chunk
        crc = zlib.crc32(data, crc) & 0xFFFFFFFF
        length += len(data)

    # Finishing off, send remainder of the compressed data, and CRC and length
    yield compressor.flush()
    yield struct.pack("<2L", crc, length & 0xFFFFFFFF)

Serve this as application/gzip:
@app.route('/stream_gzip')
def stream_gzip():
    response = Response(stream_with_context(generate_gzip()), mimetype='application/gzip')
    response.headers['Content-Disposition'] = 'attachment; filename=data.gz'
    return response

and the result can be decompressed on the fly:
curl http://127.0.0.1:8000/stream_gzip | gunzip -c | less

Comment: Migration to py3 https://gist.github.com/viewpointsa/b6be251d26af18456ad23841e56ddcb8
Comment: @themadmax: thanks for the poke; I've updated my post (clean-room style, so as to refresh my memory here, and updated the question too).
Answer: While I was extremely impressed by Martijn's solution, I decided to roll my own one that uses pigz for better performance:
def yield_pigz(results, compresslevel=1):
    cmd = ['pigz', '-%d' % compresslevel]
    pigz_proc = subprocess.Popen(cmd, bufsize=0,
        stdin=subprocess.PIPE, stdout=subprocess.PIPE)

    def f():
        for result in results:
            pigz_proc.stdin.write(result)
            pigz_proc.stdin.flush()
        pigz_proc.stdin.close()
    try:
        t = threading.Thread(target=f)
        t.start()
        while True:
            buf = pigz_proc.stdout.read(4096)
            if len(buf) == 0:
                break
            yield buf
    finally:
        t.join()
        pigz_proc.wait()

Keep in mind that you'll need to import subprocess and threading for this to work. You will also need to install pigz program (already in repositories of most Linux distributions -- on Ubuntu, just use sudo apt install pigz -y).
Example usage:
from flask import Flask, Response
import subprocess
import threading
import random

app = Flask(__name__)

def yield_something_random():
    for i in range(10000):
        seq = [chr(random.randint(ord('A'), ord('Z'))) for c in range(1000)]
        yield ''.join(seq)

@app.route('/')
def index():
    return Response(yield_pigz(yield_something_random()))

Comment: This is pointless, I'm afraid, there is no benefit to be had here. `pigz` works by divying up the input into separate blocks that can be compressed individually (into 128 KB chunks), but you are feeding it a *stream of data*, and doing so over a pipe. You are not going to be writing data fast enough for pigz to find more than a few blocks, *if that*, while adding the overhead of spinning up a separate process and passing data back and forth over pipes. You are spinning up a separate process for each request as well, which is a real drag on scalability.
Comment: Pigz is great when you have a local file you can read a whole series of chunks from from different blocks of the disk, and pass to each compression thread.
Answer: I think that currently you just sending the generator instead of the data!
You may want to do something like this (I haven't tested it, so may need some change):
def generate_zip():
    import io
    with gzip.GzipFile(fileobj=io.BytesIO(), mode='w') as gfile:
        for x in xrange(10000):
             gfile.write("this is my line: {}\n".format(x))
    return gfile.read()

Comment: That's the *whole point* of the generator; it is iterated over elsewhere. The issue is with using `zlib.compress()`. Your solution removes the ability to stream altogether.
Answer: Working generate_zip() with low memory consumption :) :
def generate_zip():
    buff = io.BytesIO()
    gz = gzip.GzipFile(mode='w', fileobj=buff)
    for x in xrange(10000):
        gz.write("this is my line: {}\n".format(x))
        yield buff.read()
        buff.truncate()
    gz.close()
    yield buff.getvalue()

Comment: This doesn't actually return any data until the last yield.
Comment: This yields 10k empty strings, then the whole document. This is also overkill. There is no need to keep separate file objects in memory, just stream the compression directly. If you do want to use a `GzipFile()` object, why not just capture the `write()` calls directly rather than use a `BytesIO()` object?
Comment: Your approach could only be fixed if you used `buff.getvalue()` in the loop (not `buff.read()`), used `buff.truncate(0)` (you are truncating to the current position, not to the start). To avoid yielding empty blocks, you may want to test if `buff.getvalue()` actually produced anything, and only yield and truncate if it did.


Ionic / Firebase - error splice is not a function (reorderArray)

Question: I have beat my head for a couple days...trying to use the  (ionItemReorder)="reorderItems($event)" to reorder a list.  I have a list of songs I'm getting from FireBase.  When I fire the reOrderItems click event I get an error: TypeError: array.splice is not a function at reorderArray
I assume it's probably something very simple in the way I'm defining "songs". I have tried several different ways...but at this point I'm just grasping at straws.
Any suggestions would be greatly appreciated.  Thank you!  ER
Typescript:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, reorderArray } from 'ionic-angular';
import { AngularFireModule} from 'angularfire2';
import { AngularFireDatabase } from 'angularfire2/database';

@IonicPage()
@Component({
  selector: 'page-songs',
  templateUrl: 'songs.html',
})
export class SongsPage {

  //songs: any = {};
  //songs = {};
  //songs = [];
  //songs: any = [];
  songs: any;
  btnName: any = 'Reorder';
  flag: any = false;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public afd: AngularFireDatabase
  )
  {
    this.songs = this.afd.list('/songs/').valueChanges();
  }

  //Button in navbar to toggle reordering the list of songs
  actionBtn(){
    if (this.btnName == 'Reorder') {
      this.btnName = 'Done';
      this.flag = true;
    }
    else{
      this.btnName = 'Reorder';
      this.flag = false;
    }
  };

  reorderItems(indexes){
    //let element = this.songs[indexes.from];
    //this.songs.splice(indexes.from, 1);
    //this.songs.splice(indexes.to, 0, element);
    this.songs = reorderArray(this.songs, indexes);
   };

  showChords(song){
    this.navCtrl.push('ChordsPage', song)
  }

}

HTML:
<ion-header>
  <ion-navbar>
    <ion-title>Songlist</ion-title>
    <ion-buttons end>
      <button ion-button small clear (click)="actionBtn();">
        {{btnName}}
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content>
    <ion-list reorder="{{flag}}" (ionItemReorder)="reorderItems($event)">
        <ion-item-sliding *ngFor="let song of songs | async ; let i = index">

          <ion-item>

{{i+1}}. {{ song.Title}}

{{song.Artist}}

          </ion-item>

          <ion-item-options side="right">
              <button ion-button (click)="showChords(song)">Chords</button>
            </ion-item-options>

            <ion-item-options side="left">
                <button ion-button color="danger" (click)="removeSong(song)">Delete
                  <ion-icon name="trash"></ion-icon>
                </button>
            </ion-item-options>

              </ion-item-sliding>
      </ion-list>
</ion-content>

Comment: where is the `reorderArray` function defined? oh i see in docs now
Comment: have you tried with `(ionItemReorder)="$event.applyTo(songs)"`?
Comment: ewizard...tried that...same error.  Thanks.
Comment: what happens if you take off the `.valueChanges()` (if it will still work without it...ive never used the method)
Comment: found this in docs: `Calling .valueChanges() returns an Observable without any metadata. If you are already persisting the key as a property then you are fine. However, if you are relying on $key, then you need to use .snapshotChanges() and transform the data with an observable .map().` so maybe try `.snapshotChanges()`?
Comment: Thanks...tried both of those didn't work.  I watched some videos last night and might be onto something ... it seems that the data might be coming back (or instantiated) as an Object and not an array ... I'm not smart enough to know the difference...but I may need to find out how to ensure (or test at least) whether 'songs' is an object or an array...and if object how to cast it into an array.
Comment: well with list it should be coming back as a `FirebaseListObservable` and then you can `subscribe` to that and access the items...and push them to `songs` - thats how i usually do it...ive never used `valueChanges()` or `snapsnotChanges()`
Answer: Subscribe to the Observable and map the items to be pushed into the songs array. Also, use the lifecycle hook ionViewDidLoad instead of the constructor for doing things at initialization.
import { AngularFireDatabase } from 'angularfire2/database';
import { ISubscription } from 'rxjs/Subscription';
import { OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';

...

export class ... implements OnDestroy {

    songslist: Observable<any[]>;
    subscription: ISubscription;
    songs: any[];

    constructor(...

    ionViewDidLoad() {

        this.songslist = this.afd.list<Item>('songs').valueChanges();
        this.subscription = songslist.subscribe(items => {
            return items.map(item => { this.songs.push(item); });
        });

    }

    ...

    reorderItems(...

    ...

    ngOnDestroy {
        this.subscription.unsubscribe(); // Make sure to unsubscribe, don't leave them open.
    }
}

Comment: Shoot..just my luck.  It looks like FirebaseListObservable was refactored in the latest version of FB: https://github.com/angular/angularfire2/blob/master/docs/version-5-upgrade.md

I will have to try to figure out how to convert your code to this ...thanks for all your help.  I feel like I'm very close.
Comment: yah i saw they updated a little bit ago...i havent used the new one yet
Comment: try what i have now
Comment: Still can't seem to make it work...fiddled with it for 5 hours today...many examples out on the web are using the older options...I thought I was in luck when I found this link: https://www.joshmorony.com/building-a-crud-ionic-2-application-with-firebase-angularfire/
Comment: That site looks like it was updated only a few day ago ... but it seems that it too has issues..seems it still uses the older method; someone made some changes to it but it's not complete. Doesn't work as written on the site.

If you could find it in your good graces it'd be really nice if you could create a blank project & a simple FB db and see if you could sort it out.  Thanks!!  ER
Comment: I think I have it working...I will update soon...thank you for all your help...I need to clean up all my code and post the final fixes.
Answer: Trying to accomplish something very similar - except with Firestore instead of the RealTime Database - had me wanting to bang my head against the wall, but finally got it working so hopefully it's helpful to you or others even though some things will be slightly different.
The array.splice is not a function error comes up when you are trying to perform the function on something that isn't an array, in this case the observable which for reasons beyond my understanding seems to be returned as a single object.
To get things working I declared each of these variables separately:
photoCollectionRef:AngularFirestoreCollection < PhotoSlide>;
photo$: Observable < PhotoSlide [] >;
photo = {} as PhotoSlide;
photoArray: any=[];

Then set each value as follows
this.photoCollectionRef = this.afs.collection('posts').doc(this.postId).collection('photos/', ref => ref.orderBy('index'));
this.photo$ = this.photoCollectionRef.valueChanges();

this.photo$.take(1).subscribe((pictures) => {
  pictures.forEach(p=>{
   return  this.photoArray.push({index:p.index, photoURL: p.photoURL, id:p.id })
  })
});

In the template file *ngFor loops over photo of photoArray (without an async pipe) and the reorderItem function called from the item group works perfectly with standard single line syntax from the ionic docs.
Then to update the indexes in the Firestore Collection, I call the below function from a button that's visible once the list order has been modified:
saveNewOrder(){
this.photoArray.forEach((element, i) => {
  this.photoCollectionRef.doc(element.id).update({
    index: i
  });
});

}
I should note that I also always use the .createId() method and then .doc(newId).set({id:newId etc}) when adding new documents rather than just .add because I find it a lot less annoying to do that than be stuck using .snapshotChanges and map function rather than just .valueChanges() - which is why the above functions work with the syntax shown
Also if you don't use the rxjs take(1) operator before the subscription it all looks fine at first but after the saveNewOrder function's executed the list repeats several times
Comment: Thank you very much for all this info ... I will look into it when I move to Firestore.
Answer: I am late getting back to this but here is my attempt at explaining how I got this working.
**Caveat - I am a hobbyist coder so I apologize in advance if I'm explaining using wrong terms or if I just understand it wrong..the code works:).
The goal is to get a list from Firebase using the NEW version of Firebase and pull it into an array so that I can present it to the screen and then use the reorderArray function to keep the array indexes in order after moving items around in a list.  So if I have an array of songs...I'll call it songList (think no Firebase yet) and assume this is my HTML:
<ion-list reorder="true" (ionItemReorder)="reorderItems($event)">
    <ion-item *ngFor="let song of songList; let i = index">
    {{i+1}}. {{song.title}} - {{song.artist}}
    </ion-item>
  </ion-list>

Then I have the standard function to reorder the array:
reorderItems(indexes) {
    this.songList = reorderArray(this.songList, indexes);
  };

Add the 'reorderArray' to the import to enable this:
import { NavController, AlertController, reorderArray } from 'ionic-angular';

After looking into this a little I think the reorderArray function does a few .splice commands to get the indexes moved around in the array.
So fast forward to replacing my array with a Firebase list.  See all the above code from the 1st post...all that works to get the list to show up on the HTML page.  But as soon as the reorderArray is fired I get "splice" errors thrown.  As it turns out the Firebase list at this point is an object and the reorderArray expects an array.  I got the below code from a Youtube video:
//Set up the songList array
    var x = this.afDatabase.list('/songs');
    x.snapshotChanges().subscribe(item => {
      this.songList = [];
      item.forEach(element => {
        var y = element.payload.toJSON();
        y["fbKey"] = element.key;
        this.songList.push(y);
      })
    })

I will try to explain as best I can what this is doing.  I set x to be a ref to my Firebase list /songs.  I invoke snapShotChanges() to get my list values and the key.  I then subscribe to the list to walk through the items.  I declare setList as an array.  I iterate over the list of items and I guess 'payload' is a special property that gets all the object data??  I think I cast all that object data into an array.  I add a new field to the list I think so I can get back at the .key value from a field?  I then push all that data into an array.
Again I'm not sure how all this magic works but it does.  Now I have an array in songList that holds all my data...and now I can use the reorderArray function to keep the indexes straight on the client side after a reorder.
But...new problem.  There is no client side representation of that index value out in the Firebase list.
The rest of this code is a little hazy as when things started working I was all over the map and adding lots of stuff to see it work.  Right now I'm having Ionic Serve issues and can't get this running right now without deploying it up to Firebase or Ionic View...so I have to go by memory.
So here is what my final HTML looks like:
<ion-list reorder="true" (ionItemReorder)="reorderItems($event)">
    <ion-item *ngFor="let song of songList | orderBy: 'sortOrder'; let i = index">
    {{i+1}}. {{song.title}} - {{song.artist}} ({{song.sortOrder}})
    </ion-item>
  </ion-list>

The only real difference here is that I have an orderBy on a new field called sortOrder.
Here's how all this works:
reorderItems(indexes) {
    var luTitle = '';
    var luArtist = '';

    this.songList = reorderArray(this.songList, indexes);

    this.songList.forEach( song => {
      this.afDatabase.database.ref('songs/' + song.fbKey + '/sortOrder').set(this.songList.indexOf(song));

      this.afDatabase.database.ref('songs/' + song.fbKey)
      .on('value', function(snapshot) {
        luTitle = snapshot.child('title').val();
        luArtist = snapshot.child('artist').val();
      })

      console.log("Index: " + this.songList.indexOf(song));
//      console.log("Title: " + song.title);
      console.log("LU Title: " + luTitle);
      console.log("LU Artist: " + luArtist);
      console.log("FB Key: " + song.fbKey);
      console.log("Sort Order: " + song.sortOrder);
    })
  };

A lot of this is just logging stuff to the console but the real work is this:
The first thing I do is run the reorderArray over the this.songList and it gets all the indexes in the right place on the client side.  Then I iterate over all the items in that array and I create a reference to the FB list using the song.fbKey that we set when we converted the initial FB list to an array.  Then I .set a sortOrder field for that song equal the the current index of that song as it exists on the client side at that moment in time.  Everything else I think after that is me logging stuff to the console to look at values.  The LU (Look Up) stuff was just me figuring out how to get a value back in from Firebase.
Now the orderBy in the ngFor immediately orders everything by the sortOrder field that basically comes in real time from FB.  I can't remember but I think if the list is brand new from FB and there is no sortOrder field yet it defaults to sorting by the key...which is fine...the first time reorder is fired all the sortOrders get set.
I'm sure there are some bugs I will discover when I get back to this...but it's working code as of now.
Thanks for reading if you made it this far.
ER


database not created in windows phone 8 using cordova sqLite plugin

Question: I am using html5 and cordova web sql and sqlite plugin for windows phone 8. i am using this
<code>var db = WebSocket.openDatabase("test", "Test DB", 2 * 1024 * 1024);
</code>
but it is not creating my database. please help
Comment: i also used
var db = window.openDatabase("test", "Test DB", 2 * 1024 * 1024);
var db = html5sql.openDatabase("test", "Test DB", 2 * 1024 * 1024);
var db = websql.openDatabase("test", "Test DB", 2 * 1024 * 1024);
Comment: Aren't you missing a parameter ? The third parameter is supposed to be a text message and not the size of the database. See: http://www.tutorialspoint.com/html5/html5_web_sql.htm
Comment: var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);

i also used this but the results are same
Comment: is it returning a null for db? I tried to execute var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); and it worked on chrome.
Comment: yes, it is returning null and i am running it in windows phone 8 using cordova 3.0.0
Comment: what kind of plugin do you use? have you already tried to run window.openDatabase instead of WebSocket.openDatabase?
Comment: i am using websql plugin on cordova for wp8 platform .I have already tried that one also
Answer: Please try using Microsoft Cordova Plugin for database. FYI, WebSql is not supported on windows phone 8 and above.


How can we Save and Restore transformation states in RaphaelJS

Question: I am using RaphaelJS for a project that requires vector drawing for visualization of some data.
I am not able to figure out how to push and pop transformation states.
(equivalent of context.save() and context.restore() in html5 canvas)
Can someone point me in the right direction?
thanks.
Answer: Could you explain why you need to push and pop transformation state?
In svg you don't really need to do that, the browsers do it for you. If you want a particular transform to apply to an element then just add a transform attribute to it. You can make a transform apply to many elements by using <g> elements (in Raphaël there's Paper.set, which can be used like a <g> element, and you have the Element.transform method to set the transforms).
Update:
context.save() - in svg terms this would be to take the current transformation matrix (CTM) of the element at a given time and storing it somewhere, in Raphaël I guess this might be Element.transform() (I'm not 100% sure if it includes whole stack of transformations or not, anyway, in pure svg the CTM can be fetched via the getCTM() method which is available on all elements). One way of doing this would be to insert a <g> element with the transformation you want.
context.restore() - in svg this would be equivalent to removing a transformation from the list of transforms, but note that in svg siblings don't "inherit" the transformation (this is unlike html5 canvas or OpenGL where the currently set matrix is just applied to anything you draw after setting the transform). If you want a transform to apply to many elements then you create a <g> which has the transformation that should apply to all the children of that element, and to restore you just insert elements to the parent of the <g> instead. Raphaël doesn't have any built-in support for the <g> element (unless you count Element.set, which is a similar concept), a guess for why Raphaël does this is that it's to prevent people from trying to do things like this since it becomes very easy to bloat the DOM without realizing it (remember, SVG is a retained mode graphics format, unlike canvas and OpenGL).
Comment: I need save() and restore() functionality because I want to write easily understandable code. Lets say, I want to draw a rectangle, and then want to draw a circle at an offset relative to rectangle (0, 50). But later, I want to draw another circle relative to that same rectangle somewhere relatively at (50,0). I have no way of saying go back to the state I was in when I drew the rectangle. Push() and Pop() would help me with that.
Comment: Someone who has some any opengl programming or HTML5 canvas programming would know why something like save() and restore() of transformation states is something we can't live without. Not sure why this isn't available in Raphael by default. I hope someone implements this.


Evaluate cos[(1/2)[arcsin(-3/5)]]. I'm not sure what i'm doing wrong.

Question: $x=\arcsin(-3/5), \; \sin x = -3/5$
**Drew a triangle to find $\cos x$
$\cos x = 4/5$
Now, I don't know what to do from here. I know I have to use a double angle formula, but when I evaluate the "$\frac{1}{2}\arcsin(-3/5)$," I get:
$\sin 2x = -3/5$
How do I continue using the double angle formula. $\sin2x = 2\sin x\cos x$ ?
Thanks for the help.
Answer: If $\arcsin\left(-\dfrac35\right)=y,-\dfrac\pi2<y<0\implies \cos y>0$
and $\cos\left[\dfrac12\arcsin\left(-\dfrac35\right)\right]=\cos\dfrac y2>0$
and $\sin y=-\dfrac35\implies\cos y=+\sqrt{1-\sin^2y}$
Now use $\cos y=2\cos^2\dfrac y2-1$
and we know $\cos\dfrac y2>0$
Comment: My friend told me about stackexchange(how it was a great website to get quick help.), and boy was he right. Thanks for the help! :D
Comment: @AdamReed, Welcome! See also : http://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Principal_values
Answer: From Pythagorus theorem
$$ \cos 2 \theta = 4/5 $$
$$ 2 \cos^2 \theta = (1 + \cos 2\theta ) $$
$$ \cos\theta = \frac{3}{\sqrt{10}}$$


Ubuntu transmits TTL 0 multicast packets

Question: IP packets with TTL 0 shall not leave host.
But when I start application which multicasts UDP packets with TTL 0, I see packets with TTL 0 leaving host for few seconds, and coming to normal behavior of TTL 0. This most likely happens after reboot and first start of application.
I confirmed packets with TTL 0 leaving host with tcpdump:
05:31:39.048304 IP (tos 0x0, id 14487, offset 0, flags [DF], proto UDP (17), length 1344)
    192.168.1.200.46968 > 184.108.40.206.1234: UDP, length 1316
05:31:39.049594 IP (tos 0x0, id 14488, offset 0, flags [DF], proto UDP (17), length 1344)
    192.168.1.200.46968 > 184.108.40.206.1234: UDP, length 1316
05:31:39.051601 IP (tos 0x0, id 14489, offset 0, flags [DF], proto UDP (17), length 1344)
    192.168.1.200.46968 > 22.214.171.124.1234: UDP, length 1316
05:31:39.053584 IP (tos 0x0, id 14490, offset 0, flags [DF], proto UDP (17), length 1344)
    192.168.1.200.46968 > 126.96.36.199.1234: UDP, length 1316

As we can see ttl is not displayed which means TTL 0, as confirmed from tcpdump man page: https://www.tcpdump.org/manpages/tcpdump.1.html (search ttl, it clearly indicated: ttl is the time-to-live; it is not reported if it is zero).
There are no any iptables rules running.
uname -a: Linux mydevice 4.15.0-101-generic #102-Ubuntu SMP Mon May 11 10:07:26 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
lsb_release -a:
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.4 LTS
Release:        18.04
Codename:       bionic

What can be the cause for this behavior, and how can I resolve this?
Answer: Solution is to join multicast group with
setsockopt(sockFd, IPPROTO_IP, IP_ADD_MEMBERSHIP, reinterpret_cast<const char*>(&mcastJoinReq), sizeof(ip_mreq))
before multicasting with sendto().
My assumption always has been that I don't need to join multicast when I have to only send multicast, i.e. I won't ever call recvfrom() to receive multicast. But regardless of only sending / only receiving, we have to join multicast.