text:
Q: Getting SQLSTATE[HY000] [2002] Connection refused when running upgrade command for Magento 2.3 I am getting the following error when running the php bin/magento setup:upgrade command in my Magento 2.3 instance:

SQLSTATE[HY000] [2002] Connection refused

I can connect to the database using the mysql -u root -p and can run commands there without any issue. So I've determined that this is an issue with Magento's connection to the DB. I have gone in and changed the env.php setting from localhost to 127.0.0.1 with no luck. Recently we did have a DNS change, but I'm not sure if that would effect the database. Are there any other solutions?

A: Check your env.php file if your db credentials  are correct.
Check if dbname has the right database that you are using, username and password are the ones you use to log into MYSQL.I would suggest you keep  'host' => 'localhost'.

A: Running the php bin/setup:config:set fixed the issue.


text:
Q: How do I find this $f(x)$? I can't seem to evaluate the $f(x)$ for this problem.
Question: If a function satisfies $f(x) f"(x)-f(x)f'(x)=(f'(x))^2$ such that $x\in R$ and $f(0)=f'(0)=1$, then identify which of the following statement(s) is (are) corect?
Statements:
$1)$Equation $f(x)=e^x$ has two solutions.
$2)$Equation $f(x)=e^x$ has exactly one solution.
$3)$$\displaystyle \lim_{x\rightarrow 0} \dfrac{f(x)-1}{x}=1$
$4)\displaystyle\lim_{x\rightarrow-\infty} f(x)=\dfrac{1}{e}$
Okay, Obviously I've observed that (3) is already correct but can't really figure out $f(x)$ for the rest.
I tried applying by parts to $$f^"(x)=\frac{f'(x)(f'(x)+f(x))}{f(x)}$$ but no fruitful result. Please help.

