BeautifulSoup returns excessive content for  tags

Question: Basically I'm trying to get all meta tags from a site with bs4.
import urllib.request
from bs4 import BeautifulSoup
response = urllib.request.urlopen("https://grab.careers/").read()
response_decode = response.decode('utf-8')
soup = BeautifulSoup(response_decode,"html.parser")
metatags = soup.find_all('meta')
file = open('text.out','w')
for x in metatags:
    file.write(str(x))
file.close()

I expect only meta tags to be returned from the above code. However, the soup returns both meta, links and scripts content as you can see from this snippet:
<meta content="Grab Careers | Working For A Better Southeast Asia" name="twitter:title" />
<meta content="Working For A Better Southeast Asia on Grab Careers�" name="twitter:description" />
<link href="https://grab.careers/" rel="canonical">

I could not find any resources addressing this problem. How can I fix this so only meta tags are returned.
Answer: To be honest, I cannot exactly figure out why this happens, but it can be resolved if you use lxml instead of html.parser:
soup = BeautifulSoup(response_decode,"lxml")

lxml packages needs to be installed, e.g. with:
pip install lxml
Comment: This works wonderful thanks a lot. I just knew that some closing tags in the response end with ">" instead of "/>" which screw up the html parser. Lxml parser has no problems though.
Answer: find_all method gives a tag along with all its children.
I think this is happening due to missing closing / for empty HTML tags.
The meta tags which are closed properly like <meta charset="utf-8"/> (note / at the end) are parsed as one single tag.
Whereas a meta tag like <meta content="max-snippet:-1,max-image-preview:standard,max-video-preview:-1" name="robots"> is not parsed as closed tag (due to missing /) and thus includes all the tags until a closing </meta> is encountered. These children tags actually include the link and script tags that you are seeing.


Runge-Kutta ODE Solver

Question: please keep in mind that the following is homework, I do not want answers, only help. If you are confused as to what I refer to in this question, or I don't make any sense, please refer to the link below.
This is my assignment
I'm trying to plot the path of a firework that weighs $.0008 kg$ and has a density of $1900 kg/m^3$, and has a burn rate of $0.0027 kg/s$ in 2d using java. The firework has a launch velocity of $22 m/s$. The only force acting on the x-axis is the drag force, and wind velocity which I can change.
The forces acting on the x axis are:
-the initial velocity $22 m/s$
-the drag force
-gravity $9.807 m/s^2$
-the wind force: anywhere from $-15$ to $15$
The drag force is computed by $F_D=(pvAC_D)/2$
$p$=fluid density$=1.2 kg/m^3$
$v$=velocity magnitude
$A$=cross sectional area$=0.00046140621$
$C_D$=drag coefficient$=.4$
Without any wind acting on the x axis, the velocity magnitude is merely: $\sqrt(22^2+0^2)=484$
Now using the formula: $F_D=(pvAC_D)/2$ we get: $F_D=(1.2*484*0.0004614*.4)/2=.05359$
Now we also add the mass times the gravity(9.8m/s^2)to get our total force on the y axis.
$F_y=-mg-F_D(v_y/v)$ ($v_y$, the velocity of y, is the same as v, the velocity magnitude, since the x axis velocity is 0, so $v_y/v=1$)
Which translates to $F_y=-0.0008*9.8-.5359*(1)=-.54374$
So there is a total of .54374 downwards force on the y axis.
My professor then says to use the Runge-Kutta ODE solver to find the velocity of $x_k+1$ and $y_k+1$ but I'm not sure how to interpret the Runge-Kutta solver into the formulas that I've already been given.
To conclude, I know the initial downward force on the object, I know that it has an initial velocity of 22 meters/s, and I know that the mass will be reducing as my path increases. I don't want to know the wind force at this time, as I want to add that in afterwards.
Could someone please help me understand how the Runge-Kutta ODE solver applies to this assignment?
To answer Kalvotom:
The total force being placed on the sphere for each axis is as such:
$F_x=-F_D(v_x/v)$ and $F_y=-mg-F_D(v_y/v)$
quoting the assignment:
"Since force equals mass times acceleration and acceleration is the first differential of velocity with time, these two equations can be expressed as two differential equations:"
$dv_x/dt=(F_Dv_x/mv)$ and $dv_y/dt=-g(F_Dv_y/mv)$
"These two ordinary differential equations cannot be solved using algebra, so we are going to have to resort to a numeric technique." AKA Runge-Kutta
Answer: In order to see where the need for an ODE solver comes from, you have to be aware of the fact that you are trying to solve Newtonian equations of motion. I do not see those equations explicitly in your analysis.
Edit: Hmm, let me try it this way (I do not want to solve your HW :-)): you want to solve
$$ z' = f(z), $$
where $z$ is a vector of unknown functions, let there be $n$ of them, and $f:\mathbb{R}^n\to\mathbb{R}^n$. The corresponding RK4 scheme (one of many RK methods available) works in the following way. Let $h$ be a small parameter (time step size) and let $z_0\in\mathbb{R}^n$ and $t\in\mathbb{R}$ be given. Then compute
$$ z_1 = z_0 + \frac{1}{6}(k_1 + 2k_2 + 2k_3 + k_4), \quad t_{1} = t_0 + h, $$
where
$$ k_1 = h f(z_0), \ k_2 = hf(z_0 + \frac{1}{2}k_1), \ k_3 = f(z_0 + \frac{1}{2}k_2), \ z_4 = h f(z_0 + k_3). $$
This gives you a mapping $z_0 \mapsto z_1$. $z_0$ are the initial data at $t$ and $z_1$ is an approximation of the solution at time $t+h$. Now you just have to iterate this map over and over again. That is, you take $z_1$ instead of $z_0$ and compute $z_2$, etc.
In your case the unknowns are $z=(x,y,v_x,v_y)$. You have $x' = v_x$, $y' = v_y$, $v_x' = \cdots$, $v_y' = \cdots$. So if we denote $f=(f_1,f_2,f_3,f_4)$ then for example $f_1(x,y,v_x,v_y) = v_x$. You have to find the other componentes, write down this iterative scheme (essentially a simple loop where you record values at each iteration) and you are done.
Comment: Hmm, let me try it this way: you want to solve
$$ x' = f(x), $$
where $x$ is a vector of unknown functions, let there be $n$ of them, and $f:\mathbb{R}^n\to\mathbb{R}^n$. The corresponding RK4 scheme (one of many RK methods available) works in the following way. Let $h$ be a small parameter (time step size) and let $x_0\in\mathbb{R}^n$ and $t\in\mathbb{R}$ be given. Then compute
Comment: I've answered Kolvotom's question at the end.
Comment: Ok. So now you have to set up the RK numeric scheme. It is written in your assignment. You just have to find what the $f$ functions are in this case.
Comment: Wouldn't the f functions be the force on x and y?
Comment: Sorry if I'm not understanding, I never took physics or calc and this is for a computer science class, perhaps I'm overthinking something that should be much simpler.
Comment: What I'm doing right now is taking the RK and applying it to $V_y$, then subtracting the drag force from it. Does that sound right?
Comment: I had to post this as a new answer:
Comment: Yeah I believe I understand what you're saying. What I'm doing right now in my program is running each initial velocity through the Runge Kutta Solver then subtracting the total force placed on the object to get the current velocity at point $V_{yk+1}$ and $V_{xk+1}

Runge-Kutta ODE Solver


How to print/render nested Paragraph values to twig template?

Question: I'm trying to figure out how I can render values from nested Paragraphs. Basically I have field/values from a Paragraph within a Paragraph I have tried experimenting and searching for answers but I can't seem display the values from the nested Paragraphs to the twig template.

Here is the sample of the code below that I have been working on
First Paragraph
{% for paragraph in node.field_sidebar_area %}

{{ paragraph.entity.field_label.value }}

        {% for block_query in paragraph.entity.field_block_query  %}

            {{ block_query.entity.body.value | raw }}

        {% endfor %}

         {% for link in paragraph.entity.field_link_item %}

{{ link.url }}

{{ link.title }}

         {% endfor %}

    Second Paragraph
    {% for object in paragraph.node.field_sidebar_content %}

        {{ object.entity.field_label.value }}

    {% endfor }

{% endfor %}

Comment: What I'm asking for here is trying to print values from nested paragraphs..
Comment: The code you posted isn't even working though? That looks like Menu twig code which won't work here. You render paragraphs like normal fields, they have their own twigs and preprocess hooks as well.
Comment: @Kevin the `field_menu` is just a machine name, it's not actually a menu.
Comment: You are using `{{ node.field... }}`  variables, they only work in `node--xxx.hml.twig` templates, not in paragaph templates. Paragraph have their own `paragraph--xxx.html.twig` templates, and you need to access fields in there with `{{ paragraph.field... }}`
Comment: @Hudri I'm using  `{{ node.field }}` on my `page.html.twig`. Currently printing the values / data to my page.html.twig template
Answer: I am also curious about the best way to do this. While I'm still trying to figure out what that is, here is what I've done:
I've enabled the Twig Tweak module, and inside the first paragraph template, I pull in the second paragraph with a selected view mode.
{{ drupal_entity('paragraph', content.field_sidebar_area[0]['#paragraph'].id(), 'MY_CUSTOM_VIEW_MODE') }}

And then in the template for the second paragraph, I can adjust the Twig as I please. Note that the naming convention would be:
paragraph--PARAGRAPH-TYPE--MY-CUSTOM-VIEW-MODE.html.twig.

Best of luck!
Comment: Sorry for my ignorance how do you fetch or print the paragraphs on the `page.html.twig`
Comment: You should be able to use that same code, but you could replace the 'MY_CUSTOM_VIEW_MODE' with 'default'. Note that this requires Twig Tweak to be enabled.
Comment: An example without Twig Tweak would be great.


using full-text search with LINQ and EF

Question: I'm trying to implement a full-text search with EntityFramework.
My DB has a table called Users and a table called UserInfoEntries. The table users is connected to some other tables, and the table UserInfoEntries contains user information.
When i want to get the user info, i go through the entries in User.UserInfoEntries and get the one with the oldest entry timestamp.
The property i want to use as the key for the full-text search is the FullName property within the UserInfoEntry.
The LINQ for getting the users with the exact FullName looks like this:
from user in objectContext.Users

let currentInfoEntry =
(from entry in user.UserInfoEntries
 orderby entry.EntryTimestamp descending
 select entry
).FirstOrDefault()

where currentInfoEntry.FullName == "Some Name"

select new UserWithInfo
{
    User = user,
    Info = currentInfoEntry
}

I would like to use the full-text search by FullName. Is there an easier way than transalting the query to SQL?
Answer: This is not full-text search. It is just a normal search with the full match. You can simplify the query by reverting it:
var query = from x in objectContext.UserInfoEntries.Include("User")
            where x.FullName == "Some Name"
            orderby x.EntryTimestamp descending
            select x;

UserInfoEntry entry = query.FirstOrDefault();
User user = entry.User;

This query expects that your UserInfoEntry entity has navigation property called User pointing to User entity.
Comment: Sorry for the missunderstanding, but i was wondering how to perform a full-text search in this case. In other words how to find a user with some name using FTS. (i.e. for a keyword matt, i would like to get all the users named matt, matthew and similar).

using full-text search with LINQ and EF


como resolver o problema Task 'scripts' is not in your gulpfile

Question: este é meu gulpfile:
<code>var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var babel = require('gulp-babel');
var minify = require('gulp-minify');

// task para o sass
gulp.task('sass', function() {
    return gulp.src('sass/**/*.sass')
        .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
        .pipe(gulp.dest('css'));
});

// tasks para JavaScript
// task para babel
gulp.task('babel', () =>
    gulp.src('scripts/**/*.js')
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(gulp.dest('js'))
);
// task minify
gulp.task('compress', function() {
  gulp.src('scripts/**/*.js')
    .pipe(minify({
        ext:{
            src:'.js',
            min:'-min.js'
        },
        exclude: ['tasks'],
        ignoreFiles: ['.combo.js', '-min.js']
    }))
    .pipe(gulp.dest('js'))
});

// scripts
// gulp.task('scripts',function(){
//     return('/scripts/**/*js')
//     .pipe(babel('babel'))
//     .pipe(minify('compress'))
// });

// task para watch
gulp.task('watch', function(){
    gulp.watch('sass/**/*.sass', ['sass']);
    gulp.watch('scripts/**/*.js', ['scripts']);
});
// task default gulp
gulp.task('default', ['sass', 'watch', 'babel', 'compress']);
</code>
O bloco scripts não existia originalmente até quando eu tento salvar meus scripts para minifica-los e toda vez o gulp trava com essa mensagem de erro ai tentei escrever a task mais agora quando removo o comentario para executar e tentar minificar o erro é diferente segue abaixo o erro.

