Limit Converges to $1$ by some identity

Question: Let $x_n>0$ and satisfy
$$\lim_{n\to\infty}(x_n^8+x_n)=2.$$
Can we show that $x_n$ converges to $1$?
I could only bound $x_n$ by $2$...
Comment: Consider the polynomial $f(x) = x^8 + x -2$, can you prove $1$ is its only root over $(0, +\infty)$? Is $f(x)$ increasing?
Answer: Hints:

Let $p:x\mapsto x+x^8$, then the function $p$ is strictly increasing on $x\geqslant0$ with $p(1)=2$ and $p'(x)\geqslant1$ for every $x\geqslant0$
Thus, $|x-1|\leqslant|p(x)-2|$ for every $x\geqslant0$
Now, use that $p(x_n)\to2$ when $n\to\infty$ and that $x_n\geqslant0$ for every $n$
Comment: To say $|p(x)-2| < \varepsilon \Longrightarrow |x-1| < \varepsilon/20$, you rather need a minoration on $|p'|$
Comment: @user10676 Indeed, thanks for notifying me.
Answer: The function $f(x)=x^8+x$ has a positive derivative $8x^7+1$ and is continuously invertible.
If $f(x_n)$ converges to $2$, then $x_n$ converges to $f^{-1}(2)$.
Solve $x^8+x=2$, it has at most one positive solution.
Comment: Which assumes that $(x_n)$ *converges*.
Comment: As $x_n^8+x_n$ converges to some $y$ and $f(x)=x^8+x$ is invertible, $x_n$ converges to $f^{-1}(y)$.
Comment: In other words: this, which is missing from the post, needs some justification.

Limit Converges to $1$ by some identity


How to destroy swipe.js completely

Question: I am using swipe.js in a project.
I am dynamically changing the data in the slider.
I have been just creating a new swipe object when the data changes, however it is not destroying the callbacks etc, which is causing problems. How can I destroy the swipe object, or at least refresh it?

  window.slider = new Swipe(document.getElementById('flyers'), {
    startSlide: 0,
    speed: 200,
    callback: function(event, index, elem) {
        $('#home .flyerNav .selected').removeClass('selected');
        $('#home .flyerNav').children().eq(index).addClass('selected');
        $('#home .flyerLoves').attr('imgId',slides[index].imgId);
        daterizer(index);
    }
  });

Comment: i have tried window.slider = null;  i honestly have no idea how to do it haha
Answer: Try the swipe2 branch. It has a kill method that will remove the event listeners it sets up. I'm assuming it's not officially "done" yet but it might work for you if it doesn't have any glaring bugs. You'd call window.slider.kill() just before you instantiate the new one.
Comment: The current master branch now has the kill method exposed as the public api. You should now be able to call `yourSlider.kill()` using the current release. The docs have not been updated yet.

How to destroy swipe.js completely


TypeError: Cannot read properties of undefined (reading 'FLAGS') discord.js

Question: so this is my bot code
const Discord = require("discord.js")
const { Client, Intents } = require('discord.js');

const client = new Client({ intents: [Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES] });

client.on("ready", () => {
  console.log('Logged in as ${client.user.tag}!')
  console.log("Bot is online!")
})

client.on("message", msg => {
  if (msg.content === "ping") {
    msg.reply("no1se");
  }
})

client.login("my token")

The error i get is this:
TypeError: Cannot read properties of undefined (reading 'FLAGS')
    at Object.<anonymous> (/home/runner/no1seAlerts-1/index.js:4:47)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
Hint: hit control+c anytime to enter REPL.
(node:2004) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

yea so im trying to make a discor dbot everytime when i try to run it and make it online i get this error code i have no idea what to do and i would really appreciate any help thank you!
Comment: Maybe is it because you forgot to put `;` in end of first line? Or maybe you are using older version of discord.js whi doesn't have flags in it?
Comment: What is the version of `discord.js` in your code?
Comment: Does this answer your question? [Discord.js v13 code breaks when upgrading to v14](https://stackoverflow.com/questions/73028854/discord-js-v13-code-breaks-when-upgrading-to-v14)
Answer: Assuming you are using discord.js v13, you can try and change your client to:
const client = new Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })

Answer: You should replace Intents with IntentsBitField
In your example it would be:
const client = new Client({ intents: [IntentsBitField.Flags.Guilds,
IntentsBitField.Flags.GuildMessages] });

This was changed with version 14 of discord.js I believe.
Alternatively you can use GatewayIntentBits:
const client = new Client({ intents: [GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages] });

More information here
Hope this helps!


Hartshorne IV Remark 4.10.9 a morphism to Jacobian variety

Question: As in the title, in Hartshorne's algebraic geometry chapter IV Remark 4.10.9, $X$ is a curve over $k$ and $J$ is the Jacobian variety of $X$ of $X$. There he defines a morphism $X^n \rightarrow J$ by "$(P_1, \cdots, P_n) \mapsto \mathcal{L}(P_1+\cdots+P_n - nP_0)$."
According to the definition of the Jacobian variety by the universal property, this is equivalent to give an invertible sheaf $\mathcal{M}$ on $X \times X^n$ such that for $(P_1, \cdots, P_n) \in X^n, \ \mathcal{M}_{(P_1, \cdots, P_n)} \simeq \mathcal{L}(P_1+\cdots+P_n - nP_0).$
But how does one know that there is such an invertible sheaf?
Answer: Define $p\colon X\times X^n\to X$ by
$$
p(x,y_1,\dots,y_n)=x
$$
and $q_{01},\dots,q_{0n}\colon X\times X^n\to X\times X$ by
$$
q_{0i}(x,y_1,\dots,y_n)=(x,y_i).
$$
Let $\Delta$ denote the diagonal divisor of $X\times X$.
Then $\mathcal{L}(\Delta)$ is a line bundle on $X\times X$ whose restriction to $X\times \{P\}$ is isomorphic to $\mathcal{L}(P)$.
Consider the line bundle
$$
\mathcal{M}:=q_{01}^*\mathcal{L}(\Delta)\otimes\dots\otimes q_{0n}^*\mathcal{L}(\Delta)\otimes p^*\mathcal{L}(P_0)^{\otimes -n}.
$$
on $X\times X^n$.
Then the restriction of $\mathcal{M}$ to $X\times \{(P_1,\dots,P_n)\}$ is isomorphic to $\mathcal{L}(P_1+\dots+P_n-nP_0)$.


How to skip the conversion process after uploading file to vimeo?

