questions about Global Proj

Question: Can someone explain the construction of the global $\mathbf{Proj}$ to me?
Although this question has been asked here, I still have several questions.

For each open affine subset $U = \mathrm{Spec} A$ of $X$, let $\mathcal{S}(U) = \Gamma(U, \mathcal{S}|_{U})$, which is a graded $A$-algebra. Then we have a natural morphism $\pi_{U}: \mathrm{Proj} \mathcal{S}(U) \rightarrow U$.

This map is from $A \rightarrow \mathrm{Proj} \mathcal{S}(U)_{f}: a \rightarrow a/1 $, right?

Let $f \in A$ and $U_{f} = \mathrm{Spec} A_{f}$. Since $\mathcal{S}$ is quasi-coherent we have $\mathrm{Proj} \mathcal{S}(U_{f}) \cong \pi_{U}^{-1}(U_{f})$.

I don't really understand the explanation under that question. Why $\mathcal S(U_f)=\mathcal S(U)_f$? And why we need $\mathcal{S}$ to be quasi-coherent?

How to glue the invertible sheaves $\mathcal{O}(1)$ on each $\mathrm{Proj} \mathcal{S}(U)$ to get an invertible sheaf $\mathcal{O}(1)$ on $\mathbf{Proj}S$

Can someone explain more explicitly? Thank you very much!

Here is my understanding:
Suppose $\mathcal{S}|_{U}=\tilde{M}$, then $\mathcal{S}|_{U}(U)_f=M_f=\mathcal{S}|_{U}(U_f)$.
Then we have this commutative diagram:
$\require{AMScd}$
$$\begin{CD}
\mathrm{Proj}\mathcal{S}(U_f)=\mathrm{Proj}\mathcal{S}(U)\times_{\mathrm{Spec}A}\mathrm{Spec}\,\mathcal A_f @>>> \mathrm{Spec}\,\mathcal A_f\\
@VVV @VVV \\
\mathrm{Proj}\mathcal{S}(U) @>>> \mathrm{Spec}\,\mathcal A.
\end{CD}$$
Answer: (1) The "old" $\operatorname{Proj}$ of a graded ring $S$ came with a canonical morphism $\operatorname{Proj} S \to \operatorname{Spec} S_0$. It seems to me that one has to define this on standard opens via $S_0 \to S_{(f)}$ and then glue. Maybe that's what your notation means.
(2) Having $\mathscr{F}(\operatorname{Spec} A_f) = \mathscr{F}(\operatorname{Spec} A)_f$ is one characterization of quasi-coherence. This is a good exercise and in the end the solution is very short.
(3) The gluing is similar to that for $\operatorname{\mathbf{Proj}}$. The key step is to show that $\mathscr{O}(1)$ on $\operatorname{Proj}$ is compatible with base change: in the notation of the referenced answer, the pullback of $\mathscr{O}_{\operatorname{Proj} B}(1)$ to $\operatorname{Proj} (B \otimes_A A')$ is $\mathscr{O}_{\operatorname{Proj} (B \otimes_A A')}(1)$. Some details are given in the Stacks Project.
Comment: Thanks for your help. I add my understanding. I think it makes sense now.

questions about Global Proj


Netezza SQL comparing two records in the same table