A: Rewrite this as :
$$\frac{f(x)f''(x)-\big(f'(x)\big)^2}{\big(f(x)\big)^2}= \frac{f'(x)}{f(x)}$$
Do you see something?

$$d\Bigg( \frac{f'(x)}{f(x)}\Bigg) =  \frac{f'(x)}{f(x)}$$
  $$\implies   \frac{f'(x)}{f(x)}= e^x $$
  This is simple linear ODE, on solving you'll get :
  $$f(x)= c \cdot e^{-e^x}$$
  Using $f(0)=1$;
  $$\boxed{f(x)= \frac{1}{e^{e^x-1}}}$$

Now you may proceed.

A: Let's solve for f(x) first.
Let $y = f(x)$. The original equation becomes:
$$ yy" -y'^2 = yy'$$
Divide both sides by y, assuming $y(x) \not= 0$:
$$ \frac{yy"-y'^2}{y^2} = \frac{y'}{y} $$
$$ \Longleftrightarrow \frac{d}{dx}\frac{y'}{y} = \frac{y'}{y}$$
$$ \Longleftrightarrow \frac{dz}{dx} = z$$
where $z = y'/y$. The general solution is $ z = Ce^x$. Applying the initial condition gives $z(0) = y'(0)/y(0) = 1 \Rightarrow C = 1$. Now solve for $y$:
$$ \frac{y'}{y} = e^x $$
$$ \Rightarrow \int \frac{y'}{y} dx = \int e^x dx$$
$$ \Rightarrow \ln y = e^x + C_1$$
$$ \Rightarrow y = C_2 \exp(e^x) $$
Applying the initial condition gives $C_2 = 1/e$, i.e.,
$$ y = f(x) = \frac{\exp(e^x)}{e}. \quad (1)$$
Now verify the following statements:

*

*$f(x) = e^x$ has two solutions: wrong

*$f(x) = e^x$ has one solution: correct

Both statements can be seen from the following:
$$ (1) \Rightarrow e^{(e^x)} = ee^x$$
Taking $\ln$ both sides gives: $e^x = 1 + x$. Solving this equation is equivalent to finding all intersections between two curves $g(x) = e^x$ and $h(x) = x+1$. Note that

*

*the two curves $g(x)$ and $h(x)$ have one obvious intersection at $x = 0$,

*the $h(x)$ line is tangential to $g(x)$ at the intersection $x = 0$,

*going leftwards from $x = 0$ to $-\infty$: $g(x)$ decreases more slowly than $h(x)$ because the slope $g'(x) > h'(x)$ for all $x < 0$.
Thus, we conclude that there is one and only one intersection at $x = 0$, hence $f(x) = e^x$ has only one solution.

*$\lim_{x\to0} \frac{f(x)-1}{x} = \lim_{x\to0} \frac{f(x)-f(0)}{x - 0} = f'(0) = 1$: correct

*$\lim_{x\to-\infty} f(x) = \frac{1}{e} $: correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android and JFileChooser I've developed a desktop application that allows the user to extract images from their phone.
When I first started this project, my android was running Gingerbread. When I plugged my phone into the laptop via USB, it would appear as a  "Device with removable storage". Therefore, the JFileChooser would pick it up.
nwdir = new JFileChooser();
            nwdir.setCurrentDirectory(new java.io.File("C:\\"));
            nwdir.setDialogTitle(choosertitle);
            nwdir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            nwdir.setAcceptAllFileFilterUsed(true);

However, I recently upgraded the phone's o/s to Icecream and it now shows up on the desktop as a "portable device". This is something that the JFileChooser cannot see?!
Has anyone got any suggestions on how to get around this problem? I was going to roll back the O/S of the phone, but this somewhat limits the application's device support.

A: The default transfer mode has been changed in Android 4.0 Ice Cream Sandwich from USB Mass Storage mode to MTP (Media Transfer Protocol) which doesn't use a standard filesystem mount. On some phones it is possible to change the USB mode while on others it may be necessary to install an apk to enable it

A: I've found a way around it by doing this.... Settings > Wireless & Network > USB utilities and click the button > then (and ONLY then) plug in USB cable


text:
Q: Qual a "maneira correta" de usar destrutores em PHP Ao procurar referencias de boas praticas em PHP para o gerenciamento de memória me deparei em diversos intendimentos de como usar destrutores.
Sei que o principal ator é o Garbage Collector más este não faz parte do escopo de minha pergunta.
Referencias:

*

*o próprio Manual PHP

*entre algumas da comunidade destaco esta

*e uma referencia externa
Más minhas leituras me trouxerem dúvidas as quais não encontrei respostas sendo elas...
Dúvidas:

*

*a função __destruct(){} vazia irá remover qualquer valor associado a classe ou é necessário explicitar estes valores em seu escopo?

*após instanciar a classe por referencia e antes do encerramento do script qual a diferença entre usar NULL e unset() por exemplo:
<?php
    $refer = new MyClass();
    $refer->hello(); // output: Hello World!

    $refer = NULL; // ou unset($refer);

    // mais blocos de código aqui...

*segundo Manual PHP a herança de clase exige que a classe "filha" explicite a chamado parent::__destruct() no destrutor... más e no caso de classes não estendidas que instanciam outra classe em seu escopo? Ao atribuir NULL ou usar unset() antes do encerramento do script forcará ambos os destrutores ou é necessário explicitar cada um? Exemplo:
<?php
    /**
    class Core
    {
         public function __construct(){}

         public function session($start=true)
         {
             if ( !$start  ) {
                  if ( isset($_SESSION) ) {
                       session_destroy();
                       return true;
                  }
             }
             session_start();
         }

         public function language()
         {
             if ( isset($_SESSION) ) {
                  $_SESSION['language'] = 'pt-BR';
             }
         }

         public function layoutEngine()
         {
             return new HandlerUI(); // outra classe
         }

         function __destruct(){
             #
         }
    }

    class HandlerUI
    {
         function __construct()
         {
             return $this;
         }

         public function Header()
         {
             return "<title>Hello World</title>";
         }

         public function NavBar()
         {
             return "This is navbar";
         }

         public function Drawer()
         {
             return "

";
         }

         public function Footer()
         {
             return "I am Footersession();
    $app->language();

    $layout = $app->layoutEngine();

    unset($app); // ou $app = NULL;
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language'];?>">
<?php
    $layout->Header();
?>

        <?php
            // navbar
            $layout->Navbar();
            // drawer
            $layout->Drawer();
        ?>

        <?php
            //
            $layout->Footer();
        ?>

    <?php
        //
        $layout->JavaScript();

        unset($layout); // ou $layout = NULL;

        // mais blocos de código aqui...
    ?>

*e a que mais me questiono: ao utilizar OPcache ou outro cache de bytecode (que guarda na memória o compilado) como é tratado a fução __destruct() neste caso de uso de cache?

Sei que não existe uma "maneira correta" visto que isto depende de caso de uso, das necessidades do código e da abordagem em estruturá-lo más busco um entendimento qualificado do mesmo.
Desde de já grato.

A: O método __destruct serve para executar uma última ação antes do objeto deixar de existir.
Um uso que pode ser feito com ele caso você construa um framework é pôr num Controller genérico chamando uma view de mesmo nome do Controller no fim da execução. Quando outros controllers extenderem esse controller genérico todos eles terão essa funcionalidade de chamar a view adequada automaticamente no fim da execução.
Exemplo de código utilizando __construct e __destruct :
<?php

class Teste
{
    private $nome;

    function __construct($nome)
    {
        echo 'O objeto foi construído.
';
        $this->nome = $nome;
    }

    function saudacao()
    {
        return 'Olá ' . $this->nome . '!
';
    }

    function __destruct()
    {
        echo 'O objeto não existirá mais após essa mensagem.';
    }

}

$teste = new Teste('Lauro');

echo $teste->saudacao();

?>

Output gerado ao executar o script acima:
O objeto foi construído.
Olá Lauro!
O objeto não existirá mais após essa mensagem.

Observação:
O PHP limpa todas as variáveis da memória no fim da execução do script. Então ao final do script, ao remover o objeto ele executa o destruct automaticamente. Mas se o objeto fosse destruído com unset o destruct seria chamado da mesma forma, só que antes do término da execução do script por completo.
Não há necessidade de declarar __construct ou __destruct se não for utilizá-los.


text:
Q: Gradle sync failed: Failed to find CMake
Hola amigos soy nuevo por aca y también en el mundo de la programación hice un curso de desarrollador web y ahora estoy en uno de desarrollo de apps en android studio lo cual estoy desde cero acabo de instalar android estudio y me da este error:

Gradle sync failed: Failed to find CMake

quisiera saber si alguien ya tiene respuestas para estos de antemano muchas gracias.

A: Da click en el texto azul para instalar CMake

con esto tu proyecto funcionara sin problema.


text:
Q: MongoDB join 2 tables and select field is null In MongoDB
I have a job sign up application. I have two collections- Jobs and HelperJobs.
The first collection contains all the jobs and the second maps Helpers to the jobs they signed up for.
I want to select all of the jobs that the current logged in user has not signed up for. So the following code works to bring back a collection of the intersection of all jobs and helper jobs but I want it to only return a collection where another field (hours) is null.
db.jobs.aggregate([{
  $lookup: {
    from: "helperjobs",
    localField: "_id",
    foreignField: "job",
    as: "temp"
  }
}])

A: Just add a $match after the $lookup using the temp.hours field to filter on:
db.jobs.aggregate([{
  $lookup: {
    from: "helperjobs",
    localField: "_id",
    foreignField: "job",
    as: "temp"
  },
  {
    $match: { "temp.hours": { $exists:false } }
  }
}])


text:
Q: Delete a project from SonarQube Does anyone know how to delete a project from a SonarQube server?
Thanks,
Ronen.

A: Login with administrator account. Select the project name. There you can see "project deletion" under configuration menu.

A: Login with an administrator account, then browse to the settings page of your project to get the button "delete project".

A: In some situations that you want to make it programatically you can use the SonarQube's Rest Web API to do so. According to SonarQube documentation:
POST api/projects/bulk_delete

Which can be used by passing the project's ID in the "keys" parameter.
I'm no pro in Curl but it should be something like this (code generated in the Postman client) for project with key "daBestProjectKey":
curl -X POST -H "Authorization: Basic YWRtaW46YWRtaW4=" -H "Cache-Control: no-cache" -H "Postman-Token: 10a0e9a1-8dae-a9d1-45f2-0d8e56de999d" -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "keys=daBestProjectKey" "http://localhost:9000/api/projects/bulk_delete"

A: [Home] button in top left corner >> [Projects] tab  in top left corner >> (under name, click on the name of your project) >> [Project Deletion] (on the left panel/dashboard at the bottom) >> [Delete project] (in the center of the page, kind of).

A: SonarQube 5.1
(released on April 23, 2015)
Consider that you need to have administrative permissions. You can perform as described in the documentation:

A: For SonarQube 5.1, following are the two options that can be followed:

A: Here is SonarQube version 4.4,
Seems each version the GUI is changed....

A: Here is the steps I use to DELETE any project from My SonarQube.

*

*Login as administrator

*Go to Administration -> Projects -> Projects Management

*Select the Project(s) you want to DELETE

*Click on Delete button at top right corner.

A: Updated for Sonar 2.11:

*

*Select the project (from the home page)

*Then click on the Project Deletion link on the bottom of the left panel

*Finally, confirm using the Delete Project button

A: In Sonar 3.6, the deletion button is in the project page, under the search input, inside the menu Configuration (you must be logged as administrator):

A: You have 2 ways to delete a project:

*

*If you are an admin of the project, you can delete it from its configuration actions
=> See "Deleting a project" in the "Project Administration" documentation page

*If you are a SonarQube administrator, then you can also delete a project from the "Project Management" page
=> See "Project Management/Project Existence" documentation page

A: This information is for SonarQube version 5.0 which is latest for now - Released on 17th January 2015
You can delete the project from Project Configuration which is present on right hand side of Project Dashboard.The same screenshot is attached below.

if you are an Administrator of SonarQube, the you have the authority to delete multiple projects.
Just go to settings and you see a tab on your left as "bulk deletion". Please find the attached screenshot for the same.

A: Sonar Admin login with uwr: admin and pwd: admin (default one) --> Setting -->Bulk Deletion -->select projects you want to delete and delete.

A: Login with an administrator account, then browse to the settings page of your project to get the button "delete project".
Here is the steps I use to DELETE any project from My SonarQube.
Login as administrator.
Go to Administration -> Projects -> Projects Management.
Select the Project(s) you want to DELETE.
Click on Delete button at top right corner.
or with the command line:
POST api/projects/bulk_delete.


text:
Q: WordPress Custom Post Type Link to Posts I have a custom post type named "University" in WordPress.
That university post type is then displayed in a dropdown on the user screen, so each user can be assigned to a university. I do have a form which automatically assigns them when they register for an account.
I need to link that University with the user, as I basically need to do a count for how many post articles have been published for a certain university.
Currently I have the following SQL query, which displays the total number of posts for the users who's ID's are 1 and 10:
SELECT DISTINCT
    wp_usermeta.meta_value,
    (SELECT COUNT(*) FROM wp_posts WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' AND wp_posts.post_author IN (1,10)) AS 'total_posts'
    FROM
        wp_usermeta
    INNER JOIN
        wp_posts ON wp_usermeta.user_id = wp_posts.post_author
    WHERE
        wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' AND wp_usermeta.meta_key = 'university_field'
    ORDER BY
        total_posts DESC

My questions is, how can I loop through just the universities and get the ID's of the users associated? Then how can I use this to display the universities in order of how many articles they have?
I am not sure if Custom Post Type is the best approach for this, as the university will require it's own page. If this is best to create a taxonomy in posts, then I would welcome feedback. However this needs to be automatic, so every article written should automatically know the user and what university, instead of them ticking their own university each time.
Any ideas on this?
Thanks so much.


text:
Q: Spring Boot REST Controller as External Dependency I have a SpringBoot REST service (App 1) that exposes some end points to return some data. You can think the application as a monitoring agent.
Any other application should be able to include my SpringBoot REST service as Maven dependency.
However, when I tested this on a second application (App 2), the REST endpoints of my SpringBoot REST service (App1 included as Maven Dependency) is not getting mapped and therefore not accessible.
What is the correct way?

A: I did something like this some time ago.
In you external dependencies you might want to remove the Spring Boot Maven plugin because you don't want executable jar.
Then add the jar as dependency to your project and make sure you scan it.
@ComponentScan(basePackages = {"com.your.project", "com.external.dependency"})


text:
Q: Proof of $\Gamma(x)\Gamma\left(\dfrac{1}{x}\right)\gt 1$ Is it possible to prove the following inequality:
$$\forall x\gt0,f(x)=\Gamma(x)\Gamma\left(\dfrac{1}{x}\right)\gt 1?$$
$f(x)$ has a minimum where $f(x)'=0$ which means:
$$\Psi(x)\Gamma(x)\Gamma(1/x)=\dfrac{\Gamma(x)\Psi(1/x)\Gamma(1/z)}{x^2}$$
It seems quite impossible to solve this equation in a closed form.
Assuming the solution is $x_m$, the minimum value of $f(x)$ shoud be $f(x_m)$ and if $f(x_m)$ is greater than one the inequality would have been proved. Is there another way to come at the same conclusion? Thanks.

A: If $$f(x)=\Gamma(x)\,\Gamma\left(\frac{1}{x}\right)$$ $$f'(x)=\frac{\Gamma \left(\frac{1}{x}\right) \Gamma (x) }{x^2}\left(x^2 \psi(x)-\psi
   \left(\frac{1}{x}\right)\right)$$ for which the only solution seems to be $x=1$.
Working the second derivative (I shall not write it), you would find that $$f''(1)=\frac{\pi ^2}{3}-2 \gamma >0$$ confirming that we face a minimum.

A: Here is another suggestion. I'm not sure if this would be "cleaner" than computing the derivative. For positive real $x$ you have:
$$ \Gamma(x)=\lim_{n\to \infty}\dfrac{n!n^x}{x(x+1)\ldots(x+n)}. $$
Since the limits exist for $x$ and $1/x$ you can multiply the terms together and try to make an inductive argument that the terms are bounded by $1$ from below.


text:
Q: Override de Propriedade Segundo alguns exemplos que encontrei estou tentando implementar um override de uma property, porém o override não funciona. Acho que esse é um tema ainda meio obscuro com poucos exemplos e pouca informação a respeito. Segue meu exemplo:
from abc import ABCMeta, abstractmethod

class Person(metaclass=ABCMeta):

    @abstractmethod
    def __init__(self, name, age):
        self.__name = name
        self.age = age

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        self.__name = value

class Myself(Person):

    def __init__(self, name, age, tel):
        super().__init__(name, age)
        self.tel = tel

    @Person.name.setter
    def name(self, value):
        super().name = 'override'

class Wife(Person):

    def __init__(self, name, age, tel):
        super().__init__(name, age)
        self.tel = tel

ms = Myself('Matheus Saraiva', 36, '988070350')
wi = Wife('Joice Saraiva', 34, '999923554')

print(ms.name)

Se minha implementação está correta, o resultado do print deveria ser:
>>> override

mas o resultado está sendo:
>>> Matheus Saraiva

Ou seja, aparentemente o override não está funcionando. O que está errado na minha implementação?

A: @MatheusSaraiva, vejo dois problemas no seu código, e estão relacionados com o conceito dos getters e setters.
Primeiro ponto, é que você está chamando no seu init a variável oculta para fazer a atribuição, e portanto, o setter não vai ser chamado, e assim, o overwrite nunca vai ter a chance de ser atribuído, a não ser que no seu código você faça alguma atribuição do tipo ms.name = "x", quando efetivamente o setter vai rodar.
Para resolver isso, é só trocar no init da classe Person o self.__name = name por self.name = name.
O segundo problema é mais profundo, e eu mesmo fiz vários testes para conseguir resolver. Inclusive encontrei um bug antigo do Python relacionado à hierarquia dos setters e getters.
Essas questões estão com o seu código super().name = 'override':
- A primeira coisa, e mais séria, é que quando você chama super(), sem explicitar os argumentos, seu programa vai puxar os valores self.__class__, self como argumentos, ou seja, a classe atual, no caso Myself e o objeto instanciado, no caso ms. Mas como estamos falando de uma propriedade da classe, ao deixar o self como segundo argumento, ele não vai reconhecer a propriedade de classe como parte desse objeto, e por isso o erro que você viu. Por esse motivo, precisamos explicitar os argumentos do super
- A segunda é que você fez uma atribuição direta ao invés de usar o método fset(), que é aquele que define, por trás dos panos, o que o decorator @property está fazendo ao definir os métodos dos setters e getters, então isso precisa estar explicito.
Usando essas correções no seu código, ele corrigido fica assim:
@Person.name.setter
def name(self, value):
    super(self.__class__, self.__class__).name.fset(self, 'override')

A: [TL;DR]
Veja essa estrategia:
class Foo(object):
    def __init__(self):
        self._foo = None
    @property
    def foo(self):
        return self._foo
    @foo.setter
    def foo(self, value):
        self._foo = value

class Bar(Foo):
    @Foo.foo.getter
    def foo(self):
        return self._foo * -1 if type(self._foo)==int else self._foo

bar = Bar()
bar2 = Bar()

# Alterando a propriedade foo da instancia bar atraves da classe Foo
bar.foo = "foo is Foo's property"
print('valor de foo na instancia bar:',bar.foo)
valor de foo na instancia bar: foo is Foo's property

# Alterando a propriedade foo da instancia bar atraves da propria instancia
bar.foo = 99
print('Valor de foo alterado pela instancia: ',bar.foo)
Valor de foo alterado pela instancia:  -99

print('Valor de foo na instancia bar2: ',bar2.foo)
Valor de foo na instancia bar2:  None

Veja funcionando no repl.it.


text:
Q: PDFAnnotation in iOS <11.1 Creating and removing PDFAnnotation works perfectly fine on iOS 11.2, but have issues on lower iOS versions (don't know about 11.1, but test device has 11.0.5 installed).
PDFView after adding annotation to the page:

PDFView after removing annotation from the page:
(fine on iOS 11.2, on iOS 11.0.1 has issues)

Sample project can be found here
Maybe there is a way, how to fix this?
Thank you.


text:
Q: How to extract specific text from webpage using Kotlin? I am working on an Android app using Kotlin. I want to extract the paragraph under Movie Info in this link https://www.rottentomatoes.com/m/john_wick_chapter_3_parabellum
I can see the content is in the div tag with id=movieSynopsis. How can I extract this text using Kotlin? Thank you!

A: Use Javascript in your WebView.
You must enable javascript in your webView. Since it is set to false by default.
After you loaded the url. Then in your webViewClient.
override fun onPageFinished(view: WebView?, url: String?){
    val script:String = "javascript:var element = document.getElementById(\"movieSynopsis\");element.textContent;"
    view?.evaluateJavascript(script) { it ->
        Log.d("DBG", it)
    }
}


text:
Q: Adding not-null column to large table SQL Server 2012 behaves differently on different servers In SQL Server 2008/2012, adding a null column to a large table (with default null) is more or less instant.
ALTER TABLE TableWithManyRows
    ADD TestNull INT NULL;

In SQL Server 2012, this should also be the case for not-null columns being set to a default value - see http://rusanu.com/2011/07/13/online-non-null-with-values-column-add-in-sql-server-11/
The following statement:
ALTER TABLE TableWithManyRows
    ADD TestWithValues INT NOT NULL DEFAULT 0 WITH VALUES;

run more or less instantly on my local machine, but very slow on the production database server.
Both are running SQL Server 2012. Running the "Null" version is instant on both, it's just the non-null case where I am seeing differences.
Is there a configuration option that could influence this? Any other suggestions on how I can track down the difference?
Solution (in case someone doesn't spot it in the comments below)
I was confused because locally I have the developer edition, which behaves like the Enterprise edition. The production server didn't have the enterprise edition.

A: ALTER TABLE TableWithManyRows
    ADD TestNull INT NULL;

Does nothing to the table's records
ALTER TABLE TableWithManyRows
    ADD TestWithValues INT NOT NULL DEFAULT 0 WITH VALUES;

Updates every record for that column to a value of 0. With a large amount of data this will take time.
Not a lot you can do about that if that is your business rule.

A: There are quite a few things that could cause this.  Performing this action requires the table to be locked for the updates.  It also has to update each row of existing data.  If you have many rows of data (as production databases typically have more than your dev copy) it will take a longer time.  Also, if the server is under a high load and many people are using the database and table, this can also cause some performance degradation while the systems waits to get an exclusive lock on the table and/or rows of data to update the schema and set the value in each existing row.


text:
Q: Sqlite insert last value from another table matched by id Clearing up my question, please help or point in the right direction.
I have following example tables:
HistoricalValue
ID  SITEID  VAL DATE
1   1      100  9/1
2   1      120  10/1
3   2      300  10/3
4   2      350  10/10

LOG
ID  SITEID  VAL   START_TIME    END_TIME    CALC
1     1     120      10:10      10:20       (END_TIME-START_TIME)*VAL

HistoricalValue table is where I enter data for each of the site, and the LOG table is where I would enter some of the parameters to calculate on.
What I want is to auto populate "VAL(ue)" column in LOG table with the last value (by id? or maybe by date) from HistoricalValue table based on the SiteID that is selected.
What is the proper way to achieve this?
Thank you in advance.

A: The best way is to allow NULL for val and fill in the true value on the fly. The following was executed in SQL Server, but little more than date manipulation will need to be changed:
with
HistoricalValue( ID, SiteID, Val, ValDate )as(
    select  1, 1, 100,  '2015-09-01' union all
    select  2, 1, 120,  '2015-10-01' union all
    select  3, 2, 300,  '2015-10-03' union all
    select  4, 2, 350,  '2015-10-10'
),
LogVal( ID, SiteID, Val, StartTime, EndTime )as(
    select  1, 1, 100, '2015-09-01 10:10', '2015-09-01 10:20' union all
    select  1, 1, NULL, '2015-10-01 10:10', '2015-10-01 10:20'
)
select  l.ID, l.SiteID, l.VAL LogVal, h.ValDate, h.val HistVal,
        coalesce( l.VAL, h.val ) as NewVal,
        StartTime, EndTime,
        DateDiff( SECOND, EndTime, StartTime) * coalesce( l.Val, h.Val ) as CalcVal
from    LogVal l
left join HistoricalValue h
    on  h.SiteID = l.SiteID
    and h.ValDate =(
        select  Max( ValDate )
        from    HistoricalValue
        where   SiteID = l.SiteID
            and ValDate < l.StartTime
            and Val is not null );

I've supplied a second Log entry with no val value to show how the latest value before that entry can be retrieved and used. I'm also assuming that the end and start times are actually date & time values, otherwise you can't tell which historical entries are prior to the log entry.

A: You would need to do a trigger to do this automatically.  If you don't have the value when inserting, then you can do:
insert into example(val1)
    select val1
    from example
    order by id desc
    limit 1;

This assumes that id is an auto-incremented column and is used to determine what the "last" inserted value was.
The trigger would be a before insert trigger that basically runs the same code.


text:
Q: Using Common Table Expression and IF EXISTS I am running a query similar to
DECLARE @VARIABLE NVARCHAR(50) = 'VALUE';

WITH MYCTE_TABLE (Column1,Column2)
AS
    SELECT
        (ColumnA, Column B
    FROM
        SomeTable
    WHERE
        ColumnA = SomeValue)

    IF EXISTS(SELECT ColumnZ FROM AnotherTable WHERE Columnz = SomeNumbers)
    BEGIN
        SELECT * FROM MYCTE_TABLE
    END
    ELSE
    BEGIN
        MYSUBQUERY2
    END
...

However, I keep getting the following error:

Incorrect syntax near the keyword 'IF'.

Each subquery works well when run independently. It seems the use of a common table expression before the IF EXISTS is causing the issue.
Any help please?

A: IF is control flow.  WITH is within a query.  You can do:
IF EXISTS (SELECT ColumnZ FROM AnotherTable WHERE Columnz=SomeNumbers)
BEGIN
    WITH MYCTE_TABLE (Column1,Column2)AS
        SELECT (ColumnA, Column B FROM SomeTable WHERE ColumnA=SomeValue)
    MYSUBQUERY1
END;
ELSE
BEGIN
    WITH MYCTE_TABLE (Column1,Column2)AS
        SELECT (ColumnA, Column B FROM SomeTable WHERE ColumnA=SomeValue)
    MYSUBQUERY2
END;

Or you could use a temporary table or table variable to store the values.

A: I really doubt, that this is the best approach... You tried to clean and shorten this for brevitiy (thumbs up for this!), but the given information is - maybe - not enough.
You cannot use a CTE in different queries. A CTE is fully inlined as part of the query...
But you could write your values into a table variable like here:
DECLARE @tbl TABLE(Column1 INT, Column2 VARCHAR(100)); --Choose appropriate types
INSERT INTO @tbl
SELECT ColumnA, ColumnB FROM SomeTable WHERE ColumnA=SomeValue;

This table variable can be used in later queries (but in the same job!) like any other table:
SELECT *
FROM SomeTable AS st
INNER JOIN @tbl AS tbl ON ...

... or similiar usages...
Another approach might be this
SELECT Column1,Column2 INTO #SomeTempTable FROM SomeWhere

This will write the result of the SELECT into a temp table (which is session wide).
I'm quite sure, that there might be a better (set-based) approach... Are the two sub-queries identical in their result set's structure? If so, you might use UNION ALL and place your "IF EXISTS" as a WHERE-clause to each sub query.


text:
Q: Hadoop replica processing Does Hadoop process replicas also? For example worker node i, in mapper phase, processes the data stored on that machine only. After data (not replica, but original) is finished to be processed in mapper phase or maybe not finished, can there be a case that, machine i processes replica data stored on that machine? Or replica is used only when some node does off?

A: Yes, processing replicas also would happen on a specific scenario called Speculative execution.
If the machine i takes too much time to process the data block stored in that machine , then the job's Application master would start a duplicate parallel mapper against the another replica of the data block stored in a different machine. This new speculative mapper will run in the machine j where the replica is stored.
Whichever mapper completes the execution first, its outputs will be considered.The other slow running mapper and its resources will be removed.
by default, the Speculative execution is enabled. You could toggle this by modifying the below properties.
mapreduce.map.speculative
mapreduce.reduce.speculative

By any case, not more than one replica of the data block will be stored in the same machine. Every replica of the data block will be kept in different machines.

A: The master node(jobtracker) may or may not pick the original data, in fact it doesn't maintain any info about out of the 3 replica which is original. Because when it saves the data it does a checksum verification on the file and saves it cleanly. Now when jobtracker wants to pick up a slot for the mapper, it takes so many things to account like number of free map slots, overhead of a tasktracker and other things. And last but not least data locality, so the closest node which satisfies almost all criteria will only be picked, it doesn't bother whether it is original or a replica and as mentioned even it doesn't maintain that identity.


text:
Q: PHP Regex for specific quotation I'm having some extreme trouble understanding how I can only get the characters inside the double quote when I only want it to get the characters when it's something like:
Item.name = "thisCouldBeAnything"

When there could be other double quotes in the parser. I'm having extreme difficulty to understand what the regex would be.

A: If you need just a valid string literal, i.e. text enclosed in double quotes and this text could possibly include backslash-escaped double quotes, try this expression:
"((?:\\"|[^"])*?)"

Demo: https://regex101.com/r/YoiDtP/1

A: Or (highjacking @Dmitry's example):
([\"\'])(.*?(?<!\\))\1

This says:

([\"\'])    # capture ' or " into group 1
(           # second group
    .*?     # anything lazily
    (?<!\\) # neg. lookbehind, make sure there's no backslash
)
\1          # the formerly captured string literal of group 1

Note, that you don't need to escape string literals in square brackets ([...]) but the StackOverflow renderer makes it very ugly otherwise.

Full PHP snippet (note the [unnecessary] group called "value" and the double escaped backslash):

<?php

$string = <<<DATA
Item.name = "thisCouldBeAnything"
Item.name = "thisCouldBe\"Any\"thing"
Item.name = 'thisCouldBeAnything'
Item.name = 'thisCouldBe\'Any\'"thing'
DATA;

$regex = '~(["\'])(?P<value>.*?(?<!\\\\))\1~';

preg_match_all($regex, $string, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
   echo $match["value"] . "\n";
}
?>

A: Based on your comment I need it to exactly be Item.name = "" It can't just search for double quotes.  Assuming you want to capture what's in double quotes:
preg_match_all('/Item.name = "(.*)"/', $string, $matches);

Or if the value inside the double quotes should not contain double quotes:
preg_match_all('/Item.name = "([^"]+)"/', $string, $matches);

Or to capture it all:
preg_match_all('/(Item.name = ".*")/', $string, $matches);


text:
Q: Cassandra DataStax driver: how to page through columns I have wide rows with timestamp columns. If I use the DataStax Java driver, I can page row results by using LIMIT or FETCH_SIZE, however, I could not find any specifics as to how I can page through columns for a specific row.
I found this post: http://cassandra-user-incubator-apache-org.3065146.n2.nabble.com/CQL-3-and-wide-rows-td7594577.html
which explains how I could get ranges of columns based on the column name (timestamp) values.
However, what I need to do is to get ALL columns, I just don't want to load them all into memory , but rather "stream" the results and process a chunk of columns (preferably of a controllable size) at a time until all columns of the row are processed.
Does the DataStax driver support streaming of this kind? and of so - what is the syntax for using it?
Additional clarification:
Essentially, what I'm looking for is an equivalent of the Hector's ColumnSliceIterator using which I could iterate over all columns (up to Integer.MAX_VALUE number) of a specific row in batches of, say, 100 columns at a time as following:
SliceQuery sliceQuery = HFactory.createSliceQuery(keySpace, ...);
sliceQuery.setColumnFamily(MY_COLUMN_FAMILY);
sliceQuery.setKey(myRowKey);
// columns to be returned. The null value indicates all columns
sliceQuery.setRange(
    null // start column
    , null // end column
    , false // reversed order
    , Integer.MAX_VALUE // number of columns to return
);

ColumnSliceIterator iter = new ColumnSliceIterator(
    sliceQuery // previously created slice query needs to be passed as parameter
    , null // starting column name
    , null // ending column name
    , false // reverse
    , 100 // column count <-- the batch size
);
while (iter.hasNext()) {
    String myColumnValue = iter.next().getValue();
}

How do I do the exact same thing using the DataStax driver?
thanks!
Marina

A: The ResultSet Object that you get is actually setup to do this sort of paginating for you by default. Calling one() repeatedly or iterating using the iterator() will allow you to access all the data without calling it all into memory at once. More details are available in the api.


text:
Q: How can I configure HTTPClient to authenticate against a SOCKS proxy? I need to set up proxy authentication against a SOCKS proxy.
I found out this post giving instructions that appear to work with common HTTP proxies.
        httpclient.getHostConfiguration().setProxy("proxyserver.example.com", 8080);

        HttpState state = new HttpState();
        state.setProxyCredentials(new AuthScope("proxyserver.example.com", 8080),
           new UsernamePasswordCredentials("username", "password"));
        httpclient.setState(state);

Would that work with SOCKS proxies as well or do I have to do something different?

A: Java supports Socks proxy configuration via preferences:

*

*socksProxyHost for the host name of the SOCKS proxy server

*socksProxyPort for the port number, the default value being 1080
e.g.
java -DsocksProxyHost=socks.mydomain.com

(edit) For your example, if the socks proxy was configured in the way outlined before:
httpclient.getHostConfiguration().setProxy("proxyserver.example.com", 8080);
Credentials cred = new UsernamePasswordCredentials("username","password");
httpclient.getState().setProxyCredentials(AuthScope.ANY, cred);

You can also use this variant (without httpclient):
SocketAddress addr = new
InetSocketAddress("webcache.mydomain.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); // Type.HTTP for HTTP

So completing the previous example, we can now add:
URL url = new URL("http://java.sun.com/");
URConnection conn = url.openConnection(proxy);

HTH

A: The Features page of Apache HTTPClient says:

Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.

With "transparent", I guess they mean that it works without you needing to do anything special. Do you have a SOCKS proxy available somewhere? Can't you just try it out to see if it works?

A: SOCKS is not supported by HttpClient 3 natively. You can try the SOCKS support in JDK as suggested by others. The side effect is that your whole JVM will go through the same SOCKS proxy.
Java 5 supports Username/Password authentication in SOCKS (type 2). All you have to do is to setup the authenticator like this,
Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password.toCharArray());
    }
});

Again, this may not work for you because it affects all authentication in your JVM (HTTP auth, Proxy Auth).

A: You can provide a custom socket factory which implements the SOCKS protocol, and register it as your default HTTP protocol handler. This solution has a limitation similar to tuergeist's answer above has - it applies globally, to any HTTP connection you'll establish through HttpClient.

If you find this a problem, take a look at this correspondence, where Oleg suggests using HttpClient 4.0, but also refers to a possible patch in HostConfiguration class for HttpClient 3.x.

Another possible solution, which is my personal favorite, is to write a wrapper HTTP proxy to the socks proxy.

A: I tried
System.setProperty("socksProxyHost", "socks.xyz.com");
System.setProperty("socksProxyPort", "1000");

and it's working fine.


text:
Q: How to optimize matrix multiplication operation I need to perform a lot of matrix operations in my application. The most time consuming is matrix multiplication. I implemented it this way
template<typename T>
Matrix<T> Matrix<T>::operator * (Matrix& matrix)
{

    Matrix<T> multipliedMatrix = Matrix<T>(this->rows,matrix.GetColumns(),0);

    for (int i=0;i<this->rows;i++)
    {
        for (int j=0;j<matrix.GetColumns();j++)
        {
            multipliedMatrix.datavector.at(i).at(j) = 0;
            for (int k=0;k<this->columns ;k++)
            {
                multipliedMatrix.datavector.at(i).at(j) +=  datavector.at(i).at(k) * matrix.datavector.at(k).at(j);
            }
            //cout<<(*multipliedMatrix)[i][j]<<endl;
        }
    }
    return multipliedMatrix;
}

Is there any way to write it in a better way?? So far matrix multiplication operations take most of time in my application. Maybe is there good/fast library for doing this kind of stuff ??
However I rather can't use libraries which uses graphic card for mathematical operations, because of the fact that I work on laptop with integrated graphic card.

A: Eigen is by far one of the fastest, if not the fastest, linear algebra libraries out there.  It is well written and it is of high quality.  Also, it uses expression template which makes writing code that is more readable.  Version 3 just released uses OpenMP for data parallelism.
#include <iostream>
#include <Eigen/Dense>

using Eigen::MatrixXd;

int main()
{
  MatrixXd m(2,2);
  m(0,0) = 3;
  m(1,0) = 2.5;
  m(0,1) = -1;
  m(1,1) = m(1,0) + m(0,1);
  std::cout << m << std::endl;
}

A: Boost uBLAS I think is definitely the way to go with this sort of thing. Boost is well designed, well tested and used in a lot of applications.

A: Consider GNU Scientific Library, or MV++
If you're okay with C, BLAS is a low-level library that incorporates both C and C-wrapped FORTRAN instructions and is used a huge number of higher-level math libraries.
I don't know anything about this, but another option might be Meschach which seems to have decent performance.
Edit:  With respect to your comment about not wanting to use libraries that use your graphics card, I'll point out that in many cases, the libraries that use your graphics card are specialized implementations of standard (non-GPU) libraries.  For example, various implementations of BLAS are listed on it's Wikipedia page, only some are designed to leverage your GPU.

A: There is a book called Introduction to Algorithms. You may like to check the chapter of Dynamic Programming. It has an excellent matrix multiplication algo using dynamic programming. Its worth a read. Well, this info was in case you want to write your own logic instead of using a library.

A: There are plenty of algorithms for efficient matrix multiplication.
Algorithms for efficient matrix multiplication
Look at the algorithms, find an implementations.
You can also make a multi-threaded implementation for it.


text:
Q: 2 exact same boxes with one having double ram - is it really that much better? With these two servers, is the 32gb ram server that much better than the 16?  Having the same cpu, would the server first bottleneck at the cpu before the extra 16gb ram comes into play? Or am I completely wrong?
Intel® Core™i7-2600 Quadcore w/Hyper-Threading
16 GB DDR3 RAM
2 x 3 TB SATA 6 Gb/s HDD 7200 rpm Software- RAID 1
Intel® Core™i7-2600 Quadcore w/Hyper-Threading
32 GB DDR3 RAM
2 x 3 TB SATA 6 Gb/s HDD 7200 rpm Software- RAID 1

A: How do you answer this?
Would I put the two into a failover pair?  No.  What if you were on the 32G server as master and it failed over?  Is that the point where you'd want to find out that 16G wasn't enough?
Don't cheat, don't skimp.  If it really matters, put the money behind it.  If money matters more than uptime, take the 16G out of the first server and sell it off.  If you are still up, that 16G didn't matter anyway.


text:
Q: Inserting data in an sqlserver using the column name from a control. c# I am trying to insert data in an SQL table by executing an Insert Query.
The problem is that I need to get the column name from a cell in the selected gridview Row.
Here's the snippet:
SqlCommand cmd30 = new SqlCommand("insert into mytable ( '"+GridView7.SelectedRow.Cells[0].Text+"' , r_id) values ('"+ GridView7.SelectedRow.Cells[1].Text +"', '"+TextBox1.Text+"')",con30);
cmd30.ExecuteNonQuery();

r_id is not a Primary Key.
Error is:
Incorrect syntax near 'r_id'.
Any Help will be appreciated.
Thanks.

A: *

*Use SqlCommand Parameters.

*Also make sure you get valid column name from GridView7.SelectedRow.Cells[0].Text;
Code:
string col1 = GridView7.SelectedRow.Cells[0].Text;
string sql = "INSERT into mytable (" + col1 + ", r_id) Values (@" + col1 + ", @rid)";
SqlCommand cmd30 = new SqlCommand(sql, con30);
cmd30.Parameters.AddWithValue("@" + col1, GridView7.SelectedRow.Cells[1].Text);
cmd30.Parameters.AddWithValue("@rid", TextBox1.Text);
cmd30.ExecuteNonQuery();


text:
Q: loop popup confusion Can someone tell me how to make my URLs properly loop into the window.open I created? I'm wondering if the loop is the right answer to make each URL rotate based on my setInterval? If yes, I was wondering if the loop needs to be under var rotate = []{for (var i = 0; i < urls.length; i++)};.
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];
var rotate = 0;
function goRandom()
{
    var newwin = window.open(
        urls[ rotate ],
        "POPUP",
        "height=400,width=600,scrollbars=yes"
    );
}
var loop = setInterval(goRandom, 5000);

A: Just change
urls[ rotate ],

to
urls[ (rotate++) % urls.length ],

The index is incremented each iteration and % urls.length (% is used for getting the remainder after division, hence it ensures the result never grows beyond the array size). You can try it here (remember to allow popups).

A: You are not updating the value of rotate..
Try doing this
<script type="text/javascript">
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];
var rotate = 0;

function goRandom( )
{
    rotate= (rotate+1) % urls.length;
    var newwin = window.open(

                                     urls[ rotate ],
                                     "POPUP",
                                     "height=400,width=600,scrollbars=yes"                          );
}
    var loop= setInterval(goRandom, 5000);
</script>

A: While the other answers are technically correct, here's a simplied version if you're just starting out with js, all that % can be confusing.
// setup urls
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];

// rotate is a global variable so can be accessed anywhere
var rotate = 0;

function goRandom( )
{
    var newwin = window.open(
                                     urls[ rotate ],
                                     "POPUP",
                                     "height=400,width=600,scrollbars=yes"                          );

    // move to the next array position
    rotate++;

    // Check if at the end of the array and move back to the beginning
    if (rotate >= urls.length)
        rotate = 0;
}

// Keep going indefinitely
setInterval(goRandom, 5000);

Now, your function is called goRandom() while this will goSequence() (or goNext()), so you can change this without any form of loop to pick a random url (though your loop var is called 'rotate' so maybe not what you wanted).
// setup urls (global so accessed from anywhere)
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];

function goRandom( )
{
    // get a random url
    var rotate = Math.floor(Math.random() * (urls.length - 1));

    var newwin = window.open(
                                     urls[ rotate ],
                                     "POPUP",
                                     "height=400,width=600,scrollbars=yes"                          );
}

// Keep going indefinitely
setInterval(goRandom, 5000);


text:
Q: Java: ServerSocket reading data from a client I am working on a simple programm for a university course. Here is the code that I have problems with:
//everything before this is unrelevant
String message = "";
BufferedReader br  = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     while((message = br.readLine()) != null) {
         System.out.println(message);
}
//everything after this is irrelevant

I also have a thread for accepting incoming connections and some other stuff that is irrelevant. The problem that I have is that I can read one message and after that nothing happens. I guess the readLine() method is the problem but I am not really sure how to solve it.
It even says in our assignment to use
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

to receive data.

A: Your client is only sending one line. You therefore don't need the loop. You should read one line and then do whatever you're supposed to do with it.


text:
Q: How does Logstash integrate with Syslog? I'm trying to figure out how Logstash integrates with syslog. Which of the following is true:

*

*Logstash itself is a bon afide syslog server (implements the syslog protocol). In this case, you configure all of your syslog client to log directly to the Logstash server via the syslog protocol. Or...

*You configure all of your syslog client to log to a centralized syslog server (such as a machine running rsyslog), and then configure some kind of bridge between the syslog server and the Logstash server? Or...

*Something else entirely?

I'm looking to understand the relationships between syslog client, syslog server, and Logstash.

A: If you use the syslog input on logstash (http://logstash.net/docs/1.4.0/inputs/syslog), you are setting up a TCP/UDP syslog server.  That means you have to tell your clients (say log4j) where your syslog server is, or configure a syslog instance already running to forward the messages on to your logstash instance (via a *.* @host syntax in /etc/syslog.conf file).
It really depends on what your requirements are -- if you need to receive logs from a unix domain socket, you'll have to use the forwarding method or setup a file watcher to watch the /var/log/* files directly.


text:
Q: Access to global variables from a module in Python? let's start with a basic code that uses a global variable :
def fun():
    print(gvar)
gvar = 3

fun()

that of course prints "3" in the console.
Then, I move my function "fun" in a module "mymod", and do :
from mymod import *
gvar=3
fun()

The result is a NameError exception (gvar is not found)
How can I solve this ? I have to mention that I need to access to various global variables which name is not always the same (the context  is complex and I do not describe it now to focus on the problem I have for now)

A: The only global variables python has, are module scoped. So in your case the variable gvar is not visible in the module mymod.
If you want to use gvar in an imported module, pass gvar as parameter to a function of mymod. If gvar belongs to mymod, define it there.

A: Just move gvar into mymod. You don't even need to import it unless you need to access its value independently.
In other words, don't try to use gvar as a genuine global, but leave it as an implementation detail of mymod.

A: I think you are doing this thing incorrectly, rather than making a variable into one script and trying to execute a function in another script using first variable, you can also send the variable to function header of function!!
So in your case your function will be like
def fun(var):
    print(gvar)

And Call Your Function From Another Script With:
gvar = 5
fun(gvar)


text:
Q: restriction on properties of Realm Model I have this model
#import <Realm/Realm.h>

@interface RGGoal : RLMObject

@property NSString *title;
@property NSNumber *totalTime;
@property NSNumber *noMileStones;
@property NSString *goalDescription;

I setup breaking points and figured that when RLMRealm *realm = [RLMRealm defaultRealm]; is called the app terminates with following

'RLMException' exception: Property of type NSNumber must descend from RLMObject

Does anyone now how to get around this problem?

A: The problem is that you're using NSNumber as type for your properties. Realm doesn't support that as NSNumber can be any numeric value (bool, integer, double, etc.). You must use types like int, float, double, etc. Please take a look at http://realm.io/docs/cocoa/0.81.0/api/Classes/RLMObject.html.

A: Since version 0.96.0, optional numbers can be stored using an NSNumber * property which is tagged with the type of the number.
You can use NSNumber *, NSNumber *, NSNumber *, and NSNumber *.
Please check https://realm.io/news/realm-objc-swift-0.96.0/


text:
Q: Why is this a group action - what is the significance of $g^{-1}$?
Let $G$ be a group acting on a variety $X$ such that every $g\in G$
  defines a morphism $\phi_g:X\rightarrow X$ given by $\phi_g(x)=g\cdot x$. If $X=\operatorname{Spec}(R)$ is affine then $\phi_g$ comes from a
  map $\phi_g^*:R\rightarrow R$. We define the induced action of $G$ on
  $R$ by $$g\cdot f=\phi_{g^{-1}}^{*}(f)$$ for $f\in R$
In other words, $(g\cdot f)(x)=f(g^{-1}\cdot x)$ for all $x\in X$

I have two questions -

*

*Why do we need $g^{-1}$ to ensure that $G$ induces an action on $R$? We have - $$(g_1 g_2)\cdot f=\phi^*_{(g_1g_2)^{-1}}(f)=\phi^*_{g_2^{-1}g_1^{-1}}(f)=(\phi^*_{g_2^{-1}}\phi^*_{g_1^{-1}})(f)$$
At this point I am confused as $$(\phi^*_{g_2^{-1}}\phi^*_{g_1^{-1}})(f)=\phi^*_{g_2^{-1}}(\phi^*_{g_1^{-1}}(f))=\phi^*_{g_2^{-1}}(g_1\cdot f)=g_2\cdot(g_1\cdot f)$$ which is not what I want to show that it is an action. So what am I doing wrong?

*Can someone explain to be how to show the "in other words" part?
Thank you.

A: (1) Your error is that $\phi^*_{g_2^{-1}g_1^{-1}}$ is $\phi^*_{g_1^{-1}}\phi^*_{g_2^{-1}}$, not $\phi^*_{g_2^{-1}}\phi^*_{g_1^{-1}}$.  We have $\phi_{gh}=\phi_g\phi_h$, but passing from $\phi$ to $\phi^*$ is a contravariant functor, so it reverses the order of composition.
(2) Suppose $\phi:X\to X$ is a morphism and $x$ is a $k$-point of $X$.  If $f\in R$, write $f(x)$ for the image of $f$ under the homomorphism $R\to k$ corresponding to $x$.  Equivalently, $f(x)=i_x^*(f)$, where $i_x:\operatorname{Spec} k\to X$ is the map corresponding to $x$.  Then $i_{\phi(x)}=\phi i_x$, so $$f(\phi(x))=i_{\phi(x)}^*(f)=i_x^*\phi^*f=(\phi^*f)(x).$$
In particular, in the case $\phi=\phi_{g^{-1}}$, the left-hand side is $f(g^{-1}\cdot x)$ and the right-hand side is $(g\cdot f)(x)$.


text:
Q: How to get rid off default css styles I have installed html5 blank template and I have created sub theme too by creating style.css and functions.php. But how should I get rid off default CSS styles that come from parent theme?

A: there are two ways,
first: if you want to remove default style, just dequeue them using  wp_dequeue_style( 'style_file_name_here' ).
second: you can rename the existing file and create a new one with the same name, just place style hook info into new style file, like:
/*
Theme Name: Theme name
Author: Author name
*/

remember, the second way is unprofessional, but you can use this one as well.

A: Go to the parent theme's functions.php and remove any enqueued styles you don't want.


text:
Q: Spring Boot requestDataValueProcessor Bean Definition Conflict I try to use SpringWebFluxSecurityin my project, but I got this error when compiling
The bean 'requestDataValueProcessor', defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebMvcSecurityConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/security/config/annotation/web/reactive/WebFluxSecurityConfiguration.class] and overriding is disabled.
I know that I have to remove the dependency to WebMvcSecurityConfiguration. The problem is I cannot figure out where that configuration is being called in my project. Do you have any idea how to find it?

A: Run a `mvn dependence:tree and you'll be able to see the dependence tree of your project. Then try to find out which are the packages of this dependencies and removes that you don't need.


text:
Q: difference between "mechanism driver" and "extension driver" in openstack could anyone explain me what is the difference between "mechanism driver" and "extension driver" in openStack.
I didnt find any document or information related to it.
Thanks in advance

A: A mechanism driver create, update, and delete
networks and ports.
An extension driver extends the core resources implemented by the
ML2 plugin with additional attributes. Methods that process create
and update operations for these resources validate and persist
values for extended attributes supplied through the API as can be port_security, this extension let you create instances who route traffic avoiding anti-spoofing rules at iptables defined by neutron.


text:
Q: Overlay two pictures in a table cell I am trying to make something which resembles a pizza maker.
Essentially, all I'm trying to do is add a translucent image on-top of another image.
I thought I could achieve this via CSS and the z-index property but I am having some issues.
The picture's are overlaying just fine, but I can not get them to be positioned in the center of the table cell for the life of me.
Here is what I have come up with.  But the positioning moves the pictures out of the table cell.

                    <asp:ImageButton ID="imgbtn_pizzabase" ImageAlign="Middle" ImageUrl="~/SiteImages/pizza_test.png" runat="server" />

                    <asp:ImageButton ID="ImageButton1"  ImageAlign="Middle" ImageUrl="~/SiteImages/findme.png" runat="server" />

.
.

.

A: You don't need z-index. Use absolute positioning. The element that is later in the DOM, is going to be on top.
Also, don't use tables to position elements. That's just bad practice. Tables are for tabular data, which a pizza isn't (I think).
So in this fiddle, I got a 'plate' which is used as a container. On (in) the plate are divs for each layer. I've used a background color and an opacity, but you could use background images (or just img tags) just as well.
Note that the plate has position: relative. A position is needed to force the layers to be absolutely positioned within the plate. That way, you can easily move the plate around and the pizza will move with it. If you need to, you can put the plate in a table cell, so you can show a table of pizza's. The css in the fiddle will automatically fix that for you.
You can horizontally center the plate in its parent by giving it a margin: 0 auto, that way it is centered in the parent cell.
http://jsfiddle.net/GolezTrol/nyzrT/1/


text:
Q: One scroll bar for 2 separate divs I have two DIV's that are side by side. One div is my side bar (Left Of Screen), the other div is my main content (Right Of Screen).
What I'm looking for:
What I want is one visable scroll bar to the far right of the screen. I would like that scrol bar to scroll both left and right div's.
My Problem:
Currently my left sidebar has a tree menu. When I expand my tree menu, I have no scroll bar to scroll down through the side bar content that was expanded. I'm able to add a scroll bar to my side bar, but that looks very ugly. I just want 1 scroll bar on the far right that handles both div's.
Can someone help me on this one?
My index.php file
<?php

include 'sidebar.php';
include 'main_body.php';

?>

My sidebar.php
<?php

    echo '<link rel="stylesheet" href="css/style.css" type="text/css">';
    echo '';

    include 'function/functions.php';
    // Establish a connection to our database
    db_connect();

    echo'

    ';

    echo'
';

    // Side Bar Start
    echo '

CUSTOMER

';

    //Display all customers from database
    query_all_customers();

    echo '

CABINET

';

    // Display all cabinets from database
    query_all_cabinets();
    echo'

';

    ?>

My main content area
<?php

    ini_set('display_errors', 1);

    echo '
';

    echo'

    Some data can go here

    and here

    and here

    Some data can go here

    and here

    and here

    Some data can go here

    and here

    and here

    Some data can go here

    and here

    and here';
    ?>

My .css file
.sidebar {
    width:200px;
    position:fixed;
    top:0px;
    left:0px;
    height:100%;
    background-color:#54524F;
    /*overflow-y: scroll;*/
}
.main {
    width: auto;
    margin-left: 200px;
}
.heading {
    margin: 1px;
    color: #fff;
    padding: 3px 10px;
    cursor: pointer;
    position: relative;
    background-color:#000000;
}
.content {
    padding: 5px 10px;
}
#submit {
    width:185px;
    background-color: black;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius:6px;
    color: #fff;
    font-family:'Oswald';
    font-size: 16px;
    text-decoration: none;
    cursor: pointer;
    border:none;
}
#submit:hover {
    border: none;
    background:#FF9933;
    box-shadow: 0px 0px 1px #777;
}
tr:nth-of-type(odd) {
    background-color:#D4D4D4;
}
.container0 {
    height: 100%;
    width: 100%;
    overflow-x: hidden;
    position: relative;
    padding-bottom: 30px;
    background-color:black;
}

JSFiddle

A: in your css, set position of the sidebar to relative and set float to left, like this:
.sidebar {
    width:200px;
    position:relative;
    top:0px;
    left:0px;
    height:100%;
    background-color:#54524F;
    float:left
}

the updated version of your jsfiddle to show you that it works :) http://jsfiddle.net/BrJDE/3/
because you dont want to have the scrollbar at the side of the page, i made some more examples for you. tell me if they are what you want, if its not, i would love to help you again.
both of these examples use 2 additional divs compared to the content you provided. these will make that you can position the scrollbar inside those div's instead of at the side of the browser. if you need me to explain the changes i made, just tell me.
scrollbar inside the page:
http://jsfiddle.net/BrJDE/6/
scrollbar inside the page at the left side of the scrolling div:
http://jsfiddle.net/BrJDE/5/


text:
Q: Showing that $3^{(3^n - 1)}$ divides $(3^n)!$ I am trying to solve the following by using induction:

Show that $3^{(3^n - 1)}$ divides $(3^n)!$ for any non-negative integer $n$.

But isn't the question incorrect, since it doesn't hold for $n=1$, or am I missing something?

A: I am afraid that the problem is incorrect.
The highest power of 3 that devides $(3^n)!$ is $\sum _{ i=1 }^{ \infty  }{ \left\lfloor \frac { 3^{ n } }{ 3^{ i } }  \right\rfloor  } $, which is equal to $\frac { 3^{ n }-1 }{ 2 } $.
The proof to the general highest power of $p$ when p is a prime number that divides $n$! can be seen
here.


text:
Q: How to group by a column and pivot wider in R I have a data frame that I am trying to group by a column and pivot_wider. Here is my data frame
df = structure(list(Date = structure(c(1608238800, 1608238800, 1608238800,
1608238802, 1608238800, 1608238800, 1608238802, 1608238800, 1608238800,
1608238802, 1608238802, 1608238800, 1608238800, 1608238800, 1608238802,
1608238800, 1608238800, 1608238800), tzone = "America/New_York", class = c("POSIXct",
"POSIXt")), Last = c(56.15, 7.9, 196.29, 311, 458.07, 18.38,
377.08, 70.61, 4.02, 372.19, 15.7, 391.2, 9.1, 66.62, 176.25,
6.9, 28.74, 128.7), ticker = c("FAS", "FAZ", "IWM", "QQQ", "SOXL",
"SOXS", "SOXX", "SPXL", "SPXS", "SPY", "SQQQ", "TECL", "TECS",
"TNA", "TQQQ", "TZA", "XLF", "XLK"), Core = c("XLF", "XLF", "IWM",
"QQQ", "SOXX", "SOXX", "SOXX", "SPY", "SPY", "SPY", "QQQ", "XLK",
"XLK", "IWM", "QQQ", "IWM", "XLF", "XLK"), Type = c("ETNBull",
"ETNBear", "ETF1x", "ETF1x", "ETNBull", "ETNBear", "ETF1x", "ETNBull",
"ETNBear", "ETF1x", "ETNBear", "ETNBull", "ETNBear", "ETNBull",
"ETNBull", "ETNBear", "ETF1x", "ETF1x")), row.names = c(NA, -18L
), groups = structure(list(ticker = c("FAS", "FAZ", "IWM", "QQQ",
"SOXL", "SOXS", "SOXX", "SPXL", "SPXS", "SPY", "SQQQ", "TECL",
"TECS", "TNA", "TQQQ", "TZA", "XLF", "XLK"), .rows = structure(list(
    1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L,
    15L, 16L, 17L, 18L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, 18L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))

head(df)

Date           Last ticker Core  Type
1 2020-12-17   56.2  FAS    XLF   ETNBull
2 2020-12-17   7.9   FAZ    XLF   ETNBear
3 2020-12-17   196.  IWM    IWM   ETF1x
4 2020-12-17   311   QQQ    QQQ   ETF1x
5 2020-12-17   458.  SOXL   SOXX  ETNBull
6 2020-12-17   18.4  SOXS   SOXX  ETNBear

I would like to group by "Core" and pivot wider using Type as the new columns and ticker as the values.
For example, i would like my new data frame to look like this
Date           Last  Core   ETNBull  ETNBear ETF1x
1 2020-12-17   56.2   XLF    FAS      FAZ     XLF
2 2020-12-17   7.9    IWM    TNA      TZA     IWM
.
.

You can see we grouped by "Core" and then spread by "Type" using 'ticker' as the values.
Here is an example of one attempt that did not have the desired results
df %>% group_by(Core) %>% pivot_wider(names_from = Type, values_from = ticker)

A: Maybe you are looking for :
library(dplyr)
library(tidyr)

df %>%
  pivot_wider(names_from = Type, values_from = ticker) %>%
  group_by(Core) %>%
  fill(ETNBull:ETF1x, .direction = 'updown')


text:
Q: Submit form one time after page load via Jquery How to submit the cart request-quote form after page load?
Below code is worked fine -
<?php if(!isset($_GET['updated'])) { ?>
<script>
jQuery(document).ready(function($) {
jQuery("#yith-ywraq-form").submit();
});
</script>
<?php } ?>

But avoid submitting forms, again and again, I reload to this action
site.com/request-quote/?updated=data
But if someone refreshes the same page site.com/request-quote/?updated=data
then I have no option to submit the form again on page load.
do you have a solution for this problem?
My requirement is I want to submit the cart request-quote form 1 time after page load?

A: You may use localStorage for this.
Take a flag in set some initial value of it.
When the form submits update it's value.
By checking the same you can avoid getting submit.
<?php if(!isset($_GET['updated'])) { ?>
    <script>
        if(!localStorage.getItem('isFormAlreadySubmit')){
            jQuery(document).ready(function($) {
                jQuery("#yith-ywraq-form").submit();
                localStorage.setItem('isFormAlreadySubmit', true);
            });
        }
    </script>
<?php } ?>

A: You can move $_GET['updated'] to localStorage or sessionStorage, then you don't need to reload the page to ?updated=data page anymore.

*

*localStorage will save updated value even when the browser is closed and reopened.

*sessionStorage will save updated value but it will be cleared if the browser is closed.

That depends on you to choose which one. So I make a demo with sessionStorage which I prefer because when the user closes the browser, it will clear the updated value, maybe the next user in that device is another (public device). I also remove the check if(!isset($_GET['updated'])) condition.
<script>
  jQuery(document).ready(function($) {
    if (!sessionStorage.getItem('updated')) {
      jQuery("#yith-ywraq-form").submit();
      sessionStorage.setItem('updated', true);
    }
  });
</script>

Update: add live demo https://codepen.io/tuandaodev/pen/jOwvrRg?editors=1111

A: You need to use a server side session variable to check (duplicate)
Answer


text:
Q: Sencha Touch, setRecord() not working. Fields are blank. I'm new to Sencha Touch...
I've been searching and asking people for hours, but cannot figure out why my detail view does not get the data (using setRecord).
I have not been able to find an example that uses Ext.NavigationView to push a view that uses the data from setRecord, so I suspect I'm doing something wrong there.
I have a tabbed view. First tab shows a list of items. Click an item disclosure to see details for that item. The detail view appears, but with no any data.

*

*The tabs are setup in the launch function of ViewPortController.

*The main view in the first tab is the PeopleListView. All the people appear in the list.

*The PeopleListView is added to an Ext.NavigationView. A reference to the Ext.NavigationView is added to the PeopleListView so it can be used later

*PeopleListViewController has a function, showDetailView, that is successfully called when a disclosure button is tapped.

*The controller's showDetailView function

*

*sets the record (which contains the correct data) on the personDetailView,

*retrieves the instance of the Ext.NavigationView and pushes the PersonDetailView.

*The record value passed to showDetailView has the correct data.

*When personDetailView appears, the fields have no data.

ViewPortController:
launch: function() {
    // var personDetailView = {
    //    xtype: 'persondetailview'
    // }
    var pplView = Ext.create('PeopleApp.view.PeopleListView');
    var pplNavView = Ext.create('Ext.NavigationView', {
        title: 'People',
        iconCls: 'home',
        useTitleForBackButtonText: true,
    });
    pplView.setNavigationView(pplNavView);
    pplNavView.add(pplView);
    . . .
    var mainViewPort = getMainViewPort();
    mainViewPort.setItems([pplNavView, . . .]);
},

PersonModel:
Ext.define('PeopleApp.model.PersonModel', {
extend: 'Ext.data.Model',
requires: ['Ext.data.proxy.Rest'],
config: {
    idProperty: 'id',
    fields: [
        { name: 'id',       type: 'auto'   },
        { name: 'name',     type: 'string' },
        { name: 'address',  type: 'string' },
        { name: 'email',    type: 'string' },
        { name: 'age',      type: 'int'    },
        { name: 'gender',   type: 'string' },
        { name: 'note',     type: 'string' }
    ],
    proxy: {
        type: 'rest',
        url: '/app/data/people.json',
        reader: {
            type: 'json',
            rootProperty: 'people'
        }
    },
}
});

PeopleListViewController:
Ext.define('PeopleApp.controller.PeopleListViewController', {
extend: 'Ext.app.Controller',
xtype: 'peoplelistviewcontroller',
config: {
    refs: {
        peopleListView: 'peoplelistview',
        personDetailView: 'persondetailview',
        peopleView: 'peopleview',
    },
    control: {
        peopleListView: {
            discloseDetail: 'showDetailView'
        }
    }
},

showDetailView: function(view, record) {
    console.log("record.data.name=" + record.data.name);

    var detailView = Ext.create('PeopleApp.view.PersonDetailView');
    //var detailView = this.getPersonDetailView();
    detailView.setRecord(record);
    var navView = view.getNavigationView();
    navView.push(detailView);
},

launch: function() { this.callParent(arguments); },
init: function() { this.callParent(arguments); },
});

PersonDetailView:
Ext.define('PeopleApp.view.PersonDetailView', {
extend: 'PeopleApp.view.BaseView',
xtype: 'persondetailview',
requires: [
    'Ext.form.FieldSet',
    'Ext.form.Text',
    'Ext.form.TextArea'
],
config: {
    title: "Person Details",
    scrollable: true,
    items: [{
        xtype: 'fieldset',
        items: [{
                xtype: 'textfield',
                name: 'name',
                label: 'Name: ',
                required: true
            }, {
                xtype: 'textfield',
                name: 'age',
                label: 'Age: ',
                required: false
            }, // etc.
        ]}
    ]}
});

Can you tell me why detailView.setRecord(record) does not get the data set in the fields of DetailViewController, and what I need to do differently?

A: I am not sure but you should use below code in your Person detail view:
items: [
    {
        xtype:'formpanel',
        id:'personDetailViewForm',
        items:[{
                 xtype: 'fieldset',
                 items: [{
                    xtype: 'textfield',
                    name: 'name',
                    label: 'Name: ',
                    required: true
                  }, {
                    xtype: 'textfield',
                    name: 'age',
                    label: 'Age: ',
                    required: false
                  }, // etc.
                ]
             }]
       }]

and in the personListViewController you can set that form's values instead of setting records to the view like:
   var detailView = Ext.create('PeopleApp.view.PersonDetailView');
   var personDetailViewForm = detailView.down('#personDetailViewForm ');
   personDetailViewForm .setValues(records);

Note that records object property names and form fields names must match and if records doesn't work try with records.data.


text:
Q: how to get all ROWIDS of a chained row in Oracle Database From Query change notification receiving a row id. with the received row id when i query the table it is returning no rows.
as the table have the 400 columns row data is stored in 2 blocks which in turn have a single row have 2 row ids. so i want to find out all the rowids of a chained row.
We used the following Database change Notification to get the Created/Updated/Deleted ROWID
DatabaseChangeNotification


text:
Q: How to use jQuery with Angular? Can anyone tell me, how to use jQuery with Angular?
class MyComponent {
    constructor() {
        // how to query the DOM element from here?
    }
}

I'm aware there are workarounds like manipulating the class or id of the DOM element upfront, but I'm hoping for a cleaner way of doing it.

A: To Use Jquery in Angular2(4)
Follow these setps
install the Jquery and Juqry type defination
For Jquery Installation npm install jquery --save
For Jquery Type defination Installation  npm install @types/jquery --save-dev
and then simply import the jquery
import { Component } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  console.log($(window)); // jquery is accessible
}

A: Now it has become very easy, You can do it by simply declaring jQuery variable with any type inside Angular2 controller.
declare var jQuery:any;

Add this just after import statements and before component decorator.
To access any element with id X or Class X you just have to do
jQuery("#X or .X").someFunc();

A: First, install jQuery using npm as follows:
npm install jquery — save

Second, go to the ./angular-cli.json file at the root of your Angular CLI project folder, and find the scripts: [] property, and include the path to jQuery as follows:
"scripts": [ "../node_modules/jquery/dist/jquery.min.js" ]

Now, to use jQuery, all you have to do is to import it in whatever component you want to use jQuery.
import * as $ from 'jquery';
(or)
declare var $: any;

Take a look at the below code that uses jQuery to animate div on click, especially in the second line. We are importing everything as $ from jQuery.
import { Component, OnInit  } from '@angular/core';
import * as $ from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Look jQuery Animation working in action!';

  public ngOnInit()
  {
    $(document).ready(function(){
        $("button").click(function(){
            var div = $("div");
            div.animate({left: '100px'}, "slow");
            div.animate({fontSize: '5em'}, "slow");
        });
    });
  }
}

A: Since I'm a dunce, I thought it would be good to have some working code.
Also, Angular2 typings version of angular-protractor has issues with the jQuery $, so the top accepted answer doesn't give me a clean compile.
Here are the steps that I got to be working:
index.html

...

...

Inside my.component.ts
import {
    Component,
    EventEmitter,
    Input,
    OnInit,
    Output,
    NgZone,
    AfterContentChecked,
    ElementRef,
    ViewChild
} from "@angular/core";
import {Router} from "@angular/router";

declare var jQuery:any;

@Component({
    moduleId: module.id,
    selector: 'mycomponent',
    templateUrl: 'my.component.html',
    styleUrls: ['../../scss/my.component.css'],
})
export class MyComponent implements OnInit, AfterContentChecked{
...
    scrollLeft() {

        jQuery('#myElement').animate({scrollLeft: 100}, 500);

    }
}

A: Just write
declare var $:any;

after all import sections, you can use jQuery and include the jQuery library in your index.html page

it worked for me

A: Angular 12
npm i jquery
this is important : npm i @types/jquery
angular.json
"scripts": [
              "node_modules/jquery/dist/jquery.min.js"
            ]

.ts file
import * as $ from "jquery";

A: Using jQuery from Angular2 is a breeze compared to ng1. If you are using TypeScript you could first reference jQuery typescript definition.
tsd install jquery --save
or
typings install dt~jquery --global --save

TypescriptDefinitions are not required since you could just use any as the type for $ or jQuery
In your angular component you should reference a DOM element from the template using @ViewChild() After the view has been initialized you can use the nativeElement property of this object and pass to jQuery.
Declaring $ (or jQuery) as JQueryStatic will give you a typed reference to jQuery.
import {bootstrap}    from '@angular/platform-browser-dynamic';
import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
declare var $:JQueryStatic;

@Component({
    selector: 'ng-chosen',
    template: `<select #selectElem>
        <option *ngFor="#item of items" [value]="item" [selected]="item === selectedValue">{{item}} option</option>
        </select>

 {{selectedValue}}
`
})
export class NgChosenComponent implements AfterViewInit {
    @ViewChild('selectElem') el:ElementRef;
    items = ['First', 'Second', 'Third'];
    selectedValue = 'Second';

    ngAfterViewInit() {
        $(this.el.nativeElement)
            .chosen()
            .on('change', (e, args) => {
                this.selectedValue = args.selected;
            });
    }
}

bootstrap(NgChosenComponent);

This example is available on plunker: http://plnkr.co/edit/Nq9LnK?p=preview
tslint will complain about chosen not being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file
interface JQuery {
    chosen(options?:any):JQuery;
}

A: A simple way:
1. include script
index.html

2. declare
my.component.ts
declare var $: any;

3. use
@Component({
  selector: 'home',
  templateUrl: './my.component.html',
})
export class MyComponent implements OnInit {
 ...
  $("#myselector").style="display: none;";
}

A: I am skipping installation of jquery since this point has been mentioned in all of the posts created prior to mine. So, you have already installed jquery. Importing t into your component like this
import * as $ from 'jquery';

will work, but there is another 'angular" way to do this by creating a service.
Step no. 1: create jquery.service.ts file.
// in Angular v2 it is OpaqueToken (I am on Angular v5)
import { InjectionToken } from '@angular/core';
export const JQUERY_TOKEN = new InjectionToken('jQuery');

Step. no. 2: register the service in app.module.ts
import { JQUERY_TOKEN } from './services/jQuery.service';
declare const jQuery: Object;

providers: [
    { provide: JQUERY_TOKEN, useValue: jQuery },
]

Step no. 3: inject the service into your component my-super-duper.component.ts
import { Component, Inject } from '@angular/core';

export class MySuperDuperComponent {
    constructor(@Inject(JQUERY_TOKEN) private $: any) {}

    someEventHandler() {
        this.$('#my-element').css('display', 'none');
    }
}

I will be very grateful if somebody can explain pros and cons of both methods: DI jquery as a service vs. import * as $ from 'jquery';

A: Others already posted. but I give a simple example here so that can help some new comers.
Step-1: In your index.html file reference jquery cdn

Step-2: assume we want to show div or hide div on click of a button:
 <input type="button" value="Add New" (click)="ShowForm();">

  //-----.HideMe{display:none;} is a css class----//

     <app-pricedetails></app-pricedetails>

  <app-pricemng></app-pricemng>

Step-3:In the component file bellow the import declare $ as bellow:
declare var $: any;

than create function like bellow:
 ShowForm(){
   $('#PriceForm').removeClass('HideMe');
 }

It will work with latest Angular and JQuery

A: Please follow these simple steps. It worked for me. Lets start with a new angular 2 app to avoid any confusion. I'm using Angular cli. So, install it if you don't have it already.
https://cli.angular.io/
Step 1: Create a demo angular 2 app
ng new jquery-demo

you can use any name. Now check if it is working by running below cmd.(Now, make sure that you are pointing to 'jquery-demo' if not use cd command )
ng serve

you will see "app works!" on browser.
Step 2: Install Bower (A package manager for the web)
Run this command on cli (make sure that you are pointing to 'jquery-demo' if not use cd command ):
npm i -g bower --save

Now after successful installation of bower, Create a 'bower.json' file by using below command:
bower init

It will ask for inputs, just press enter for all if you want default values and at the end type "Yes" when it'll ask "Looks good?"
Now you can see a new file (bower.json) in folder "jquery-demo". You can find more info on https://bower.io/
Step 3: Install jquery
Run this command
bower install jquery --save

It will create a new folder (bower_components) which will contain jquery installation folder. Now you have jquery installed in 'bower_components' folder.
Step 4: Add jquery location in 'angular-cli.json' file
Open 'angular-cli.json' file (present in 'jquery-demo' folder) and add jquery location in "scripts". It will look like this:
"scripts": ["../bower_components/jquery/dist/jquery.min.js"
              ]

Step 5: Write simple jquery code for testing
Open 'app.component.html' file and add a simple code line, The file will look like this:

  {{title}}

If you click on me, I will disappear.

Now Open 'app.component.ts' file and add jquery variable declaration and code for 'p' tag. You should use lifecycle hook ngAfterViewInit() also. After making changes the file will look like this:
import { Component, AfterViewInit } from '@angular/core';
declare var $:any;

@Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css']
})
export class AppComponent {
     title = 'app works!';

     ngAfterViewInit(){
           $(document).ready(function(){
             $("p").click(function(){
             $(this).hide();
             });
           });
     }
}

Now run your angular 2 app by using 'ng serve' command and test it. It should work.

A: Using Angular Cli
 npm install jquery --save

In angular.json under scripts array
"scripts": [ "node_modules/jquery/dist/jquery.min.js" ] // copy relative path of node_modules>jquery>dist>jquery.min.js to avoid path error

Now to use jQuery, all you have to do is to import it as follows in whatever component you want to use jQuery.
For example importing and using jQuery in root component
import { Component, OnInit  } from '@angular/core';
import * as $ from 'jquery'; // I faced issue in using jquery's popover
Or
declare var $: any; // declaring jquery in this way solved the problem

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

ngOnInit() {
}

jQueryExampleModal() { // to show a modal with dummyId
   $('#dummyId').modal('show');
}

A:
1) To access DOM in component.
import {BrowserDomAdapter } from '@angular/platform-browser/src/browser/browser_adapter';
constructor(el: ElementRef,public zone:NgZone) {
     this.el = el.nativeElement;
     this.dom = new BrowserDomAdapter();
 }
 ngOnInit() {
   this.dom.setValue(this.el,"Adding some content from ngOnInit");
 }

You can include jQuery in following way.
2) Include you jquery file in index.html before angular2 loads

    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

You can use Jquery in following way, Here i am using JQuery Ui date picker.
    import { Directive, ElementRef} from '@angular/core';
    declare  var $:any;
    @Directive({
      selector: '[uiDatePicker]',
     })
    export class UiDatePickerDirective {
      private el: HTMLElement;
      constructor(el: ElementRef) {
        this.el = el.nativeElement;

     }

    ngOnInit() {
        $(this.el).datepicker({
         onSelect: function(dateText:string) {
            //do something on select
         }
        });
    }
}

This work for me.

A: Global Library Installation as Official documentation here

*

*Install from npm:
npm install jquery --save

*Add needed script files to scripts:
"scripts": [
  "node_modules/jquery/dist/jquery.slim.js"
],
Restart server if you're running it, and it should be working on your app.

If you want to use inside single component use import $ from 'jquery'; inside your component

A: This is what worked for me.
STEP 1 - First things first
// In the console
// First install jQuery
npm install --save jquery
// and jQuery Definition
npm install -D @types/jquery

STEP 2 - IMPORT
// Now, within any of the app files (ES2015 style)
import * as $ from 'jquery';
//
$('#elemId').width();

// OR

// CommonJS style - working with "require"
import $ = require('jquery')
//
$('#elemId').width();

#UPDATE - Feb - 2017
Lately, I'm writing code with ES6 instead of typescript and am able to import without * as $ in the import statement.   This is what it looks like now:
import $ from 'jquery';
//
$('#elemId').width();

Good Luck.

A: You can implement the lifecycle hook ngAfterViewInit() to add some DOM manipulations
ngAfterViewInit() {
            var el:any = elelemtRef.domElement.children[0];
            $(el).chosen().on('change', (e, args) => {
                _this.selectedValue = args.selected;
            });
}

Be careful when using router because angular2 may recycle views .. so you have to be sure that the DOM elements manipulations are done only in the first call of afterViewInit .. ( You can use static boolean variables to do so )
class Component {
    let static chosenInitialized  : boolean = false;
    ngAfterViewInit() {
        if (!Component.chosenInitialized) {
            var el:any = elelemtRef.domElement.children[0];
            $(el).chosen().on('change', (e, args) => {
                _this.selectedValue = args.selected;
            });
            Component.chosenInitialized = true;
        }
    }
}

A: If you use angular-cli you can do :

*

*Install the dependency :
npm install jquery --save
npm install @types/jquery --save-dev

*Import the file :
Add "../node_modules/jquery/dist/jquery.min.js" to the "script" section in .angular-cli.json file

*Declare jquery :
Add "$" to the "types" section of tsconfig.app.json
You can find more details on official angular cli doc

A: step 1: use the command : npm install jquery --save
step 2: you can simply import angular as :
import $ from 'jquery';
that's all .
An example would be :
import { Component } from '@angular/core';
import  $ from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  constructor(){
    console.log($('body'));
  }

}

A: Why is everyone making it a rocket science?
For anyone else who needs to do some basic stuff on static elements, for example, body tag, just do this:

*

*In index.html add script tag with the path to your jquery lib, doesn't matter where (this way you can also use IE conditional tags to load lower version of jquery for IE9 and less).

*In your export component block have a function that calls your code: $("body").addClass("done"); Normaly this causes declaration error, so just after all imports in this .ts file, add declare var $:any; and you are good to go!

A: I do it in simpler way - first install jquery by npm in console: npm install jquery -S and then in component file I just write: let $ = require('.../jquery.min.js') and it works! Here full example from some my code:
import { Component, Input, ElementRef, OnInit } from '@angular/core';
let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');

@Component({
    selector: 'departments-connections-graph',
    templateUrl: './departmentsConnectionsGraph.template.html',
})

export class DepartmentsConnectionsGraph implements OnInit {
    rootNode : any;
    container: any;

    constructor(rootNode: ElementRef) {
      this.rootNode = rootNode;
    }

    ngOnInit() {
      this.container = $(this.rootNode.nativeElement).find('.departments-connections-graph')[0];
      console.log({ container : this.container});
      ...
    }
}

In teplate I have for instance:

something...

EDIT
Alternatively instead of using:
let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');

use
declare var $: any;

and in your index.html put:

This will initialize jquery only once globaly - this is important for instance for use modal windows in bootstrap...

A: //installing jquerynpm install jquery --save
//installing type defintion for the jquerytypings install dt~jquery --global --save
//adding jquery library into build configuration file as specified(in "angular-cli-build.js" file)
vendorNpmFiles: [
  .........
  .........
  'jquery/dist/jquery.min.js'
]

//run the build to add the jquery library in the build   ng build
//adding the relative path configuration(in system-config.js)
 /** Map relative paths to URLs. */
    const map: any = {
    .....,
    .......,
    'jquery': 'vendor/jquery/dist'
   };
/** User packages configuration. */
const packages: any = {
......,
'jquery':{ main: 'jquery.min',
format: 'global',
defaultExtension: 'js'}};

//import the jquery library in your component file
import 'jquery';

below is the code snipppet of my sample component
import { Component } from '@angular/core';
import 'jquery';
@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  list:Array<number> = [90,98,56,90];
  title = 'app works!';
  isNumber:boolean = jQuery.isNumeric(89)
  constructor(){}
}

A: The most effective way that I have found is to use setTimeout with time of 0 inside of the page/component constructor. This let's the jQuery run in the next execution cycle after Angular has finished loading all the child components. A few other component methods could be used but all I have tried work best when run inside a setTimeout.
export class HomePage {
    constructor() {
        setTimeout(() => {
            // run jQuery stuff here
        }, 0);
    }
}

A: Here is what worked for me - Angular 2 with webpack
I tried declaring $ as type any but whenever I tried to use any JQuery module I was getting (for example) $(..).datepicker() is not a function
Since I have Jquery included in my vendor.ts file I simply imported it into my component using
import * as $ from 'jquery';
I am able to use Jquery plugins (like bootstrap-datetimepicker) now

A: You could also try to import it with the "InjectionToken".
As described here: Use jQuery in Angular/Typescript without a type definition
You can simply inject the jQuery global instance and use it. For this you won't be needing any type definitions or typings.
import { InjectionToken } from '@angular/core';

export const JQ_TOKEN = new InjectionToken('jQuery');

export function jQueryFactory() {
    return window['jQuery'];
}

export const JQUERY_PROVIDER = [
    { provide: JQ_TOKEN, useFactory: jQueryFactory },
];

When set correctly in your app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

import { JQ_TOKEN } from './jQuery.service';

declare let jQuery: Object;

@NgModule({
    imports: [
        BrowserModule
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        { provide: JQ_TOKEN, useValue: jQuery }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

You can start using it in your components:
import { Component, Inject } from '@angular/core';
import { JQ_TOKEN } from './jQuery.service';

@Component({
    selector: "selector",
    templateUrl: 'somefile.html'
})
export class SomeComponent {
    constructor( @Inject(JQ_TOKEN) private $: any) { }

    somefunction() {
        this.$('...').doSomething();
    }
}

A: add this code Below in src/Main.ts will important jquery and all function in all project
import * as jquery from 'jquery';
import * as bootstrap from 'bootstrap';

not forget npm i @types/jquery and npm i @types/bootstrap

A: Install jquery
Terminal$ npm install jquery
(For bootstrap 4...)
Terminal$ npm install popper.js
Terminal$ npm install bootstrap
Then add the import statement to app.module.ts.
import 'jquery'

(For bootstrap 4...)
import 'popper.js'
import 'bootstrap'

Now you will no longer need


text:
Q: Optimised method to find all solutions of inequality I am trying to find the number of solutions of inequality
c > (a+(b^2)−1)/(a−1)
subject to constraints 2<=a<=A, 1<=b<=B, 1<=c<=C.
The approach I am using till now is to use a nested loop with outer loop for a and inner loop for b. I am trying to find ways to optimize my approach since A can be as large as 10^9.
Any suggestions would be appreciated.

A: Use numpy for vectorized operations. You can do something like this ->
import numpy as np

a = np.arange(2,A)
b = np.arange(1,B)
a1 = a.repeat(len(b), axis=0)
b1 = b.repeat(len(a), axis=0)

rhs = (a1 + (b1**2) -1) / (a1 - 1)


text:
Q: Ranks of matrix Find the rank of the following matrix
$$\begin{bmatrix}1&-1&2\\2&1&3\end{bmatrix}$$
My approach:
The row space exists in $R^3$ and is spanned by two vectors. Since the vectors are independent of each other(because they are not scalar multiples of each other). Therefore, the row rank of the matrix which is the rank of this is two, which is the correct answer.
However, I'm still confused as to why the answer is the answer. If the row space exists in R^3 doesn't it have be be spanned by at least three vectors. For example, the unit vectors $u_1, u_2, u_3$ span row space and are independent of each other so the rank of the space should be 3.
Can someone please tell me the flaw in my logic/understanding?

A: With the case of $\mathbb{R}^3$, the dimension is 3, since it has a basis that contains 3 elements.
The row space of your matrix lives as a "subspace" of the bigger structure $\mathbb{R}^3$. That is, you don't view it as $\mathbb{R}^3$, but rather as its own entity within $\mathbb{R}^3$. It's a nicely structured chunk of $\mathbb{R}^3$, if you will.
Being its own entity, it must have its own basis! The row space is filled with linear combinations of the two rows of your matrix, and since the two rows are linearly independent (as you rightfully pointed out), its basis contains only 2 elements, so its dimension is 2!
I think an example is more enlightening. Consider this simpler matrix instead:
$$\begin{bmatrix}1&0&0\\0&1&0\end{bmatrix}$$
Its rows are linearly independent, but are elements of $\mathbb{R}^3$. In this case, your intuition wouldn't have told you  that the dimension is $3$ simply because they are elements of $\mathbb{R}^3$, right? If you look at its row space (i.e., the linear combination of its rows), I'm sure you can see the plane, which is of dimension 2.

A: The rank of a matrix is simply the number of nonzero rows in reduced row echelon form (rref). If you find the Reduced row echelon form of this given matrix it will yield:
(1, 0, 5/3)
(0, 1, -1/3)
Clearly, there are 2 nonzero rows in the reduced row echelon form of the given matrix. Thus, the rank is thereby 2.

A: The definition of rank is the number of linearly independent row vectors of a matrix. For a matrix with $n$ linearly independent col, the max of rank is $n$.
Span means the linear combination of these vectors includes all vectors in this space, which means at least there are $n$ vectors(for matrix with col $n$).


text: Q: Login session problem I can't log in into my session because after I insert the password I got blank screen and I can't log to the desktop, but if I choose guest session at login screen the desktop start normally, I don't know what is the problem so can anyone help me and sorry for my english.


text:
Q: C# Delegate eventhandler SelectedIndexChanged I want to pass another value to the method LeCmb_Statut_SelectedIndexChanged, how can I proceed?
I have the code:
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
   ...
   DropDownList LeCmb_Statut = new DropDownList();
   string tempLabel = reader["LIBELLE"].ToString();
   string templabelVeh = reader["LIBVEH"].ToString()
}

How can I pass these temp variables into LeCmb_Statut_SelectedIndexChanged?
LeCmb_Statut.SelectedIndexChanged += new EventHandler(LeCmb_Statut_SelectedIndexChanged);

A: You could use the Tag property of dropdownlist.
first, create a simple DTO:
public class LabelDTO
{
   public string Label {get;set;}
   public string LabelVeh {get;set;}
}

then:
while (reader.Read())
{
   ...
   DropDownList LeCmb_Statut = new DropDownList();
   LabelDTO lbl= new LabelDTO(){Label=reader["LIBELLE"].ToString(), LabelVeh=reader["LIBVEH"].ToString()};

    LeCmb_Statut.Tag=lbl;
}

then inside the LeCmb_Statut_SelectedIndexChanged:
LeCmb_Statut_SelectedIndexChanged (object sender, System.EventArgs e)
{
    LabelDTO labelDTO= ((DropDownList)sender).Tag as LabelDTO ;
    if (labelDTO!=null)
     {
        ///here you can use the label and labelVeh properties.

     }
}

A: You can use an anonymous method to capture them:
string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += delegate {
    // do something fun with   tempLabel  and templabelVeh
};

this could be inline for small blocks, or for longer code - just pass to a method:
string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += delegate {
    DoSomethingFun(tempLabel,templabelVeh);
};

or if you need the sender/args:
string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += delegate(object sender, EventArgs args) {
    DoSomethingFun(sender,args,tempLabel,templabelVeh);
};

or in C# 3.0:
string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += (sender, args) =>
    DoSomethingFun(sender,args,tempLabel,templabelVeh);