at Gulp. (/home/rafaelejosi/Área de
  Trabalho/projetos/gulpfile.js:40:6)
  at module.exports (/home/rafaelejosi/Área de
  Trabalho/projetos/node_modules/orchestrator/lib/runTask.js:34:7)
  at Gulp.Orchestrator._runTask (/home/rafaelejosi/Área de
  Trabalho/projetos/node_modules/orchestrator/index.js:273:3)
  at Gulp.Orchestrator._runStep (/home/rafaelejosi/Área de
  Trabalho/projetos/node_modules/orchestrator/index.js:214:10)
  at Gulp.Orchestrator.start (/home/rafaelejosi/Área de
  Trabalho/projetos/node_modules/orchestrator/index.js:134:8)
  at Gulp. (/home/rafaelejosi/Área de
  Trabalho/projetos/node_modules/gulp/index.js:36:18)
  at Gaze. (/home/rafaelejosi/Área de
  Trabalho/projetos/node_modules/glob-watcher/index.js:18:14)
  at emitTwo (events.js:87:13)
  at Gaze.emit (events.js:172:7)
  at Gaze.emit (/home/rafaelejosi/Área de
  Trabalho/projetos/node_modules/gaze/lib/gaze.js:129:32)
Answer: percebi o erro no meu próprio código está em uma chamada do watch
<code> // task para watch gulp.task('watch', function(){ gulp.watch('sass//.sass', ['sass']); gulp.watch('scripts//.js', ['scripts']); });
</code>
Alterei a palavra scripts por babel que é outra task do meu código e resolvi o problema
<code> // task para watch gulp.task('watch', function(){ gulp.watch('sass//.sass', ['sass']); gulp.watch('scripts//.js', ['babel']); });
</code>


How does my textbook come up with this statement? I don't believe it to be true.

Question: My textbook (Introduction to Algorithms) states the following:

When polynomially comparing $n^\epsilon$ and $lgn$, it states that $n^\epsilon$ is polynomially greater for any positive $\epsilon$. Does it mean for positive integers? Because in the case of $\epsilon = 0.1$, we have $n^{0.1}$ compared against $lgn$. Is $lgn$ not polynomially larger in that case?
Also, nowhere that I see in the book elsewhere does it state to assume $\epsilon$ is an integer. In fact, above that there's an example where $\epsilon$ is 0.2, so I don't think that assumption is being made.
Should it read that $\epsilon$ is an integer? Or am I not understanding polynomial comparisons?
Comment: No, for any positive real $\epsilon$, $x^\epsilon > \log x$ for sufficiently large $x$.
Answer: Expanding on my comment: take the limit
$$\lim_{x\to\infty} \frac{x^\epsilon}{\log x} = \lim_{x\to\infty} \epsilon x^\epsilon = \infty.$$
Therefore for some $n$, $\frac{x^\epsilon}{\log x} > 1$ for $x>n$, so for $x > \max(1,n)$,
$$x^\epsilon > \log x.$$


Summands of a free product with amalgamation

Question: I'm currently reading Freedman's paper on the Mobius energy of knots. In the proof of Theorem 4.3, he constructs a cylindrical covering $N$ of a tame knot $\gamma_K$, contained a tubular neighborhood $M$ of said knot. He claims that $\gamma_K$ is a core curve of the cylindrical covering, and it appears it's done through an entirely algebraic argument.
Specifically, he claims that by the Van Kampen theorem, $\pi_1(M - \gamma_K) = \pi_1(N - \gamma_K) \ast_{\pi_1(\partial N)} \pi_1(M - \text{int}(N))$. As $\pi_1(M-\gamma_K) = \pi_1(\partial N) = \mathbb{Z} \oplus \mathbb{Z}$, we can deduce both summands of the free product with amalgamation are also $\mathbb{Z}\oplus \mathbb{Z}$. Is there an algebraic reason why this must hold? In other words, if $G \ast_K H = \mathbb{Z} \oplus \mathbb{Z}$, and $K = \mathbb{Z} \oplus \mathbb{Z}$, can we deduce that $G = H = \mathbb{Z} \oplus \mathbb{Z}$?
Answer: No: let $G= \mathbb{Z} * \mathbb{Z} = F(x,y)$ and $H= \mathbb{Z} =F(z)$, and write $K= \mathbb{Z} \oplus \mathbb{Z} = F(a,b)/(ab=ba) $. Define $\varphi_1: K \to G$ by $\varphi_1(a) := xyx^{-1}y^{-1}$ and  $\varphi_1(b):=1$ (note it is well-defined in the quotient) and $\varphi_1: K \to H$ as $\varphi_2(a) :=1$ and $\varphi_2(b) :=z$. Then $$G *_K H = F(x,y,z)/(xyx^{-1}y^{-1}=1, z=1) = F(x,y)/(xy=yx) = \mathbb{Z} \oplus \mathbb{Z}.$$


Android relationships between fragments

Question: I'm using some fragments programmatically in activity. There is one button in my first fragment and when i click to this button, it replaces to second fragment.My second fragment's background is 90% transparent, and when it starts, i can see button which is situated in first fragment, and it also works. I want to stop or do something, because i dont want to see first fragment features and use it.
First Fragment
public class RegistrationFirstFragment extends Fragment {

RegistrationSecondFragment rf;

ImageButton btnNewUser,btnNewAgent;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //return super.onCreateView(inflater, container, savedInstanceState);

    View v =inflater.inflate(R.layout.fragment_registration_first,container,false);

    rf = new RegistrationSecondFragment();

    btnNewUser = (ImageButton)v.findViewById(R.id.btnNewUserRegistrationFirstFragment);
    btnNewAgent = (ImageButton)v.findViewById(R.id.btnNewAgentRegistrationFirstFragment);

    btnNewUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "Transaction completed succesfully", Toast.LENGTH_LONG).show();

            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.flRegistrationFirst, rf);

            ft.commit();

        }
    });

    return v;
}

}
Second Fragment
public class RegistrationSecondFragment extends Fragment {

RegistrationFirstFragment rtl;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    rtl = new RegistrationFirstFragment();
    //return super.onCreateView(inflater, container, savedInstanceState);

    View v =inflater.inflate(R.layout.fragment_registration_second,container,false);

    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
   // ft.replace(R.id.flRegistrationFirst, rf);
    ft.remove(rtl);

    ft.commit();

    return v;

}

}
Main Activity
public class RegistrationActivity extends AppCompatActivity{

RegistrationFirstFragment fr;

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

    fr = new RegistrationFirstFragment();

    FragmentManager fm = getSupportFragmentManager();

    FragmentTransaction ft = fm.beginTransaction();

    ft.add(R.id.flRegistrationFragment,fr);

    ft.commit();

}

}
Answer: You can put
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

(the parameter fragment would be an instance of your second fragment)
into your onClick(View view){...} method to change the fragment instead of adding it.
Next time code for understanding your problem btw ;)
Answer: Add to fragment layout android:clickable="true". Int his way fragment will catch event so the click will not be caught by "main fragment".
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true" />

Answer: Give android:clickable="true" for Second Fragment root layout parent, when ever fragment opens It catches the click event of root and ignored previous click events.
Second One: If u use replace Fragment it's better than add fragment.
 getActivity().getSupportFragmentManager().beginTransaction().replace
        (R.id.YOUR_CONTAINER, 'FragmentObject').addToBackStack("TAG").commitAllowingStateLoss();

Android relationships between fragments


auto-accept SSL certificates in Windows