Question: I think this a though in-depth question… I haven't found any posts, FAQ, help files or Google results about is.
I'm building an app that uses vimeo API to upload and steam video.
The problem that vimeo conversion time is too long.
Is there any way to skip vimeo's conversion process (especially when using the API to upload)?
Is it possible to upload a video converted to the exact final file that vimeo will eventually stream and skip the long conversion process?
I read the Compression Guidelines (https://vimeo.com/help/compression) and saw that "Adobe Media Encoder" doesn't support all the specifications (the vimeo presets, aren't aligned with the guidelines)
So, any help –

Is it possible to skip conversion?
If yes, how?
If no, any recommended video converter software that can convert according to vimeo compression guidelines to save on conversion time…?

Thanks,
Help will be very much appreciated!
Comment: I doubt this is possible. Either way, I think I'd be asking Vimeo, not SO.
Comment: Keep in mind that their conversion process may be transcoding to a dozen different formats to deal with different browsers, codecs, etc. that users use. I don't know that for a fact, but it would make sense. And they do a really good job of making their videos available on many platforms. (Unlike YouTube where half their content is just unavailable on most devices.)
Answer: According to Vimeo staff Mark's post:

We re-encode all videos that are uploaded without exception.

But as stated by user1118321, they need to encode at least a low-res (non-HD) version of your movie, in case you upload a HD video, of course.


Clean URLs not working, I can't log in to Admin Panel

Question: I just moved my drupal website to another host. But I am unable to login as mysite.com/user. It gives me a 404 not found error which means clean urls are not working afaik.
So, I checked PHP configuration with phpinfo(); and there is "mod_rewrite" visible in "loaded modules" section.
Anyway, I wanted to disable clean urls, however if I try to login as mysite.com/?q=user, it redirects to mysite.com/user and it is giving 404 not found error again.
So I kinda have no way to login to my website to update URL aliases. I have renamed my .htaccess file to disable it, result did not change.
I have updated this line:
  RewriteRule ^ index.php [L]

to this line:
  # RewriteRule ^ index.php [L]
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Still, nothing changes. Since I can't control the web server, all I have is FTP and MySQL. Any ideas?
Answer: You can add this line to your settings.php file and it would allow you to login
$conf = array( 'clean_url' => 0,);

Another method is to find the .htaccess file in D7 root, and open it,
find the "# RewriteBase /drupal" in codes, delete the "#", change the "drupal" to your file's name: my file is "blog",
"RewriteBase /blog" - the end change to this.
Comment: Hi, thank you, the configuration array has solved my problem. I mean, at least I have disabled Clean URLs. I can go like this, but I'll try to use Clean URLs now. My website is running under no folder, even not something like httpdocs. So I update the line as "RewriteBase /" but no, nothing changes. Any ideas?
Answer: Why you not try first to disable the clean urls from site using something like
$conf = array(
   'clean_url' => 0,
);

in settings.php, or maybe searching in the database with phpmyadmin the variable clean_url. Also, take a look to this post https://drupal.org/node/256410


discord.py embed avatar command

Question: So I've been trying to make a discord.py command that sends the mentioned users avatar in a embed.
this is what i have so far
<code>@client.command()
async def v1_3(ctx, user: discord.User):
    avurl = user.avatar_url
    embed=discord.Embed(title=f"{user.name}", description=f"{avurl}", color=0xf20202)
    await ctx.send(embed=embed)

</code>
Comment: Does this answer your question? [Upload an embed image?](https://stackoverflow.com/questions/47515361/upload-an-embed-image)
Answer: so what your doing is putting the url in the description field, what you wanna do is:
<code>@client.command()
async def v1_3(ctx, user: discord.User):
        embed = discord.Embed(title=f'{user.name}' , color = 0xf20202)
        avurl = user.avatar_url
        e.set_image(url=f'{avurl}')
        await ctx.send(embed=embed)
</code>
this will send the embed with the users avatar

discord.py embed avatar command


error: cannot access ListViewCompat class file for android.support.v7.internal.widget.ListViewCompat not found

Question: i have this error when updated appcompat to 23.1.1 :
Error:(264, 51) error: cannot access ListViewCompat
class file for android.support.v7.internal.widget.ListViewCompat not found

appcompat : 23.1.1
target 23
compile 23
sdk 24.3.1
Answer: With the new compileSdkVersion 27 seems that android.support.v7.widget.ListViewCompat doens't exist anymore. Now you should use android.widget.ListView
Comment: None of the other anwswers worked for me, had to change to android.widget.ListView.
Answer: It looks like it was moved out of the internal package android.support.v7.internal.widget.ListViewCompat.
It is now found in android.support.v7.widget.ListViewCompat.
Update your java files to
import android.support.v7.widget.ListViewCompat;

and your layout files accordingly
<android.support.v7.widget.ListViewCompat
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Comment: i will check this in another time , i change my code to avoid use this class , by the way probably your advise looks true .


Gerar XML com base no XSD

Question: recebi aqui uns arquivos XSD para usar em uma aplicação que desenvolvi... gostaria de saber como faço para gerar uns XML de exemplo no Visual Studio para poder me situar na exportação dos dados. Quando tento fazer via Visual Studio em Generated XML example, dá uma mensagem de erro "...namespace was not resolved".
Segue exemplo de uns do XSD.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:cadastroDomiciliar="http://esus.ufsc.br/v2000/cadastrodomiciliar" xmlns:condicaoMoradia="http://esus.ufsc.br/v2000/condicaomoradia" xmlns:enderecoLocalPermanencia="http://esus.ufsc.br/v2000/enderecolocalpermanencia" xmlns:familiaRow="http://esus.ufsc.br/v2000/familiarow" xmlns:headerCdsCadastro="http://esus.ufsc.br/v2000/headercdscadastro" targetNamespace="http://esus.ufsc.br/v2000/cadastrodomiciliar" version="1.0">

  <xs:import namespace="http://esus.ufsc.br/v2000/headercdscadastro" schemaLocation="v2000headercdscadastro.xsd"/>

  <xs:import namespace="http://esus.ufsc.br/v2000/enderecolocalpermanencia" schemaLocation="v2000enderecolocalpermanencia.xsd"/>

  <xs:import namespace="http://esus.ufsc.br/v2000/condicaomoradia" schemaLocation="v2000condicaomoradia.xsd"/>

  <xs:import namespace="http://esus.ufsc.br/v2000/familiarow" schemaLocation="v2000familiarow.xsd"/>

  <xs:element name="cadastroDomiciliarTransport" type="cadastroDomiciliar:cadastroDomiciliarTransport"/>

  <xs:complexType name="cadastroDomiciliarTransport">
    <xs:sequence>
      <xs:element maxOccurs="1" minOccurs="0" name="dadosGerais" type="headerCdsCadastro:headerCdsCadastroTransport"/>
      <xs:element maxOccurs="1" minOccurs="0" name="enderecoLocalPermanencia" type="enderecoLocalPermanencia:enderecoLocalPermanenciaTransport"/>
      <xs:element maxOccurs="1" minOccurs="0" name="condicaoMoradia" type="condicaoMoradia:condicaoMoradiaTransport"/>
      <xs:element maxOccurs="1" minOccurs="0" name="stAnimaisNoDomicilio" type="xs:boolean"/>
      <xs:element maxOccurs="unbounded" minOccurs="0" name="animaisNoDomicilio" type="xs:long"/>
      <xs:element maxOccurs="1" minOccurs="0" name="quantosAnimaisNoDomicilio" type="xs:string"/>
      <xs:element maxOccurs="unbounded" minOccurs="0" name="familias" type="familiaRow:familiaRowTransport"/>
      <xs:element maxOccurs="1" minOccurs="0" name="tpCdsOrigem" type="xs:int"/>
      <xs:element maxOccurs="1" name="uuid" type="xs:string"/>
      <xs:element maxOccurs="1" name="uuidFichaOriginadora" type="xs:string"/>
      <xs:element maxOccurs="1" minOccurs="0" name="fichaAtualizada" type="xs:boolean"/>
      <xs:element maxOccurs="1" minOccurs="0" name="statusTermoRecusaCadastroDomiciliarAtencaoBasica" type="xs:boolean"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

Answer: primeiro passo, coloque todos os seus xsd no mesmo local, aqui vamos chamar de:
Arquivo01.xsd // Não possui referencias
Arquivo02.xsd // Possui referencia a um tipo declarado no arquivo 01
Arquivo03.xsd // Possui referencia a um tipo declarado no arquivo 01
Arquivo04.xsd // Possui referencia a um tipo declarado no arquivo 02

Então abra o Visual Studio Command Propmt e execute o seguinte comando.
xsd.exe Arquivo01.xsd Arquivo02.xsd Arquivo03.xsd Arquivo04.xsd /class

Note que a ordem que você declara os *.XSD é importante, por exemplo, se você coloca-se o Arquivo02.xsd antes do Arquivo01.xsd, como o arquivo Arquivo02.xsd possui uma depedencia com Arquivo01.xsd, o comando iria disparar uma exceção.
Porém se inverter a ordem do Arquivo02.xsd com o Arquivo03.xsd, não terá problemas, afinal ambos não dependem do outro.
Agora tendo como base o seu arquivo sem algumas propriedades (afinal não sei qual é a estrutura dos seus imports).
arquivo.xsd
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:cadastroDomiciliar="http://esus.ufsc.br/v2000/cadastrodomiciliar" xmlns:condicaoMoradia="http://esus.ufsc.br/v2000/condicaomoradia" xmlns:enderecoLocalPermanencia="http://esus.ufsc.br/v2000/enderecolocalpermanencia" xmlns:familiaRow="http://esus.ufsc.br/v2000/familiarow" xmlns:headerCdsCadastro="http://esus.ufsc.br/v2000/headercdscadastro" targetNamespace="http://esus.ufsc.br/v2000/cadastrodomiciliar" version="1.0">
  <xs:element name="cadastroDomiciliarTransport" type="cadastroDomiciliar:cadastroDomiciliarTransport"/>
  <xs:complexType name="cadastroDomiciliarTransport">
    <xs:sequence>
      <xs:element maxOccurs="1" minOccurs="0" name="stAnimaisNoDomicilio" type="xs:boolean"/>
      <xs:element maxOccurs="unbounded" minOccurs="0" name="animaisNoDomicilio" type="xs:long"/>
      <xs:element maxOccurs="1" minOccurs="0" name="quantosAnimaisNoDomicilio" type="xs:string"/>
      <xs:element maxOccurs="1" minOccurs="0" name="tpCdsOrigem" type="xs:int"/>
      <xs:element maxOccurs="1" name="uuid" type="xs:string"/>
      <xs:element maxOccurs="1" name="uuidFichaOriginadora" type="xs:string"/>
      <xs:element maxOccurs="1" minOccurs="0" name="fichaAtualizada" type="xs:boolean"/>
      <xs:element maxOccurs="1" minOccurs="0" name="statusTermoRecusaCadastroDomiciliarAtencaoBasica" type="xs:boolean"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

então ao executar o seguinte comando:
xsd.exe arquivo.xsd /class

será gerado o seguinte arquivo:
arquivo.cs
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://esus.ufsc.br/v2000/cadastrodomiciliar")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://esus.ufsc.br/v2000/cadastrodomiciliar", IsNullable=false)]
public partial class cadastroDomiciliarTransport {

    private bool stAnimaisNoDomicilioField;

    private bool stAnimaisNoDomicilioFieldSpecified;

    private long[] animaisNoDomicilioField;

    private string quantosAnimaisNoDomicilioField;

    private int tpCdsOrigemField;

    private bool tpCdsOrigemFieldSpecified;

    private string uuidField;

    private string uuidFichaOriginadoraField;

    private bool fichaAtualizadaField;

    private bool fichaAtualizadaFieldSpecified;

    private bool statusTermoRecusaCadastroDomiciliarAtencaoBasicaField;

    private bool statusTermoRecusaCadastroDomiciliarAtencaoBasicaFieldSpecified;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public bool stAnimaisNoDomicilio {
        get {
            return this.stAnimaisNoDomicilioField;
        }
        set {
            this.stAnimaisNoDomicilioField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool stAnimaisNoDomicilioSpecified {
        get {
            return this.stAnimaisNoDomicilioFieldSpecified;
        }
        set {
            this.stAnimaisNoDomicilioFieldSpecified = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("animaisNoDomicilio", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public long[] animaisNoDomicilio {
        get {
            return this.animaisNoDomicilioField;
        }
        set {
            this.animaisNoDomicilioField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string quantosAnimaisNoDomicilio {
        get {
            return this.quantosAnimaisNoDomicilioField;
        }
        set {
            this.quantosAnimaisNoDomicilioField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public int tpCdsOrigem {
        get {
            return this.tpCdsOrigemField;
        }
        set {
            this.tpCdsOrigemField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool tpCdsOrigemSpecified {
        get {
            return this.tpCdsOrigemFieldSpecified;
        }
        set {
            this.tpCdsOrigemFieldSpecified = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string uuid {
        get {
            return this.uuidField;
        }
        set {
            this.uuidField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string uuidFichaOriginadora {
        get {
            return this.uuidFichaOriginadoraField;
        }
        set {
            this.uuidFichaOriginadoraField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public bool fichaAtualizada {
        get {
            return this.fichaAtualizadaField;
        }
        set {
            this.fichaAtualizadaField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool fichaAtualizadaSpecified {
        get {
            return this.fichaAtualizadaFieldSpecified;
        }
        set {
            this.fichaAtualizadaFieldSpecified = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public bool statusTermoRecusaCadastroDomiciliarAtencaoBasica {
        get {
            return this.statusTermoRecusaCadastroDomiciliarAtencaoBasicaField;
        }
        set {
            this.statusTermoRecusaCadastroDomiciliarAtencaoBasicaField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool statusTermoRecusaCadastroDomiciliarAtencaoBasicaSpecified {
        get {
            return this.statusTermoRecusaCadastroDomiciliarAtencaoBasicaFieldSpecified;
        }
        set {
            this.statusTermoRecusaCadastroDomiciliarAtencaoBasicaFieldSpecified = value;
        }
    }
}

agora para criar o seu arquivo xml, use o seguinte codigo:
var cadastro = new cadastroDomiciliarTransport();
/* preencha o seu objeto */

var xmlSerializer = new XmlSerializer(typeof(cadastroDomiciliarTransport));
using(var stringWriter = new StringWriter())
{
    using(var xmlWriter = XmlWriter.Create(stringWriter))
    {
        xmlSerializer.Serialize(xmlWriter, cadastro);
        var xml = stringWriter.ToString(); // Your XML
    }
}

No exemplo acima usei um StringWriter, caso queira escrever um arquivo, use o FileStream e um StreamWriter.
Comment: Tenho que olha a data da pergunta antes de publica uma resposta,
Answer: Se o xsd for válido, basta abri-lo no Visual Studio. Uma janela Xml Schema Explorer irá aparecer, ai é só clicar em um dos elementos da raiz com o botão direito e selecionar a opção Generate Sample XML.

Gerar XML com base no XSD


Difference between cross product (cross join, Cartesian product) and natural join

Question: While writing in SQL, how would I know if I should use cross product (cross join, Cartesian product) or natural join?
Comment: http://sqlfiddle.com/#!15/223f7/1
Comment: Possible duplicate of [Relational Algebra - Cartesian Product vs Natural Join?](https://stackoverflow.com/questions/14127306/relational-algebra-cartesian-product-vs-natural-join)
Comment: @philipxy Honestly, I might be more inclined to close the other one as a dupe of this one. The other one gets into a lot of minutia about a mental model of the theoretical concept and largely ignores the practical considerations. In the process, it adds a lot of unnecessary complexity.
Answer: CROSS JOIN creates all possible pairings of rows from two tables, whether they match or not. You don't use any join condition for a cross product, because the condition would always be true for any pairing.
An example of using CROSS JOIN: you have tables of ShoeColors and ShoeSizes, and you want to know how many possible combinations there are. SELECT COUNT(*) FROM ShoeColors CROSS JOIN ShoeSizes;
NATURAL JOIN is just like an INNER JOIN, but it assumes the condition is equality and applies for all columns names that appear in both tables. I never use NATURAL JOIN, because I can't assume that just because columns have the same name, that they should be related. That would require a very strict column naming convention, and practically no real-world project has such discipline.
Comment: The only time I might use `NATURAL JOIN` is in an exploratory throw-away query. When I'm trying to view data manually and directly using a SQL client and the query I'm writing will never need to be maintained and I'm confident for that specific situation and the consequences of a mistake are virtually nothing, I might use it just to save myself some typing.
Answer: In simple words,cross join performed a cartesian product among the rows of two different tables..where the columns name may or may not be matched......but in natural join its mandatory that in order to perform join operation columns name of two tables must be matched
Answer: Natural join is a cross join with where condition being on columns with same name from both tables.
Let's assume that you have two tables: A and B
>>select * from A;

            col1 col2 col3
            ---------------
            1     2    1
            1     4    0
>>select * from B;
            col1 col2
            ---------
            1     2

            1     3

>>select * from A cross join B;

    col1 col2 col3 col1_2 col2_2
    -----------------------------
    1     2    1    1      2
    1     2    1    1      3
    1     4    0    1      2
    1     4    0    1      3

>>select * from A natural join B;

    col1 col2 col3
    ---------------
    1     2    1
    1     2    1

For further details visit my post. https://eduit.nuxaavi.com.mx/2021/10/16/producto-cartesiano-sql/


Converting inherited class to a custom one

Question: I have a custom Deck class that inherits a List with a custom Card class.
Code for Deck:
public class Deck : List<Card>
        {
            public void DrawCard(Deck d)
            {
                d.Add(this[0]);
                this.RemoveAt(0);
            }
            public Deck(bool deckHasCards)
            {
                if (deckHasCards)
                {
                    for (int i = 1; i <= 13; i++)
                    {
                        this.Add(new Card(i, Card.Suit.CLUBS));
                        this.Add(new Card(i, Card.Suit.DIAMONDS));
                        this.Add(new Card(i, Card.Suit.HEARTS));
                        this.Add(new Card(i, Card.Suit.SPADES));
                    }
                }
            }
            public void Shuffle()
            {
                Random rng = new Random();
                int n = this.Count;
                while (n > 1)
                {
                    n--;
                    int k = rng.Next(n + 1);
                    Card value = this[k];
                    this[k] = this[n];
                    this[n] = value;
                }
            }
        }

and for Card:
public class Card
    {
        public Suit s { get; set; }
        public int num { get; set; }
        public enum Suit
        {
            HEARTS,
            DIAMONDS,
            CLUBS,
            SPADES
        }
        public Card(int number, Suit suit)
        {
            num = number;
            s = suit;
        }

        public override String ToString()
        {
            return num + " of " + s.ToString().ToLower();
        }
    }

Everything works great, but if I want to perform any LINQ operations on a Deck object, I have no way of converting it back to a Deck. Is there a (correct) way to go about doing this?
Comment: You may want to abstract out your operations that you perform on your deck.  Use `List` or `IEnumerable` instead of `Deck` everywhere, then make `Shuffle` and `DrawCard` part of a `DeckOperations` class or extension methods that operate on `IEnumerable`.
Comment: Since Linq is creating _new_ collections/enumerables on the fly, this makes sense. The queries themselves are _not_ object references to your original `Deck` object. Perhaps you can post some sample code/usage of what you're doing, or what you'd like to do.
Comment: @ChrisSinclair I understand my original object is not being changed, I would just like to have a way to convert the post-LINQ object back to a Deck. IE: `deck = deck.Where(card => card.num == 2).toDeck();`
Comment: Do you mean you want to create a _new_ deck out of some set of cards (that is, a new `Deck` that consists of the "2"-cards from your original `deck`?) EDIT: If so, is it ok if the same `Card` object can exist in more than one deck simultaneously?
Comment: Well, for all intents and purposes, yes. Sorry, that was dumb of me to set the same object equal to the new one - probably confusing.
Comment: No problem. Did you see my edited question (pretty critical for a proposed answer)?
Comment: I didn't - but yes, that is fine.
Comment: I would suggest following cadrell0's suggestion. But for a quick/dirty fix, maybe just define an extension method on `IEnumerable` called `ToDeck`, and expose the List's constructor that takes an `IEnumerable`. The `ToDeck` extension would just create a new `Deck` with that constructor passing in all the queried cards. EDIT: Also, consider making your cards immutable. :) Might make for some cheats at Poker otherwise! (but more importantly, avoid issues by having the same `Card` existing in multiple decks)
Comment: Okay. Purely out of curiosity, why is your idea undesirable?
Answer: You could add a new constructor to Deck:
public Deck(bool deckHasCards, IEnumerable<Card> cards)
{
    foreach (Card c in cards)
        this.Add(c);
}

And use a line like this:
var deck = new Deck(deckHasCards: true, cards: deck.Where(card => card.num == 2));


Is there a way to print out a list of all possible template files for a page?

Question: Including template files used for views, rows, blocks, etc. on that page?
Answer: I suggest review Theme Developer module http://drupal.org/project/devel_themer, it will help to find possible templates that can help to modify (theming) specific parts of your site.
in this resource http://drupal.org/node/209561 you will find how to use the module.
Comment: Yeah I know about devel_themer but it's slow and clunky and I'd prefer an alternative method.
Comment: @Joren, I suggest give a second chance to Theme Developer module, when the module is ready, only with two clicks it will show a list of possible options of templates. Due that is for test/development enviroments, is not for productions enviroments (in my case, I have disabled the module in test enviroments, because seems to have conflicts with some views, but when it has been necessary, has been very useful).


JavaScript as a robust hack for inline-block de-spacing

Question: I'm keen to use inline-block extensively as part of a fluid, responsive design, rather than lots of float: left and clearfix hacks. Until HTML5/CSS3 provides a way of ignoring spaces, and everyone upgrades to browsers that support this new feature (i.e. maybe five years if we're lucky) there will always be problems making this kind of layout.
There are a lot of hacks you can use to avoid the problem of browsers rendering space between inline-blocks: write code without spaces, comment out the spaces, some horrible font size hacks, etc. but None of them feel that great to me. I'm thinking instead of adding some inline JavaScript to the very bottom of my body tag:
document.getElementById('base').innerHTML = document.getElementById('base').innerHTML.replace(/\x3e\s+\x3c/g, '\x3e\x3c');

Essentially a post-hoc implementation of the "write code without spaces" implementation. I've tested it on a range of browsers and they all seem pretty happy with it - my question is: is there some grave hidden danger that I'm not seeing?
I've created a demo here: http://jsfiddle.net/edwardc/wdz5t/
Obviously there may be occasions when I actually want space - I can deal with those easily. And there might be issues with JavaScript bindings falling off - I'm pretty sure all my jQuery bindings will always attach after a script at the bottom of the body runs, and even if there's an issue, .on() should provide an easy fix.
Answer: The pure HTML/CSS methods you've mentioned in your post work fine without requiring your website's users to have scripts enabled.
Here is a CodePen example from this CSS-tricks article which shows all of the methods which don't feel great for you in action.
Your JavaScript is a good enough solution, by the look of things (provided you're not wanting to support IE7), but you may also want to apply some of the above methods as a fall back.
Answer: With regard to your question, there isn't any real downside to what you are attempting, save for the fact that your page will take longer to render — because the page will already have started being evaluated — plus it will depend on the speed and existence of JavaScript. One thing you could do to avoid doing things twice is to wrap your page content using nosript.

The above would mean non-js browsers would just get on rendering the page, and js-enabled browsers wouldn't render anything until executing the document.write.
I can't recommend the above however, or using display: inline-block for what you are trying to do...
Basically because I don't find using floats much of a problem — that's probably because I do find browsers rendering unexpected whitespace a tad annoying — to me, rather than any of this trickery, it's far far easier and more stable and supported to do the following:

One

Two

Three

Where the css would be:
.overflow-fix {
  overflow: hidden;
}

li {
  float: left;
}

Over my years of web development, I have only ever come across one situation where I needed to overflow content from within a float... it was only in that case that I needed to use the rather awkward "clear fix". I also seem to have avoided the need for centering any inline content, that might just have been luck however.
+1 to James Donnelly — as he indeed has given an exact and correct answer in keeping with inline-block. However, to me, it feels that anything which leads you to mess around with the markup layout, should be avoided until it is a last resort.


Qualquer linguagem de programação usa memória?

Question: Quando eu escrevo um programa em qualquer linguagem de programação, compiladas ou interpretadas, é necessário uma RAM para executar? Por favor explique.
Sendo mais específica, fiz um editor de texto usando JavaScript. Quando esse editor de texto é executado no JavaScript, o que acontece? Isso vai direto para a memória ou vai direto para o processador?
Pois se temos o código fonte de algum programa, é de se imaginar que esse código fonte de alguma maneira é livre, não depende do sistema operacional e sim da linguagem que foi escrita.
Em virtude disto, um código fonte + linguagem de programação, não precisaria, ou não teria necessariamente algum tipo de armazenamento, para tal feito. Isto é, de tanto faz compilar ou interpretar, é o mesmo. Se você compila, de alguma forma faz com que haja uma interpretação o mesmo acontece com interpretadores. E não necessitaria de RAM também.
Comment: Nem nós existimos sem memória... :(
Comment: Se não me falha a memória, para que qualquer programa seja executado ele deve ser carregado na memória do computador. Memória RAM é usada pelo processador para armazenar os arquivos e programas que estão sendo processados. https://pt.wikipedia.org/wiki/RAM
Comment: Relacionado: https://pt.stackoverflow.com/q/209542/64969
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer:
Quando eu escrevo um programa em qualquer linguagem de programação, compiladas ou interpretadas, é necessário uma RAM para executar?

Teoria
Toda linguagem de programação precisa ser Turing Complete, caso contrário ela não pode receber esta denominação. Isso significa que toda linguagem de programação, entre outras características, precisa ter um meio de armazenar dados e isso é feito em memória.
Qual tipo de memória? Isso não é especificado. Então na teoria não precisam ser RAM.
Em geral um programa precisa estar em memória para ser executado. Novamente não precisa ser RAM.
Prática
A memória usada para conter o programa ou armazenar dados de sua execução é a RAM. Seria difícil fazer diferente, pelo menos em arquitetura Von Neumann. Claro que poderia usar uma memória secundária, de massa, como um disco, mas a performance sofreria muito.
De fato, quando há mais dados do que memória RAM disponível é comum que parte deles sejam colocados em memória de massa, mas no momento do uso sempre precisa estar na RAM, e o sistema operacional deve gerenciar isto, provavelmente através de memória virtual.

Sendo mais específica, fiz um editor de texto usando JavaScript. Quando esse editor de texto é executado no JavaScript, o que acontece?

Sobre o carregamento e execução da programação já foi respondido. Também como o computador entende o código.
Mas em JavaScript é um pouco diferente. Ele recebe o código fonte e precisa interpretá-lo ou compilá-lo. Na verdade, quase todo mecanismo de JavaScript é JITtado. Então há um processo de transformação do fonte em código binário. Tudo isto é feito por um software, então só esse processo já usa muita memória, para armazenar o fonte, os passos intermediários e o resultado final binário que será executado. Claro que toda essa memória vai sendo liberada conforme o uso, se tudo correr bem e o código do JITTer for bem-feito, como costuma ser.

Isso vai direto para a memória ou vai direto para o processador?

O processador possui apenas registradores limitados, mesmo os mais poderosos ficam na casa das dezenas ou centenas, cada um podendo ocupar uma palavra. Então é virtualmente impossível trabalhar só com o processador. Não importa o tipo de linguagem. Claro que no momento exato da execução de uma operação o dado em questão estará no registrador, não pode operar direto na RAM.
Imagine que tem um problema muito complexo para resolver na mão, como faz? Vai executando cada passo e cada resultado vai sendo escrito em papéis para poder usar depois, certo? No computador isso é RAM. Quando está fazendo uma conta, manipulando algo é comum fazer um cálculo intermediário totalmente descartável, isto é feito em RAM, mas depois é jogado fora. Alguma coisa é tão simples que você faz de cabeça, isto é o processador usando registradores.
Então, sim, qualquer tipo de linguagem precisa de RAM para manter seus dados.

Pois se temos o código fonte de algum programa, é de se imaginar que esse código fonte de alguma maneira é livre, não depende do sistema operacional e sim da linguagem que foi escrita.

Sim, mas não vejo relevância neste contexto. Pelo menos isso parece fazer pouco sentido ao que foi perguntado. Código algum tem relevância para o sistema operacional.

Em virtude disto, um código fonte + linguagem de programação, não precisaria, ou não teria necessariamente algum tipo de armazenamento, para tal feito.

Não, como já demonstrado.

Isto é, de tanto faz compilar ou interpretar, é o mesmo. Se você compila, de alguma forma faz com que haja uma interpretação o mesmo acontece com interpretadores.

É, mas não vejo o que isso tem a ver com o contexto apresentado na pergunta. A frase final nem faz muito sentido.

E não necessitaria de RAM também.

Não consigo imaginar porque não necessitaria. Acho que lendo esta resposta e todos os links apresentados entenda que precisa sim. Precisa para o fonte, para o binário, para os dados, e estou falando só o uso direto do programa, nem do entorno dele que precisa também.
Também deve ser de interesse:

Como é desenvolvida uma linguagem de programação?
A primeira linguagem de programação
O que são e onde estão a "stack" e "heap"?

Coloquei no GitHub para referência futura.
Comment: Eu costumo ter cuidado com palavras fortes como *todas*. Nem toda linguagem de programação é turing-completa. É verdade que não existe linguagem não-turing completa de largo emprego comercial, mas existem linguagens funcionais como *Charity* que não são turing-complete.
Comment: @Renan Toda linguagem de programação é *turing complete* por definição. Se uma linguagem se autodenomina, ou popularmente as pessoas denominam fora da definição ela precisa justificar isso, mesmo assim não quer dizer que seja. Como não conheço a linguagem e de onde está tirando sua definição, não posso falar nada.


getPluginDefinition custom QueueWorker empty after upgrade

Question: I've got a custom queue worker that used to work fine in Drupal 9, but stopped working after the upgrade to Drupal 10.
I've narrowed it down to the getPluginDefinition method not returning anything. So in the core Cron.php I get a warning on the following line:
$lease_time = $worker->getPluginDefinition()['cron']['time'];

If I comment out this line, and just set the $lease_time to 1 my QueueWorker works fine. Clearly the worker itself is OK, but getting the meta data fails for some reason.
This is what my class definition looks like:
namespace Drupal\module_send_pdf\Plugin\QueueWorker;

use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A Mail Sender that sends e-mails on CRON run.
 *
 * @QueueWorker(
 *   id = "module_pdf_mail_sender",
 *   title = @Translation("PDF Mail Sender"),
 *   cron = {"time" = 105}
 * )
 */
class MailSender extends QueueWorkerBase implements ContainerFactoryPluginInterface {

protected $mailManager;

  public function __construct(MailManagerInterface $mail_manager) {
    $this->mailManager = $mail_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {

    return new static(
      $container->get('plugin.manager.mail')
    );
  }

As far as I can tell that markup is OK. So what am I missing?
Comment: @baikho: added constructor and create method. As mentioned though: the class gets instantiated fine. If I ignore the pluginDefinition not returning data my items gets processed.
Comment: IMHO ContainerFactoryPluginInterface in average custom code is not necessary unless you really need it to write test routines. Use \Drupal::service() instead. Refactor the code depending on DI to services.
Comment: Seems like an issue with your dependency injection given your implementation of `ContainerFactoryPluginInterface`. Can you show us your class constructor and `create()` method?
Answer: Please change your constructor and create() method to match the ContainerFactoryPluginInterface interface for the plugin definition details to be passed to the parent class:
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, MailManagerInterface $mail_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->mailManager = $mail_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('plugin.manager.mail')
    );
  }

Comment: That works! Thanks!

The real question is: how did that ever work in Drupal 9?
Comment: Looks like `Cron.php` has underwent some changes in the queue handling and `processQueue()` in D10 does not provide a fallback on the cron time definition. Regardless, if the queue worker subclass adheres to the base class it should work with both core versions.


Function which becomes just a relation on $R^{-}$?

Question: Consider the function on the variable $x\in R$ and the parameter $a\in R$:
$$f(x)=\frac{a-\sqrt{x}}{a+\sqrt{x}}$$
Of course if $x>=0$ you have a simple function $f:R \rightarrow R$.
If $x<0$ you can write:
$$f(x)=\frac{a-\sqrt{(-1)(-x)}}{a+\sqrt{(-1)(-x)}}$$
$$f(x)=\frac{a-[\pm i\sqrt{(-x)}]}{a+[\pm i \sqrt{(-x)}]}$$
So now there are 4 possibilities according to the signs you put:
$$\binom{+}{+} \rightarrow f(x)=\frac{a-[i\sqrt{(-x)}]}{a+[i \sqrt{(-x)}]}=e^{i\theta(x)} $$
$$\binom{+}{-} \rightarrow f(x)=\frac{a-[+i\sqrt{(-x)}]}{a+[-i \sqrt{(-x)}]}=1 $$
$$\binom{-}{+} \rightarrow f(x)=\frac{a-[-i\sqrt{(-x)}]}{a+[+i \sqrt{(-x)}]} =1$$
$$\binom{-}{-} \rightarrow f(x)=\frac{a-[-i\sqrt{(-x)}]}{a+[-i \sqrt{(-x)}]} e^{-i\theta(x)} $$
Finally:
$$ f(x)=\begin{cases}
1 \\
 e^{-i\theta(x)}\\
e^{i\theta(x)}
\end{cases}
$$
So I'd say that for $x<0$ $f(x)$ isn't anymore a function...Is it right?
Answer: This is not a function over the complex numbers, since the square root of a complex number is not a well-defined notion. See How do I get the square root of a complex number?
Comment: I know how to get the root of a cn, however do you confirm that my result is right?


Form submitting to wrong function when changing class dynamically

Question: I'm sure there's a simple explanation for this but I haven't been able to find the right words to use when searching for answers.
When users fill out the form .InvoiceForm it submits via Ajax. After it's submitted remove the .InvoiceForm class and add .UpdateInvoice. When a user submits a .UpdateInvoice form it explains that they are about to make a change and they have to click to say "Yes I want this to be updated".
The issue is that unless I refresh the page so that the form is loaded with the .UpdateInvoice form, I don't get the confirmation which means it's still submitting as a .InvoiceForm form. Is there anything I can do to fix this?
Edit to show code:
Code that runs if there's no record
$('.InvoiceForm').submit(function(e) {

        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            cache: false,
            dataType: 'json',
            context: this,
            data: $(this).serialize(),
            beforeSend: function() {
                $(".validation-errors").hide().empty();
            },
            success: function(data) {
                $(this).removeClass('InvoiceForm');
                $(this).addClass('UpdateInvoice');
                $(this).find('.btn').val('Update');
                $(this).find('.id').val(data.invoice_id);
                $(this).find('.btn').removeClass('btn-default');
                $(this).find('.btn').addClass('btn-danger');
                $(this).find('.AddRow').removeClass('hide');
                $(this).find('.invoiceDetails').html(data.returnedData);
                $(this).parent().next().find('.grade').focus();

            }
        });
        return false;
};

Code that runs if there is a record being updated
$('.UpdateInvoice').submit(function(){

        var r = confirm("Are you sure you want to make this update?");
        if (r == true) {
            $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            cache: false,
            dataType: 'json',
            context: this,
            data: $(this).serialize(),
            beforeSend: function() {
                $(".validation-errors").hide().empty();
            },
            success: function(data) {

                alert('This row has been updated');
                $(this).find('.total').html(data);
            }
        });
        } else {

        }
       return false;
   });

The function for .UpdateInvoice doesn't run unless I refresh the page.
Thanks for your help.
Comment: You need to provide a code example of what you have been trying to do.
Comment: It sounds like there is JavaScript that runs when the page loads to set up the confirmation. But it can't set up the confirmation if the UpdateInvoice form isn't there when the page loads. You need that code to execute after the UpdateInvoice form is added to the page. If you show your code someone can help you with that.
Answer: You bind a click event on '.UpdateInvoce' before it even being created, hence it'll not work. I think you need to use .live() in order to make it works. See document here: jQuery's live()
HTML:
<button id="click_me" class="new">Click Me</button>

Script:
$(function () {
    $('.new').click(function (e) {
        $('.result').text("Im new !");
        $(this).removeClass("new");
        $(this).addClass("update");

        // Bind UpdateInvoice's click event on the fly
        $('.update').live(bindUpdate());
    });

    function bindUpdate() {
        $('.update').click(function (e) {
            $('.result').text("Update me !");
        });
    }
});

jsfiddle's demo
Comment: Does on() do the same thing as live()? It says live() has been depreciated.


classical occupancy problem in Feller - $r$ balls in $n$ cells - poisson approximation

Question: I'm reading Feller's Introduction to Probability Vol. 1 page 103, and I'm try to wrap my head around the following.
There is a step from the section on classical occupancy problem (section 2 of chapter IV). The classical occupancy problem involves the random distribution of $r$ balls in $n$ cells, where we seek the probability $p_m(r,n)$ of finding exactly $m$ cells empty.
In Chapter IV, (2.6) we have

(2.6) $\hspace{1in}$ $ \{ne^{-(\nu+r)/(n-\nu)} \}^\nu < \nu! S_{\nu} < \{ne^{-r/n}\}^\nu$
Then $\lambda$ is set
$$ne^{-r/n} = \lambda $$
and suppose that $r$ and $n$ increase in such a way that $\lambda$ remains constrained to a finite interval: $0 < a < \lambda < b$.
For each fixed $\nu$ the ratio of extreme members in (2.6) then tend to unity, and so
$$ 0 \leq \frac{\lambda^\nu}{\nu!} - S_{\nu} \to 0 $$

How did he arrive at the last step?

Appendix:
$S_\nu$ is defined as below
$$ S_\nu = {n \choose \nu} \left( 1- \frac{\nu}{n} \right)^r$$
for every $ \nu \leq n $
For example,
$ S_1 = \Sigma p_i $,  where $p_i$ is the probability that the $i$th bin is empty.
$ S_2 = \Sigma p_{ij} $,  where $p_{ij}$ is the probability that the $i$th and $j$th bins are empty, for all $i$ and $j$ and $i<j$.
$ S_3 = \Sigma p_{ijk} $, ... and so on.
Answer: Define
$$R = \left( \frac{n \exp[-(\nu+r)/(n-\nu)]}{n \exp(-r/n)} \right)^\nu$$
The book claims, and it's not too hard to show, that $R \to 1$ as $r, n \to \infty$.  Since the posted question is about "the last step", we will leave a proof of this first part to the reader.  With the above definition of $R$, the initial inequality can then be written
$$ R \cdot (n \exp(-r/n))^\nu < \nu! S_{\nu} < (n \exp(-r/n))^\nu$$
With the substitution $\lambda = n \exp(-r/n)$,
$$ R \cdot \lambda^\nu < \nu! S_{\nu} < \lambda^\nu$$
so
$$ R \cdot \frac{\lambda^\nu}{\nu!} < S_{\nu} < \frac{\lambda^\nu}{\nu!}$$
$$ - \frac{\lambda^\nu}{\nu!} < -S_{\nu} < -  R \cdot \frac{\lambda^\nu}{\nu!}$$
$$ 0 < \frac{\lambda^\nu}{\nu!} -S_{\nu} < (1-R) \cdot \frac{\lambda^\nu}{\nu!}$$
From this last inequality, we see that as $R \to 1$,
$$0 \le  \frac{\lambda^\nu}{\nu!} -S_{\nu} \to 0$$


Parse URL with Regex C#

Question: I am getting the current URL with:
   string url = HttpContext.Current.Request.Url.AbsoluteUri;
//url = blahblahblah.aspx?NUMBER=8798494651&FULLNAME=Ronald

After this, I want to use url.Split() to obtain the value after both equals signs. This would normally be straight forward but as you can see the first value has an obvious end character of '&' while the other does not. Furthermore, the FULLNAME value can always be different.
I have seen other Regex parsing questions/answers on here but of course they are all for specific cases.
Thanks in advance.
Comment: Try this: http://www.codeproject.com/Articles/9433/Understanding-CGI-with-C
Comment: Why not you retrieve value as:::
 var num = Request.QueryString["NUMBER"];
 var name= Request.QueryString["FULLNAME"];
Comment: @DCODE I tried that. It was not picking up the values. I would get an error that way. That is why I am thinking of parsing the current url instead
Comment: @JonathanScialpi then try option as below
Comment: @JonathanScialpi What error are you getting?
Answer: Try this
var uri = new Uri("blahblahblah.aspx?NUMBER=8798494651&FULLNAME=Ronald");
var query = HttpUtility.ParseQueryString(uri.Query);

var var1 = query.Get("NUMBER");
var var2 = query.Get("FULLNAME");

Comment: that worked well thanks @DCODE

Parse URL with Regex C#


An intuitive understanding of Cauchy completeness?

Question: The standard procedure for completing a metric space is adding a limit for every Cauchy sequence, thus making the space Cauchy-complete. When elementary analysis is first taught, however, the completeness of the real numbers is usually introduced using the axiom of completeness, which asserts that the real numbers are Dedekind complete, that is, every Dedekind cut is generated by a real number (or equivalently, every upper-bounded nonempty subset has a least upper bound). For the real numbers, the two definitions coincide; but for a general metric space, the Dedekind definition is stronger.
I'm struggling to understand, or to give an intuitive explanation, for why the Cauchy definition truly implies "completeness", in the sense that any "place" (or "hole") in the space will have a point in it. I can rationalize the Dedekind definition: it basically implies that wherever you "cut" the line, you will find a number there; thus there are no "holes". If this definition was provable from the Cauchy one, I would not have complained; However the Cauchy definition is strictly weaker, and thus I'm struggling to see why does Cauchy completeness truly counts as "completeness", in the intuitive or geometric sense of "continuousness". Can anyone find a sort of intuitive or graphical explanation for that?
Comment: You need an ordering on the space for the concept of Dedekind completeness to make sense. General metric spaces aren't ordered.
Comment: If you build real numbers as the Cauchy completion of rational, you can prove that Dedekind criterion also holds. So the Cauchy definition is not weaker than Dedekind, and it allows to complete the spaces where the order of elements is not defined.
Comment: @Wolfram Cauchy completeness is weaker in the sense that for an ordered field, Dedekind completeness is equivalent to Cauchy completeness plus the field being Archimedian. A non-Archimedian ordered field can be Cauchy complete, but not Dedekind complete.
Comment: A metric space is an Archimedian setting, no two distinct points have an infinitesimal distance.
Comment: see [here](http://faculty.uml.edu/jpropp/dedekind.pdf) for a related discussion
Comment: @DanielFischer That is true, but still doesn't explain why Cauchy completeness is related to the intuitive notion of "continuousness".
Comment: I don't know what your "intuitive" notion of "continuousness" is, so I can't say much about that. Perhaps that if there were a hole (a missing point), you could approximate that arbitrarily well with points that are still there, and that would give rise to a Cauchy sequence (in sufficiently nice spaces, a Cauchy filter in more general spaces) that doesn't converge.
Comment: @DanielFischer That definitely helps me understand, thank you. It has now occurred to me, though, that Cantor's lemma is also a nice explanation for "continuousness", since you would like every "converging" sequence of intervals to converge to a point and not a "hole". Is Cantor's lemma equivalent to Cauchy completeness?
Comment: "Cantor's lemma" being that a sequence of nested closed intervals whose length shrinks to $0$ has nonempty intersection? In an Archimedian setting, that's equivalent to Cauchy completeness. In a non-Archimedian setting, it isn't, since the Cauchy criterion is defined using the Archimedian $\mathbb{Q}$ or $\mathbb{R}$, while the length of a nondegenerate closed interval could be infinitesimal, so a Cauchy sequence need not generate a sequence of intervals whose length shrinks to zero. Hence the intersection property need not guarantee a limit of the Cauchy sequence then.
Comment: @DanielFischer I'm actually slightly confused now, since Wikipedia says the properties are indeed equivalent: https://en.wikipedia.org/wiki/Cantor's_intersection_theorem (see section "Variant in complete metric spaces") Does wikipedia define the Cauchy criterion different than you?
Comment: @DanielFischer Of course, now I understand... thank you so much.
Answer: Maybe it helps to look at a quite simple example of a set that is Dedekind-complete, but not Cauchy-complete.
Take the set $S=(-\infty,0)\cup[1,\infty)\subset\mathbb R$, with the order and metric obtained by restricting the order and metric of $\mathbb R$.
Now intuitively, you see that there's a gaping hole in this set. However, the hole is not visible to the order. Indeed, this set is Dedekind-complete in that every bounded set has a supremum (least upper bound) and an infimum (greatest lower bound).
But wait, you ask, what about the set $N=(-\infty,0)$? Well, it has a supremum in $S$, and that supremum is $1$. That's because $1$ is clearly an upper bound, and in $S$ there's no upper bound that's lower, so $1$ is the supremum of $N$.
In short, the order cannot see the hole in the line; it sees the line as if the two parts were glued together.
On the other hand, the metric does see the hole, after all, all elements of $N$ have a distance larger than $1$ from the element $1$. And in particular, some Cauchy sequences will not converge, for example the sequence $a_n = -1/n$. So this set is not Cauchy complete, and the Cauchy completion will effectively add the $0$ to this set, giving $S'=(-\infty,0]\cup[1,\infty)$.
Interestingly, for $S'$ both the order and the metric will see that there's a gap (the order by seeing that there are two elements, $0$ and $1$, with no element in between), but $S'$ is both Dedekind-complete and Cauchy-complete.
Finally, let's look at the case that both $0$ and $1$ are missing, that is, at the set $S''=(-\infty,0)\cup (1,\infty)$. Now both Dedekind and Cauchy will see that there's a gap (the set $N$ now has no supremum, and the sequence $a_n$ doesn't converge). However Dedekind will fill that gap with a single element (which might represent any single point in the interval $[0,1]$), while Cauchy will fill it with two elements, $0$ and $1$. In other words, it adds the border points of the hole.
So for this case, the Cauchy results more closely resemble the intuitive notions of continuity: If there's a macroscopic gap, it will see it and fill in the border points if missing. While Dedekind might not see the gap at all, and if it does, it will just glue everything together with a single additional point.


Popular list-group bootstrap com ajax

Question: Olá, a todos.
Estou tentando popular uma list-group bootstrap com ajax mas não estou conseguindo. Já pesquisei em vários lugares sobre isso e não consegui resolver.
O código php está ok e o json que retorna do php também está ok.
Segue o código html
<!DOCTYPE html>

<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="robots" content="noindex, nofollow">
<link rel="stylesheet" href="css/bootstrap.min.css"/>

Artigos
Selecione um item para ler o artigo

Answer: Estás a escapar aspas sem necessidade e a gerar HTML inválido.
Em vez de \" deves ter somente " uma vez que inicias as strings com aspa simples '.
Então muda
$('#lista').append(''+dados[i].titulo+'');

(e corrigindo o + em falta em +dados[i].id'), para:
$('#lista').append('' + dados[i].titulo + '');

Comment: Funcionou, dando uma olhada aqui foi falha minha, pois além do problema que você apontou, o arquivo estava com nome diferente na pasta js.

Obrigado pela ajuda!
Answer: Além dos problemas citados na resposta do @Sergio, há outro erro em seu código que é a causa do problema: você está carregando o jQuery no final do documento, após o código.
Carregue a biblioteca jQuery preferencialmente no  do documento:

Comment: Obrigado, mas mesmo colocando no head ainda não funcionou.
Comment: Funcionou, dando uma olhada aqui foi falha minha, pois além de ter colocado a chamada do jquery no fim da página, o arquivo estava com nome diferente na pasta js.

Obrigado pela ajuda!

Popular list-group bootstrap com ajax


Let $T_n=\sum\limits_{i=1}^n\frac{(-1)^{i+1}}{2i-1}$ and $T=\lim T_n$, show that $\sum\limits_{n=1}^\infty(T_n-T)=\frac{\pi-2}8$

Question:
Let $T_n=\sum\limits_{i=1}^{n}\frac{(-1)^{i+1}}{2i-1}$ and $T=\lim\limits_{n \to\infty}T_n$, show that $\sum\limits_{n=1}^\infty(T_n-T)=\frac{\pi}{8}-\frac{1}{4}$.

Attempt:
I know that $Im(\frac{1}{2}log(\frac{1+i}{1-i}))=T$, but I have no idea how to evaluate $Im(\frac{1}{2}log(\frac{1+i}{1-i}))$
Comment: Something doesn't look right. Did you mean to sum $T_n$ over $i$? Did you mean to have an upper bound of $\infty$?
Comment: @copper.hat Thanks for spotting the typo, the question should be correct now.
Comment: Note that $$T_n-T=(-1)^{n+1}\int_{0}^{1}\frac{x^{2n}}{1+x^{2}}\,dx$$
Comment: The sum is thus $$\int_{0}^{1}\frac{x^{2}}{(1+x^{2})^{2}}\,dx=\int_{0}^{\pi/4}\sin^{2}t\,dt$$
Answer: I expand my comment into an answer with rigorous justification of all the steps.

We have $$\frac{1}{1 + x^{2}} = 1 - x^{2} + x^{4} - \cdots + (-1)^{n}\frac{x^{2n}}{1 + x^{2n}}\tag{1}$$ Integrating with respect to $x$ over interval $[0, 1]$ we get $$\int_{0}^{1}\frac{dx}{1 + x^{2}} = T_{n} + (-1)^{n}R_{n}\tag{2}$$ where $$R_{n} = \int_{0}^{1}\frac{x^{2n}}{1 + x^{2}}\,dx\tag{3}$$ Clearly we can see from $(3)$ that $$0 \leq R_{n} \leq \int_{0}^{1}x^{2n}\,dx = \frac{1}{2n + 1}$$ and hence by Squeeze theorem we have $\lim_{n\to\infty}R_{n} = 0$ and hence taking limit of $(2)$ when $n\to\infty$ we get $$\int_{0}^{1}\frac{dx}{1 + x^{2}} = \lim_{n \to \infty}T_{n}$$ so that $$T = \int_{0}^{1}\frac{dx}{1 + x^{2}}$$ Therefore from $(2)$ we get $$T_{n} - T = (-1)^{n + 1}\int_{0}^{1}\frac{x^{2n}}{1 + x^{2}}\,dx\tag{4}$$ and hence $$\sum_{k = 1}^{n}(T_{k} - T) = \int_{0}^{1}\frac{1}{1 + x^{2}}\sum_{k = 1}^{n}(-1)^{k + 1}x^{2k}\,dx$$ or $$\sum_{k = 1}^{n}(T_{k} - T) = \int_{0}^{1}\frac{x^{2} + (-1)^{n + 1}x^{2n + 2}}{(1 + x^{2})^{2}}\,dx$$ or $$\sum_{k = 1}^{n}(T_{k} - T) = \int_{0}^{1}\frac{x^{2}}{(1 + x^{2})^{2}}\,dx + (-1)^{n + 1}P_{n}\tag{5}$$ where $$P_{n} = \int_{0}^{1}\frac{x^{2n + 2}}{(1 + x^{2})^{2}}\,dx$$ And like before we can see that $$0 \leq P_{n} \leq \int_{0}^{1}x^{2n + 2}\,dx = \frac{1}{2n + 3}$$ and hence by Squeeze we see that $P_{n} \to 0$ as $n \to \infty$. Hence taking limit of $(5)$ as $n \to \infty$ we get $$\sum_{k = 1}^{\infty}(T_{k} - T) = \int_{0}^{1}\frac{x^{2}}{(1 + x^{2})^{2}}\,dx = \int_{0}^{\pi/4}\sin^{2}t\,dt = \frac{\pi - 2}{8}$$ where we use the substitution $x = \tan t$ in the last step.
Answer: You are over-complicating things. It is well-known that $T=\sum_{k\geq 1}\frac{(-1)^{k+1}}{2k-1}=\frac{\pi}{4}$, and by summation by parts:
$$\sum_{n=1}^{N}(T_n-T) = N(T_N-T)-\sum_{n=1}^{N-1}n (T_{n+1}-T_n)=\sum_{k\geq N}N\frac{(-1)^{k+1}}{2k+1}+\sum_{n=1}^{N-1}n\frac{(-1)^{n+1}}{2n+1} $$
can be re-written as
$$ \sum_{n\geq 1}\min(n,N)\frac{(-1)^{n+1}}{2n+1}\stackrel{N\to+\infty}{\longrightarrow}\sum_{n\geq 1}'\frac{n}{2n+1}(-1)^{n+1} $$
by the dominated convergence theorem, where $\sum'$ stands for a Cesàro sum. Since $\sum_{n\geq 1}'\frac{1}{2}(-1)^{n+1}=\frac{1}{4}$, your series equals:
$$ \frac{1}{4}-\frac{1}{2}\sum_{n\geq 1}\frac{(-1)^{n+1}}{2n+1}=\frac{1}{4}-\frac{4-\pi}{8}=\color{red}{\frac{\pi-2}{8}}.$$


How to make weights continous with db_update?

Question: With pure MySQL, I can do something like:
SET @weight:=0;
UPDATE mymodule_table
  SET mymodule_weight=@weight:=@weight+1
  ORDER BY mymodule_weight, mymodule_id;

Is there a Drupal way to achieve similar result? Can I avoid calls to db_query and push it with db_update or db_merge?
MySQL solution adapted from this answer.
Answer: Adding the expression is no problem, but neither UpdateQuery nor MergeQuery implement an orderBy() method. Neither will support setting a local variable first either, as far as I can tell (I'm not even sure a standard query will let you do that actually).
So I think it's safe to say that the answer is no, unless you subclass either UpdateQuery or MergeQuery, and add the sorting and variable declaration functionality yourself.
Comment: Thanks. I'm disappointed, but at least I wasn't blind not to see how to do it. I will not accept for now, maybe there is a way without variable that can be done "Drupal way". Feel free to remind me after a week or two (but I guess you may be too busy to do that).


Replace spaces with one dash and only allow Aphanumeric in Javascript

Question: I'm trying to achieve this kind of result:
From This  is a test to this-is-a-test
But I'd like to implement these rules:

Convert all spaces to dash.
Only allow one space (dash) between each two words.
Don't allow a dash a the beginning or end of the sentence.
Only allow letters, numbers and à ç _ è - é ù.

For now I'm using this partial solution:
const str = "This is dope";
const result = str.trim().replace(/\s+/g, "-").toLowerCase();
console.log(result) // this-is-dope

But this doesn't solve the whole problem because it doesn't have all the rules I mentioned.
I appreciate any help in this matter!
EDIT: I'm using React, and I need to implement this solution in an input field as follow :
Using the solution from mplungjan :
// state to hold the typed value
const [text, setText] = useState("");

<input
  type="text"
  onChange={(e) => {
    setText(
      e.target.value
        .trim()
        .replace(/^-+|-+$/g, "")
        .replace(/[-\s]+/g, "-")
        .replace(/[^a-zA-Z0-9\-àç_èéù]/g, "")
        .toLowerCase()
    );
    // unable to type spaces or dashes at all so far
    console.log(text);
  }}
  value={text}
/>

Comment: So you want to sanitize the string?
Comment: Both examples work, what is the question? Is there a non working example? Do you want to check beforehand if these rules are valid, of correct them afterwards?
Comment: Did you mean *any Unicode letter* when you mentioned *`à ç _ è - é ù`*?
Comment: I see, the *Don't allow a dash a the beginning or end of the sentence.* rule is not in sync with the live input validation requirement. You must allow leading/trailing hyphens to allow typing them at all.
Comment: @Dwix Then try `value.replace(/[-\s]+/g, "-").replace(/[^a-zA-Z0-9àç_èéù-]+/g, "").toLowerCase()`, without `trim()`.
Comment: It seems you can still disallow the initial `-`. I posted an answer with a React snippet.
Comment: The example I provided is just a partial solution, it doesn't have all the rules I mentioned (I still can add multiple spaces/dashes between words, add dash at the beginning or end etc...)
Comment: @WiktorStribiżew I only need those characters, I updated my question.
Comment: @WiktorStribiżew Your solution works partially, as you said I still can type dashes at the beginner/end, but can we at least convert spaces to dash while allowing only one space (dash) between each two words?
Comment: @WiktorStribiżew I guess your solution is good enough `.trim().replace(/[-\s]+/g, "-").replace(/[^a-zA-Z0-9àç_èéù-]+/g, "") .toLowerCase(),` I can type dashes at the beginning & end it's not a big deal. But can we also allow typing space and right away it converts to a dash? Because for now I'm unable to type a space.
Comment: @WiktorStribiżew Ah I see, I forgot about the trim, Thank you!
Answer: You can use

function App() {
  const [text, setText] = React.useState('');
  function toKebabCase({ target: { value } }) {
    setText( value.replace(/[-\s]+/g, "-").replace(/^-/, '').replace(/[^a-zA-Z0-9àç_èéù-]+/g, "").toLowerCase() )
  }
  return

      Text: <input type='text' onChange={toKebabCase} value={text} />

}
ReactDOM.render(<App/>, document.querySelector('#root'))

The value.replace(/[-\s]+/g, "-").replace(/^-/, '').replace(/[^a-zA-Z0-9àç_èéù-]+/g, "").toLowerCase()  will

replace one or more whitespace and/or hyphen chars with a single - (with .replace(/[-\s]+/g, "-")) and then
remove the first - (with .replace(/^-/, ''))
remove any chars other than ASCII letters, digits, _, -, à, ç, è, é and ù (with .replace(/[^a-zA-Z0-9àç_èéù-]+/g, ""))
turn the result into lower case (with .toLowerCase()).
Comment: I ended up removing the first `-` using an if statment, but this is even better. Thank you
Answer:

const str = "- This is0 dope $$ !";
const result = str.toLowerCase().replace(/[^0-9a-z ]+/g,'').trim().replace(/\s+/g, '-');
console.log(result)


Is there a way to poll a socket in C# only when something is available for reading?

Question: I'm wondering whether there is a way to poll a socket in c# when only one of the conditions (data is available for reading) is satisfied, I'm aware of the socket.Poll method but this can return true if any number of the 3 conditions specified returns true as specified here: MSDN: Socket.Poll
Answer: According to the MSDN documentation there are three causes that return true for

Poll(microSeconds, SelectMode.SelectRead);

if Listen() has been called and a connection is pending
If data is available for reading
If the connection has been closed, reset, or terminated

Let's see if we can discriminate them:

You always know if Listen() has been called before, so you don't need to consider that cause if you have not.
Ok, you go for that.
Means that you can not stay in the Poll() call and need to find out what really happened. One option is to check the socket's state immediately after Poll() returned.

Conclusion:

needs not to be considered
and 3. can be handled by checking the socket state each time true is returned.

So I would go for (untested):
if (s.Poll(microSeconds, SelectMode.SelectRead)))
{
  if (!s.Connected)
    // Something bad has happened, shut down
  else
    // There is data waiting to be read"
}

Comment: You should check Connected before calling poll or poll for Write first before reading as that is what Connected does under the hood anyways.
Comment: Thank you all for your response.
Answer: You could use Socket property Available. It returns how much data is available to read.
Answer: Found something in class NetworkStream. Property NetworkStream.DataAvailable returns true if data is available for reading. Object of networkstream is returned dealing with  TcpListener and TcpClient. This is one abstraction level higher than socket.
I found no way to come from Socket to NetworkStream. A NetworkStream is using a socket and is the stream representation of a socket. But I dont know what the networkstream is doing there with the socket.
Comment: NetworkStream also has .CanRead and .CanWrite which I have found very useful.
Answer: You could use the select() system call on the underlying handle.
Comment: My first thought too, but not shure if this is what dark-star really means.
Answer: You can use Select() method instead of Poll().
Actually when looking into Socket.Poll with ILSpy (reflector tool) the internal code is calling select on the socket.
In addition, calling Poll() in a tight loop will increase memory allocation as it does a new IntPtr[] on each call.
Calling Select() lets you reuse the arrays instead of allocating new ones under the hood.
Answer: true if  Listen has been called and a connection is pending;
-or-
true if data is available for reading;
-or-
true if the connection has been closed, reset, or terminated;
otherwise, returns false.
I understand that you want to check if the second option is the one returning true? After checking if the Poll returns true, you can check if the connection is open, that means; not connection, closed, reset or terminated.
If it is open, then it's the second option return true.
Comment: like: if (m_sock.Poll(-1, SelectMode.SelectRead) && (m_sock.Connected == true)) ?


Note groupings and readability in unusual time signatures

Question: Some of the music i'm trying to write seem only to fit in to some of these very obscure time signatures simply to be able to fit the right number of notes in rather than them being used because they have the 'feel' of that obscure time signature, they instead feel like 4/4 or 6/8 bars with 'extra' 16th notes in them, so we have 13/16 bars and 17/16 bars like this:
Currently I have them grouped in 6 6 5 for the 17 16 bars and 6 6 1 for the 13 16 bars, though after discussion with my piano teacher, we concluded that it looked wrong, but couldn't conclude how to make it right after discussing just these 4 bars for half an hour, and she insisted that using 4 4 4 4 1 and that 6 6 1 bar was incorrect despite it helping to simulate the idea of a '4 4 bar with an extra 16th note'.
Any tips on improving the readability and making this more 'technically correct' would be greatly appreciated, even just a better note grouping system would help.
EDIT: I have tried the suggestion involving using normal time signatures but adding grace notes to imply the same effect but making it easier to read and I've written it like this:

I'll be able to discuss the other alternatives such as using 7:6 tuplets with my piano teacher later this week, since i need to be sure that in bar 32 and 34, the last tenuto notes are very tenuto indeed ( they sound only a little bit shorter than the quavers ).
P.S. Sadly the music software i use doesn't allow irregular tuplets such as 7:6 and 6:5, which might have been useful, but i should gain access to a full version later this year and i'll be able to experiment with using them where appropriate e.g. using a 6:5 tuplet for the last 6 16th notes in bar 32 and 34, to show they should be played just a little bit faster (and thus fit it into 4 4)
Comment: I think you are being too "literal" with your notation - this may be a consequence of trying to get the "correct" playback from computer software. Bars with 16 and 12 16th-notes, and a 7:6 tuplet, or a grace note,  to sneak in the extra note somewhere, would be just as comprehensible for a human player. Unlike computers, humans don't count mathematically exact time.
Answer: A different (albeit difficult with a program like Sibelius) approach comes from Olivier Messiaen's notion of additive rhythm. With additive rhythm, Messiaen could use (as one example) a common time signature like 4/4 but actually have seventeen sixteenth notes in the measure instead of just sixteen. This added sixteenth note thus doesn't really destroy the feeling of 4/4 time, it just slightly elongates one of the beats. Wikipedia describes it as "lengthening individual notes slightly or interpolating a short note into an otherwise regular rhythm."
Your two 13/16 bars, for instance, really strike me as 6/8 bars with an extra, added sixteenth note at the end. The 17/16 bars could be viewed as 4/4 bars.
As I said above, this would be difficult to do in something like Sibelius. (At least I assume it would be...I don't use it.) LilyPond would be much better suited for a project like this.
But even if you don't like this concept, you may consider trying to beam things as if the 17/16 bars were in 4/4 and the 13/16 bars were in 6/8. At the very least, it would give the performer some more common beamings to deal with.
Answer: Things certainly get tricky once we step outside the common time signatures and the solution to choose becomes more and more subjective the further removed you become.  Generally speaking, groupings are used to convey phrasing and allow for easier reading.  Those are the two things to really consider when trying to notate your music, which it seems you understand at this point.  Tradition note groupings usually follow a standard for readability a little more than phrasing.  For example, in 4/4 you are usually expected to group the first two beats and last two beats, with some exceptions (like dotted quarter-dotted quarter-quarter), but when you have heavy syncopation, the expectation is that you notate based on readability, not phrasing, with the understanding that the rhythms encountered are against the beat.
Conveying Phrasing
We typically find that odd meters are divided by beats in sets of 2 or 3 subdivisions (the denominator of your time signature).  Sometimes you will find groupings of 4 or 6 but this can be interpreted as combining 2 sets of 2 or 3.  So we don't typically find a grouping of 1 beat, not that it's necessarily wrong, just that it doesn't follow the convention.  The problem ends up being that there are a couple ways to interpret the term phrasing: 1) The way the part that is being notated is phrased; 2) The way the time signature is structured.  As I mentioned above, sometimes the approach is to spell things out to delineate your beats, so writing syncopation against the beats doesn't necessarily feel like you are notating the phrasing as outlined in number 1 but it does convey number 2 and could be argued that the syncopation against the beat actually better conveys the phrasing than to base your groupings on the part/line you're playing.
So making the decision based on phrasing can become difficult as to whether you choose to group your notes for a given part or within a more approachable meter for the purpose of syncopation.
Grouping for Easy Reading
I find this to be more challenging than grouping for phrasing.  Typically we find that odd meters are just harder to read in general, so it's difficult to choose what the easiest way to write something that will still be difficult to read would be.  I would ultimately suggest that finding as much consistency as possible is going to be your best bet for readability.  If it's going to be difficult either way, you want to make sure that once it's interpreted, it doesn't need to be reinterpreted every new phrase/measure/etc.  I find that it's easiest to read smaller groupings when reading odd meters, so I might prefer to read two sets of 3 1/16 notes instead of one set of 6, or potentially three sets of 2 1/16 notes if that more properly spells out your phrasing.
One suggestion I received from my composition teacher back in college was that it may be easier for players to read if you just leave everything in 4/4.  I was writing some stuff that had no consistency to the meter, which I just left in 4/4, and he was suggesting that instead of reworking the piece to have the meter change to match the phrasing, which would be changes pretty constantly and not back and forth between two meters like your piece appears to be doing, it would potentially be easier to read in 4/4.  The thought was that the reader could just focus on playing what's there, instead of having to think about the next meter they were approaching every measure.  This approach could be helpful to some extent but it doesn't really tell you anything about what's happening in the music that you're reading, so you would surely want to supplement that with phrase markings.
In Conclusion
When you're making your decision, you'll want to determine who will actually be reading this and in what context.  If you will be giving it to a performer to have them play it, then you would probably want to make sure that your phrasing is well conveyed, leaving as little interpretation to the player as possible.  If you're writing it out for someone to sightread, then you will want to make sure that it's as readable as possible, preventing them from getting confused by odd groupings.  If you're just writing it out for yourself, you should probably just write it out however it makes sense to you.  On the whole, you just want to make sure that whoever has to read it won't have to guess what your intent was when writing it.
Answer: "Normal" time signatures were developed along time to fulfil, in a clear and concise way, most of the needs of the music that was being written. If new music does not fit into that paradigm it doesn't make sense to try strictly adhere to the conventions, particularly if that hinders legibility and clarity regarding the intention of the composer.
For me, the example you provide seems clear enough, so I don't see any strong reason to do it differently. Unless you wish to stress certain specific accentuations, splitting into multiple bars with changing time signatures would make a more cluttered and difficult to read score. But if you find that 6 6 5 and 6 6 1 better conveys your intention, that should be your criteria, not (supposed) "correctness".
Space arrangement of note groups within the same bar (e.g. more whitespace), if you're able to do it with the score typesetting tool you're using, may perhaps be used to further improve readibility. Also don't be afraid to text annotate your score if you find it necessary to make your intention more clear (if what you want is that the phrases be played as "two groups of 6 and one additional group of 5 or of 1", consider making a small initial footnote in the beginning of your score saying exactly that).
Readability and clearly transmitting your intention as a composer are more important than trying to guess how would Mozart have written it in the 18th century (he wouldn't have written it, not in the 18th century anyway :-).
Answer: As far as i am aware, note grouping applies to the beats in a bar. 3/4 has crotchet groupings because it has 3 crotchet beats. 6/8 has dotted crotchet groupings because it has two dotted crotchet beats. In 16/17 and 13/16, there are no [official] groupings of any type. Therefore, i would suggest grouping your notes depending on how the beats are arranged in this specific example.
In this case, you are trying to simulate a 4/4 bar with an extra 16th note, so group in terms of beats. Is it three beats and one longer beat? In this case use 4 4 4 5 groupings. Is it 4 beats with an extra note? in this case use 4 4 4 4 1 groupings. The same applies to your 13/16 bars: Is it two beats and one longer beat? In which case use 4 4 5. Or is it three beats with an extra note? In which case use 4 4 4 1.
Of course, in simpler time signatures you would change the signature to one with an equal bar length but different beat lengths, however this does not strictly apply to irregular time since there is no defined way to group notes.


A function in $H(div)$ not in $H^1$

Question: Let $\Omega$ be a bounded domain. I am not sure what a function in
$H($div$) = \{ u\in L^2(\Omega):\nabla\cdot u \in L^2(\Omega) \}$
but not in
$H^1 = \{ u\in L^2(\Omega): \frac{\partial u}{\partial x_i}\in L^2(\Omega) \}$
would look like. I know that at least two space dimensions are needed, but I haven't figured out how to construct an example.
Edit: I forgot to specify for a bounded domain.
Answer: Example:
For concreteness we suppose our bounded domain contains the origin in the interior, but in the general case we can do a translation.
Take
$$ u(x,y) = \begin{pmatrix} H(y) \\ 0 \end{pmatrix} $$
where $H$ is the Heaviside function. $u$ is a bounded function defined on a bounded domain, so $u$ is in $L^2$. The divergence of $u$ can be computed explicitly to be 0. But $\partial_y u$ is equal to the Dirac $\delta$ along the $x$-axis, and is not in $L^2$.
Example: One may say that the previous example is too singular. We can give a slightly less singular example. assume the origin is on the boundary of your domain. Let
$$ u(x,y) = \begin{pmatrix} \frac{-y}{r} \\ \frac{x}{r} \end{pmatrix} $$
Again $u$ is a bounded (smooth) function on a bounded domain so is in $L^2$. You can directly compute that $\nabla \cdot u = 0$.
But
$$ \partial_y u = \begin{pmatrix} - x^2 / r^3 \\ - xy/r^3 \end{pmatrix} $$
within the sector $\{x^2 \geq y^2\}$ you have that the first factor is bounded below by $1/r$, which is not square integrable.
Comment: A similar approach also works in higher dimensions. Start with an arbitrary vector field $V$ that is tangent to the spheres. Then for any radial function $A$, the vector field $AV$ is divergence free. So all you need to do is to choose $A$ to be fast decaying (to guarantee that $u\in L^2$) and high frequency (so that $V \partial A$ is not in $L^2$).
Comment: Thank you! Unfortunately, I didn't make enough specifications on my problem. I do work on bounded domains, so I was hoping to find an example in a bounded domain. Also, is there something that doesn't involve computing the curl? My understanding of functional analysis is fairly limited, so I don't know how the curl relates to $H^1$.
Comment: @Ken: in regards to curl, you argue by contradiction. If $u$ were in $H^1$, then $\partial_x (u_y) \in L^2$ and $\partial_y (u_x) \in L^2$ hence $\nabla\times u \in L^2$. No functional analysis needed, just basic multivariable calculus. I will edit with bounded domains.
Comment: I really appreciate your help. I think I figured out where my understanding was too limited.

A function in $H(div)$ not in $H^1$


Doubt with display a query using Custom Field Module in View

Question: I have installed the CustomField module.  I have a view and I'd like to add a new column in a table in the view.  The content of this column is a result of a query to a table different to node.  Is this possible with this module?
I am using Drupal 6.
Answer: You can set up relationships in views to pull data from other tables should you have to.  There's a screencast from Drewish here on how they work and how to set them up.
Basically, you'd need to set up a relationship based on a part of the current data in the row.  After this, more data is exposed to you in the fields section of views.
If I'm misunderstanding your question and you'd just like to embed a view withing a view, then check our the Views Field View module.

This module allows you to embed a view as a field in a view.
This view can accept arguments from fields of the parent view using
  tokens.


Flex HTMLLoader component not raising mouseDown events for all mouse clicks

Question: I have built a Air 2/Flex 4 kiosk application with Flash Builder 4. Currently I am implementing a touch screen browser to enable users to navigate company training videos.
In an attempt to improve the usability of the website on the touchscreen I have placed the HTML component in an adaption of Doug McCune's DragScrollingCanvas (updated to use the flex 4 'Scroller' component) to allow users to scroll the webpage by dragging their finger across the screen. The mouseDown event is used to start scrolling the viewport.
In addition the webpage was modified to disable text selection with the following css:
html {
    -webkit-user-select: none;
    cursor: default;
}

The problem I face is that the HTMLLoader component only fires a mouseDown if a link/input/button on the webpage is clicked, not when the background or any text is clicked.
In addition if I remove the custom css the mouseDown event will not fire when text is being selected, but will if previously highlighted text is clicked.
As an alternative I also tried adding a group container with the same dimensions as the HTMLLoader to detect the mouseDown events (so that the group container and HTMLLoader have the same Dragable parent container) and was able to capture mouseDown events and scroll the viewport as expected. However as the mouse event is handled by the group container, I am now unable to navigate the webpage.
Does anybody know why the HTMLLoader component is not raising mouseDown events for all mouse clicks?
Answer: There is another way to resolve the problem, only is add mouse down event listener for the htmlLoader's parent. set the useCapture param to true.
parent.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler, true);

Answer: I faced the same problem, a way to resolve this is to write javascript when load web page complete.
I do it like this:
<mx:HTML id="html" ... >
  <mx:complete>
    var document:Object = html.htmlLoader.window.document;
    var body:Object = document.getElementsByTagName("body");
    body[0].onmousedown = function(o:Object):void
    {
      trace("mouseDown");
      ...
    }
  </mx:complete>
</mx:HTML>

Comment: I just slapped myself in the head, I cant believe I didnt think of that already - great solution thanks!