Question: I am trying to do a basic insert from one table (#1) into another (#2), however I created a flag column in table #2 which in order to correctly set, I need to be able to determine the difference between 2 records in the source table (#1). This second table is sort of a verisoning table. It indicates there are multiple records of something from table #1, but that they are different versions (different version being that only 1 or two supplementary fields in table #1 are different) and table#2 will show what was different between the two/three versions.
in table #2 I will have a "Why was this added" flag which will either be "P", "B", or "J" depending on the source records in table #1.
If the difference between the two records in table #1 were in column date, then the flag will be "P". If the difference between the two records was in column amount, then the flag will be "B". If the difference was both date and amount, then the flag will be set to "J".
So how would I go about during my insert statement comparing two records' fields from the same table??
Any advice would be appreciated. I believe in Netezza SQL I cannot create virtual tables which is why google hasn't served me well.
Comment: It would be best if you include a code snippet.
Answer: <code>select t1.id, 'j'
from table t1
join table t2
  on t2.id  t1.id
 and t2.date <> t1.date
 and t2.amount <> t2.amount;
select t1.id, 'p'
from table t1
join table t2
  on t2.id == t1.id
 and t2.date <> t1.date
 and t2.amount = t2.amount;
select t1.id, 'b'
from table t1
join table t2
  on t2.id = t1.id
 and t2.date = t1.date
 and t2.amount <> t2.amount;
</code>


Como utilizar Jquery com Vue.js?

Question: Durante a implementação do Vue.js com sematic-ui,
tenho o seguinte Jquery para abrir o modal:
$('.ui.modal').modal('show');

como fazer essa integração no Vue?
Comment: Nessa aula do Vedovelli ensina como abrir um modal jquery. http://www.vedcasts.com.br/series/vuejs/aula19
Comment: Esse link aí, sempre que clica, volta para a mesma página. @MarcelloRGonçalves
Answer: Com v-el é possível "marcar" os elementos html para serem usados dentro de componentes.
Também é possível usar diretivas customizadas para fazer essas manipulações.
hello
world

this.$els.msg.textContent // -> "hello"
this.$els.otherMsg.textContent // -> "world"

Referências:
http://vuejs.org/api/#v-el
http://vuejs.org/examples/select2.html
Answer: Ao fazer o include de jQuery via tag script o objeto jQuery estará automaticamente atrelado ao objeto window, podendo então ser utilizado normalmente dentro de um componente Vue. Basta pegar uma referência ao markup do modal utilizando v-el.
Ex.:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

One fine body…

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

E no seu componente:
{
  methods: {
    metodoAssociadoAoCliqueUsuario () {
      jQuery(this.$els.modal).modal('show')
    }
  }
}

Answer: Essa resposta é para aqueles que caíram aqui pelo Google ou busca no SO mesmo.
Não é indicado usar Jquery com Vue, pois ambos manipulam o DOM (no Vue temos o virtual DOM e essa é somente a resposta simples). Sempre que precisar usar algo que usa o jquery (como o materialize, apesar da versão a partir do 1.0 não utlizar mais,  ou bootstrap) procure se não existe algum componente pronto para Vue. Hoje em dia (2019), é possível chamar o jquery normalmente num 'method' ou 'computed' do Vue, e executá-lo como no exemplo do Fabio Vedovelli.
{
    methods: {
        metodoaAssocioadoAoClique: function() {
            $('#id_do_componente').modal('show');
        }
}

Uma coisa importante a se lembrar é, que caso tenha necessidade de chamar um outra função dentro  da chamada jquery, deve inicializar o 'this' antes, como se segue:
{
    methods: {
        outraFuncao: function() {
            return alert("teste")
        }
        metodoaAssocioadoAoClique: function() {
            var self = this;
            $('#id_do_componente').modal({
                //como opção do componente, tenho que chamar outra função
                self.outraFuncao();
            });
        }
}

Não sou ainda um profundo conhecedor, pois ainda estou conhecendo e experimentado o Vue (e também sou novo em programação ainda).
Referências:
https://vuejsdevelopers.com/2017/05/20/vue-js-safely-jquery-plugin/
DOM e o Virtual DOM do Vue
https://medium.com/js-dojo/whats-the-deal-with-vue-s-virtual-dom-3ed4fc0dbb20
Esse é um Vue contra Jquery (mais propaganda para o Vue do que uma análise)
https://www.educba.com/vue-js-vs-jquery/

Como utilizar Jquery com Vue.js?


launch sms application from browser in Meteor

Question: A Meteor client code running on smartphone needs to send SMS using the phone sms app. How would you approach this task with out EmailSMS gateway?
All the SO posts I read were not Meteor specific. Any one tried this Cordova extensions and can give some feedback on how to use it? Thanks
Answer: The Cordova access rules you mention are only to handle special links that open the device's default app which handles the corresponding service.
Think of it exactly like a Open a mail composer in a browser, that opens an email creation window from your default mail client when you click on the link. You can even pre-populate the body content of your SMS, like with the mailto link.
Now if I understand correctly your objective, you would like to automatically send an SMS, as if you had sent an email to an Email2SMS 3rd party service that would convert it to an SMS and send it to your recipient on your behalf. Except that you want to get rid of that 3rd party?
In that case, you would be interested in actual Cordova plugins for SMS functionality.


How to call a space in which every G$_\kappa$-set is open

Question: Recall that in a topological space $X$, we say that a subset $A\subset X$ is a G$_\delta$-set if $A$ is the intersection of countably many open sets of $X$. Also, we say that $X$ is a $P$-space if G$_\delta$-sets are open.
Now, call as G$_\kappa$-set the intersection of $\kappa$ many open sets, where $\kappa\geq\aleph_0$ is a cardinal. I would like to know if there is some standard name for those spaces in which G$_\kappa$-sets are open, for a fixed cardinal $\kappa\geq \aleph_0.$
Motivation: this kind of space arose in my PhD thesis, but I do not know any references in which they appear. I'm temporary calling them as $P_\kappa$-spaces.
Comment: Excelent choice.
Answer: Sikorski (1950) call these spaces as $\omega_\mu$-additive spaces.


Como criar as tabelas ao iniciar o Sisitema com JSF e JPA?

Question: Galera, como faço para que quando o sistema inicie as tabelas sejas criadas automaticamente? Do jeito que está meu sistema as tabelas só são criadas quando algum tipo de acesso ao banco é feito. Por exemplo na tela de login basta pressionar o botão logar que as tabelas são criadas. Minha intenção é que sejam criadas ao iniciar o sistema.
Estou usando JPA + JSF + MySql
Comment: Qual Servidor está usando?
Comment: Tá usando Hibernate também?
Answer: No seu caso eu criaria uma classe que implementasse ServletContextListener que é um Listener que verifica quando o inicio e fim de uma aplicação, ao implementar essa classe dois métodos sobrescritos são criados: contextInitialized() e contextDestroyed().
No método contextInitialized() você inicia o que você quer junto com o servidor, exemplo:
@Override
public void contextInitialized(ServletContextEvent sce) {
    emf = Persistence.createEntityManagerFactory(pu);
    System.out.println("Contexto Inicializado");
}

E no método contextDestroyed() você coloca tudo que deseja finalizar junto com o servidor, exemplo:
@Override
public void contextDestroyed(ServletContextEvent sce) {
   emf.close();
}

Por fim é só registrar o Listener no web.xml
<listener>
  <listener-class>com.util.suaclasse</listener-class>
</listener>

Answer: No meu caso que uso o wildfly, eu fiz o seguinte:
Configurei no arquivo standalone.xml as seguintes entradas:
Em <datasources eu adicionei:
<datasource jndi-name="java:jboss/datasources/pokemax" pool-name="pokemax" enabled="true" use-java-context="true">
                    <connection-url>jdbc:mysql://localhost:3306/banco?useTimezone=true&serverTimezone=UTC</connection-url>
                    <driver>mysql</driver>
                    <security>
                        <user-name>user</user-name>
                        <password>senha</password>
                    </security>
                </datasource>

Em <drivers:
<driver name="mysql" module="com.mysql">
                        <driver-class>com.mysql.jdbc.Driver</driver-class>
                        <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
                    </driver>

E adicione o driver do mysql no diretório: /opt/wildfly-10.1.0.Final/modules/system/layers/base/com/mysql/main.
Caso as pastas não existam pode criar elas normalmente.
Ainda neste diretório, adicione um arquivo chamado module.xml com as seguintes informações:
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.mysql">
<resources>
<resource-root path="mysql-connector-java-6.0.4.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
</dependencies>
</module>

Pronto, só atente para as suas configurações como banco, user, senha, versão de driver do mysql, etc.
Answer: Defina o valor da propriedade "hibernate.hbm2ddl.auto" como "update".
Dessa forma, qualquer alteração nas entidades JPA será refletida no banco de dados quando o servidor iniciar a aplicação.
Segue exemplo utilizando MySQL, hibernate e servidor Wildfly 9
<persistence-unit name="myPU" transaction-type="JTA">

    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <jta-data-source>java:jboss/datasources/myDataSource</jta-data-source>

    <properties>
        <property name="javax.persistence.validation.mode" value="none" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
    </properties>

</persistence-unit>


Como a declaração de uma classe no Python lida com o escopo externo?

Question: Para exemplificar, vamos considerar essa declaração de classe:
x = 1

class Foo:
    a = x
    b = [x]
    c = [x for _ in range(1)]

print(f'x = {x}')  # x = 1
print(f'Foo.a = {Foo.a}')  # Foo.a = 1
print(f'Foo.b = {Foo.b}')  # Foo.b = [1]
print(f'Foo.c = {Foo.c}')  # Foo.c = [1]

Veja funcionando no Ideone | Repl.it
O que mostra que durante a declaração da classe o valor de x é buscado no escopo global, dado que no escopo da classe não está definido. Porém, se definirmos um valor para x na classe a saída muda:
x = 1

class Foo:
    x = 2
    a = x
    b = [x]
    c = [x for _ in range(1)]

print(f'x = {x}')  # x = 1
print(f'Foo.a = {Foo.a}')  # Foo.a = 2
print(f'Foo.b = {Foo.b}')  # Foo.b = [2]
print(f'Foo.c = {Foo.c}')  # Foo.c = [1]

Veja funcionando no Ideone | Repl.it
Os valores de Foo.a e Foo.b passam a utilizar o valor de Foo.x, mas o valor de Foo.c continua considerando o x global.
Esse comportamento se dá porque em Foo.c é utilizado a list comprehension? Como, de fato, o interpretador gerencia o escopo durante a declaração de uma classe?
Answer: Que loucura! Achei essa thread falando disso, o nome é List Comprehensions Leak. O prório Guido explica aqui.
Comportamentos diferentes em python 2 e 3 (baseado no post do Guido):
x = 42
a = [x for x in (1, 2, 3)]
print(x) # imprime 3 no py2 e 42 no py3

Para você acessar o x local não pode usar list comprehension,
acho que fizeram isso para evitar o tal leak
x = 111

class Foo:
    x = 222
    a = x
    b = [x]

    c = [x for _ in range(1)]

    d = []
    for _ in range(1):
        d.append(x)

print(f'x = {x}')  # x = 111
print(f'Foo.a = {Foo.a}')  # Foo.a = 222
print(f'Foo.b = {Foo.b}')  # Foo.b = [222]
print(f'Foo.c = {Foo.c}')  # Foo.c = [111]
print(f'Foo.d = {Foo.d}')  # Foo.c = [222]


How to correctly utilize the timezone option in Highcharts

Question: Long story short:
I want to show the dates in the x-axis based on my customer timzeone which is coming from the server i.e 'Asia/Calcutta' ..etc
I have set useUTC to false and provided the timezone like this:
time:{
  useUTC: false,
  timezone: 'Asia/Calcutta',
}

Yet, I see Highchart is handling the DST transition and I can see 1 hour is missing from the x-axis because of my own time zone which is "Europe/London".
Note; There's no DST in use in 'Asia/Calcutta' timezone
Live Demo: https://jsfiddle.net/Sayed110/o2s0y64f/57/
Comment: I think that it is a bug, could you report it on the Highcharts Github issue channel? https://github.com/highcharts/highcharts/issues
Comment: @SebastianWędzel
It turned out that I needed to use UTC dates in iso format.
and also I needed to set `useUTC` to true.
Highcharts  documentation not clear at all

when I converted my dates to UTC and provided the correct timezone; I start to see the correct result
Answer: I had to set useUTC to true and convert my dates to UTC.
and that was enough to fix the issue.


Are there infinitely many pairs of rational numbers such that...

Question: Are there infinitely many pairs of rational numbers $(a,b)$ such that $a^3+1$ is not a square in $\mathbf{Q}$, $b^3+2$ is not a square in  $\mathbf{Q}$ and $b^3+2 = x^2(a^3+1)$ for some $x$ in $\mathbf{Q}$?
This question can be phrased also as follows:
Are there infinitely many rational numbers $(a,b)$ such that the extensions $\mathbf{Q}(\sqrt{a^3+1})$ and $\mathbf{Q}(\sqrt{b^3+2})$ are quadratic and equal?
Comment: What motivated this question?  It seems like this should have some relation to elliptic curves.
Answer: Yes.  Consider the two elliptic curves:
$$7r^2 = a^3+1$$
and
$$7s^2 = b^3+2.$$
One can check (using SAGE or MAGMA) that these two curves have infinitely many rational points (in fact they both have rank 1).
For rational points $(a,r)$ and $(b,s)$ on these curves we have that $a$ and $b$ satisfy the requirements of your question.
Comment: I chose 7 because this was the smallest square-free positive integer for which both curves have positive rank.  If you don't care that $a$ and $b$ vary, you could take $b=0$ and look at the curve $2r^2=a^3+1$, which has infinitely many rational points.
Comment: Question: Do I understand correctly that we always have $\mathbf{Q}(\sqrt{a^3+1}) =\mathbf{Q}(\sqrt{7}) = \mathbf{Q}(\sqrt{b^3+2})$ if $(a,r)$ and $(b,s)$ lie on the curve?
Comment: I like this answer a lot. It prompts the following question: Are there infinitely many square-free integers $n$ such that $nr^2=a^3+1$ has positive rank and $ns^2=b^3+2$ has positive rank?


Difference behavior between a python global variable and a global list?

Question: I am confused with the python's design of global variables, it seems quite different for a normal global variable and a global list, consider the following code:
global_list = []
global_var = 0

def foo():
    for i in range(10):
        global global_var  # without this, error occurs
        global_var += 1
        global global_list  # without this, fine!
        global_list.append(i)

foo()
print(global_list)
print(global_var)

The code is quite self-explained, I would like to know why this is the case, what is the logic behind that. Besides, I've also tested a dictionary, it behaves like a list. What about other stuff, such as a class instance or something...
Comment: The *type* of the object is irrelevant. The semantics are exactly the same.
Answer: From the Programming FAQs:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global.

When you write:
global_var += 1

You are assigning a value to the name global_var after you have already referenced the global version The += construct needs to read the global then reassign to it — it's equivalent to:
global_var = global_var + 1
^            ^
|            |--global reference
|- local assignment

According to the above rule, this would make it a local variable unless declared global but you've already referenced the global.
When you write:
global_list.append(i)

You are not assigning a new value to the name global_list. global_list still points to the same array, the same thing happens with a dictionary. You would need to declare global global_list if you tried to reassign with something like:
global_list = global_list + [i]

Comment: It doesn't really matter what the value is @喵喵是我的猫猫. What matters is whether or not you are reassigning the name (i.e. using `=`). If you can alter a user instance in-place without reassigning the name binding you don't need the global. Since things like numbers are immutable, you can't really change them without a reassignment.
Comment: what about a user declared instance.
Comment: In your answer, `According to the above rule, this would make it a local variable unless declared global but you've already referenced the global.`, if I don't declare it as global, this statement would be a wrong one, instead of making it a local variable.
Comment: If you don't declare it as global and you write `global_var = global_var + 1` You are assigning a local variable with `global_var =`, but trying to read a global with `global_var + 1`. Python evaluates the right hand side first and finds the global variable, but then it's not clear what to do in the assignment on the left-hand side.
Comment: Even if I write `global_var = global_var + 1 `, the code is still a wrong one in my case(python 3.64): `UnboundLocalError: local variable 'global_var' referenced before assignment
`


What is this hook supposed to do?

Question: I need to modify the query of one of my views. I've found hook_views_query_alter(), but can't for the life of me figure out what I'm supposed to do with it. According to the API,

This hook should be placed in MODULENAME.views.inc and it will be
  auto-loaded. MODULENAME.views.inc must be in the directory specified
  by the 'path' key returned by MODULENAME_views_api(), or the same
  directory as the .module file, if 'path' is unspecified.

OK, so I know to put the function with the hook in a views.inc file. But what do I need to put in the actual .module file? I can't seem to find any examples of complete module code that uses this hook to point me in the right direction. Does my module code contain the MODULENAME_views_api() and nothing else?
Answer: If your module doesn't need to implement any other hooks, then yep, hook_views_api() is all you need in your .module file.
As long as you provide the right path in hook_views_api(), Views will know where to look and will dynamically include the files when they're needed.
Usually you need to put files[] = mymodule.FILENAME.inc in your module's .info file for the dynamic code registry to pick it up, but from the looks of it that isn't the case for Views.
If you're looking for some code examples for this, take a look at the Administration Views module; it's .module file contains only hook_views_api() as well (and it works), so you can be confident you're doing the right thing.
Comment: This is the "proper" thing to do, but I don't recall a case where putting the hooks for altering queries or and of the build phases directly in a .module didn't work.
Comment: I'm not really sure to be honest I don't use views all that often, anything I came up with would just be a guess! There are a fair few people who visit this site who know a lot about views programming though so it might be worth asking it as a separate question
Comment: @MPD You're right it will always work in a .module file either way. Views just makes sure the file it suggests you put the hook in is included when the hook is invoked
Comment: So I could skip the .inc file entirely and just put in in the .module? My module isn't going to be doing anything other than modifying the query.
Comment: Yep, the .module file for any enabled module will be included during the bootstrap phase and views will only ever invoke the hook after that's happened. What I'm not sure of is if views expects the .inc file to be there whether or not it's got code in it. But I think you'll be able to test for that quite easily anyway
Comment: Yup, I can try it easily. So, I know this is sort of a different question, but where can I find the syntax for the various query modifiers? One of the examples I found looked like this: `$query->orderby[0] = "FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') ASC";` I'm not sure what that syntax is saying. Does it mean order by the node.type field, where nodes with story are first, then page, and so on? Or something else? I need to be able to group on multiple fields (and not all fields are on the initial node (relationships.)
Comment: The code registry is used only for classes and interfaces; it doesn't contain any information about functions. The Views module needs compatibility with previous Drupal versions, or it could have used [hook_hook_info()](http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_hook_info/7) to automatically load files containing hook implementations. To notice that [hook_hook_info()](http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_hook_info/6) in Drupal 6 has a completely different purpose.

What is this hook supposed to do?


Runtime crash when updating an image at each frame in Qt/QML

Question: The application is running fine and randomly crashes, the debugger is displaying this error :

0xc0000005: read access violation,
QOpenGLFunctions_3_2_Compatibility::glBeginTransformFeedBack

but that doesn't help that much since I don't know where this function is used.
Through my tests I think that the problem is coming from the image display. The program retrieves raw data from a remote device connected to a camera and the application is displaying it to show the video in QML app. When I comment for example the source of the image in QML, it doesn't crash.
In a thread :
bool success;
DWORD bytesRead;
DWORD lastError;
const unsigned int imgSize = IMG_HEIGHT * IMG_WIDTH * 1;

_rawData = new uchar[imgSize];

while(!_abort)
{
    if(_namedPipe != INVALID_HANDLE_VALUE)
    {
        /* Get raw data from the pipe */
        success = ReadFile(
            _namedPipe,
            _rawData,
            imgSize,
            &bytesRead,
            NULL);

        if(success)
        {
            /* Build an image from the raw data and send it to the PipeVideoStreamPlayer */
            QImage clImage(_rawData, IMG_WIDTH, IMG_HEIGHT, QImage::Format_Indexed8);

            _videostr->updateImage(clImage);
        }else

...

Image provider :
PipeVideoStreamPlayer::PipeVideoStreamPlayer(QQuickView* ptrApp)
: QQuickView(),
  QQuickImageProvider(QQmlImageProviderBase::Image)
{
    _ptrApp = ptrApp;
}

Update function :
void
PipeVideoStreamPlayer::updateImage(const QImage& image)
{
   _myImage = image;
    QObject* objMain = (QObject*) _ptrApp->rootObject();
    QQuickItem *obj = objMain->findChild<QQuickItem*>("videoStreamFrame");

    QMetaObject::invokeMethod(obj, "reload");
}

In QML, image + reload function called at each frame :
Image {
    objectName: "videoStreamFrame"
    cache: false
    anchors.centerIn: parent
    source: "image://videostream/yellow"

    function reload() {
        var oldSource = source;
        source = "";
        source = oldSource;
    }

The app can run for 5 minutes before crashing, and sometimes it takes only 10 seconds.
If I comment the reload function it doesn't crash either.
EDIT:
Here are the modifications I've done so far :
class StreamPainter : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QImage streamImage READ streamImage WRITE setStreamImage NOTIFY streamImageChanged)
public:
    StreamPainter(QObject *parent = 0);
    ~StreamPainter();

    QImage streamImage();
    void setStreamImage(QImage clImage);

signals:
    void streamImageChanged(QImage Image);

public slots:
private:
    QImage _streamImage;
};

QImage StreamPainter::streamImage()
{
    return _streamImage;
}

void StreamPainter::setStreamImage(QImage clImage)
{
    _streamImage = clImage;
    emit streamImageChanged(clImage);
}

Set context :
view->engine()->rootContext()->setContextProperty("streamImage", streamImage);

In my thread :
QImage clImage(_rawData, IMG_WIDTH, IMG_HEIGHT, QImage::Format_Indexed8);

_spvideostr->setStreamImage(clImage);

Now I need to display the image in QML but how to do it here without ImageProvider ?
Comment: What's_ptrApp? Those lookup lines in updateImage don't look thread-safe, as you're accessing objects from the main UI thread from your worker thread. I'd rather send the whole QImage to the other thread, via a signal. (It's implicitly shared, so the copying is cheap). Also, I'd export it via a Q_PROPERTY to QML and use a binding in there, instead having knowledge about QML items in the C++. Or, even better, make the movie item a custom QQuickItem painting the frames itself.
Comment: Thanks for your answer. I've added the code part about _ptrApp. Sorry I'm still learning QML and I have difficulties to understand your method but I will try with those new informations.
But how to refresh the image only in QML ?
Answer: I didn't managed to change really the code to display the image, I think a lot of problems are coming from how the thread is used in my program but for the moment I managed to fix the problem by using a mutex around the private _myImage variable in the request function called by QML and the updateImage called by the thread :
QImage PipeVideoStreamPlayer::requestImage(const QString & id, QSize * size, const QSize & requestedSize)
 {
    Q_UNUSED(id)
    Q_UNUSED(size)
    Q_UNUSED(requestedSize)

    _mutex.lock();
    _prevImage = _myImage;
    _mutex.unlock();
    return _prevImage;
 }

When _myImage is locked I send the previous image. Since it isn't happening a lot I should just lose some frames from time to time but it will not be visible.
void
PipeVideoStreamPlayer::updateImage(const QImage& image)
{
    _mutex.lock();
   _myImage = image;
   _mutex.unlock();
    QObject* objMain = (QObject*) _ptrApp->rootObject();
    QQuickItem *obj = objMain->findChild<QQuickItem*>("videoStreamFrame");

    QMetaObject::invokeMethod(obj, "reload");
}


Using local variables outside their functions

Question: I understand that functions are useful for code which will be used multiple times so I tried creating a function to save myself time and make my code look neater. The function I had looks like this:
def drawCard():
    drawnCard = random.choice(cardDeck)
    adPos = cardDeck.index(drawnCard)
    drawnCardValue = cardValues[adPos]

However, I am not sure how to return these variables as they are local(?). Therefore, I can not use these variables outside the function. I am just wondering if someone could help edit this function in a way where I could use the drawnCard and drawnCardValue variables outside the function?
Comment: [`return`](http://docs.python.org/3/reference/simple_stmts.html#the-return-statement)
Answer: Use return:
def drawCard():
    drawnCard = random.choice(cardDeck)
    adPos = cardDeck.index(drawnCard)
    drawnCardValue = cardValues[adPos]
    return drawnCard, drawnCardValue

drawnCard, drawnCardValue = drawnCard()

Note, you could also write drawCard this way:
def drawCard():
    adPos = random.randrange(len(cardDeck))
    drawnCard = cardDeck[adPos]
    drawnCardValue = cardValues[adPos]
    return drawnCard, drawnCardValue

These two functions behave differently if cardDeck contains duplicates, however. cardDeck.index would always return the first index, so drawnCardValue would always correspond to the first item which is a duplicate. It would never return the second value (which in theory could be different.)
If you use adPos = random.randrange(len(cardDeck)) then every item in cardValue has an equal chance of being selected -- assuming len(cardValue) == len(cardDeck).


SQL Server 2008 R2 Writing To Text File

Question: I used to write to text files from SQL Server using the code listed below:
DECLARE @FS INT         --File System Object
DECLARE @OLEResult INT  --Result message/code
DECLARE @FileID INT     --Pointer to file

--Create file system object (OLE Object)
EXECUTE @OLEResult = sp_OACreate 'Scripting.FileSystemObject', @FS OUT
IF @OLEResult <> 0 PRINT 'Scripting.FileSystemObject.Failed'

-----OPEN FILE-----
EXECUTE @OLEResult = sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 8, 1
IF @OLEResult <> 0 PRINT 'OpenTextFile.Failed'

It appears this is no longer supported in sql server 2008 r2.  How should I export to text files in sql server 2008 r2?
Link claiming this is no longer supported:
http://social.msdn.microsoft.com/Forums/en/transactsql/thread/f8512bec-915c-44a2-ba9d-e679f98ba313
Answer: What that article is referring to as deprecated is SQL DMO (having been replaced with SQL SMO beginning with SQL Server 2005).  However, your code does not use SQL DMO objects so you're really barking up the wrong tree.  The post you link to just coincidentally uses the sp_OA* procs to create instances of SQL DMO objects.
You need to turn the Ole Automation Procedures option on in your SQL instance.  As a security precaution it's turned off by default.  This option is required in order to to use the sp_OA* procs.
This should do it for you.
sp_configure 'show advanced options',1
GO

reconfigure
GO

sp_configure 'Ole Automation Procedures',1
GO

reconfigure
GO

Comment: You are correct about the article referring to the DMO.  I made sure these options were set and I still can't open/create the text file to write to.
Comment: It fails on the line where it tries to create/open the text file.
Comment: What's the error that you're seeing?  Most likely it's a permissions problem, or the files in question don't exist.
Comment: When I execute the line to create or open the file if everything goes ok @OLEResult should equal 0, but it is being set to a negative number.
Comment: Specifically it returns -2146828218.
Comment: Ok, then you'll need to research what that error code means in the context of the Scripting.FileSystemObject class and the OpenTextFile method on that class.  Again, it's likely to be a permissions issue or a file existence issue.  The problem is definitely not related to a deprecated feature in SQL Server 2008R2, though.  That nasty error code is definitely a COM error code which means your calls to the sp_OA* procs are happening.
Comment: Do you have any idea where I can get more information on these error messages? I have tried google and msdn with no luck.
Comment: I think it is an unauthorized access error. Is it possible SQL Server isn't getting administrator permissions? How would I solve this?
Comment: Yes, it's possible.  COM errors are notoriously evil to troubleshoot.  There are different accounts that are used depending on what context the statements are run as (interactive, via a SQL Agent job step, etc)
Comment: The error in question is pretty easy to find, convert `-2146828218` from Dec to Hex (using calc.exe in Programmer's mode) and you get `FFFFFFFF800A0046` in `Qword` mode, which is the default. Take `800A0046` (or change to `Dword` mode) and after googling it you'll get `Permission Denied`.

SQL Server 2008 R2 Writing To Text File


iOS: Displaying information from an XML (DTD) file on to the screen?

Question: I am very new to this area but I've been assigned this task.  I have been working on this for three weeks with no success and am hoping someone can either help me or point me in the right direction.
I am trying to display information from a DTD file on to my iOS's screen.  The DTD file is on the web server.  I can Parse the file fine, and everything seems to be working so far.  But when I go to display the information (inside of a tableView) it comes up blank.
What I need to know is this:

What's the best way TO show the output of the file (tableView, view, etc.?)

I have looked at sample code, read articles, etc. about this topic and am confused about how to SHOW the output.
Answer: Any number of possible causes ...it might be useful to post the  table datasource code in your question.  I think the most common cause is a not-hooked-up datasource outlet on the table view.  Please check the table view's connections in the xib/storyboard and make sure it's datasource outlet is connected to the class with the datasource code (these methods), probably the view controller that contains the table.
The connection's inspector is the rightmost tab on xcode's righthand pane.
Comment: Thanks for the help.  I didn't include the code because I didn't know how at the time I wrote that.  Anyway, your post did help.


How can I check which method of checking a port state is more efficient?

Question: I'm writing a script to schedule port checks on some of my servers, and report the state. I am planning to go along with one of two options:

Pipe the output of netcat (nc) into a perl variable, and check the return state
my $rcode=`nc -z 126.96.36.199 80; echo $?`

Use the perl module IO::Socket::PortState to do the same thing.
use IO::Socket::PortState qw(check_ports);
my %porthash = ( ... );
check_ports($host,$timeout,\%porthash);
print "$proto $_ is not open ($porthash{$proto}->{$_}->{name})
    if !$porthash{$proto}->{$_}->{open};

I'd like to go along the more efficient (shorter time, more specific) route.
Is there a rule of thumb regarding this? As in piping the output of a system command/unix utility is more/less efficient than using a perl module? Or are different perl modules different, and one can check the same only by setting up multiple iterations of these checks and compare the time taken by this versus a system call to execute a unix utility?
Comment: Yes. The rule of thumb is to benchmark it.
Comment: Benchmark -- definitely. I'd only add that you should be explicit about what you mean by "efficient".
Comment: I meant time efficient and precise (less false values).
Comment: you might consider use Socket; directly.  as this is the baseline socket implementation from perl, and a near direct mapping from c it should be the best means of doing this in perl.  Though tbh you could probably just as easily write it in C at this point, Socket.pm is that close to socket.h
Answer: This isn't really an answer to your question so much as a suggested implementation.
Just a quick run at an untested example of using Socket.pm.
This is probably the fastest perl implementation.  But at the point you are using socket.pm you may as well just write it in C with socket.h.  They are a near 1:1 mapping.
Ref:
#!/usr/bin/perl -w

use Socket;

$remote  = $ARGV[0];
$port    = $ARGV[1];

print ":: Attempting to connect to - $remote.\n";
$iaddr = inet_aton($remote) or die "Error: $!";
$paddr = sockaddr_in($port, $iaddr) or die "Error: $!";
$proto = getprotobyname('tcp') or die "Error: $!";

socket(SOCK, PF_INET, SOCK_STREAM, $proto) or die "Error: $!";
connect(SOCK, $paddr) or die "Error: $!";

print ":: Connected Successfully!\n";


Couldn't find suitable architecture for linking arm64 in Mach-O file Payload/Runner.app/PlugIns/OneSignalNotificationServiceExtension

Question: When archiving the project, I'm getting the below error after tap on distributing in Xcode
couldn't find suitable architecture for linking arm64 in Mach-O file /var/folders/36/x3lk24wj2333jtl767bbzgc80000gn/T/ipatool20210917-65819-szkdq8/universal-MachOs/Payload/Runner.app/PlugIns/OneSignalNotificationServiceExtension.appex/OneSignalNotificationServiceExtension
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: I solved this issue in Xcode
In my case architecture arm64 was excluded
Go Build settings > excluded architecture Section > click and remove exculded architecture


Array is not iterable in useReducer()

Question: To practice React hooks I wrote a simple todo site with ReactTS. I faced a problem that I keep receiving an error that my todos array is not iterable, despite it is defined as TodoProps[] in State type
Error occurs logically after 'add' button click
Error: state.todos is not iterable
If I write console.log(state.todos) I receive undefined
I checked code on medium and it seems to be identical to mine, but anyway I cannot resolve this issue.
(Error place marked in code)
TodoProps:
export interface TodoProps {
      title: string
      id: number
      todoKey?: number
      completed: boolean
}

LayoutContext.tsx:
import { createContext, useState, ReactNode } from 'react'

export const TodoListContext = createContext<any>({})
export const TitleContext = createContext<any>({})

type LayoutContextProps = {
      children: ReactNode
}

export const LayoutContext = ({ children }: LayoutContextProps): JSX.Element => {
      const [title, setTitle] = useState<string>('')
      const [todoList, setTodoList] = useState<object[]>([
            {title: 'Todo 1', id: 418759},
            {title: 'Todo 2', id: 440123}
      ])

      return (
            <TitleContext.Provider value={{ title, setTitle }}>
                  <TodoListContext.Provider value={{ todoList, setTodoList }}>
                        {children}
                  </TodoListContext.Provider>
            </TitleContext.Provider>
      )
}

Layout.tsx:
import { Button, Todos, Input } from 'Components'
import { LayoutContext } from 'Context/LayoutContext'
import cn from 'classnames'
import styles from './Layout.module.scss'

export const Layout = (): JSX.Element => {
      return (

                  <LayoutContext>
                        <Todos/>
                        <Input/>
                        <Button>Add</Button>
                  </LayoutContext>

      )
}

Button.tsx:
import styles from './Button.module.scss'
import { ButtonHTMLAttributes, DetailedHTMLProps, ReactNode, useReducer, useContext, useEffect } from 'react';
import { TodoListContext, TitleContext } from '../../Context/LayoutContext';
import { TodoProps } from 'Components/TodoComponent/Todo';

interface ButtonProps extends DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> {
      children: ReactNode
}

export const Button = ({ children }: ButtonProps): JSX.Element => {
      const { todoList } = useContext(TodoListContext)
      const { title, setTitle } = useContext(TitleContext)

      type State = { todos: TodoProps[] }

      type Action = { type: 'addTodo', payload: string }

      const reducer = (state: State, action: Action) => {
            switch (action.type) {
                  case 'addTodo':
                        const newTodoCard: TodoProps = {
                              title: action.payload,
                              id: Math.floor(Math.random() % 10),
                              completed: false
                        }

                        console.log(todoList)
                        console.log(state.todos)

                        return {
                                     Error here
                                     \/\/\/\/\/\/\/\/\/\/\/\/\/\/
                              todos: [...state.todos, newTodoCard]
                                     /\/\/\/\/\/\/\/\/\/\/\/\/\/\
                        }
            }
      }

      const [state, dispatch] = useReducer(reducer, todoList)

      const handleAdd = (e: any) => {
            e.preventDefault()

            dispatch({ type: 'addTodo', payload: title})
            setTitle('')
      }

      return (
            <button
                  type='submit'
                  onClick={handleAdd}
                  className={styles.button}
            >{children}</button>
      )
}

Don't know if I can add any more information..
Comment: Your initial state is `todoList`, which is an array, not an object with a key of `todos`.
Comment: Where did you wrapped your button with `LayoutContext`?
Answer: You are passing an array to the initial state into your reducer and accessing it as an object in your reducer so you just need to change these lines
from
const [state, dispatch] = useReducer(reducer, todoList)

To
const [state, dispatch] = useReducer(reducer, { todos: todoList });

and you are good to go.
Comment: Could you please help with this question https://stackoverflow.com/questions/75570226/on-click-during-navigate-the-viewcount-values-is-still-0

Array is not iterable in useReducer()


Linhas em Colunas sem Predefinição de colunas - SQL Server

Question: Ola, estou com uma dificuldade transformar linhas em colunas no SQL Server.
Não consegui escrever nada ainda... Pensei no PIVOT, mas como não é sempre a mesma quantidade de colunas, não estou conseguindo pensar em como fazer...
Tenho essas 2 tabelas:

Resultado esperado:

É para um relatório isso.
Comment: Que tal uma function ou uma subConsulta?
Comment: @Marconi, como faria? O meu maior problema está sendo em, eu nao ter uma quantidade definida de colunas, ou seja, neste exemplo eu fiz com 4 defeitos, mas eu posso ter mais, tanto quanto eu posso ter menos
Comment: Como se eu tivesse um contador que me mostrasse o item que tem mais defeito e este seria o meu limite para aquele relatorio, seguindo entao, eu terias os demais itens com seus respectivos defeitos. Ou seja, se o item com a maior quantidade de defeitos for 5, entao terei 5 colunas de defeitos e assim, os demais defeitos de cada item, seria distribuido nestas 5 colunas
Answer: Leooso, você precisa fazer um PIVOT em cima de um INNER JOIN, seria algo assim... exemplo
SELECT equ.Id, equ.Equipamento, def.*
FROM equipamento equ
INNER JOIN defeito def
ON equ.Id = def.EquipamentoID

Agora o PIVOT:
DECLARE @registros as table (
    id int,
    equipamento varchar(50),
    Defeito1 varchar(50),
    Defeito2 varchar(50),
    Defeito3 varchar(50),
    Defeito4 varchar(50)
)

SELECT *
FROM @registros
PIVOT (
    MAX(Valor)
    FOR Campo IN
    ([Nome], [Email], [tel], [campoX], [campoY])
) AS pvt
ORDER BY idRegistro

Veja também:
Transformar linhas em colunas com seus respectivos valores
Comment: Perdão, não tinha reparado, vou dar uma olhada
Comment: Mas eu nao tenho uma quantidade exata de defeitos entendeu? Assim como posso ter 5 posso ter 20, pode ser que eu nao esteja conseguindo visualizar a sua solução
Comment: Dando uma melhor analisada eu entendi a sua solução, porem eu não posso ter fixo esses seguintes valores: (No meu caso) `([Defeito 1],[Defeito 2],[Defeito 3],[Defeito 4])` pq eu não sei quantos podem vir a existir...
Comment: Leo, veja o link que eu te passei (Transformar linhas em colunas com seus respectivos valores) pq o camarada fez com um número variável de colunas também, do jeito que você quer.
Comment: Mais uma vez desculpa por não ter prestado atenção, deu certo aqui, obrigado


Large sample limit of linear and ridge regression

Question: I wanted to check if these reasonings are correct.
The formula for a multilinear regression, input $X_{s,i}$, where $s$ is the sample and $i$ the features, and output $Y$, is given by:
$$\beta=(X^+X)^{-1}X^+Y$$
Now if we define:
$Q_{ij}=\sum_s X_{si}X_{sj}, M_j=\sum_s X_{js}Y_s$
than the equation is equivalent to:
$$\beta_i=\sum_{j} [Q^{-1}]_{ij}M_{j}$$
Now we can add the number of samples into this formula $N_s$:
$$\beta_i=\sum_{j} [Q/N_s]^{-1}_{ij}[M/N_s]_{j}$$
and observe that we have some sample averages:
$Q_{ij}/N_s=\sum_s \left( X_{si}X_{sj}\right) /N_s  \rightarrow E[X_iX_j]$
and:
$M_j/N_s=\sum_s \left( X_{js}Y_s \right)/N_s \rightarrow E[X_jY]$,
so that in the large sample limit we expect:
$$\beta_i \rightarrow (E[X_*X_*])_{i,j}^{-1}E[X_jY]$$

Question 1. Is this result expected/trivial/correct ?

Now we can try to get a large sample limit for Ridge regression. Looking at internet this implies that $Q$ must be replaced with $Q+\lambda I$ and the formula becomes, after inserting as before the number of samples:
$$\beta^R_i=\sum_{j} [(Q+\lambda I)/N_s]^{-1}_{ij}[M/N_s]_{j}$$
But here it looks that as before:
$(Q+\lambda I)/N_s \rightarrow Q/N_s \rightarrow E[X_iX_j]$
because the added factor becomes negligible. If we want to have a different limit we should have $\lambda$ scaling with the samples : $\lambda=\rho N_s$ and in this case:
$(Q+\rho N_s I)/N_s \rightarrow Q/N_s \rightarrow E[X_iX_j]+\rho I$
, so that:
$$ \beta^R_i \rightarrow (E[X_*X_*]+\rho I)_{i,j}^{-1}E[X_jY] $$

Question 2. Is this result expected/trivial/correct ?
Question 3. If yes, is it correct that the ridge regression factor should scale with $N_s$ to get a finite value ?
Question 4. Can we understand something about the behavior of Ridge regression looking at the large sample limit formulas?
Answer: Basically, yes.

Indeed, consistency of OLS for linear projection coefficients is basically an application of the law of large numbers.
Indeed - ridge is a tool to trade off some bias against less variance in small samples. When sample size goes to infinity, that tradeoff vanishes when the number of parameters stays constant.
Technically, yes, although - see 2) - I would not see why one would want a different limit.
Probably - e.g., again see 2): the ridge adjustment only matters in finite samples.
Comment: Thanks I think I had the math right but not the interpretation... +1 I will take some time to think about your answer and if I do not have further questions accept...
Comment: Thanks for your insights. I have the impression that this effect may be also clear if we consider a derivation of Ridge regression as maximizing a posterior that one gets putting a prior on the linear weights. Independently of the prior with infinite data one should recover the correct values. The regularization should serve in this sense to speed up convergence with the number of samples.
Comment: This kind of bias is a bit different instead than model bias, that instead survives in the infinite sample limit.
Comment: I just added what where my thoughts/understanding reading your answer. If you have some comment let me know but in any case I accept the answer and thank you again.
Comment: Yes, I agree with your view and perspective that the data will dominate regular priors in large samples and that this is therefore a finite sample effect, unlike inconsistency resulting from e.g. omitted variables which does not wash out with more data - comparing many apples with many oranges does not make the comparison any better...


asterisk confbridge and answering machine detection

Question: I have an outbound conferencing system using asterisk. I call all the participants and connect them to music on hold. when the last participant answers I start the ConfBridge application.
I want to know if the call to the last participant was answered by a human or voicemail, and I thought about using the AMD application. Is it possible to run this application after starting the ConfBridge app?
Answer: Asterisk call usually have 2 channels
There are no any issues start one channel to confbridge other to AMD
You also can improve confbridge( expert/god-like c/c++ skill required) to do what you needed.
Comment: I have to start ConfBridge as soon as the last participant answers, and as far as I understand the call to ConfBridge from the dialplan is synchronous, so I can't call AMD afterwards. The only solution I came up with is what you suggested - take the logic from the AMD app and integrate it with the ConfBridge app.
Comment: You can call AMD on other leg of call. Also it seams usless for me do confbirdge after that AMD,usually it have sense do via vesa: first AMD,after that Confbridge if human.
Comment: The other participants have to hear everything the last participants says. This means that I have to put him in the conf bridge as soon as he joins. Otherwise, if I run AMD and only then join the conference the other participants may not hear what he says until AMD is done.
Comment: If so,other participants WILL hear voicemail,no? If you insist, you can do AMD in other thread connected via chanspy. However anyway seams such setup go far beyond your asterisk skill. You have learn more(maybe some curses?) or hire expert.
Comment: I have no problem with the other participants hearing voicemail. if you explain the setup to me I believe I can do it. How can I fork the call to two threads?
Comment: Create enother call(google asterisk dialout) and bind it via chanspy command.


Admin approved file uploads

Question: I want to allow all authenticated users to upload files, but I want them to be approved first before they're publically viewable.  I'm currently using a single image field for the uploads, that can have unlimited values.
I'm not sure what is a good way of going about this.  Let's say, the user uploads 4 images, which are all shortly after approved.  Then, later, they upload one more image... I still want the first four to be publically viewable, but I don't want the fifth one to be until it's approved.
Also, I am kind of concerned about the fact that the files would be downloadable immediately, as soon as they are uploaded via sites/default/files.  Is this a big deal?  Concerned about copyright violations and such.
Answer: I believe what you wanted is similar to commerce file module where users can upload file and have configurable settings, where you can limit access duration, number of downloads etc. and about this one downloadable immediately, as soon as they uploaded via sites/default/files. Is this a big deal? yes it is big deal once you uploaded it in sites/default/files everyone can access it and download anytime without restriction you may violate some regulation. you should upload it outside Drupal where users can't access it via url. Where in commerce file already have this settings where you could place your file folder outside Drupal. I am not sure if this is already available in Drupal 8.

Admin approved file uploads


The recored file is empty in kurento

Question: Kurento can't record video, my code is like below,
<code> WebRtcEndpoint webrtcEndpoint =..;
 RecorderEndpoint recorderEndpoint = new RecorderEndpoint.Builder(getPipeline(), "file:///tmp/test.webm")
            .withMediaProfile(MediaProfileSpecType.WEBM)  //I also tried MP4
            .stopOnEndOfStream()
            .build();

    recorderEndpoint.addRecordingListener(new EventListener<RecordingEvent>() {

        @Override
        public void onEvent(RecordingEvent event) {
            log.info("start recording for userId: {}, live:{}", getUserId(), getLiveId());
        }

    });

    recorderEndpoint.addStoppedListener(new EventListener<StoppedEvent>() {

        @Override
        public void onEvent(StoppedEvent event) {
            log.info("stopped recording for userId: {}, live:{}", getUserId(), getLiveId());
        }

    });

    recorderEndpoint.addPausedListener(new EventListener<PausedEvent>() {

        @Override
        public void onEvent(PausedEvent event) {
            log.info("Pause recording for userId: {}, live:{}", getUserId(), getLiveId());
        }

    });

    recorderEndpoint.addErrorListener(new EventListener<ErrorEvent>() {
        @Override
        public void onEvent(ErrorEvent event) {
            log.info("record error: {}, live:{}, event:{}", getUserId(), getLiveId(),event.getType()+ "|" +  event.getErrorCode() + ":" + event.getDescription());
        }
    });

    webrtcEndpoint.connect(recorderEndpoint);

    log.info("recorderEndpoint.record() called!");
    recorderEndpoint.record();
</code>
I'm sure webrtcEndpoint is connected and make video normally.
The problem is the file test.webm created in the directory /tmp; but it is empty!
The problem appear when my android connect to server. If I use browser, doesn't have the issue.  Any reason it can be?
Answer: Finally, I got the answer. The reason is the service side try to connect both video and audio, while client (device) only send video, so the record can't start. The issue was actually fixed on client side.

The recored file is empty in kurento


How to set pre-amp to avoid noise?

Question: I have got a Taylor 312ce 12-fret. Since I could not find any acoustic multi-effect processor which has no pre-amp integrated in it (which is also something I do not get), I now got a Trace Elliot Transit a. The problem however is that it amplifies the quite low noise of the guitar itself such that it results in a constant, quite high, noise level. You can find an amplified sound example here. First part is without pre-amp, second part is with pre-amp. All equalizers are set to flat. You may ignore the hum, this is another issue (tackled in a separate question).
Edit: Setting the external pre-amp's treble control to -15db nearly eliminates the hiss. Turning the treble control on the guitar's preamp to a maximum however does not reintroduce it. Any ideas? Is this normal preamp noise?
Comment: The Taylor website says the pickup works like a microphone.  I did not find any details on its design.  The red and white wiring in the picture suggests a  balanced output in a shielded cable between the electronics and some sort of socket I cannot see.  I wonder if it needs a microphone pre-amp perhaps with balanced input and 1/4" output between the guitar and the Trace Elliot Transit a.  It might kill the hum too.  May be a trip to a music store where they sell stage equipment is in order.
Answer: Ignoring the hum, the hiss is most likely radio frequency interference. It's all around us, always, so this is probably due to bad shielding somewhere. Possibly in your guitar since there will be signal carrying cables after the guitar preamp. So, assuming you have nothing else in the signal path the bad shielding is either in your guitar, lead or in your pre-amp. First place to check is your lead. Swap this out. If the problem persists there may be a problem with your pre-amp. If it's brand new that's unlikely. Test the guitar by moving it around. Does the sound change? If yes it's poor shielding in the guitar. But... check this article out about gain structure: http://livesoundadvice.com/circuit-theory/sound-advice-pa-performance/
Comment: Could be right Emma, thinking about it, the most common place for problems is where you get mechanical contact, such as a jack lead socket in the body of the guitar. Could be the ground is not making good contact. However if it`s a balanced out and a mono jack is being used this could also point to the source. Might be worth trying a stereo jack lead. Even if this then goes down to mono at the pre-amp stage it might cure it.

How to set pre-amp to avoid noise?


Create block user flag, hide users from view

Question: I have created a social site where users can flag other users as "blocked". The primary view for the site lists users along with a bit of profile2 data and a "block" flag link. Users cannot see themselves in the view.
What relationships and filter criteria do I need to add to hide blocked users from the view on a per-user basis?
Example use case: 4 users, User A blocks User C
User A's view:

User B
User C (message about how you blocked them)
User D

User B's view:

User A
User C
User D

User C's view:

User B
User D

User D's view:

User A
User B
User C
Comment: You can add a **filter criteria** (Flags: Flagged (False))to list only those user who are not flagged by the current user. For this you have to use relationship as **Flags: User flag**
Answer: I couldn't find a way to do this within Views, despite the seemingly simple task and the various decent explanations found around the internet (nit3ch's comment included). The explanations limited the view results too much or in the wrong way.
I ended up using a Views PHP filter field to perform the filtering task:
<code>global $user;
$flags = flag_get_user_flags('user', NULL, $row->uid);
if( array_key_exists('block', $flags) && array_key_exists($user->uid, $flags['block'])){
    //dsm($row); // optional debug
    return TRUE; // prevents row from being displayed
}
</code>


How to make galleries relative to particular nodes?

Question: I have a site with news and I want to make it possible for admin to add image gallery to Articles (nodes) the admin wants. So, the idea is to make gallery image field for every content type from which images should be taken. If admin wants gallery for that article the admin can upload images, if the admin don't the admin can just leave it alone, and Drupal renders that node without gallery perfectly normal.
So, I made that gallery image field for every content type, and used Views module for taking and rendering pictures. But, whereas views taking pictures at content type level not node level, that is the reason why unpleasant consequence appear: gallery from particular node, shows on every node of that type.
My question is how to make galleries relative to particular nodes (specific gallery for specific node)? And it should be extremely easy for admin to manipulate.
Comment: "and used Views module for taking and rendering pictures." - why? Drupal is perfectly capable of displaying multi-value image fields even without use of Views. Just use this capability and you will get your "specific gallery for specific node". Or am I missing something?
Answer: The simplest way: Use colorbox module
In the structure of the content type add an image type (with multiple values allowed) and put its display type to be a colorbox gallery
The complex way: use view slideshow and computed field
Still add an image field to the content type, but set its rendering to hidden.
Add a computed field with the value equal to the node nid and the display a view that take the node nid as contextual filter and render the image field using the slideshow plugin.
Set the display of this computed field as unsanitized.
Computed code:
<code>if (!$entity->nid) node_save($entity);
</code>
Display Code (PHP):
<code>$display_output = views_embed_view('<your view name>','<your view display name>',$entity_field_item['value']);
</code>
You can get an example here: http://agriregionieuropa.univpm.it/content/event/test-antonello (tab "video ed immagini").
The video slideshow uses the second approach (in this case videos, in your case photoes, it's the same), while the photo gallery uses the colorbox approach.
Answer:
how to make galleries relative to particular nodes (specific gallery for specific
node).

You have probably forgot the contextual filter "content nid" in your views:
In the option "When the filter value is not available":

add "content nid" in your view
check the line "Provide default value"
Select "Content ID from URL" from the dropdown
Answer: You could use that gallery field formatter which gives you the ability to make the image field which have multiple values to be displayed as a gallery   You could control the field display settings from its display settings per content type


JavaScript to change value of textbox

Question: This code is for an unsubscribe form, where I need to toggle whether or not a checkbox is checked on initial start, and then change values based on a user's selection.
Basically, I'm passing a value into the html through our email platform. If the value is I, the checkbox should be checked and the value I. Conversely, if the value is O, the checkbox should not be checked and the value O.
For the data to be passed back into our email platform I have to use a hidden input to capture the value, otherwise it won't actually send the I or O back.
The JavaScript, which I have as a  tag in the head (HTML Email)
var initValue = function() {
    var permStat = document.getElementById("emailPref").value
    if(permStat === "I"){
      document.getElementById("checkbox").checked = true;
    } else {
      document.getElementById("checkbox").checked = false;
    }
  }
  var changeValue = function(){
    var optValue = document.getElementById("checkbox").value;
    if(optValue === "I"){
      document.getElementById("checkbox").value = "O";
      document.getElementById("emailPref").value = "O";
      document.getElementById("checkbox").checked = false;
    } else {
      document.getElementById("checkbox").value = "I";
      document.getElementById("emailPref").value = "I";
      document.getElementById("checkbox").checked = true;
    }
  }

The visible label for toggling the style (using CSS only)
<input type="checkbox" id="checkbox" name="emailPerm" value="$EMAIL_PERMISSION_STATUS_$" onload="initValue();" onclick="changeValue()">

And the hidden input, the one that passes data back to our email platform
<input type="hidden" id="emailPref" name="EMAIL_PERMISSION_STATUS_" value="$EMAIL_PERMISSION_STATUS_$">

Additional info
On loading with I value, it appears as this (which would be the "O" value):

On clicking, after this state, the value does set to "O" and the styling remains the same. On a second click, the value goes back to "I" and displays properly:

**I apologize in advance if this is an obvious mistake, since I typically cannot use JavaScript in HTML emails but since this is technically presented as a landing page, it works.
Thanks!
Comment: If you're setting the hidden input with data from the Server aren't you able to simply create an input that's checked depending on that same data?
Comment: @zfrisch yes, that is what the initValue function is aiming to do. It's pulling in the value of that and _supposed_ to be adjusting the value of checked, but it isn't
Answer: The problem is that onload is not a valid attribute for a checkbox. Because of this your initValue never runs. Add a script tag like so below your elements.

JavaScript to change value of textbox


move marker realtime from database firebase to mapbox

Question: I want to move a marker based on realtime database firebase like tracking the user. When the database updates the location, mapbox will update the position marker. I have a problem on my website, when javascript get location from database, marker will update but marker becomes duplicates and not delete previous data. So please help me to make delete previous data and just display update marker.
The code is given below
The result of code
Comment: Please don't share code as image but instead add into the answer. You can read why here - https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors
Answer: You are creating a new marker each time. Instead you could store each TeamLeader name and the corresponding marker in a json object and just update their coordinates.
you need to create a json object (called teamLeaderMarkers in the example), and also store the team leader name (teamLeaderName in the example.
Then inside your callback function in setInterval, you'd have something like this:
if (teamLeaderMarkers.hasOwnProperty(teamLeaderName)){
    teamLeaderMarkers[teamLeaderName].setLngLat([long,lat]);
} else{
    let marker = new mapboxgl.Marker(el);
     marker.setLngLat([long,lat])
     marker.addTo(map);
    teamLeaderMarkers[teamLeaderName] = marker;
}


Limit of $\frac{x^c-c^x}{x^x-c^c}$ as $x \rightarrow c$

Question: My question is: Show that $\lim_{x \rightarrow c} \frac{x^c-c^x}{x^x-c^c}$ exists and find its value.
Because the limit is 0/0 I've tried using L'Hopital's rule, but every time I differentiate it I still get 0/0?
We're given this hint in the question: use the fact that $a^b=\exp(b\log(a))$ and I've tried doing this to be able to differentiate and use L'Hopital's rule, and also for trying to rearrange it. Can anyone help please?
Comment: If you perform L'Hopital the $c^c$ in the denominator should dissapear and you should get a defined value.
Comment: Ahh I did make a mistake! I didn't do that, but didn't consider c^c as a constant when differentiating haha my bad! Thank you :)
Answer: No need invoke L'Hospital here, just rewrite the fraction:
$$\frac{x^c-c^x}{x^x-c^c}=\frac{(x^c-c^c)-(c^x-c^c)}{x-c}\frac{x-c} {(x^x-c^c)}$$
By definition,

$\dfrac{(x^c-c^c)}{x-c} \;$ tends to the derivative of  $x^c$ at $x=c$, i.e. to $c^c$;
$\dfrac{(c^x-c^c)}{x-c}\; $ tends to the derivative of $c^x$ , i.e. $c^c\ln c$.
$\dfrac{(x^x-c^c)}{x-c}\; $ tends to the derivative of $x^x$, i.e.$\;c^c(\ln c+1)$.

Thus $\;\lim\limits_{x\to c}\dfrac{x^c-c^x}{x^x-c^c}=\dfrac{c^c(1-\ln c)}{c^c(1+\ln c)}=\dfrac{1-\ln c}{1+\ln c}$.
Answer: Why turn to L'Hopital at all, whose hypotheses are not so easy to check anyway? Rather consider the "simple" derivatives of the functions $f(x)=x^c$, $g(x)=c^x$ and $h(x)=x^x$, namely, $$f'(x)=cx^{c-1}\qquad g'(x)=c^x\ln c\qquad h'(x)=(1+\ln x)x^x$$ Using these at $x=c$, one gets the limits $$\lim_{x\to c}\frac{x^c-c^c}{x-c}=f'(c)=c^c$$
$$\lim_{x\to c}\frac{c^x-c^c}{x-c}=g'(c)=c^c\ln c$$
$$\lim_{x\to c}\frac{x^x-c^c}{x-c}=h'(c)=(1+\ln c)c^c$$ Now, for every $x\ne c$,$$\frac{x^c-c^x}{x^x-c^c}=\frac{\frac{x^c-c^c}{x-c}-\frac{c^x-c^c}{x-c}}{\frac{x^x-c^c}{x-c}}$$ thus, the desired limit is $$\lim_{x\to c}\frac{x^c-c^x}{x^x-c^c}=\frac{f'(c)-g'(c)}{h'(c)}=\frac{1-\ln c}{1+\ln c}$$
Answer: You can apply L'hopital rule, there's nothing wrong in it. Why reinvent the wheel? Lets differentiate wrt $x$:
$$\lim_{x\to c}\frac{cx^{c-1}-c^x \ln(c)}{xx^{x-1}+x^x \ln(x)} = \frac{1-\ln(c)}{1+\ln(c)}$$
Here we have used that $\frac{d(x^x)}{dx} = x\cdot x^{x-1} + x^x \ln(x)$, which can be directly evaluated (i dont remember the name of the theorem) and also by taking logarithms.


Mark method to never return nil

Question: I'm developing an API using Objective-C, this API has protocol with some fictional method:
- (NSString *)gimmeString; // Want implementations to never return nil

I'm a big fan of providing context, so I heavily use everything for that purpose including attributes like __attribute__((nonnull)) and friends. What I'm asking is if there a way to provide context and possibly add a compile time check for method implementation saying "this method never returns nil" when compiled with clang?
i.e. I'd love to have something like:
@protocol MyProtocol
- (NSString *)gimmeString __attribute__((no_I_never_really_really_return_that_weird_nil));
@end

@implementation MyProtocolAdopter
- (NSString *)gimmeString
{
    return nil; // WARNING! You're returning nil, YOU PROMISED!
}
@end

instead of just:
@protocol MyProtocol
// This method should never return nil
- (NSString *)gimmeString;
@end

@implementation MyProtocolAdopter
- (NSString *)gimmeString
{
    // muvahaha, I lied!
    return nil;
}
@end

I understand it is impossible to fully determine that at compile time, but detecting return nil; or functions which for sure evaluate to nil is fine.
Idea with something like __attribute__((objc_method_family(copy))) seems weird and unacceptable, but I didn't manage to find anything better then just adding a comment leaving my API users in a bit scarier and more unreliable world.
Answer: - XCode 6.3 -
Since XCode 6.3 you, actually, can annotate pointers to be nullable and nonnull and get compile time checks.
- (nonnull NSString *)gimmeString;

- Pre XCode 6.3 -
After some research, which included digging into clang and gcc docs I found that there's no way to achieve what I want in Objective-C.
Thoughts why is that so:
I believe that's because there's no way to determine that at compile time at some sophisticated level of quality. You can't tell for sure if method always returns not-nil at compile time. And determining if method could return nil is something shaky, guess, it's possible to evaluate all
return %something_which_evaluates_to_nil_at_compile_time%;

and warn on all methods which depend on that, but, for example, you can't be sure that some -init method does not always return nil or some web request get's you a request without additional context provided everywhere and you'll end up with false-negatives.
Even -dequeueReusableCellWithIdentifier:forIndexPath: from UITableView which guaranties to always return valid cell is defined as just:
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier
                           forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);

What I've came up with:
So, what I've came up in Objective-C is providing context without compile-time checks. I add comments like that:
@protocol MyProtocol
/**
 *  Creates and returns a string.
 *
 *  @note Implementations should never return nil.
 *
 *  @return A string, guarantied not to be nil.
 */
- (NSString *)gimmeString;
@end

Also one more thing could be done to make this more readable, we can define an empty define and append it to the end of declaration, like this:
// Marks method to never return nil
#define MD_RETURNS_NONNULL

@protocol MyProtocol
/**
 *  Creates and returns a string.
 *
 *  @note Implementations should never return nil.
 *
 *  @return A string, guarantied not to be nil.
 */
- (NSString *)gimmeString MD_RETURNS_NONNULL;
@end

So eye catches this line making your code more readable, making your code users happier because they understand what you want to emphasise easier.
Swift
And the last but not the least is suggestion to move to Swift. In Swift this is possible and built in, you just define your method to return not an optional type:
protocol MyProtocol {
    func gimmeString -> String
}

And you're good to go.
Conclusion
If you really want checks like this in Objective-C there's no magic, you only do it at the run time, at the same time you could provide context, which is great. But oh, wait, there's also Swift option, we'll anyway migrate to it at some time, so take your time and spend some of it learning this great new language. This need is a great example where Swift's safety features are really suitable.
UPD: Played with OCLint a bit, looks like something like this could be achieved using it (or just writing a custom Clang extension).
Comment: Not sure what you are attempting to achieve with the bounty. You already have the correct answer. Objective C is dynamic and is not type safe in this case. Swift has been created with this issue as one of its main design goals.
Comment: @LeoNatan Yeah, I think it's correct as well. Just curious if there are some related under the hood nerdy details or some experimental clang branch which does something around what I want.

Mark method to never return nil


WITH CHECK | NOCHECK OPTION FOR EXISTING DATA CHECK ENFORCEMENT IS IGNORED

Question: I am using Visual Studio 2012, with a SQL database project and running database analysis against this database and it is raising the following warning:
WITH CHECK | NOCHECK OPTION FOR EXISTING DATA CHECK ENFORCEMENT IS IGNORED.
My understanding of the error is that the CHECK and NOCHECK constraints will be ignored for the existing data when the script is run (in each case for me, it is an ALTER TABLE).
My question is thus, why would a check constraint be ignored?
Warning ID number
It seems the warning ID has changed so I am including both below so that it is easily searchable in future.
In Visual Studio 2010 this had the warning ID of: SQL03159
In Visual Studio 2012 this has the warning ID of: SQL70588
Related Information
ALTER TABLE [dbo].[MyTable] CHECK CONSTRAINT [FK_MyTable_SomeCol]
Comment: I'm using Visual Studio 2010, and the warning ID I get is SQL70588 for an SSDT project. Is the VS2010 warning ID in your question for a non-SSDT DB project?
Answer: It isn't about redundancy, but rather the fact that the project is desired state, or the ideal state of the DDL schema.
When applying the project to an existing database, the process (publish, dacpac deployment, etc) will enforce the check constraints as the delta is applied. The with check and with nocheck are therefore meaningless in the project DDL that defines the table and subsequent constraint(s).
The only place CHECK and NOCHECK are honored are in the pre and post deployment scripts.
EDIT:
If you ever generate a script from a dacpac you will notice things happen in phases.
When it comes to applying new constraints, they are always added WITH NOCHECK. The final phase is applying WITH CHECK to all constraints that need it, AFTER post deployment scripts are run. This allows the maximum amount of customization to occur during the various phases, including the pre and post deployment script phase.
Answer: In my case, this occurred in a script I imported that had a structure like this:
CREATE TABLE [dbo].[ELMAH_Error]
(
    [ErrorId]     UNIQUEIDENTIFIER NOT NULL,
)
GO
ALTER TABLE [dbo].[ELMAH_Error] WITH NOCHECK ADD
    CONSTRAINT [PK_ELMAH_Error] PRIMARY KEY NONCLUSTERED ([ErrorId]) ON [PRIMARY]
GO

When I look at the above code, the WITH NOCHECK looks redundant since the table should have only just been created and therefore be empty. So I suspect this code analysis warning is pointing out this redundancy.
Answer: Use the "FOREIGN KEY" statement in the table creation script, do not use the "ALTER TABLE" later to create the foreign key. Example:
CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

Hope this helps!


Restore /var owner and group (mysql and apache needed)

Question: Huh, I feel kinda dumb right now.
Just did an
<code>chown -R www-data:www-data .*
</code>
and voilá, /var is all messed up.
Already fixed some to root, but mysql refuses to start.
How can I restore the owner/group to /var/* on a Ubuntu 10.04.1 LTS ?
Thanks!
Comment: If nothing better, boot up other ubuntu VM and copy one by one :(
Answer: Try this:
<code>$ chown -R mysql:mysql /var/lib/mysql
</code>
Comment: Done it already, did't work. also fixed the mysqld.sock :|
Comment: So, did that work, then?
Comment: To MySQL, yes. Thank you. Now I have to check the rest, some things might be broken too and I didn't notice...yet :|


Permissions in windows forms

Question: We have developed an ERP system in Windows Forms,  users need to have granular permissions throughout the system. To achieve this, each form is pretty much its own exe. We have a main menu where we add a MenuItem to the database and we can then give users permission to access this.  We will then pass a  Guid through to each exe as an id for the "Session". Permissions are checked before the exe is launched not by the exe itself.
So our "Main Menu" is built up of these exe's the table is "Id, Title, Exe,..,..).
So over the years the project has grown, we now have one solution with over 800 small projects in it and  4 shared dll's (Data, BL,UI,Printing).  Our VS solution really struggles with performance.
I was thinking of combining the forms into a few projects, using a custom attribute to use reflection to build the menu. I guess then, instead of launching an exe we would use reflection to instantiate the form and display it? Would this be the best way to go about this? Or is there some framework designed for Windows Forms that can handle this?
Also would this improve VS performance? same amount of code just less projects?
Aside from this we also have in-app permissions used to enable/disable controls. Though i don't think they would be affected by this.
Answer: I'm not sure of your intermediate steps but an approach I've used recently in an erp system was to use a variation of the command pattern. If you put into a command the logic to check security and start the form or a variation of that then you could use reflection to locate the command or locate them all at startup and store them in a list. either way it is relatively simple to do.
<code>public interface ICommand
{
    Guid GetUniqueId();
    bool Execute();
}
</code>
Then the actual command can be something like
<code>  public class YourWinformCommand: ICommand
    {
        private User _user;
        private Guid _securityCode = new Guid(".......");

        public Guid GetUniqueId()
        {
            return _securityCode;
        }

        public  bool Execute()
        {

            if (_user.HasAccessTo(_securityCode))
            {
                //Load the winform here.

                return true
            }

             return false;
        }
    }
</code>
With a command for each entry point you should be able to merge the winforms into logical sets and place them in dlls instead. now once that's done use reflection locate a given command by its interface and testing for the identifier
<code>    /// <summary>
    /// This class contains methods to construct a concrete object from an interface.
    /// </summary>
    public static class ServiceFactory
    {

        /// <summary>
        /// Builds a concrete instance of an interface
        /// </summary>
        /// <typeparam name="T">The interface of the object</typeparam>
        /// <returns>If found, a concrete object is returned that implements the interface</returns>
        public static T Build<T>() where T : class
        {
            string applicationPath = AppDomain.CurrentDomain.BaseDirectory;

            string[] files = Directory.GetFiles(applicationPath, "*.dll");

            foreach (string file in files)
            {
                // Dynamically load the selected assembly.
                Assembly theAssembly = Assembly.LoadFrom(file);

                // See if the type implements T.
                foreach (Type type in theAssembly.GetTypes())
                {
                    if (ImplementsInterface(type, typeof(T)))
                    {
                        // Use late binding to create the type.
                        return (T) theAssembly.CreateInstance(type.FullName);
                    }
                }
            }
            return null;
        }

        public static bool ImplementsInterface(this Type type, Type ifaceType)
        {
            return type.GetInterfaces().Any(x => x == ifaceType);
        }

}
</code>
From that code modify it to include the guid in the equation or modify it to return all commands, your choice.
Hope it helps.

Permissions in windows forms


Dominating function for derivative of moment generating function

Question: Let $X$ be a random variable and the moment generating function
$$\psi_X:(-\varepsilon,\varepsilon)\rightarrow \mathbb{R}_+,\quad \psi_X(t):=E[e^{tX}]$$
be defined, such that $\psi_X(t)<\infty$ for all $t\in(-\varepsilon,\varepsilon)$. According my textbook we have
$$\psi^{(n)}_X(0)=\frac{d^n}{dt^n}E[e^{tX}]\bigg|_{t=0}=E[\frac{d^n}{dt^n}e^{tX}\bigg|_{t=0}]=E[X^n],$$
where differentiation and integration can be interchanged by using dominated convergence.
However what is the dominating function here? It is clear that for all $t\in(-\varepsilon,\varepsilon)$, we have
$$\frac{d^n}{dt^n}e^{tX}=X^n\ e^{tX}$$
So I need to find a integrable dominating function $h:\Omega\rightarrow\mathbb{R}_+$, such that
$$\forall t\in(-\varepsilon,\varepsilon): |X^n\ e^{tX}|\le h$$
Does someone has a hint on this one?
Thanks a lot in advance!
Comment: I do not think the exact method you propose will work. Say $X\ge 0$ for simplicity. The smallest possible dominating function is $\sup_{|t|<\varepsilon} |X^n e^{tX}|=X^n e^{\varepsilon X}$. You know that $E[e^{\varepsilon X}]<\infty$, but this does not imply $E[X^ne^{\varepsilon X}]<\infty$.
Answer: There's no need for differentiation under the integral sign. First note that for $|t|<\varepsilon$, $$\frac{|t|^n|X|^n}{n!}\leq e^{|tX|}\leq e^{tX}+e^{-tX}$$
So $X$ has moments at any order.
Next, $E(e^{tX})=E\left(\sum_{k=0}^\infty\frac{(tX)^k}{k!}\right)$ and note that for all $n$, $$\left| \sum_{k=0}^n\frac{(tX)^k}{k!} \right|\leq \sum_{k=0}^n\frac{|tX|^k}{k!} \leq e^{|tX|}\leq e^{tX}+e^{-tX}$$
The DCT applies and yields $\Psi_X(t)=E\left(\sum_{k=0}^\infty\frac{(tX)^k}{k!}\right) = \sum_{k=0}^\infty\frac{t^k}{k!}E(X^k)$.
Hence $\Psi_X$ coincides with a power series over $(-\varepsilon, \varepsilon)$. It is therefore infinitely differentiable at $0$ with $\psi^{(k)}_X(0)=E(X^k)$.
Comment: @Mike The power series $\varphi: t\mapsto \sum_{k=0}^\infty\frac{t^k}{k!}E(X^k)$ has a radius of convergence at least $\varepsilon$. By a standard result in the theory of power functions, it infinitely differentiable at $0$. Now since $\Psi_X$ and $\varphi$ coincide over $(-\varepsilon, \varepsilon)$ the statement carries over to $\Psi_X$.
Comment: Hello, I am reading this answer and have a question. In the last step, you said the MGF concides with power series over the $\varepsilon$-neighborhood of $0$, then it is infinitely differentiable at $0$. Is there a theorem saying this? Thank you.
Answer: The short answer to your question is that you can always find a
$\delta >0$ s.t. for all $t<\epsilon - \delta$, $|x^n e^{t|x|}| \leq |x|^n e^{(\epsilon-\delta)|x|}$, and $|x|^n e^{-\delta |x|}$ is bounded for all $n$ and $\delta$, while $e^{\epsilon |x|}$ is integrable by assumption.
First, consider the case $n=1$.Then,
$$\psi'(t) = \lim_{h\rightarrow 0} \frac{\psi(t+h)-\psi(t)}{h} = \lim_{h\rightarrow 0} E[\frac{e^{(t+h)X}-e^{tX}}{h}].$$
Now, choose $\delta>0$ s.t. $0<\delta<\epsilon$. Assume $t$ and $h$ are small enough s.t. $t\pm h \in (-\epsilon + \delta, \epsilon - \delta)$. By the Mean Value Theorem, for any x, there exists a $t' \in [t,t+h]$ s.t.
$$ \frac{e^{(t+h)x}-e^{tx}}{h} = x e^{t'x}. $$
Since $t' \leq \epsilon - \delta$,
\begin{equation}
|xe^{t'x}| \leq |x|e^{|t'x|} \leq |x|e^{(\epsilon -\delta)|x|} \leq C e^{\epsilon|x|},
\end{equation}
where $C=\delta^{-1}e^{-1}$, the maximum of $f(x)=|x|e^{-\delta|x|}$. Next, observe that $e^{\epsilon|x|}\leq e^{\epsilon x}+e^{-\epsilon x}$, which is integrable by assumption. This allows to use dominated convergence to deduct the claim.
The case $n>1$ follows by induction and using a similar bound, i.e.,
$$|x^{n}e^{t'x}| \leq |x^{n}| e^{(\epsilon-\delta)|x|} \leq Ce^{\epsilon|x|},$$ where $C = \max_x f(x) = max_x\{|x|^n e^{-\delta|x|}\} \leq (n/\delta)^ne^{-n}$, which, again, is integrable by the same logic as in the base case $n=1$.


What is the latest stable valid linux kernel for 3.8 version?

Question: I want to know the latest stable kernel version of 3.8. Can any one help me out for this issue?
I browsed for this issue but I didnt get the solution
Comment: Looking down ftp://ftp.kernel.org/pub/linux/kernel/v3.x/ , it seems to be 3.8.13.  But why do you want to know?  What's the underlying question, here?
Comment: Since i want to build the latest kernel instead of upgrading the operating system. thanks for your answer
Answer: Looking down ftp://ftp.kernel.org/pub/linux/kernel/v3.x , it seems to be 3.8.13.
I've repeated my comment as an answer so I can warn you against this.  I do have production systems which use hand-built kernels, because there are compelling business reasons to use them, but they are a huge maintenance overhead.  I don't yet understand why you think you need to do this, but I can say with some certainty that it will be a lot of time and effort for you.
I don't know ubuntu's support policies, but my understanding is that as long as 12.04 is in support, you can expect to find any important fixes from later kernels back-ported into the repositories, so just doing an apt-get upgrade should fix any security issues.  Once the OS falls out of support, you have bigger problems than the kernel falling out of rev, and need to arrange and upgrade as a matter of priority; just keeping the kernel updated won't keep you secure.
In addition, on some Red Hat systems I've done this on in the past, it turns out that Red Hat have been pulling in technology from some much later kernel, and that when I compiled a vanilla kernel from a numerically-later version that the old RH one, it wasn't yet up-to-date enough to fully support the library environment of the RH glibc etc.
Comment: this is for research, but not for the production


Difference between an $L^p$ space on a bounded set and a periodic $L^p$ space?

Question: I'm confused about the concept periodic $L^p$ space. Let $\mathbb{T}$ be the quotient space $\mathbb{R}/\mathbb{Z}$. Here are my questions:

What is the Lebesgue measure on $\mathbb{T}$? How do people assign measures on a quotient space?
What exactly is the difference between $L^p(\mathbb{T})$ and $L^p([0,1])$?

What I think is that $L^p([0,1])$ is the restriction of $L^p(\mathbb{R})$ functions on $[0,1]$; while $L^p(\mathbb{T})$ is the space of periodic functions (with period $1$) $f$ on $\mathbb{R}$ such that $f1_{[0,1]}\in L^p([0,1])$.
Could anyone come up with references for detailed explanation?
Comment: There's really no effective difference between these two spaces (i.e., they are isomorphic). Given any $f \in L^p([0,1])$ you can periodize it to get $f \in L^p(\mathbb{T})$. You start to see differences when you consider the Sobolev space $H^1(\mathbb{T})$ compared with $H^1([0,1])$. The periodization of $f \in H^1([0,1])$ may not be in $H^1(\mathbb{T})$, since you may introduce a bad discontinuity.
Answer: To quote Tao's comment on this question:

One can define the Lebesgue measure on ${\bf T}$ by identifying that space with one of its fundamental domains, such as $[0,1)$. The spaces ${\bf T}$ and $[0,1)$ are thus isomorphic as measure spaces, and so $L^p({\bf T})$ and $L^p([0,1))$ are isomorphic as normed vector spaces. However, ${\bf T}$ and $[0,1)$ differ in other respects if one considers other structures than the measurable structure. For instance, from the point of view of topological structure ${\bf T}$ is compact and not simply connected, while $[0,1)$ is non-compact and simply connected. The differential structure is also different, for instance the identity function $x \mapsto x$ on $[0,1)$ is smooth using the differential structure of $[0,1)$, but is not even continuous if one replaces the domain with ${\bf T}$. In particular, PDE on $[0,1)$ and on ${\bf T}$ are quite different.
If one only cares about the measurable structure, then $[0,1)$, $[0,1]$, and ${\bf T}$ are isomorphic (up to null sets), and if one only cares about the normed vector space structure, $L^p([0,1))$, $L^p([0,1])$, and $L^p({\bf T})$ are all isomorphic. However, for applications to PDE one usually needs more structure than just the measurable or normed vector space structure (in particular, one needs differential structure), and then the three domains are all inequivalent (for instance the Sobolev spaces on the three domains behave differently).
Answer: One possible answer to your question is the following:
The space $[0,1)$ forms, with respect to the subspace topology, a topological group under ordinary addition, and the space $\mathbb{T} := \mathbb{R} / \mathbb{Z}$ forms, with respect to the quotient topology, a topological group under addition modulo $1$. The map
$$ \varphi : [0,1) \to \mathbb{T}, \quad x \mapsto e^{2\pi i x} $$
is an isomorphic homeomorphism between the topological groups $([0,1), +)$ and $(\mathbb{T}, +_1)$, and hence $\mathbb{T} \cong [0,1)$ as topological groups. From this it follows that $L^p ([0,1)) \cong L^p (\mathbb{T})$.
A slightly different approach regarding the identification of $\mathbb{T}$ and $[0,1)$ is given in $\S 3.1.1$, called the The n-Torus $\mathbb{T}^n$, of Grafakos' Classical Fourier Analysis.


Erro ao instalar Compass no Mac

Question: Estou tentando instalar o compass na minha máquina e me deparo com o seguinte erro.
Estou usando com comando com sudo.
<code>    Building native extensions.  This could take a while...
    ERROR:  Error installing compass:
    ERROR: Failed to build gem native extension.

    /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby -r      ./siteconf20140930-1189-279ned.rb extconf.rb
    checking for ffi.h... *** extconf.rb failed ***
    Could not create Makefile due to some reason, probably lack of necessary
    libraries and/or headers.  Check the mkmf.log file for more details.  You may need configuration options.

    Provided configuration options:
       --with-opt-dir
       --without-opt-dir
       --with-opt-include
       --without-opt-include=${opt-dir}/include
       --with-opt-lib
       --without-opt-lib=${opt-dir}/lib
       --with-make-prog
       --without-make-prog
       --srcdir=.
       --curdir
       --ruby=/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby
       --with-ffi_c-dir
       --without-ffi_c-dir
       --with-ffi_c-include
       --without-ffi_c-include=${ffi_c-dir}/include
       --with-ffi_c-lib
       --without-ffi_c-lib=${ffi_c-dir}/
       --with-libffi-config
       --without-libffi-config
       --with-pkg-config
       --without-pkg-config
     /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:434:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
    You have to install development tools first.
    from       /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:549:in `block in try_compile'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:502:in `with_werror'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:549:in `try_compile'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:1044:in `block in have_header'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:895:in `block in checking_for'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:340:in `block (2 levels) in postpone'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:310:in `open'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:340:in `block in postpone'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:310:in `open'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:336:in `postpone'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:894:in `checking_for'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:1043:in `have_header'
from extconf.rb:16:in `<main>'

extconf failed, exit code 1

Gem files will remain installed in /Library/Ruby/Gems/2.0.0/gems/ffi-1.9.5 for inspection.
Results logged to /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-13/2.0.0/ffi-1.9.5/gem_make.out
</code>
Alguém já teve o mesmo erro? sabe como resolvo?
Answer: Aparentemente você não está conseguindo compilar uma extensão em código nativo da gem. Ou seja, essa gem precisa de algo externo ao ruby que provavelmente foi programado em C.
Recomendo instalar programas para compilar C, como as developer tools do xcode, e atualizar o seu ruby. Essa resposta tem instruções de como instalar as developer tools: https://stackoverflow.com/a/9329325/4068246 [em inglês].
Comment: Então Daniel, já fiz isso de instalar o Developer Tools do Xcode, e tentei por diversas vezes atualizar o ruby. Mais até agora nada disso funcionou.
Comment: @william-costa , Você já tentou usar o RVM para gerenciar a versão do ruby na sua máquina. Uma vez tive problema de não conseguir instalar uma gem que resolveu magicamente quando troquei para o ruby 2.1.2 .
Comment: Não tentei isso ainda Daniel. Vou procurar saber.

Erro ao instalar Compass no Mac


bundle.js not getting created

Question: I am trying to create simple webpack project using vs code.
It has two folders:
1.dist
2.src
i have app.js file in src folder and i need the bundle file to be created with the webpack command
for this i am using below command
webpack ./src/app.js ./dist/bundle.js

but this command is giving below error
ERROR in multi ./src/app.js ./dist/app.bundle.js
Module not found: Error: Can't resolve './dist/app.bundle.js' in 'D:\Webpack\WEBPACK-101'
 @ multi ./src/app.js ./dist/app.bundle.js
There is some minor thing which I am missing, it would be very helpful if anyone can figure it out what exactly I am missing?
Thanks in advance!!!
Comment: Please post your webpack config
Comment: currently i have not created the webpack config file, i am only having the package.json file for now
Answer: You will need to create webpack.config.js
const path = require('path');

module.exports = {
  entry: './src/app.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

Update package.json
{
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
+     "build": "webpack"
    },
.....
}

And Run
npm run build

More Details
Comment: Thanks Captain for instant reply!!! main.js  file got created by just running webpack command
Answer: If you don't have a webpack.config.js file, you can rely on the default configuration for that, but you need to do some things before.
First, your "main" script has to be in: src/ and it should be named index.js
By default the output is always dist/.
So knowing that, you can run: webpack. And your bundle is going to be generated.

Or you could webpack --entry ./src/app.js --output ./dist/bundle.js
Comment: i have index.js file in src folder
Comment: i just ran webpack cmd and it worked, main.js file got created in dist folder,Thanks
Comment: why "webpack ./src/app.js ./dist/bundle.js"  command is not working?
Comment: You said it was called app.js.

Just run webpack, it should compile.
Comment: my bad,i missed to mention index.js file
Comment: Because it is wrong. correct is: `webpack --entry ./src/app.js --output ./dist/bundle.js`. But it is good for you to know everything.
Answer: First of all it is important that all data in fajl package.json will be entered through the command line/ terminal/gitshell...Than, on windows 10 I resolved the problem with typing in terminal next:
$ npm install typescript

bundle.js not getting created


How do assign a role to user after add to cart in ubercart in drupal 7?

Question: I am using ubercart for my site.. I need to assign a role to user after shopping with price base.. If user does $300 shopping then role 10%-role . if user does $400 shopping then 20%-role etc.. And remember these role next shopping.
Answer: Try to do this using Rules.

Add a new rule on event complete checkout.
Give your required conditions.
Add Assign role to user as action.

For your scenario you can do it using multiple rules.
Hope this will help you.


Using terminal to sort data and keep the format in notepad.exe

Question: I'm using Ubuntu Bash within Windows 10 and I have a text document with:
{u'osidjfoij23': 3894798, u'oisjdao':234567, u'oaijsdofj': 984759}

using tr, in terminal I change my output to
'osidjfoij23': 3894798,
'oisjdao':234567,
'oaijsdofj': 984759}

when opening the same document via notepad.exe, the newline "\n" added from tr doesn't register and all the data gets presented as a paragraph.
I know this is because bash and notepad have different encodings for their documents, is there a way to make these work together or an alternative I can use for notepad?
Answer: You can use unix2dos to convert a file to Windows line endings. Linux programs handle Windows line endings fairly well, so this shouldn't break anything (especially if that's JSON as it appears to be).
Comment: was worried for a second because dos2unix was all that was showing up in apt-cache, but I saw it came bundled with unix2dos as well. Just tried it out and works exactly like I needed. Thank you!