Question: we use some software that will ssh to a bunch of machines and do something.  The problem is in our test lab, the vm's are re-new (destroy and re-created) very often, so the software will treat the vm as new, which it is, and will fail because the authenticity of the host cannot be established.  I ended up manually putty in, accept the cert., and the software will be happy.  Putty in a few hundreds vm's is not fun :-(
So, I want to know is there any Windows command tool that I can automate to accept the certificate?  (We are in a closed lab, so I am not too worry about security)
Thanks in advance!
PS: I know there are some solutions for Linux env., but this one is Windows
Comment: You can use `cygwin` and standard `openssh` from their repository with all the pros and cons of linux environment.
Comment: Thanks. That idea came across my mind, but I was hoping for a simpler tool.  It's a start.  I need to dig a little deeper to see if it will work.  Thanks again.
Answer: Find the answer from another post to use pscp.exe C:\> echo y | pscp.exe -l user -pw password -ls 192.168.0.1:/, and can be scripted to loop through multiple IP's, etc
Answer: As long as you're using the standard distribution of PuTTY, there are no arguments you can give it that will auto-accept host unknown host keys. The developer is simply against the idea in principal due to security concerns. Read it from the horse's mouth here.
However, you can work around the problem outside of PuTTY if you know all of the host keys in advance.  PuTTY is just checking a registry location in HKCU for known hosts.  So you can basically just pre-populate HKCU with your known hosts before running PuTTY.  There are a variety of ways you can do that.  The page referenced above even has a link to a script that will convert a 'known_hosts' file to a .REG file.

auto-accept SSL certificates in Windows


Duas funções no mesmo evento onclick javascript

Question: Tenho duas funções que precisam interagir na mesma DIV.
# ambienteEdit(this);
A função dela é que ao manter a DIV pressionada por 3 segundos, seja aberto a tela de confirm() do javascript, passando o ID.
# vistoriaIniciar(this);
Essa função, ao clicar apenas uma vez na DIV seja encaminhado para outra outra tela passando alguns parâmetros.
Tentativa:

vistoriaIniciar(), funciona, mas o ambienteEdit() não funciona. Se eu removo o vistoriaIniciar() a função ambienteEdit() funciona.
Pergunta:
Como fazer para ter os dois eventos na mesma DIV?
Obrigado.

function ambienteEdit(object) {
   let aID     = object.getElementsByClassName('aID')[0].value;

   let delay;
   document.addEventListener("mousedown", function() {
     delay = setTimeout(_ => confirm("Dialogo"), 3000)
   });

   document.addEventListener("mouseup", function() {
     clearTimeout(delay);
   });

   console.log(aID)
}

function vistoriaIniciar(object) {
  let aID     = object.getElementsByClassName('aID')[0].value;
  let aCodigo = object.getElementsByClassName('aCodigo')[0].value;
  let aNome   = object.getElementsByClassName('aNome')[0].value;

  window.location='vistoriaIniciar.html?codigo='+aCodigo+'&ambiente='+aNome+'&id_ambiente='+aID;
}

  BLA BLA BLA

Comment: Adicionar deliberadamente a todo click um document.addEventListener está errado, tanto na sua pergunta quanto nas respostas, não é assim que se usa os eventos ouvintes, pode até funcionar, mas não está correto e vai registrando uma série de coisas que não estarão mais sendo usadas, consumindo o que não faz nada após a primeira adição.
Comment: Aparece algum erro no CONSOLE?
Comment: @PauloHDSousa Sem erro, só não executa o `ambienteEdit`.
Comment: Porque você quer que o sistema aguarde 3 segundos para abrir uma confirmação?
Comment: Dá uma olhada aqui: https://stackoverflow.com/a/52751982/11890088
Comment: @DanielZazula porque é algo que estou fazendo para celular. Na mesma DIV a pessoa passa para outra tela, mas se a pessoa manter pressionado abrirá a tela de edição.
Answer: O evento onclick só vai ser disparado se você clicar e soltar. Com isso, o document.addEventListener("mousedown"... só será criado se isso acontecer ao menos uma vez.
Chame a função ambienteEdit num atributo de evento onmousedown na div:

E a função ficará assim:
function ambienteEdit(object) {
   let aID     = object.getElementsByClassName('aID')[0].value;

   let delay = setTimeout(_ => confirm("Dialogo"), 3000)

   document.addEventListener("mouseup", function() {
     clearTimeout(delay);
   });

   console.log(aID)
}

Answer: Você está fazendo um redirect no método  vistoriaIniciar()
window.location='vistoriaIniciar.html?codigo='+aCodigo+'&ambiente='+aNome+'&id_ambiente='+aID;

E está esperando  3 segundos para rodar o confirm no método ambienteEdit()
O que acontece é que o redirect está acontecendo antes de 3 segundos, por isso parece que seu método não foi chamado, mas ele simplesmente está esperando os 3 segundos.
Por isso que ele funciona quando você tira vistoriaIniciar(), porque não tem redirect.
Para resolver faça o seguinte, mova o seu método ambienteEdit para o LOAD da pagina e remova ele do onclick da div, vai ficar assim.

E sua div.

            BLA BLA BLA

Comment: Qual seria a solução?
Comment: @Thiago Eu não sei o que você quer fazer, eu separaria os métodos, REDIRECT em um elemento e abrir o confirm em outro
Comment: Se clicar uma vez na DIV, vai para outra tela. Se clicar e segurar por 3 segundos, abre o confirm.
Comment: @Thiago tenta desse modo.


SQL maior data de um registro antes da data determinada

Question: Seguinte tem o seguinte caso:
Tb_importacao [cod_titulo,data,imp_situacao]

cod_titulo   data_imp    situacao
1           2015-04-10      1
1           2015-04-11      2
1           2015-04-11      1
1           2015-04-13      2
1           2015-04-14      3
1           2015-04-14      4

Preciso da maior data que tenha situacao 1 where data_imp < 2015-04-13.
Minha tabela real possiu mais que um cod_titulos...
Vlw!
Comment: E qual é a dúvida?
Comment: `SELECT MAX(data_imp) FROM tb_importacao WHERE data_imp < '2015-04-13' AND situacao = 1` ?
Comment: + -  assim siatuação 1 = ativo, 2 = desativo

O cara fica indo e voltando na minha base
preciso da maior data de que ele estava ativo e a maior de inativo, para saber se na minha data alvo ele estava ativo ou nao.
Comment: Raphael, acabei de editar o sql, pode testar novamente?
Comment: Rafael:
assim eu so trago a maior data
preciso disso por cod_titulo
Comment: É que você não forneceu todas as informações na pergunta... assim a gente vai indo no chute, pode editar ela e fornecer uma explicação detalhada do que você quer e talvez um exemplo do resultado final esperado?
Comment: data_alvo = 2015-04-13 situacao_alvo = 1

Resultado esperado

cod_titulo   data_imp    situacao

1           2015-04-11      1
Comment: Raphael, você pode editar sua pergunta no link (editar) logo abaixo dela, ou por aqui: http://pt.stackoverflow.com/posts/58826/edit
Comment: Tem como alguém ajudar nesta questão de datas? http://pt.stackoverflow.com/questions/120596/como-fazer-um-sql-que-consulte-apenas-o-dia-de-uma-data
Answer: Indo por partes:

Selecionar a maior data_imp => MAX(data_Imp)
Quando a data_imp for menor que 2015-04-13
e a situação for 1 =>WHERE data_imp < '2015-04-13' AND situacao = 1
Por cada cod_titulo => GROUP BY cod_titulo

Juntando tudo:
SELECT cod_titulo, MAX(data_imp) FROM tb_importacao
WHERE data_imp < '2015-04-13' AND situacao = 1
GROUP BY cod_titulo

Comment: exemplo a data da situacao 1 saiu 2015-04-10
so que esse cod_titulo teve uma situacao 2 no dia 2015-04-11
entao no dia 13 que é o alvo no caso esse cara nao estava ativo eé isso que preciso
Comment: Não entendi. A *query* da minha resposta traz ou não o resultado que espera? Se não qual é o esperado?
Comment: Devolução 09/04/2015 16:19
Reingresso 09/04/2015 16:19
Importação 09/04/2015 16:19

no dia 9 esse cara nao tava ativo pois o ultimo registro devolve o cara

preciso saber se o cara tava ativo na data alvo
Answer: Você poderia testar esse SQL? Ia deixar nos comentários mas é muito grande.
Talvez precise de alguma adaptação ainda para chegar ao resultado exato que você precisa.
Só avisar que vamos modelando ela. (Não tenho como testar)
SELECT imp1.cod_titulo, MAX(imp2.data_imp) as data_ativa, MAX(imp3.data_imp) as data_inativa FROM tb_importacao as imp1
JOIN tb_importacao as imp2 ON imp2.situacao = 1
JOIN tb_importacao as imp3 ON imp3.situacao = 2
WHERE imp1.data_imp < '2015-04-13'
GROUP BY cod_titulo

No caso ele vai retornar duas datas. A maior data ativa (data_ativa) e maior data inativa (data_inativa), então você compara com sua data alvo na programação.
Comment: Cara o problema é que a data_imp esta numa tabela e a situacao em outra D=
Comment: Ah... ai não ia conseguir adivinhar isso... A estrutura que você forneceu na pergunta não é a sua tabela então? Qual é essa tabela de situacao?
Comment: É que o treco ta complexo man
O sistema aqui eh uma merda

Tenho a IMPORTACAO que é onde tem a data de entrada do registro
Tenho a IMPORTACAO_HISTORICO que tem a situacao e o cod_titulo

Sua query estava seguindo o rumo certo so que nao te forneci os dados mesmo

obrigado
Comment: kkkk, testei aqui uma tabela com a estrutura que você forneceu na pergunta e aparentemente está funcionando esse SQL. Só precisamos adaptar a sua situação, você não pode fornecer mais detalhes? Ou você pega o sql ali em cima e edita para unir com sua tabela de situacao, ou essa situacao é uma foreign key na tabela tb_importacao?
Answer: Tente utilizando a função GREATEST.
select greatest(col1, col2, col3, col4) from tab1;


Exibir informações do User Profile do Wordpress na página, apenas quando o respectivo campo está preenchido

Question: Criei campos para as mídias sociais no editor de perfil para um template. Testei em links estáticos e estão funcionando corretamente:
 function author_social_media ($profile_fields){

    $profile_fields['facebook'] = 'Facebook URL';

    return $profile_fields;

    $facebookHandle = the_author_meta('facebook');

}

O que estou tentando fazer é mostra-los apenas quando estão preenchidos, mas não estou tendo sucesso. O preenchimento não é obrigatório. Tentei da seguinte maneira:

<?php if(isset($profile_fields['facebook']){
        echo "<a href="<?php the_author_meta('facebook'); ?>">Facebook";
        } else{
        echo '';
        }
?>

Grato desde já.
Answer: Verifica se o seu teste não está vindo como uma string vazia, pois o comando isset só verifica se é nulo, segundo esse link:
http://php.net/manual/pt_BR/function.isset.php
Então faça o teste assim:
if($profile_fields['facebook'] != "")

Outra coisa, reparei que no código que você postou, no IF mesmo, falta fecha um parenteses ")". Dá uma olhada nisso também.
Comment: Sugiro o [`empty()`](http://php.net/manual/pt_BR/function.empty.php)
Comment: Obrigado pessoal, funcionou.


SmartDL for ftp

Question: I need a python code which can download files from a ftp server. I need a built in multi-part download managing package which can help me to retrieve files faster. I tried SmartDL but the problem is I don't know how to retrieve files in a ftp server. Also I used the add_basic_authentication to ensure that, I am passing the right credentials. Please help me with a solution.
I have no problem using any other solution/package which uses Multipart download.
P.S:- I need to save the Downloaded files on to an Object storage on Cloud. The size of each file may be 300MB and I need to download 20TB of data.
Thanks in anticipation.
Answer: Take a look at ftplib, it's a simple FTP library which will permit you to download files from a FTP server.
Comment: I dont think that supports Multipart download.

SmartDL for ftp


Change CKEditor autoGrow_maxHeight

Question: Can I change CKEditor's autoGrow_maxHeight at runtime (jquery or etc)? I've tried
CKEDITOR.replace ('editor1', { autoGrow_maxHeight: x });

And also destroying the instance before trying to recreate it, with a new maxHeight.
I'm trying to keep the maxHeight to the height of the browser window (minus about 220 px of other stuff on the page). This is when I do the main replace of the text area:
autoGrow_maxHeight: (window.innerHeight-220)

This works for the initial creation of the editor. But the problem is when you resize the browser window - I have no way of saying 'redetermine that autogrow height please'.
Answer: At the moment, once defined, this property's value will last until CKEditor instance is destroyed. So to set a different value you got to destroy your editor and re-create it. Another possibility is to modify plugin's code to match your needs. Sorry.
Comment: Actually, looking at the [autogrow plugin code](https://github.com/ckeditor/ckeditor-dev/blob/master/plugins/autogrow/plugin.js) I think that it may be possible to modify the values by `editor.config.*`. But it needs tests to see if it works correctly.

Change CKEditor autoGrow_maxHeight


Can you prove the Law of Large Numbers?

Question: So clearly it is not hard to experimentally prove that the more times something is done, say rolling a die, the closer your experimental results come to your theoretical likelihoods, but is there a mathematical way to show why this occurs?
Thanks
Comment: the simplest version would be if $X_k$ are iid random variables with mean $\mu$, then $S_n=\frac{1}{n}\sum_{k=1}^nX_k$ converges (in probability and a.s.) to the constant $\mu$.  see any book on probability or start with http://en.wikipedia.org/wiki/Law_of_large_numbers
Comment: @user What precisely do you think the statement of the law of large numbers is? You have to formalize it before you can prove it - which the Wikipedia page mentioned above does.
Answer: Yes, most proofs prove the Chebychev inequality and then use that to prove the law of large numbers. http://en.wikipedia.org/wiki/Law_of_large_numbers#Proof_using_Chebyshev.27s_inequality

Can you prove the Law of Large Numbers?


Is it feasible to learn violin (mostly) by oneself?

Question: First of, I know there are lots of similar questions here in Music Stack Exchange. My point here is not abstractly ask whether it is possible at all to learn violin by self study and get a "absolutely impossible, give up" or "if you work hard enough you can accomplish anything in the world" answer; rather, I want to ask those with more experience if I can - given my sets of skills, experiences and constraints - successfully self study violin - and which strategies should I adopt in order to optimize the process.
My music background
So, I have studied classical piano for 2 years, but that was 4 years ago. In this time, I continued to play and to pick up some new pieces, but without all that rigorous practice (i.e., no metronome, no scales practice etc). I have a solid understanding of musical theory, I can read sheets effortlessly and I have a reasonably good ear.
Since I was a child, I have always taken a self study approach to many things, generally to my benefit. I'm quite comfortable with the idea of sitting in front of a desk for hours until I understand the topic I am studying. Nevertheless, it is generally a good strategy to give a "boost" in the beginning in order to get a solid base, and then continue by oneself.
So, as for violin, what would be a good strategy in this regard? More specifically, which specific topics (posture, arc holding etc) should I find a teacher to help me with, so that I can go on them and study for myself? (given my current musical knowledge)
I know that any teacher would have a different say about this. My point here is to ask for the advice of those who have either taught or learned violin as to which points they think are really "essential".
Thanks.
Comment: If you think you can, why ask.  The violin is particularly complex, the entire fret-less string family is complex.  Piano is an equal tempered instrument (keys define the only notes you have).  The violin family can be played in Just or equal temperament.  Unless you have that good an ear a teacher would be a good idea (you need to get the correct fingering etc).  Bowing technique takes a lot of time to master as well.  I would learn the technique from a master.  i.m.o it is not advisable to try on your own, too much room for misunderstanding and bad habits.
Comment: By the way, I learned classical violin at age 5, classical bass too for many decades.  Now I am mainly a guitarist (but I use a bow when I play Dazed and Confused ;-)).
Answer: Violin is one of the least anatomically suitable instruments, and a linear bow action does not only require counteracting different leverage but also counterbalancing the weight of the bow itself (vertical instruments like cello and double bass have a lot less problems in that regard and also larger pressure overall).  As a consequence, violinists are very prone to taking shortcuts: locking some joints in finger, wrist, arm, shoulder belt, clenching some stuff, using only a limited amount of bow length and so on.  Any strategically unused joint ends up as helpful as locked knees for running.  Also many violinists suffer back problems.
There are lots of opportunities for shortcuts leading to faster successes at various separate endeavours at the price of longterm failure when needing to utilize all stuff together.
Good, healthy, and sustainable technique is an issue for basically all instruments.  But it's rarely as pervasive a topic as when playing the violin.
Answer: I had piano lessons for many years and taught myself guitar, and now I'm working on violin and clarinet. The biggest difference I've found in violin and clarinet line up with the current comments and the other answer: just making a single note with the proper technique is extremely difficult. That is not true with piano or guitar. Certainly not piano. Press a key and you get the sound.
It is important to be ergonomic on piano and guitar to prevent injury. That's also true for the violin, but it's also a big challenge to use a technique that creates a solid note that is also ergonomic. If I spend 30 minutes practicing the violin, it's about 20 minutes of just bowing while thinking about my posture, arm position, hand position, grip on the bow, etc. etc. Each different string, note, volume level, and articulation requires extensive practice to make it sound correct. Again, this is very different from the piano where you can play staccato by just lifting your finger and play legato by holding it down. Pressing any key on the piano is pretty much like pressing any other.
I would get a children's violin book, like the first Suzuki method book or something like that, and I would also get a full-length mirror. Make sure you at least have a start on learning posture, position of the violin on your neck, head position, bow positions, grip, and bow technique before you start to try to learn any music. The mirror is so you can look at yourself and make sure you have everything in the right place. It's better to have a teacher who knows what you should look like and can watch and correct, otherwise you have to try to concentrate on being the teacher and student at the same time.


How to pass multiple parameters to Crystal Reports using C#?

Question: I used this code to pass a parameter to Crystal Reports, but I can't pass multiple parameters. How can I change this code to pass multiple parameters from C# to Crystal Reports?
<code>this.Cursor = Cursors.WaitCursor;

RPT.RPT_Sale_by_day report = new RPT.RPT_Sale_by_day();
RPT.Form_RPT frm = new RPT.Form_RPT();

report.SetParameterValue("@date1", dt_num1.Value);

frm.crystalReportViewer1.ReportSource = report;
frm.ShowDialog();

this.Cursor = Cursors.Default;
</code>
Comment: Have you tried simply putting in more `report.SetParameterValue(paramName, paramValue)` lines?
Comment: Yes , and didn't work
Comment: Not sure if this is the same version (using `CrystalDecisions.CrystalReports.Engine.dll` myself), but the technique I used was to request the list of parameters from the report itself (`ReportDocument.ParameterFields`), go over them, and detect by `Name` which ones you want to set a value in. I don't remember seeing any @ symbols in these parameter names though.
Answer: <code>//Initiating created Crystal Report
    ParameterValues  Params =new ParameterValues();            // Creating collection of parameters
    ParameterDiscreteValue Par_Ref =new ParameterDiscreteValue();    // Discrete parameter that comes from SP and shows on Crystal Report

    String PARAMETER1_VALUE ="123";
    String PARAMETER2_VALUE = "ABC";

        Params.Clear();         // Cleaning data collection
    Par_Ref.Value = PARAMETER1_VALUE; // Assigning discrete value to our variable

    Params.Add(Par_Ref);   //Adding discrete parameter to parameter collection
    report.DataDefinition.ParameterFields["PARAMETER1_NAME"].ApplyCurrentValues(Params); //Applying values from our collection to Crystal Report parameters

    Params.Clear();
    Par_Ref.Value = PARAMETER2_VALUE;
    Params.Add(Par_Ref);
    report.DataDefinition.ParameterFields["PARAMETER2_NAME"].ApplyCurrentValues(Params);
</code>
Comment: As many others on here, I don't speak spanish - your comments are of no value to me and the other non-spanish-speakers. It's a good idea to include some Explanation on *why* and *how* your code solves the issue, but please do it in english instead.


Snake Game Program - Making the Body of the Snake

Question: EDIT: (QUESTION ANSWERED)

So I have a Thread controlling x and y and making it change. My problem is that when the snakes body gets put up in the GUI it puts it directly on top of the head instead of 12 spaces behind it. I know why it's doing it but I am not sure how to fix this problem.
From what I understand, it's drawing the body and then the head but it's using the same x and y spaces...what really needs to happen is that it needs to draw the head, go through the Thread, then draw the body parts so that it does it a space behind the head (because the head will have moved forward)...so on and so forth... I just can't figure out how to do it.
Here is the Thread runner which i highly doubt you will really need but just to be sure
class ThreadRunnable extends Thread implements Runnable {

  private boolean allDone = false;
  private boolean RIGHT;
  private boolean LEFT;
  private boolean UP;
  private boolean DOWN;
  public ThreadRunnable (boolean up, boolean right, boolean down, boolean left){

    UP = up;
    RIGHT = right;
    DOWN = down;
    LEFT = left;

  }
  public void run() {

    if(UP == true) {
      try {
        while(UP) {
          if (y <= yBase && y >= 0) {
            y = y - 12;
          }
          else {
            y = yBase;
          }
          Thread.sleep(40);
          repaint();

          if (allDone) {
            return;
          }
        }
      }
      catch (InterruptedException exception) {
      }
      finally {
      }
    }

    if(RIGHT == true) {
      try {
        while(RIGHT) {
          if (x <= xBase && x >= 0) {
            x = x+12;
          }
          else {
            x = 0;
          }
          Thread.sleep(40);
          repaint();

          if(allDone) {
            return;
          }
        }
      }
      catch (InterruptedException exception) {
      }
      finally {
      }
    }

    if(DOWN == true) {
      try {
        while(DOWN) {
          if (y <= yBase && y >= 0) {
            y = y+12;
          }
          else {
            y = 0;
          }
          Thread.sleep(40);
          repaint();

          if (allDone) {
            return;
          }
        }
      }
      catch (InterruptedException exception) {
      }
      finally {
      }
    }

    if(LEFT == true) {
      try {
        while(LEFT) {
          if (x <= xBase && x >= 0) {
            x = x-12;
          }
          else {
            x = xBase;
          }
          Thread.sleep(40);
          repaint();

          if (allDone) {
            return;
          }
        }
      }
      catch (InterruptedException exception) {
      }
      finally {
      }
    }
  }
}

Here is the "Drawing" part of the code
public void paintComponent(Graphics g) {
  super.paintComponent(g);
  setBorder(BorderFactory.createLineBorder(Color.WHITE));

  this.setBackground(Color.black);

  if (numOfFood == 1) {
    g.setColor(Color.BLUE);
    g.fillRect(foodX,foodY,12,12); //Paints the food
  }
  else {
    foodX = random.nextInt(105)*12; //Random x for food position after snake eats
    foodY = random.nextInt(59)*12; //Random y for food position after snake eats

    numOfFood = 1;
  }
  Rectangle headRect = new Rectangle( x, y, 12, 12 ); //The head (not painted)
  Rectangle foodRect = new Rectangle(foodX, foodY, 12, 12); //The food (not painted)

  if ( body.size() >= 0) {
    body.add(new BodyPart( x, y, 12, 12));
    body = new ArrayList<BodyPart>( body.subList( body.size() - n, body.size() ) );
    g.setColor(Color.RED);
    for ( int i = body.size() - 1; i >= body.size() - (n-1); i--  ) {
      g.fillRect( body.get( i ).getX(), body.get( i ).getY(), body.get( i ).getWidth(), body.get( i ).getHeight() ); //This is calling a class that will get these parts of the array list (x,y,width,height)
    }
  }

  g.setColor(Color.RED);
  g.fillRect(x,y,12,12); //Draws head
  g.setColor(Color.WHITE);
  g.fillRect(x+2,y+2,8,8); //This is a white square in the middle of the head to show that it is the head

  if (headRect.intersects(foodRect)) {

    numOfFood = 0;
    n++;

  }
}

EDIT: QUESTION ANSWERED BELOW

All that was required was to move the
setBorder(BorderFactory.createLineBorder(Color.WHITE));
and the
this.setBackground(Color.black);
to an earlier part of the code and not in the drawing method there...
I also changed my ArrayList into a normal Array and just made it insert the head location into the beginning of the Array and then made it print the next time around (after the head had moved)
  g.setColor(Color.RED);

  //Prints the body parts
  if (n > 0) {
    for (int i = 0;i < n; ++i) {
      g.fillRect(body[i][0],body[i][1],12,12);
    }
  }

  //Inserts the head location
  for (int i = n-1;i >= 0; --i) {

    body[i+1][0] = body[i][0];
    body[i+1][1] = body[i][1];

    if (i == 0) {
      body[i][0] = x;
      body[i][1] = y;
    }

  }

Thank you so much for all the help
Comment: Your paintComponent is messed up as you've got program logic in there where it doesn't belong.  It really should do nothing but draw and that's it. All randomizations, all creation of ArrayLists need to be done elsewhere, likely in your game loop.  Also don't set background and borders in there. Do that once in the constructor.
Comment: Also you can remove that one: `if (body.size() >= 0) ...`.
Comment: I removed the background and borders thing outside of the draw area and it worked...thanks @HovercraftFullOfEels!
Answer:
Move the head forward one.
Put a body segment where the head was.
Erase the last body segment.

None of the other body segments need move.
Comment: Well yes, i am trying to do that...and I know that is not what it does at the moment...I am not sure how to do it because the repaint is through the thread
Comment: Can you draw the head?  Use the same code with a different image to draw a body segment.  Draw an image blank space over the last body segment to erase it.
Comment: (... = /n) Deleting the end isn't that hard but i can't figure out what all is going wrong. This is a sample output when there are 5 body parts...

5 (408,288) (408,276) (408,252) (408,252) (408,228) (408,216)...
5 (408,312) (408,288) (408,276) (408,252) (408,252) (408,228)...
5 (408,324) (408,312) (408,288) (408,276) (408,252) (408,252)...
5 (408,348) (408,324) (408,312) (408,288) (408,276) (408,252)...

I can't find the pattern that is making it print this way...it should be printing each one (y value) -12 apart....sometimes it does and sometimes it doesn't...I can't figure out why.


Font "Herr Von Muellerhoff Regular" gets cut off (Slider Revolution - Wordpress)

Question: In Google chrome, the slides with the font "Herr Von Muellerhoff Regular" gets cut off, and ive no idea why.
I hve no real experience with Fonts but i think the font is the problem.
Can anyone confirm that the geometricts of this font arent correct ?
the first is the slide,
the second is the highlightet text on google fonts,
the thirs shows the cursor
after this "test" my thought was that the font isnt correct.
Any ideas ?
see screenshot:
Answer: Adding the css property padding-right:12px; to the involved elements should solve your problem.
If you have the same problem on the bottom with the letters y,q,p,g,j,.. you can do the same with padding-bottom
Comment: Thank you a lot ! Damn why i dont thought on that padding :X havent thougt on that because the bottom and top was fine ...
Comment: This Css fixed it for every letter in chrome !`#slide-padding {
    padding-right: 45px !important;
}`


Convergence of $\sum_{k=1}^\infty ke^{-\sqrt{k}}$

Question: So I've tried ratio test and it was inconclusive. I think comparison test would work with $\frac {k}{e^\sqrt{k}} \le \frac {k}{k^3}=\frac {1}{k^2}$ since $e^\sqrt k \ge k^3$ for large enough k. But I couldn't prove that inequality with induction. Can you help me prove that inequality or give me another way to show the convergence?
Thanks for your effort and time.
Comment: Do you know how to show $\frac{e^x}{x^{3/2}} \to \infty$ as $x \to \infty$?
Comment: @angryavian I think so, yes.
Answer: $e^{\sqrt k} \geq \frac {(\sqrt k)^{4}} {4!}$. Hence $\frac k {e^{\sqrt k}} \leq \frac {24} {k^{2}}$.
Comment: Does that come from the expansion of the $e^\sqrt k$, if so I don't know it yet. But still thanks for the help.
Answer: It suffices to show that the inequality $e^\sqrt k \ge k^3$, that is $\frac{k^3}{e^\sqrt{k}}\leq 1$, holds eventually. This follows from the fact that
$$\lim_{k\to \infty}\frac{k^3}{e^\sqrt{k}}=0<1.$$
Actually $\lim_{k\to \infty}\frac{k^a}{e^{k^b}}=0$ for any positive numbers $a$ and $b$.


Trigger a js function on orientationchangeend inside svelte:body

Question: I want to display a message with a black background whenever the viewport orientation is portrait mode in svelte.
I used svelte-viewport-info to get the orientation of the viewport.

<svelte:body
  on:orientationchangeend={() => { console.log(
    'Screen Orientation changed to: ', Viewport.Orientation + (
      Viewport.detailledOrientation == null
      ? ''
      : '(' + Viewport.detailledOrientation + ')'
    )
  ) }}
/>

I want to change the display property of a div

When in landscape mode, display set to none
When in portrait mode, display set to block

I found a js syntax to call function after a certain amount of time interval
var test = 0;
var interval;

function check_test() {
    if( test == 1 ){
        clearInterval( interval );
        console.log( "Test is 1 now!" );
    }
}

interval = window.setInterval( check_test, 1000 );

So inside this above function that is called every 1000 millisecond/1 second.
I found a syntax to use if statement in svelte here in #template-syntax-if
How do I perform all this in svelte it's along confusing

I have to repeatedly call function using window.setInterval after certain interval
Function needs to check the viewport Orientation from on:orientationchangeend inside svelte:body
Use the if in svelte to set the display property of a div to block or none depending on the viewport Orientation from step 2
Comment: What about your task is confusing?  "I want to change the display property of a div" - why are you not changing the display property of a div? The "interval" code you found is noise, forget about that. You  don't want to do that on an interval. You want to do that on the `orientationchangeend` event. You already have all the code you need. Your remaining question has precisely nothing to do with svelte. You're asking "how can I set the display property on a div" and that should not to be too hard to figure out.
Answer: From the svelte-viewport-info docs

CSS Classes
In addition, the package also adds or removes the following CSS classes depending on the current device orientation:
Portrait - indicates that the device is currently in any "Portrait" orientation
Landscape - indicates that the device is currently in any "Landscape" orientation

So you don't even have to track any event, you can simply use these classes to change the display of the div >> REPL
(The compiler doesn't see any elements with the classes Landscape and Portrait, so the :global() modifier must be added so that they get compiled)

    only visible in Portrait Mode

Comment: I need to reduce the size of an image when `screen height` is `133%` of screen `width` or `less`. How do I do it?
Comment: @SanthoshDhaipuleChandrakanth better you post a new question for this with a detailed explanation
Comment: here is the question [Dynamically detection of screen height and screen width to change the height and width of an image in svelte](https://stackoverflow.com/questions/70983393/dynamically-detection-of-screen-height-and-screen-width-to-change-the-height-and)


Robust GAM that covers Gaussian distribution

Question: I was looking at CrossValidate archives as well as r-archives and crantastic...for a package that has a robust approach to generalized additive models. I found two packages "robustgam" and "rgam" but their implemented functions
cover only binomial and Poisson distributions (pls correct me if I am wrong).
I would greatly appreciate if anyone could share with us other R-packages or robust approaches of general additive modeling that might have a better performance with  small data sets ($n<100$ records or 50 -100 records).
Comment: Interesting thought...I am not sure but sounds that it might work! Did you have in mind a specific pacgage like mgcv, or robustgam or rgam? Thank you VERY MUCH for your immediate response. I sincerely appreciate it.
Comment: no, that was wrong...
Comment: yes...thank you any new ideas?
Answer: The mgcv package contains a scaled-t family for the conditional distribution of the response, that, like the Gaussian, has support for the entire real line (is suitable for a response that is continuous and is bounded at -Inf and +Inf), but which has heavier tails than the Gaussian.
Estimating the model requires estimating another parameter of the distribution, the degrees of freedom, the smaller the degrees of freedom the heavier the tails of the conditional distribution of the response.
Because of the heavier tails in this distribution, the model is made more robust to more extreme observations as they have higher probability density until the scaled-t with suitable degrees of freedom than under the Gaussian, all else equal. As a result, the model doesn't need to move the fitted smoother towards these extreme values, to achieve a reasonable fit.
To use it, use family = scat() in the call the gam() or bam().
Comment: This was what I was thinking. Question, though: does this use the same error distribution for every input (akin to OLS having constant variance), or are the degrees of freedom allowed to change?
Comment: But see https://stats.stackexchange.com/questions/45784/fitting-t-distribution-in-r-scaling-parameter/195113#195113, MASS (the book) advices against trying to estimate $\nu$, it looses robustness.
Comment: @kjetilbhalvorsen Yep; good point. The *gamlss* package at least parameterises the its *t* distribution using *mu*, *sigma* and *nu*. Not sure how this changes things with respect to your Answer & the stuff in MASS?
Comment: @Dave The `scat` family in *mgcv* doesn't allow for a linear predictor (beyond an intercept) for $\nu$; in general though, one could have a model for $\nu$. The *VGAM*, *gamlss* packages allow for this as do more general packages like *brms*/*Stan* etc


Determine the number of strings that start and end with the same letter

Question: I'm trying to figure out this question and this is my thought process right now. Any help would be appreciated because I feel like im doing something wrong.
Considering a string of 28 characters, how do we determine how many strings would start and end with the same letter (only lowercase) . If I dont consider the first and last character, then there are 26 characters left. Each character has the possibility of being one of the 26 possible letters in the alphabet. So is that 26 characters x 26 letters = 676. Then since there are 26 letters in the alphabet, then the first and last characters could be one of the 26 possible letters. So 676 x 26 =  17576, which is the answer?
Answer: The number of $26$-character strings from a $26$-letter alphabet isn't $26\times 26$, it's $26\times 26\times\cdots\times 26=26^{26}$. Multiplying that by one more factor of $26$ to account for the first/last character should give you your answer, $26^{27}$.
Answer: Not quite; the number of $26$ letter strings is $26^{26}$, not $26\cdot 26$. This is because we have $26$ choices for the first letter, times $26$ choices for the second letter, times $26$ choices for the third letter, and so on and so forth. Perhaps trying a few small cases would help you understand the intuition. But you are correct about the second part; once you determine the middle string, you simply multiply by $26$ to account for the first and last letter.


Displaying files from resources folder and making them downloadable

Question: I am trying to create a sort of download list where I grab all the files from the resources folder.. my php file is in a different folder to that..
and then I want to make them like links so people can download those files
I tried this:
<?php
    foreach(glob('*.*') as $filename) {
        echo $filename."
";
    }
?>

However I don't know how to grab files from my resources folder or make them downloadable :(
Cheers!
Comment: Is the resources folder web-accessible? If it is you can create `` elements and build their `href` parameters to point to each file; if it's not you will have to build a downloader script which basically will send the right HTTP headers then serve the file through `readfile`.
Comment: so you tried echo'ing the names of files. ok... and what did not work about that? what are you trying to do besides echo'ing a filename?
Answer: You can scan the directory and grab the the files with scandir
    $dir    = '/tmp';
    $files1 = scandir($dir);

   //Check if file is not . OR ..

    $ignore = array(".", "..");
    foreach($files1 as $key => $value){
      if (!in_array($value, $ignore)) {
        echo $value;
      }
    }

For more information read :
http://php.net/manual/en/function.scandir.php
In order to make a downloadable link I would like to know what kind of files you want to download.
Comment: I was able to use a .htaccess call: AddType application/octet-stream .jpg .png .pdf .doc .docx .mp4 .etc
Comment: Nice, glad to help :)
Comment: First of all thanks! :D

Secondly however, how do i get rid of the first '.' and '..' objects in the array? and how would I make these objects downloadable?
Comment: Downloadable files will include word documents, pdf files, text files and images
Comment: When I use your code above nothing displays even though I have images in the resources folder?
Comment: Ahh I was thinking that I just wasn't too sure! Thanks :D but how would I go about making these files downloadable?


How to encode Pre-Shared Key (PSK) of and L2TP IPSEC connection managed by Network-Manager

Question: If I create a VPN L2TP IPSEC connection using Network-Manager GUI, I introduce the PSK, but this one looks different on /etc/NetworkManager/system-connection/myvpn.nmconnection
I am thinking the PSK gets encoded somehow, since it begins with 0s it's probably binary base64 encoded (I read this in NetworkManager's docs). I have no clue how to encode this.
I am also guessing, if I want to create a connection with nmcli connection add from terminal (I use Ubuntu Server 20.04), I will need to encode the PSK so it will be properly read in the config file. How should I go about this?
Can I just type the PSK in plain text into the command or change the Key/Value pair inside the .nmconnection file without using GUI so it will be read and interpreted the right way?
Thanks!
Answer: libreswan and strongswan accept PSKs that are plain text or base64 starting with 0s. Similarily you can use either format in the vpn connection configuration file you want to edit.
If you edit the connection configuration file (e.g. to change to plain text PSK), be sure to issue the following so that any connection changes are picked up:
nmcli con reload


Is the C chord here C minor or C major?

Question: I'm composing a funeral march and I have noticed that just from looking at the bass, the C chord is ambiguous. The piece is in the key of F minor. That doesn't really help because both C minor and C major are used in the key of F minor. Here is the entire first theme of my funeral march:

First 4 bars have this ambiguity with the C chord because there is no Eb or E natural. Next 4 bars are basically E dim7 with an F pedal. And the last 4 bars clearly state C major in every other bar.
So I'm really only asking about the first 4 bars here. Is the C chord in those bars(which is every other chord) C major or C minor? Or are there too few notes to tell?
Comment: Or, an alternative analysis: the first four measures (at least) are all F minor, but the bass has neighbor-tone Gs on every other beat.
Comment: A thought: Is it a chord on C or a suspension of the F minor harmony?
Comment: Well, when I was composing the first theme, I was thinking of it as a C chord and not as a suspension.
Comment: @Caters: why  are the 4th notes before the triplets double dotted in the 2nd line? Don't you think this is an error? and in the left hand the 2nd fourth note should be under the 8th note triplets.
Comment: @AlbrechtHügli I was wanting both the triplets and the double dotted quarter notes(or at least single dotted). I guess I will have to change the triplets to sixteenth note triplets to do that.
Comment: In this case the quarter notes must be single dotted, as the sixteenth triplets are one eighth note.
Comment: Does it matter whether that chord is C major or C minor?  If so, why?
Comment: @phoog No, it doesn't matter, it's just that I thought that knowing whether or not that chord is C minor would help since I do modulate to C minor for the second theme.
Answer: In the Key of F min C is the V.  If you are trying to create a resolution (you'd be in harmonic or melodic at this point) then you'd want to use the C maj, or more appropriately C7.  Otherwise moving to C minor in the key of F min is fine.  You wrote it so you must make that decision.  If you are avoiding the E, Eb in the first 4 bars I'd look at the melody.  Is the melody in the first line hinting at melodic or harmonic minor?  If not then the "ambiguity" may not be an issue.  From a strict harmony point of view I am not used to this, I'd pick a 3rd and use it.
That being said, without the appearance of E in the melody and without the need for a true resolution in the first line it is fine to stick with natural minor, waiting for the next line or last line to create the tension of the V7.  In line one you are not approaching the F from below so there may not be a strong feeling of resolution.  I'd experiment with both Cmin and Cmaj and see what the difference is.  Putting the C7 in the last measure of the first line would create the classic resolution and your melody is a G so it will work.  You just need to decide whether you want that strong of a harmony there.
I would guess that the "classic" approach to harmonizing in a minor key would be to use melodic minor and that might push you into a C7 at the end of the melodic ideas (motifs).
Comment: Every classic harmony test and workbook I've seen has a standard set of rules that can be considered best practices and yes, all notes of a chord are typically present (with the exception of the 5th of the V7).  I don't now why that bothers you so much.  In trying to help people understand these things it is not helpful to throw all rules and procedures away.  We learn to appreciate the patterns in music by learning these rules.  Then learn to break them.
Comment: In key Fm, C is V. True as far as V instead of v. But v exists in key Cm too. There is **No** compunction to use a third in any harmony. No rule says 'thou must...' So leaving it genderless isn't going to be problematic, surely. Why can't the listener fill in the gaps?
Comment: @ Tim: is **gender** the English term for major and minor? I've been always  wondering about the translation of "Tongeschlecht" how we call in German these 2 *genders*
Answer: There are no C chords in the first four bars. What you have is a single F chord, plus some non-chord tones including the Gs in the left hand.
To repeat the old, old advice, stop looking at the notes on the staves and LISTEN to what you wrote! Your first four bars sound perfectly fine, but your analysis of them is misguided.
In fact when you do attempt to make C chords in bars 8 10 and 12, the result sounds clumsy because you have second inversion C chords (with G in the bass). Second inversion chords are not stable, and any harmony textbook should explain the limited number of ways they can be successfully used - but those ways don't include what you wrote.
Comment: Second inversion dominant triad though is no problem, right, since it can resolve in a similar way to an augmented sixth chord(Bar 12 has that augmented sixth like resolution going on, with both G and E moving to F in contrary motion, turning a sixth into an octave), just to the tonic instead of the dominant? If the tonic was also in second inversion, then it would be a problem, but the tonic is in root position, so I don't see any problems with the second inversion dominant.
Comment: Six-four chords tend to fall into three categories: where the bass is a pedal point (the pedal six-four), the cadential six-four (a subset of the pedal six-four), and the passing six-four (where the bass pitch of the six-four functions as a passing tone). (Some include a fourth type, the arpeggiated six-four.) But since the bass here is a *neighbor* to the F, it's technically an "illegal" six-four. Hence my own reasoning, which aligns with guest's, that these Gs are just neighbor tones.
Comment: @Richard Just because most second inversion chords fall into those 3 categories doesn't mean that a "Neighbor 6/4" is illegal. And I showed how such a chord can be convincing, resolve it like it's an augmented sixth chord to a root position chord with the span of an octave. I do exactly that in bar 12 of the piece. The other neighbor chords are part of an alternating figuration. And would you consider the G to be a neighbor tone in the second line? I wouldn't because of the tritone between G and Db, which form half of the vii dim7 of F minor.
Answer: As in the 3rd line in the repetition of phrase A the melodic motif  is varied and contains a harmonic respectively melodic 7th of the scale (natural E = major 3rd in V 2nd inversion) - also in the final bar - I would use in all cases a C- chord.
Comment: So in every C chord except in the bars where I use an E natural, you would use C minor? Hmm, that might fit well with the mood I'm going for in the piece.

Is the C chord here C minor or C major?


Finding $\small{\max\limits_{a+b+c=3}\frac{1}{\sqrt{a^2-3a+3}}+\frac{1}{\sqrt{b^2-3b+3}}+\frac{1}{\sqrt{c^2-3c+3}}.}$

Question: Let $a,b,c\ge 0: a+b+c=3.$ Find maximum $$P=\frac{1}{\sqrt{a^2-3a+3}}+\frac{1}{\sqrt{b^2-3b+3}}+\frac{1}{\sqrt{c^2-3c+3}}.$$
By $a=b=c=1,$ we got that $P=3$ and we will prove it is desired maximal value.
I tried to use upper bound $$\frac{1}{\sqrt{a^2-3a+3}}\le x.a+y$$
But I'm stuck to find it now. For example $$\frac{1}{\sqrt{a^2-3a+3}}\le \frac{a+1}{2}$$ is saving occuring equality but is wrong in general.
Hope someone can give some advice to help me. Thank you.
Comment: You could try first showing $(a,b,c)=(1,1,1)$ solves $\nabla_{a,b,c,\lambda} L=0$
Comment: Why do you write "we will prove P = 3 is desired maximal value" when you do not prove anything?
Comment: You can solve it with derivatives.
Comment: Your example is true !
Answer: For $a=b=c=1$ we obtain a value $3$.
We'll prove that it's a maximal value.
Indeed, by C-S $$\sum_{cyc}\frac{1}{\sqrt{a^2-3a+3}}\leq\sqrt{\sum_{cyc}\frac{1}{(a^2-3a+3)(2a+3)}\sum_{cyc}(2a+3)}$$ and it remains to prove that:
$$\sum_{cyc}\frac{1}{(a^2-3a+3)(2a+3)}\leq\frac{3}{5}$$ or
$$\sum_{cyc}\frac{1}{((a+b+c)^2-3a(b+c))(3a+b+c)}\leq\frac{27}{5(a+b+c)^3},$$ which is true by BW: https://www.wolframalpha.com/input?i=27-5%28x%2By%2Bz%29%5E3%281%2F%28%28%28x%2By%2Bz%29%5E2-3x%28y%2Bz%29%29%283x%2By%2Bz%29%29%2B1%2F%28%28%28x%2By%2Bz%29%5E2-3y%28x%2Bz%29%29%283y%2Bx%2Bz%29%29%2B1%2F%28%28%28x%2By%2Bz%29%5E2-3z%28y%2Bx%29%29%283z%2By%2Bx%29%29%29%2Cx%3Da%2Cy%3Da%2Bu%2Cz%3Da%2Bv
Comment: AM-GM by $2a+3$ is nice enough, +1
Comment: Love it when OP accepts the Lagrange multiplier bash method instead of Cauchy Schwartz :)
Answer: Suppose $f(x,y,z)=x+y+z-C=0$ And $g(x,y,z)=\mu(x)+\mu(y)+\mu(z)$
By Lagrange Multipliers, we have:  $\lambda=d\mu/dx=d\mu/dy=d\mu/dz$
$\mu(x) = \frac{1}{\sqrt{x^2-3x+3}}$
$\frac{d \mu}{dx}=\frac{(2x-3)(-1/2)}{(x^2-3x+3)^{3/2}}$
This implies $x=y=z=1$ and $g(1,1,1)=3$
We also have: $ x^2-3x+3= (x-3/2)^2+3/4$ suggesting a minimum occurs when $x=y=z=3/2$ but that is not allowed by our constraint. Other potential extrema occur on  boundaries where $x,y,z$ take on values from $\{0,3\}$ Possibilities are
$z=0. x+y=3\implies y=3-x$
$\frac{1}{\sqrt{(x-3/2)^2+3/4}}+\frac{1}{\sqrt{(3/2-x)^2+3/4}}$
$g(3,0,0)=5/\sqrt{3}<3$
$g(3/2,3/2,0)=5/\sqrt{3}<3$
So max is 3.
Answer: Another way.
Let $c=0$.
Thus, since $$a^2-3a+3=\left(a-\frac{3}{2}\right)^2+\frac{3}{4}\geq\frac{3}{4},$$ we obtain:
$$\sum_{cyc}\frac{1}{\sqrt{a^2-3a+3}}\leq\frac{4}{\sqrt3}+\frac{1}{3}=\frac{5}{\sqrt3}<3.$$
Let $f(a,b,c,\lambda)=\sum\limits_{cyc}\frac{1}{\sqrt{a^2-3a+3}}+\lambda(a+b+c-3)$ and $abc\neq0$.
Thus, in the inside critical point $(a,b,c)$ should be $$\frac{\partial f}{\partial a}=\frac{\partial f}{\partial b}=\frac{\partial f}{\partial c}=0,$$
which gives
$$\frac{2a-3}{\sqrt{(a^2-3a+3)^3}}=\frac{2b-3}{\sqrt{(b^2-3b+3)^3}}=\frac{2c-3}{\sqrt{(c^2-3c+3)^3}}.$$
Now, let $a\neq b$ and $a\neq c$.
Thus, $$\frac{2a-3}{\sqrt{(a^2-3a+3)^3}}=\frac{2b-3}{\sqrt{(b^2-3b+3)^3}}$$ gives
$$(2b-3)^2(a^2-3a+3)^3=(2a-3)^2(b^2-3b+3)^3$$ or
$$(a-b)(a+b-3)P(a,b)=0,$$ where $P$ is a polynomial of two variables, which gives $P(a,b)=0.$
Also, by the similar way $$\frac{2a-3}{\sqrt{(a^2-3a+3)^3}}=\frac{2c-3}{\sqrt{(c^2-3c+3)^3}}$$ gives
$$(a-c)(a+c-3)P(a,c)=0,$$ which gives $P(a,c)=0$.
But, $$P(a,b)-P(a,c)=$$
$$=\tfrac{(2b-3)^2(a^2-3a+3)^3-(2a-3)^2(b^2-3b+3)^3}{(a-b)(a+b-3)}-\tfrac{(2c-3)^2(a^2-3a+3)^3-(2a-3)^2(c^2-3c+3)^3}{(a-c)(a+c-3)}=$$
$$=(b-c)(2a-3)^2(b+c-3)\sum_{cyc}a^2=0,$$
which gives $a=\frac{3}{2}$ or $b=c$.
If $a=\frac{3}{2}$(here we have a saddle point), so $c=\frac{3}{2}-b$ and we need to prove that:
$$\frac{1}{\sqrt{b^2-3b+3}}+\frac{1}{\sqrt{b^2+\frac{3}{4}}}+\frac{2}{\sqrt3}\leq3,$$ which is true, but my proof of this statement is very ugly.
But the case $b=c$ says that it's enough to prove our inequality for equality case of two variables.
Let $b=a$ and $c=3-2a$, where $0\leq a\leq\frac{3}{2}.$
Thus, we need to prove that:
$$\frac{2}{\sqrt{a^2-3a+3}}+\frac{1}{\sqrt{4a^2-6a+3}}\leq3$$ or
$$9(a^2-3a+3)(4a^2-6a+3)\geq\left(\sqrt{a^2-3a+3}+2\sqrt{4a^2-6a+3}\right)^2$$ or
$$18a^4-81a^3+140a^2-108a+33\geq2\sqrt{(a^2-3a+3)(4a^2-6a+3)}$$ and since
$$18a^4-81a^3+140a^2-108a+33=$$
$$=18\left(a^2-\frac{9}{4}a+1\right)^2+\frac{1}{8}(103a^2-216a+120)>0,$$ it's enough to prove that:
$$(18a^4-81a^3+140a^2-108a+33)^2\geq4(a^2-3a+3)(4a^2-6a+3)$$ or
$$(a-1)^2(36a^6-252a^5+749a^4-1202a^3+1099a^2-546a+117)\geq0,$$ which is true because
$$36a^6-252a^5+749a^4-1202a^3+1099a^2-546a+117=$$
$$=\left(6a^3-21a^2+\frac{41}{2}a-5\right)^2+62\left(a^2-\frac{281}{124}a+\frac{6}{5}\right)^2+$$
$$+\frac{9665a^2-23560a+16864}{6200}>0.$$
Answer: Remarks: We may use the Taylor approximation of $f(x) := \frac{1}{\sqrt{x^2-3x+3}}$ around $x = 1$:
$\frac{1}{\sqrt{x^2-3x+3}}
\sim 1 + \frac12(x - 1) - \frac18(x - 1)^2 + \cdots$.
However, we must use it locally.
For example,
we have $(1 + (x-1)/2)^2 - [f(x)]^2 = \frac{(x^2 + x - 1)(x - 1)^2}{4(x^2 - 3x + 3)}$. Thus, we have
$f(x) \le 1 + \frac12(x - 1)$
if $x^2 + x - 1\ge 0$.

WLOG, assume that $a\ge b \ge c$.
Let
$$f(x) := \frac{1}{\sqrt{x^2-3x+3}}.$$
Fact 1: $f(x)$ is strictly increasing on $[0, 3/2]$, and strictly decreasing on $[3/2, 3]$.
Fact 2: $f(x) \le 1 + \frac12(x - 1)$ on $[5/8, 3]$.
(Note: $(1 + (x-1)/2)^2 - [f(x)]^2 = \frac{(x^2 + x - 1)(x - 1)^2}{4(x^2 - 3x + 3)}$.)
Fact 3: $f(x) \le 1 + \frac12(x - 1) - \frac18(x - 1)^2$ on $[1, 3]$.
(Note: $(1 + \frac12(x - 1) - \frac18(x - 1)^2)^2
- [f(x)]^2 = \frac{(x^3 - 12x^2 + 30x + 37)(x - 1)^3}{64(x^2 - 3x + 3)}$.)
If $c \le 1/3$, by Fact 1, we have
$$P \le f(1/3) + f(3/2) + f(3/2) < 3.$$
If $c \ge 5/8$, by Fact 2, we have
$$P \le 1 + \frac12(c - 1) + 1 + \frac12(b - 1) + 1 + \frac12(a-1) = 3.$$
If $1/3 < c < 5/8$ and $b < 1$, by Fact 1, we have
$$P \le f(5/8) + f(1) + f(3/2) < 3.$$
If $1/3 < c < 5/8$ and $b \ge 1$, by Fact 3, we have
\begin{align*}
 P &\le \frac{1}{\sqrt{c^2 - 3c + 3}}
 + 1 + \frac12(b - 1) - \frac18(b - 1)^2
 + 1 + \frac12(a - 1) - \frac18(a-1)^2\\
 &= \frac{1}{\sqrt{c^2 - 3c + 3}}
 + 2 + \frac12(1 - c) - \frac{(a - 1)^2 + (b - 1)^2}{8}\\
 &\le \frac{1}{\sqrt{c^2 - 3c + 3}}
 + 2 + \frac12(1 - c) - \frac{(a - 1 + b - 1)^2}{16}\\
 &= \frac{1}{\sqrt{c^2 - 3c + 3}}
 + 2 + \frac12(1 - c) - \frac{(1 - c)^2}{16}\\
 &= \frac{1}{\sqrt{c^2 - 3c + 3}} + 3 - \frac{(c + 3)^2}{16}\\
 &> 0
\end{align*}
where we use $\frac{(c+3)^4}{16^2} > \frac{1}{c^2 - 3c + 3}$ for all $c > 1/3$.
We are done.
Comment: Now, I know a new thing Taylor approximation. +1
Comment: @TATAbox Thanks.
Comment: @RiverLi Could you please help me out: https://math.stackexchange.com/questions/4748373/prove-fracab-fracbc-fracca-ge-sqrt4-lefta2b2c2-right ?
Comment: @Dragonboy Some people will post their answers.
Comment: @RiverLi Today, I found a proof based on your ideas which divide into some cases. I'll post it soon.
Comment: @TATAbox Nice. I am not satisfied with my solution.
Answer: Here is my second proof.
Fact 1. If $x, y, z \ge 0$ with
$x^2 + y^2 + z^2 + \frac34 x^2y^2z^2 \le \frac{15}{4}$. Then $x + y + z \le 3$.
(The proof is given at the end.)
Now, let
$$x := \frac{1}{\sqrt{a^2-3a+3}}, \quad, y := \frac{1}{\sqrt{b^2-3b+3}}, \quad z := \frac{1}{\sqrt{c^2-3c+3}}.$$
We can prove that
$$x^2 + y^2 + z^2 + \frac34 x^2y^2z^2 \le \frac{15}{4}. \tag{1}$$
(The proof of (1) is given at the end.)
By Fact 1, we have $x + y + z \le 3$.
We are done.
$\phantom{2}$

Proof of Fact 1.
We have $x + y \le \sqrt{2(x^2 + y^2)} \le \sqrt{15/2} < 3$. It suffices to prove that
$$z^2 \le (3 - x - y)^2. \tag{A1}$$
From $x^2 + y^2 + z^2 + \frac34x^2y^2z^2 \le \frac{15}{4}$, we have
$$z^2 \le \frac{15/4 - x^2 - y^2}{1 + 3x^2y^2/4}. \tag{A2}$$
From (A1) and (A2), it suffices to prove that
$$\frac{15/4 - x^2 - y^2}{1 + 3x^2y^2/4} \le (3 - x - y)^2. \tag{A3}$$
Let $p = x + y, q = xy$. Then $p < 3$ and $p^2 \ge 4q$.
(A3) is equivalently written as
$$3(3 - p)^2q^2 - 8q + 8p^2 - 24p + 21\ge 0$$
or (converting it to a quadratic function in $(p^2/4 - q)$)
\begin{align*}
 &3(3 - p)^2 (q - p^2/4)^2 + \left(8 - \frac{27}{2}p^2 - \frac32p^4 + 9p^3\right)(p^2/4 - q)\\
 &\quad +
 \frac{3}{16}(p^4 - 2p^3 - 3p^2 - 4p + 28)(p-2)^2 \ge 0
\end{align*}
which is true since $8 - \frac{27}{2}p^2 - \frac32p^4 + 9p^3 \ge 0$ and $p^4 - 2p^3 - 3p^2 - 4p + 28 \ge 0$ for all $0 \le p \le 3$.
We are done.
$\phantom{2}$
Proof of (1).
We need to prove that
\begin{align*}
 &\frac{1}{a^2-3a+3} + \frac{1}{b^2-3b+3} + \frac{1}{c^2-3c+3} \\[6pt]
 &\quad
 + \frac34 \cdot \frac{1}{a^2-3a+3}\cdot \frac{1}{b^2-3b+3}\cdot \frac{1}{c^2-3c+3}\\[6pt]
 & \le \frac{15}{4}.\tag{B1}
\end{align*}
We use the pqr method.
Let $p = a + b + c = 3, q = ab + bc + ca, r = abc$. We have $q \le p^2/3 = 3$.
(B1) is equivalently written as
$$15r^2 + (-45q + 123)r + 41q^2 - 222q + 294 \ge 0. \tag{B2}$$
Using degree four Schur inequality, we have
$$r \ge \frac{5p^2q - p^4 - 4q^2}{6p} =
- \frac29q^2 + \frac52 q - \frac92.\tag{B3}$$
From (B2) and (B3), we have
\begin{align*}
 &15r^2 + (-45q + 123)r + 41q^2 - 222q + 294\\[6pt]
 \ge{}& 15r \cdot \left(- \frac29q^2 + \frac52 q - \frac92\right) + (-45q + 123)r + 41q^2 - 222q + 294\\[6pt]
 ={}& \left(- \frac{10}{3}q^2 - \frac{15}{2}q + \frac{111}{2}\right)r + 41q^2 - 222q + r + 294\\[6pt]
 \ge{}& \left(- \frac{10}{3}q^2 - \frac{15}{2}q + \frac{111}{2}\right)\cdot \left(- \frac29q^2 + \frac52 q - \frac92\right) + 41q^2 - 222q + r + 294\\[6pt]
 ={}& \frac{1}{108}(80q^2 - 240q + 531)(3 - q)^2 \\[6pt]
 \ge{}& 0
\end{align*}
where we use $- \frac{10}{3}q^2 - \frac{15}{2}q + \frac{111}{2} \ge 0$.
We are done.
Comment: Nice solution! +1. By the way, we can use contradiction method to prove the fact 1.
Answer: Proof.
By your try, we get $$\frac{1}{\sqrt{x^2-3x+3}}\le \frac{x+1}{2}$$ is true for all $x\ge \dfrac{\sqrt{5}-1}{2}.$
WLOG, assuming that $a\ge b\ge c \implies a\ge 1\ge c.$ We divide the original problem into two cases.
Case 1: $c\ge \dfrac{\sqrt{5}-1}{2}$ then $$\sum_{cyc}\frac{1}{\sqrt{a^2-3a+3}}\le \frac{a+b+c+3}{2}=3.$$
Case 2: $c< \dfrac{\sqrt{5}-1}{2}.$ We consider two subcases.
$\bullet b\le 1:$ Notice that $$a^2-3a+3=\left(a-\frac{3}{2}\right)^2+\frac{3}{4}\ge \frac{3}{4}.$$
$$b^2-3b+3=(2-b)(1-b)+1\ge 1.$$
$$c^2-3c+3=(1-c)^2+2-c>\left(1-\frac{\sqrt{5}-1}{2}\right)^2+2-\frac{\sqrt{5}-1}{2}=6-2\sqrt{5}.$$
It implies $$\sum_{cyc}\frac{1}{\sqrt{a^2-3a+3}}< \frac{2}{\sqrt{3}}+1+\frac{1}{\sqrt{5}-1}<3.$$
$\bullet b\ge 1 \implies 2\ge a\ge b\ge 1.$ Consider the function $f(x)=\dfrac{1}{\sqrt{x^2-3x+3}}$ for $x\in [1;2]. $
Notice that $$f''(x)=\frac{8x^2-24x+15}{4(x^2-3x+3)^{\frac{3}{2}}}<0, \forall x\in[1;2]$$
Thus, by Jensen inequality $$f(a,)+f(b)\le 2f\left(\frac{a+b}{2}\right)=2f(t)=\frac{2}{\sqrt{t^2-3t+3}}.$$
The rest is proving $$\frac{2}{\sqrt{t^2-3t+3}}+\frac{1}{\sqrt{(3-2t)^2-3(3-2t)+3}}\le 3,$$or $$\frac{2}{\sqrt{t^2-3t+3}}+\frac{1}{\sqrt{4t^2-6t+3}}\le 3,$$which is true for all $1\le t\le 2.$
The proof is done. The maximal value is $3$ achieve at $a=b=c=1.$
Comment: We can continue to find more proofs.
Comment: Yes, the isolated fudging works.
Comment: A good one!  Thank you.
Answer: Here is my third proof.
We use the so-called isolated fudging.
After homogenization, it suffices to prove that, for all $a, b, c \ge 0$ with $a + b + c > 0$,
$$\sum_{\mathrm{cyc}} \frac{a + b + c}{\sqrt{9a^2 - 9a(a + b + c) + 3(a + b + c)^2}} \le 3. \tag{1}$$
It suffices to prove that, for all $a, b, c \ge 0$ with $a + b + c > 0$,
$$\frac{a + b + c}{\sqrt{9a^2 - 9a(a + b + c) + 3(a + b + c)^2}} \le \frac{10a^2 + 7b^2 +7c^2 + 2a(b + c) - 4bc}{8(a^2 + b^2 + c^2)}. \tag{2}$$
We split into two cases.
Case 1. $a = 0$
(2) becomes
$$\frac{1}{\sqrt{3}} \le \frac{7b^2 +7c^2 - 4bc}{8(b^2 + c^2)}$$
which is true (easy).
Case 2. $a > 0$
WLOG, assume that $a = 1$. (2) is written as
$$\frac{1 + b + c}{\sqrt{9 - 9(1 + b + c) + 3(1 + b + c)^2}} \le \frac{10 + 7b^2 +7c^2 + 2(b + c) - 4bc}{8(1 + b^2 + c^2)}. \tag{3}$$
Let $p = b + c, q = bc$. Then $p^2 \ge 4q$.
(3) is written as
$$\frac{1 + p}{\sqrt{3p^2 - 3p + 3}} \le \frac98 - \frac{2p^2 - 2p - 1}{8(p^2 - 2q) + 8}. \tag{4}$$
If $2p^2 - 2p - 1 \ge 0$, using $p^2 \ge 4q$, it suffices to prove that
$$\frac{1 + p}{\sqrt{3p^2 - 3p + 3}} \le \frac98 - \frac{2p^2 - 2p - 1}{8(p^2 - 2\cdot \frac{p^2}{4}) + 8}$$
which is true for all $p \ge 0$ (not difficult).
If $2p^2 - 2p - 1 < 0$, it suffices to prove that
$$\frac{1 + p}{\sqrt{3p^2 - 3p + 3}} \le \frac98 - \frac{2p^2 - 2p - 1}{8(p^2 - 2\cdot 0) + 8}$$
which is true for all $p \ge 0$ (not difficult).
We are done.
Comment: You impressed me again. +1
Comment: (2) is very nice!
Comment: But it is quite hard to motivate it.
Comment: @Dragonboy Yes, often it is not easy by hand.


How do I create a progress bar?

Question: I need to implement a progress bar using Drupal 7. This is the code I am actually using.
$form[$name][$name.'_enc'] = array(
  '#type' => 'submit',
  '#value' => t($name.' Enable'),
  // '#submit' => array('submit_'.$name.'_enc'),
  '#ajax' => array(
    'callback' => 'submit_'.$name.'_enc',
    'wrapper' => 'ajax-response-goes-here',
    'method' => 'replace',
    'effect' => 'fade',
    'progress' => array (
      'type' => 'bar',
      'message' => 'convert..',
      'url' => 'misc/progress.js',
      'interval' => '1500'
)

Comment: Have you considered using the [Batch API](http://api.drupal.org/api/drupal/includes!form.inc/group/batch/7)?
Comment: Its usually CSS property changes. Based on server response keep on increasing width till you reach 100 %
Answer: What you set as ['#ajax']['progress']['url'] is wrong: It's not the URL for a JavaScript file, but it's the callback path to use to determine how full the progress bar is. The menu callback should return a value that indicates if the operation has been completed, or it is completed at 10%, 20%, 50%, etc. Looking at the code contained in the progress.js file, I notice the value is expected to be between 0 and 100.
As side note, the value passed in ['#ajax']['progress']['message'] should be passed to t().
Answer: Progress bar example:
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Import'),
    '#ajax' => array(
        'callback' => 'import_submit_callback',
        'wrapper' => 'import-form',
        'progress' => array(
            'type' => 'bar',
            'message' => t('Importing..'),
            'url' => 'import/progress', //url to fetch current progress percentage
            'interval' => '1000' //progress bar will refresh in 1 second
        )
    ),
);

Then create menu like this for url 'import/progress' :
$items['import/progress'] = array(
    'title' => t('Import progress'),
    'page callback' => 'import_progress',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);

Then output json data indicating current status like this in that page callback function:
function import_progress() {
    $progress = array(
        'message' => t('Starting import...'),
        'percentage' => -1,
    );

    $completed_percentage = variable_get('import_status'); // calculate progress percentage here

    if($completed_percentage){
        $progress['message'] = t('Importing...');
        $progress['percentage'] = $completed_percentage ;
    }

    drupal_json_output($progress);
}

Answer: I have created one menu call back called sales/progress . Here i have called one function as in below
function sales_progress() {
   echo '{"percentage":"25","message":"Processing more..."}';
}

Here 25 is a static percentage value. You can customize percentage value & message text as your wish.
Periodically the above function will be called. And progress bar value will be updated. For more details reference link

How do I create a progress bar?


How to get output of a sql with additional special characters

Question: Long story...
I am trying to geenrate a crosstab query dynamically and run it as a psql script..
To achieve this, I want the last line of the sql to generated and appended to the top portion of the sql.
The last line of the sql is like this.... "as final_result(symbol character varying,"431" numeric,"432" numeric,"433" numeric);"
Of which, the "431", "432" etc are to be generated dynamically as these are the pivot columns and they change from time to time...
So I wrote a query to output the text as follows....
psql -c "select distinct '"'||runweek||'" numeric ,' from calendar where runweek between current_runweek()-2 and current_runweek() order by 1;" -U USER -d DBNAME > /tmp/gengen.lst

While the sql provides the output, when I run it as a script, because of the special characters (', "", ) it fails.
How should I get it working? My plan was then loop through the "lst" file and build the pivot string, and append that to the top portion of the sql and execute the script... (New to postgres, does not know , dynamic sql generation and execution etc.. but I am comfortable with UNIX scripting..)
If I could somehow get the output as
("431" numeric, "432" numeric....etc) in a single step, if there is a recommendation to achieve this, it will be greatly appreciated.....
Comment: If you run this from the shell (and quoting is your problem) you could use a here-document.
Answer: Since you're using double quotes around the argument, double quotes inside the argument must be escaped with a backslash:
psql -c "select distinct '\"'||runweek||'\" numeric ,' from calendar where runweek between current_runweek()-2 and current_runweek() order by 1;"

Heredoc can also be used instead of -c. It accepts multi-line formatting so that makes the whole thing more readable.
(psql [arguments] <<EOF
  select distinct '"'||runweek||'" numeric ,'
     from calendar
     where runweek between current_runweek()-2 and current_runweek()
   order by 1;
EOF
) > output

By using quote_ident which is specifically meant to produce a quoted identifier from a text value, you don't even need to add the double quotes. The query could be like:
select string_agg( quote_ident(runweek::text), ',' order by runweek)
 from calendar
 where runweek between current_runweek()-2 and current_runweek();

which also solves the problem that your original query has a stray ',' at the end, whereas this form does not.
Comment: Rewriting it like this select string_agg(quote_ident(runweek::text),' numeric,' order by runweek)
     from (select distinct runweek from calendar
     where runweek between current_runweek()-2 and current_runweek()
  ) a;   gives the output as ""432" numeric,"433" numeric,"434" which is not exactly what I want, but I used shell commands to append the missing "numeric" string to the code... while adding the string " numeric ," in the subquery results in the "" place for the entire string and not just the "433" or "432".... but at least I have a way to move forward.... Thanks...


Why am I getting data from the database slowly?

Question: I use nestjs with typeorm and postgresql, I get data from the database in 150-200ms, but if you wait 20 seconds and send a request to the backend again and get the data, then I get the data in 1000ms or 1500ms, although in theory and in general it should usually be 150- 200ms? Tried to use sequelize result was same. As if, if you wait, the server starts to fall asleep and wakes up for a long time when the request goes to it again.
This is code how I do request to database:
async getProducts() {
   const products = await this.productRepository.find();
   return products;
}

Please any ideas, answers, options
Answer: It is very unlikely that Nestjs is adding a significant delay here. The code you posted looks okay-ish.
Try removing the "surroundings" (as in moving parts) to get to the bottom of this. E.g. execute this method in the main.ts
Hint: if your service would be called MyService you could access it there like this:
const service = app.get(MyService);

Another way would be to remove everything that is involved in the response of the request:

Your code from controller -> service -> repository
Code that could intercept: Middlewares, Pipes, Guards, Interceptors

By switching Sequelize to TypeORM you kinda removed the DB communication layer as a suspect, if your investigation does not yield anything helpful you should consider looking into the underlying DB and the specified connection options (if any, e.g. pool size). Most likely the causing code should be in the application tho. For Sequelize and TypeScript, you can also enable logging to get better insights. Good luck on your research!


BlockHound Detects WebClient's ExchangeFunction's .next() Method As Blocking

Question: I am profiling my reactor application using BlockHound. I have a filter on my ExchangeFunction:
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
final ClientRequest.Builder builder = ClientRequest.from(request);
return Mono.defer(() -> next.exchange(builder.build())) //detects blocking call
    .transform(reactiveUtil::contextualize)
    .publishOn(Schedulers.parallel());
}

BlockHound detects a blocking call on the next.exchange(). Now since I am using WebClient with Netty, why would this call be non-blocking? Subscribing this on an elastic thread does not help.
Comment: What is the stacktrace shown by BlockHound?
Comment: @PhilClay
https://gist.githubusercontent.com/pandepra/8a5991b30c5385daffc283d2e33219d3/raw/5f07ff93a131dcdd62f53b4f7954a303f08ffc3b/gistfile1.txt
Answer: According to your gist, BlockHound is detecting java.io.FileInputStream.readBytes(..) as blocking deep within the SSL handshake.
This problem has been reported in https://github.com/reactor/reactor-netty/issues/939 and appears to be resolved in the latest releases.


Is there an algorithm or method to tell if a fraction can be represented exactly in a particular base?

Question: For instance, 1/3 cannot be represented exactly in base 10, but in many other bases it can.
Is there an algorithm that will tell you, given x,y,z, where x and y form a ratio of integers (a fraction) and z is the base, whether it can be represented exactly or must be approximated?
I feel like this is a stupid question and there's some really obvious way to tell that I'm not thinking of.
Answer: There is an easy algorithm. Assuming $x,y$ coprime, the fraction $\dfrac{x}{y}$ has a terminating representation in base $z$ if and only if all prime divisors of $y$ are also prime divisors of $z$, or, equivalently, if $y$ divides some power of $z$.
Since integers are unproblematic, we can assume that $0 < x < y$.
If $\dfrac{x}{y}$ has a terminating representation in base $z$, then that representation is
$$\frac{x}{y} = \sum_{k=1}^n \frac{d_k}{z^k},$$
where every digit is an integer $0 \leqslant d_k \leqslant z-1$. Then we have
$$z^n\cdot \frac{x}{y} = \sum_{k=1}^n d_k\cdot z^{n-k} =: r \in \mathbb{N},$$
and
$$\frac{x}{y} = \frac{r}{z^n}.$$
Since the fraction $\dfrac{x}{y}$ was assumed reduced, the above equality implies $z^n = k\cdot y$ and $r = k\cdot x$ for some $k \in \mathbb{N}$, so $y$ divides a power of $z$, hence has no prime factors that don't divide $z$.
Conversely, if $y$ is a divisor of a power of $z$, say $z^n = m\cdot y$ for some $m \in \mathbb{N}$, then
$$\frac{x}{y} = \frac{m\cdot x}{m\cdot y} = \frac{m\cdot x}{z^n}.$$
Let the integer $r = m\cdot x$ have the base-$z$ expansion
$$r = \sum_{k=0}^q d_k\cdot z^k.$$
Then we have
$$\frac{x}{y} = \frac{r}{z^n} = \sum_{k=0}^q d_k z^{k-n} = \sum_{j = n-q}^{n} \frac{d_{n-j}}{z^j},$$
a terminating representation of $\dfrac{x}{y}$.
Comment: Wow I would love to see a proof of that. Doesn't make any sense to me on the surface.
Comment: Okay, give me a few minutes (well, I'm a slow typist, a few more).
Comment: Haha only on Math.SE are proofs composed upon request. I was just passively dreaming, not actually asking you to create one. Thanks so much!
Comment: Nice, Dan Fisher, slow typist, fast thinker.


Confusion about a rational function

Question: There's a function $f(x)=\frac{(x+2)(x+1)}{(x-4)^2(x+1)}$
I'm a little confused: is this function considered to be defined at  $x=-1$? On the one hand, if you plug in $-1$, you'll get $0/0$. But on the other hand, $(x+1)/(x+1)=1$... Also does $x=-1$ count as a zero of this function? I have the same confusion here.
And if somebody's asking "How many removable singularities does $f$" have" (the correct answer is 1), what does "removable singularity" mean in real analysis? If it means removable discontinuity, then why does it have one such discontinuity? If we ignore the $x+1$'s (whose quotient is 1), the only discontinuity is an infinite discontinuity.
Answer: The function is not defined at $x=-1$ due to division by zero. However, it does have a limit as $x\rightarrow -1,$ namely
$$\lim_{x\rightarrow -1}f(x)=\frac{(x+2)}{(x-4)^2}\Bigg|_{x=-1}=-1/25.$$
The end result is that the graph of $f$ has a hole (removable discontinuity) at the point $(x,y)=(-1,-1/25)$.
The only other point where $f$ is not defined due to division by zero is at $x=4$. The limit of $f$ as $x\rightarrow 4$ is $+\infty$. Thus, $f$ has a vertical asymptote at $x=4$.

Confusion about a rational function


match a BEGIN and END in antlr

Question: how can I say to antlr if you see a 'BEGIN' then at this line you must see an 'END'?
here is my code ( i only need the BEGIN/END when i have multiple statements)
whileStatement
    : 'WHILE' expression 'DO'
         'BEGIN'?
               statement
         'END'?
    ;

and my statements
statement
    :   assignmentStatement
    |   ifStatement
    |   doLoopStatement
    |   whileStatement
    |   procedureCallStatement
    ;

Answer: No experience with ANTLR, but generally in BNF/context-free grammars you'd express this as
whileStatement
    : 'WHILE' expr 'DO'
      statementBlock
    ;

statementBlock
    : statement
    | 'BEGIN' statement* 'END'
    ;

or add statementBlock as an alternative in the definition of statement.
Comment: You might also define statement so that it can include the BEGIN and END, so that programmers can separate code into blocks at any point.

match a BEGIN and END in antlr


AttributeError: 'str' object has no attribute 'subs'

Question: I am making a definition which will help me replace the varials of a polynomial but I get this error
from sympy import *

x = Symbol('x')
def velocidad_media(t0,t1,poli):
    D1=poli.subs(x,t0)
    D0=poli.subs(x,t1)
    D3=D1-D0
    T= t1-t0
    Re=D3/T
    print("la velocidad media es",Re,"m/s")

pol=input("ingrese la funcion del lanzamiento: ")
a= int(input("ingrese el tiempo inicial en segundos: "))
b=int(input("ingrese el tiempo final en segundos: "))
punt=int(input("ingrese el punto en donde quiere hallar la velocidad instantanea: "))velocidad_media(a,b,pol)`

Error message :
AttributeError: 'str' object has no attribute 'subs'

Answer: The input returns a str type, but you are treating it as a sympy expression.
What you can do it to parse the string pol into an sympy expression with the function parse_expr.
e.g.
from sympy import *
from sympy.parsing.sympy_parser import parse_expr

x = Symbol('x')
pol = parse_expr('x**2 + x + 1')
pol.subs(x,1)


Data level aggregation for price elasticity

Question: I have just started working on price elasticity and I have some fundamental question.
Question 1: I have daily price and sales data for a product, now if I want to calculate the price elasticity should I aggregate the data at a weekly or some other level or should I directly feed the data into a regression model.
Question 2: Now let's assume the data size is very large and I cannot run models on daily data which in this case leads me to aggregating the data at a weekly level. The questions is how do I aggregate the data which contains these scenarios:
1) There may be multiple price points within the week
2) One product may have same price for 2 weeks then its price change for another week and then the price reverts back to original in the next week.
Answer:
Question 1: I have daily price and sales data for a product, now if I
  want to calculate the price elasticity should I aggregate the data at
  a weekly or some other level or should I directly feed the data into a
  regression model.

I think you can do both ways: aggregate by days (but if price deviates inside a day you will loose some information), and aggregate by price while adjusting for the number of days the price was holding.
The later is better, to my mind, as you will see the clear dependence between price and volume. It should look this way:
price: 1.02; 1.03; 1.04; 1.05...
sales: 1.4M; 1.3M; 1.2M; 1.2M...

Question 2: Now let's assume the data size is very large and I cannot
  run models on daily data which in this case leads me to aggregating
  the data at a weekly level.

Averaging the price on a daily basis will do the trick, but, again, with some loss of information.


Slide a DIV up on load and down on click

Question: I'd like my "newsbox" div to slide up from the bottom of the page to above my footer on page load (with a little delay) then I'd like the DIV to slide down if the user clicks on "newsClose". Tried something but without success (have no knowledge in js) - Thanks for your help
JSFiddle: http://jsfiddle.net/7whAs/
JS
$(document).ready(function() {
    jQuery('#newsbox').delay(2000).slideDown();
    jQuery(function() {
    jQuery('.newsClose').click(function (e) {
        e.preventDefault();
        jQuery('#newsbox').slideUp();
    });
});

HTML

Blablablablabla blablabla blablabla Blabla blabla

        Close X

CSS
#newsbox {
    background-color: #CCC;
    display:none;
    width: 750px;
    z-index: 10000;
    float: left;
    position: fixed;
    bottom: 45px;
    padding-top: 10px;
    padding-right: 20px;
    padding-bottom: 10px;
    padding-left: 20px;
}

.news-text {
    float: left;
    width: 600px;

}
.news-text p {
    color: #666666;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 11px;
    line-height: 13px;
}
.news-continue {
    float: left;
    width: 70px;
    text-align: center;
    margin-top: 10px;
    margin-left: 20px;
}
.news-close {
    width: 60px;
    margin-right: auto;
    margin-left: auto;
    text-align: center;
}
.news-close a,
.news-text a {
    color: #3E718E;
}
.news-continue a,
.news-close a {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 11px;
    line-height: 11px;
    font-weight: normal;
    color: #FFF;
    display: block;
    padding-top: 5px;
    padding-right: 0px;
    padding-bottom: 5px;
    padding-left: 0px;
    background-color: #3E718E;
}

.news-close a:hover {
    text-decoration: underline;
}
.news-continue a:hover,
.news-close a:hover {
    background-color: #333333;
    color: #FFF;
}

.news-close {
    float: right;
    width: 60px;
    font-size: 10px;
    line-height: 11px;
    text-align: right;
}

Answer: You were close. First enable jQuery on your fiddle (it's on the left side), then eliminate your second DOM ready function:
Demo    http://jsfiddle.net/7whAs/1/
$(document).ready(function() {
    jQuery('#newsbox').delay(2000).slideDown();
    jQuery('.newsClose').click(function (e) {
        e.preventDefault();
        jQuery('#newsbox').slideUp();
    });
});

Comment: also if you decide to work with the shorthand '$' for jQuery (which should be fine), you can stick with it in the rest of your code (replace jQuery by $), but that is just esthetics.