MS Access 2016 VBA causes "Enter parameter value" window

Question: I have a form with filter textbox. Filter works as a macro command "ApplyFilter" with following filter string:
<code>[fullname] & [phoneNumber] Like '*' & [Forms]![frmTest]![frmFilter] & '*'
</code>
It works until I try to add VBA code to the form. Even if there is no code in VBA module I get "Enter parameter Value: [Forms]![frmTest]![frmFilter]" popup window when I try to apply filter.
If I set "HasModule" property of the form to "No" the filter works again.
It's not only just about filter or macro commands. It's the same with referencing form values in SQL queries like [Forms]![frmTest]![frmFilter]. It works without VBA module. It doesn't work if form has VBA module - "Enter parameter value" window appears.
What am I missing?
Answer: Seems like it's an issue with non-latin characters in form controls names. Such controls are displayed as "?????" in VBA module. I made a new form and renamed all controls with latin characters and everything works with enabled VBA module. As soon as I add a button with non-latin name everything breaks and starts working after deleting it.


Convert "/" to "-" with rewrite rule

Question: I have the following rewrite rule in my server:
<code>RewriteEngine On
RewriteBase /
RewriteCond $1 !^(index\.php|static)
RewriteRule ^(.*)$ /index.php?$1 [L]
</code>
It's main porpuse is to convert every folder requested to the server into a parameter. For example, requesting example.com/foo fighters gets converted to example.com/index.php?foo fighters.
Pretty cool, huh? Well, there's one problem. If anyone enters, for example, AC/DC, due to the extra slash. Is there any way to rewrite that / to -, making it work with the current rewrite rule?
Comment: can you edit your question to provide examples of what is currently happening and what should happen? For example "the url `/AC/DC` currently maps to `/index.php?/AC/DC`, but should map to `/index.php?AC-DC`.  Meanwhile, what should `/AC-DC` map to?  You definitely shouldn't allow two URLs to map to the same thing, so if there is currently ambiguity, force one to "become" the other, using a separate 301 rule.
Comment: Why would the slash be a problem? The rewrite rule you currently have is a very common one. Can you explain your situation bit more?
Comment: It's the way i handle the slashes. Rewriting a single / to a -, if possible, would be much easier than refactoring the whole code after the folder gets converted to parameter.
Answer: Use the B flag to url-encode the parameter.
http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_b

Convert "/" to "-" with rewrite rule


Dynamic graph generation with apache

Question: I recently setup a cron on one of my servers to monitor the connection status. Basically a ping is issued every minute and the result is appended with the date to a data file.
I am currently able to fetch the data file trough apache and to generate a graph with gnuplot locally. But I wonder if there is an easy way to do this directly in apache.
I'd like to call some page in apache, which would trigger a gnuplot generation then render the generated file directly.
Do you know any tool/set of tools to help me do that ?
Thank you.
Answer: Don't do this yourself. There are many monitoring applications available that already do what you want.
One solution just for the connection status could be Smokeping (it does much more, but is easy to configure for this purpose).
Comment: Thank you for your answer. I actually don't really *want* to do this myself. But my searches were not conclusive. I'll try smokePing and keep you posted.

Dynamic graph generation with apache


Pandas multiiindex boolean slice

Question: I'm so new to this I don't have the vocabulary to properly frame the question.  Nor do I know how to include the output very well.
I'm trying to slice a multi indexed dataframe of COVID19 data.  I want to select data from countries other than China.  I know how to slice using a multiindex based on countries I want to see, I just don't know how to look at everything but a country or set of countries.
                     1/22/20   1/23/20   1/24/20...
Country   Province
China      Hubei       28        28         28
Italy       NaN         0         0          0
...

Obviously the dataframe is much bigger.  All I want to do is slice by excluding rather than explicitly including.
df.loc['China']
Gives me all rows with China.  How do I slice to exclude?  Below doesn't work, but it gives the idea:
df.loc[!='China']
Any hints?
Thanks!
Answer: Use Index.get_level_values with filtering in boolean indexing:
df1 = df[df.index.get_level_values(0) != 'China']
print (df1)
                  1/22/20  1/23/20  1/24/20
Country Province
Italy   NaN             0        0        0

Comment: Thanks!  Exactly what I needed.  And after reviewing [get_level_values](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.get_level_values.html#pandas.MultiIndex.get_level_values) I understand how it works!

Pandas multiiindex boolean slice


How to calculate number of submitted webforms?

Question: I want to show the number of submitted webforms in a block in the front page of my website.
I searched and found (( function webform_get_submission_count )) . But I'm absolute beginner: I know it is inside webform.submission.inc, but then where shall I call it? How to place it in a block like in the following image:

Any help would be greatly appreciated.
Answer: Another option would be to use Views to create a view of webform submissions, and display the count from that.
Answer: Since you wrote you're an absolute beginner, you might want to consider using contributed modules to do so. Be aware however that reporting about webform submissions can be a bit challenging, especially if you try to do so with the Views module. Below are a few alternatives to consider.
Webform add-on modules
There are many Webform related modules which extend Webform, including integrations with third-party software.
As a sample, if you'd want to create charts from the submitted webform results, there seem to be even 2 alternatives to pick from (with extremely similar module names ...):

Webform Charts, to display Webform results in a graphical manner using a charting library.
Webform Chart, which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

Another possible module to consider,  is the Views Aggregator Plus module. Here is an excerpt from its project page:

Works great with Webform 7.x-4.x (aggregate your webform submission results tables).

Module Forena
Display Webform Submission Data using Views is a bit challenging. As an alternative to installing Webform MySQL Views (which depends on Data and Schema), consider the Forena module. Here is a quote about it:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

So in this case you'd use Forena to report about the Webform data stored in the Webform tables, which are contained in your Drupal database.
Disclosure: I'm a (co-)maintainer of the Forena module,
I hope this does not violate the site's policy on self-promotion.


Proxy pass with host in headers causes loop redirects

Question: Use case
We need to redirect to current website (ip1 - https://host.com/path) from a new server (ip2) that will host another website under root path (https://host2.com/). In the end, this last website will be hosted as https://host.com/, meaning that we will have one website on https://host.com/ (hosted on ip2) and another one on https://host.com/path (that is hosted on ip1)
NGINX is running on ip2 server.
Current website only accepts requests from host.com
Current config
This is what we are trying to do right now on ip2 server
location /path/ {
  proxy_pass https://ip1/path;
  proxy_redirect off;
  proxy_set_header Host host.com;
}

If we try to access https://host2.com/path, the config is working well.
When we change the DNS to set ip2 as host.com and then if we try to access https://host.com/path, NGINX is processing the request but then we have infinite 302 redirections to https://host.com/path (until browser eventually stops the process)
Do you have any idea how to solve this issue ?
Thanks a lot !
Comment: I *think* you need to balance your slashes, `location /path/ ` needs to match with `proxy_pass  https://ip1/path/ ;` also with a trailing slash
Answer: We finally found a configuration to handle this issue :
location /path/ {
  proxy_pass https://ip1/path/;
  proxy_redirect off;
  proxy_set_header Host host.com;
}

Watch out to the protocol (https) and the trailing slash character.
We moved the DNS to redirect host.com to ip2 and it's working like a charm !
Comment: This `proxy_pass https://;` doesn't work... if you're using an ssl config you proxy to http. Please don't post questions and then misleading answers to your own questions on the web. It pollutes the comment section for everyone else...


Can MAE be higher than MSE?

Question: I am using Mean Absolute Value(MAE) and Mean Squared Error(MSE) as my evaluation parameters for the regression model. I am trying to predict the future values for time series model and have used CNN fro the same. However, my CNN model is giving very low values for MSE compared to MAE. On such example is
MAE:0.04978915070122473, MSE:0.004155844765967494

I know for sure that MAE has to be always less than MSE since we are squaring the coefficients in MSE.
Comment: |+-0.1| = 0.1 > 0.01 = (+-0.1)^2
Answer: You're forgetting about squaring small numbers. Here is an example where the MSE would be smaller:
import numpy as np
label = np.array([0.392, 0.342, 0.344, 0.534])
predict = np.array([0.394, 0.340, 0.347, 0.525])

MSE = np.average((label - predict)**2)
MAE = np.average(np.abs(label - predict))

print(MSE)
print(MAE)

>>>2.4500000000000043e-05
>>>0.0040000000000000036

label *= 1000
predict *=  1000

MSE = np.average((label - predict)**2)
MAE = np.average(np.abs(label - predict))

print(MSE)
print(MAE)

>>>24.5
>>>4.0

Can MAE be higher than MSE?


How to list all files in a directory Silverlight

Question: I need some quick code just to see what files are listed when I run the code for the current directory.
I have an SQLite database file which I would like my Silverlight Application to use but I don't know where to put it as I can't find what directory the application is working from.
Can anyone help me out here?
Answer: Generally you cannot access the local filesystem in Silverlight - it runs in it's own sandbox.  You should be able to deploy your SQLite db as part of your solution, so it's available from the sandbox.  Or you can expose your db via a webservice, and then your Silverlight app can use service calls to talk to the db.
Comment: Would you be able to provide a basic way to use a web service to gain access to the file on the server? thanks.
Comment: Here's a project (looks like Python) that exposes a SQLite db as a webservice.  http://code.google.com/p/restful-sqlite.  If your data is going to be read-only, then you might try using oData.  Here's a article on creating a C# oData service - http://www.hanselman.com/blog/CreatingAnODataAPIForStackOverflowIncludingXMLAndJSONIn30Minutes.aspx


Select esconder/mostrar DIVs de acordo com o valor selecionado (jquery)

Question: Tenho um select e alguns divs assim:
<select name="numerounidades" id="numerounidades">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>

Aí precisava de uma função em jquery que esconde ou mostra os divs de acordo com a seleção, ex:
Valor 1: só mostra o div id 1
Valor 2: mostra o div id 1 e 2
Valor 3: mostra o div id 1, 2 e 3
Valor 4: mostra o div id 1, 2, 3 e 4

Tem uma forma de montar uma função jQuery simples pra isso? A única forma que sei é fazer um if para cada valor selecionado.
EDITADO
Montei uma gambiarra que deu certo, mas acredito que exista uma forma melhor de se fazer isso certo?

1

2

3

4

$(document).ready(function() {
$('.d1').hide();
$('.d2').hide();
$('.d3').hide();
$('.d4').hide();
    $("#numerounidades").change(function(){
$('.d1').hide();
$('.d2').hide();
$('.d3').hide();
$('.d4').hide();
        var numero = 'd'+$(this).val();
        $('.'+numero).show();
        });
});

Answer: Usando um loop for() fica facil:

$("#1,#2,#3,#4").hide();
$("#numerounidades").change(function(){
    var num = parseInt($('#numerounidades option:selected').val());
    for (var i = 1; i <= num; i++) {
        $("#"+i).show();
    }
});

<select name="numerounidades" id="numerounidades">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>

a

b

c

d

Comment: Perfeito, Brigadão!
Comment: minha gambiarra é colocar $("#1,#2,#3,#4").hide(); no inicio do .change
Comment: Eu quem agradeço por poder ajudar
Comment: na verdade tem uma alteração pra fazer, se seleciona 2 e depois 3, vai normal, mas se selecionar 1 de volta, ele não ta escondendo os outros
Comment: isso, vc executa o fechamento dps a abertura
Answer: Caso queira uma solução com javascript puro

var numero_unidades = document.getElementById('numerounidades');

numero_unidades.onchange = () => {

  var optionSelected = numero_unidades.options[numero_unidades.selectedIndex].value;

  hide(['1', '2', '3', '4']);

  if(optionSelected){
    for(var index = 1; index <= optionSelected; index++)
      show(`${[index]}`);
  }

}

function hide(array) {
    for (var item = 0; item < array.length; item++)
        document.getElementById(array[item]).style.display = 'none';
}

function show(array) {
    for (var item = 0; item < array.length; item++)
        document.getElementById(array[item]).style.display = 'block';
}
<select name="numerounidades" id="numerounidades">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>

a

b

c

d


how to test push notification in android phonegap?

Question: I downloaded the push notification sample project from MarkNutter Project and imported it as android project  its working fine as of now I am able to register from device
Since I do not have some server to send notification to device, How sould I test if the device is receiving some notifications?
Answer: There are some steps that maybe you haven't done yet:

First you must register in Google APIs site, select Services: https://code.google.com/apis/console/
Turn the Google Cloud Messaging toggle to ON
In the Terms of Service page, accept the terms.Now you need to create the Server Key
Press "API Access" button
Press "Create new Server key". Either a server key or a browser key should work. The advantage to using a server key is that it allows you to whitelist IP addresses.
Press "Create".
You can find your ProjectID from the URL in your Google API console. Usually it looks like this: https://code.google.com/apis/console/#project:12345678912:access In this example, it would be: 12345678912
With your app ID and sender ID just change them in the code you get from MarkNutter Project and you'll be done.


Erro no applicationContext-security.xml

Question: Meu 1º arquivo xml applicationContext-security.xml:
<?xml version="1.0" encoding="UTF-8"?>

<http auto-config="true">

    <intercept-url pattern="/admin/*" access="ROLE_ADMINISTRADOR" />
    <intercept-url pattern="/restrito/*" access="ROLE_USUARIO" />
    <form-login login-page="/publico/login.jsf"
        always-use-default-target="true" default-target-url="/restrito/principal.jsf"
        authentication-failure-url="/publico/login.jsf?login_error=1" />
    <logout/>
    <remember-me />
</http>

<authentication-manager>
    <authentication-provider>
        <jdbc-user-service data-source-ref="financeiroDataSource"
            authorities-by-username-query="SELECT u.login, p.permissao
                                         FROM usuario u, usuario_permissao p
                                        WHERE u.codigo = p.usuario
                                          AND u.login = ?"
            users-by-username-query="SELECT login, senha, ativo
                                   FROM usuario
                                  WHERE login = ?" />
    </authentication-provider>
</authentication-manager>

E tem este outro applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="financeiroDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>java:comp/env/jdbc/FinanceiroDB</value>
    </property>
</bean>
</beans>

Todos estão na pasta WEB-INFO.
Es são os erros no log do tomcat:
1º
GRAVE: Context initialization failed
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]
Offending resource: ServletContext resource [/WEB-INF/applicationContext-security.xml]
2º
set 09, 2014 9:47:18 PM org.apache.catalina.core.StandardContext listenerStart
GRAVE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]
Offending resource: ServletContext resource [/WEB-INF/applicationContext-security.xml]
Minhas libs:
spring-2.5.6.jar
spring-security-cas-3.1.0.RELEASE.jar
spring-security-core-3.1.0.RELEASE.jar
spring-security-openid-3.1.0.RELEASE.jar
spring-security-remoting-3.1.0.RELEASE.jar
spring-security-samples-contacts-3.0.2.RELEASE-sources.jar
spring-security-samples-tutorial-3.0.2.RELEASE-sources.jar
Comment: Parece que o XML de configuração não está no padrão requerido. Dependendo do IDE você pode validar esse XML antes de executar a aplicação. Qual IDE você está usando?
Comment: @Luídne Estou usando o Eclipse
Comment: Poste também seu XML. Vai ajudar muito nesse caso.
Comment: Mudei a descrição do erro e adicionei os meus arquivos. @Luíde
Comment: Que versão do Tomcat e Spring Security você está usando?
Comment: Mais uma coisa, quais as libs você está usando no projeto?
Comment: @Luídne adicionei na descrição as libs que estou usando do spring. E atualizei os dois erros que acontecem ao iniciar o tomcat.
Answer: O que está acontecendo é o seguinte, no XML o manipulador do namespace http://www.springframework.org/schema/security não está sendo encontrado. Isto porque está faltando uma biblioteca que contém essa classe manipuladora.
E para tal, a biblioteca do framework que está faltando é a: spring-security-config-3.1.0.RELEASE.jar
Se você ver os arquivos dentro da pasta META-INF deste .jar verá os arquivos que define a classe que tratará esse namespace.

Portanto, basta adicionar a biblioteca mencionada que o erro não ocorrerá mais.
  Porém, é bom adicionar todas as outras bibliotecas do Spring Security no projeto e caso queira reduzir o tamanho do .war vá removendo uma de cada vez para ver quais não são necessárias.

Outras informações:
http://www.baeldung.com/unable-to-locate-spring-namespacehandler-for-xml-schema-namespace

Erro no applicationContext-security.xml


Intersection multiplicity

Question:
Let $f=y^2-x^3$ and $g=y^3-x^7$. Calculate the intersection multiplicity of $f$ and $g$ at $(0,0)$.

I know the general technique for this (passing to the local ring) but I having difficulty with the fact that $3,7,2$ have no common factors.
Answer: Using the properties of intersection number can save much time for the
calculation of intersection numbers.
If $P$ is a point, two affine plane curves $F$ and $G$ have no common
components, then: (see section 3.3 in Fulton's algebraic curves)

$I(P,F\cap G)=I(F\cap (G+AF))$ for any $A\in k[X,Y]$;
$I(P,F\cap G)=m_p(F)m_P(G)$, when $F$ and $G$ have not tangent
lines in common at $P$.
$I(P,F\cap GH)=I(P,F\cap G)+I(P,F\cap H)$ for $H\in k[X,Y]$.

Now, $P=(0,0)$,
$I(P,y^2-x^3\cap y^3-x^7)=I(P, y^2-x^3\cap
((y^3-x^7)-(y^2-x^3)x^4))$
$\quad =I(P,y^2-x^3\cap y^2)+I(P,y^2-x^3\cap y-x^4).$
And $I(P, y^2-x^3\cap y^2)=I(P,x^3\cap y^2)=3\times 2=6$.
$I(P, y^2-x^3\cap y-x^4)=I(P, y^2-x^3\cap
((y-x^4)-(y^2-x^3)x))$
$\quad =I(P,y^2-x^3\cap y(1-xy))=3$.
Thus $9=6+3$ is the
desired number.

$I(P,y^2-x^3\cap y(1-xy))=I(P,y^2-x^3\cap y)+I(P,y^2-x^3\cap (1-xy))$,
$I(P,y^2-x^3\cap y)=I(P,-x^3\cap y)=3$ and $I(P,y^2-x^3\cap (1-xy))=0$ ($P$ is not the zero of $1-xy$).
Comment: Thanks. I don't understand the last bit. Isn't the multiplicity of $y^2-x^3$ equal to 2 (because that is the lowest power) and the multiplicity of $y(1-xy)$ equal to 2?
Comment: Dear @user137090, see the update.
Comment: @user137090. I have come across an example when the point of intersection is not (0,0). $f=x+y-2$ and $g=x^2+y^2-2$ intersect at (1,1). How do we compute the multiplicity in the way you describe? Thanks
Comment: is it ok in such a case to translate by (1,1) so it is equivalent to finding intersection multiplicity of $x+y$ and $x^2+2x+y^2+2y$ at (0,0)?
Comment: Yes, you are absolutely right. Please take a look at Fulton's book "algebraic curve"
Answer: I think you no longer need an answer, but I'd like to write something here since it may help some other students.
We need four lemmas here(You can find them in lecture 2 of Andreas Gathmann's notes in Plane Algebraic Curves):
Lemma (1): For any three plane curves F, G, H, $$\mu_p(F, G)=\mu_p(F, G+FH)$$
Lemma (2): For any three plane curves F, G, H, $$\mu_p(F, GH)=\mu_p(F, G)+\mu_p(F, H)$$
Lemma (3): $\mu_p(F, G)\ge 1$ iff $P\in F\cap G$.
Lemma (4): $\mu_p(F, G)=1$ iff $<F, G>=I_p$, where $I_p =\{f/g: f, g\in K[x, y], f(P)=0, g(P)\neq 0\}$.
Now we can compute $\mu_0(y^2-x^3, y^3-x^7)$.
$\begin{align}\mu_0(y^2-x^3, y^3-x^7)\overset{by (1)}{=}\mu_0(y^2-x^3, y^3-x^7-y(y^2-x^3))=\mu_0(y^2-x^3, x^3y-x^7)\overset{by (2)}{=}\mu_0(y^2-x^3, x^3)+\mu_0(y^2-x^3, y-x^4)\overset{by (1)}{=}\mu_0(y^2-x^3+x^3, x^3)+\mu_0(y^2-x^3-y(y-x^4), y-x^4))=\mu_0(y^2, x^3)+\mu_0(x^4y-x^3, y-x^4)\overset{by (2), (2), respectively}{=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=}6\mu_0(y, x)+\mu_0(x^3, y-x^4)+\mu_0(xy-1, y-x^4)\overset{by (4), (1), (3), respectively}{=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=}6+\mu_0(x^3, y-x^4+x(x^3))+0=6+\mu_0(x^3, y)\overset{by (2)}{=}6+3\mu_0(x, y)\overset{by (4)}{=}6+3=9\end{align}.$
Comment: Trying to fit all of that math in one line is really rough for formatting and readability. Please consider breaking it up in to different lines and using connecting phrases instead of trying to \overset your explanations above the equals signs.

Intersection multiplicity


Learning combinatorial optimization, online convex optimization, and submodular function maximization

Question: What is the best way to learn combinatorial optimization, online convex optimization, and submodular function maximization? I currently found textbooks online and papers related to these topics but I am looking for example problems to solve, specifically for submodular function maximization, with python/c++ code to solve the problem. Are there any recommendations and online resources which would enable to learn and apply these topics quickly? My mathematics background is up to graduate school-level linear algebra and probability.
Answer: A course on submodular function maximization to self-teach:
EE596B - Submodular Functions, Optimization, and Applications to Machine Learning, Spring Quarter, 2014
Has lectures and lecture notes to learn.


How to solve a differential equation?

Question: I'm trying to solve the system $$\frac{d^4x}{dt}+4x=0,\quad\frac{d^3x}{dt}+x=0.$$ However, I don't know of any method of tackling such a problem. Can anyone please provide a route to a solution? Please say what method are needed to be applied to solve such a problem.
Comment: If you're trying to solve them together,  just add the two equations together and get a $x^{(4)}+x^{(3)}+5x=0$,  then solve via the methods below
Comment: @Alan: If you add the linear equations $x+y=3$ and $x-y=1$, you get $x=2$. Are its solutions all solutions of the original system? This is very misleading.
Comment: Maybe a textbook would be useful?
Comment: True, you have to go back and ensure that the solutions found also solve the individual ones.
Answer: If we differentiate the second equation once and subtract from the first, we obtain $dx/dt = 4x$, so $x=Ce^{4t}$. Only for the constant $0$ do we get a solution of each of the original equations.
We can see this from a slightly more complicated perspective. As @Ian's solution points out, the general solution must be a linear combination of functions of the form $e^{\lambda t}$, where $\lambda^4+4=0$. But it must simultaneously be a linear combination of functions of the form $e^{\mu t}$, where $\mu^3+1=0$. There can be no such linear combinations, other than $0$.
Answer: I see now that this is a system of equations.
Differentiating the second equation $x'''' + x' = 0$. Together with the first equation $x'''' + 4x = 0$, we have $x' = 4x$, or $x(t) = Ae^{4t}$.
But substituting that form of $x$ back into either equation, we see $A = 0$.
Hence the only solution to the system is the trivial solution, $x(t) = 0$.
Answer: You have a linear ordinary differential equation with constant coefficients. Any such problem can, at least in principle, be solved by the use of the characteristic polynomial. (In practice finding the roots may be difficult in certain cases.)
For example, in your first problem, the characteristic polynomial is $p(\lambda)=\lambda^4+4$. This has roots $\lambda_j=4^{1/4} e^{i \pi/4 + j \pi/2}$ for $j=0,\dots,3$. Hence the general solution to the homogeneous problem is $x(t)=\sum_{j=0}^3 c_j e^{\lambda_j t}$, for (complex) constants $c_0,\dots,c_3$.
Comment: @SimonS Thanks, I will correct it.
Comment: ...Now that mistake was just mindless on my part. Corrected!

How to solve a differential equation?


IPv4 is leaking when using an IPv6 proxy

Question: We've purchased access to a set of proxies which all have different public IPv6 addresses. When we access sites such as whatismyip.com, however, it shows that we also have a public IPv4 address. I've looked up these IPv4 addresses (such as 126.96.36.199) and they belong to Cloudflare. I was told that most likely we are "leaking CDN", but I don't understand what that means and I'm no longer in contact with the person who said it. There are only a few of these IPv4 addresses shared among the hundreds of IPv6 proxies, and I'm afraid they are being used to tie our proxies together. There has been evidence suggesting as much.
So I suppose my questions are:
1) Please explain what he means by leaking CDN or what is likely to be going on here.
2) Is there a way to block those IPv4 addresses from being exposed?
Answer: This is a very normal part of using any kind of proxy (a CDN such as Fastly, Cloudflare, etc or something like squid on a corporate network). They generally add honest headers to say "Hey, I'm a proxy, the real user is on this IP address here". That's because the clients IP address is often a part of identifying session data for websites.
Cloudflare allow you to turn this off. See this here (assuming that is the product you're using, I'm not actually entirely sure what you've purchased).


What is this set $\mathbb{R}$ mod $2\pi$

Question: What does it mean for S = $\mathbb{R}$ mod $2\pi$? Can someone please explain as this notation is new to me.
Answer: First, define an equivalence relation $\sim$ on $\mathbf{R}$ via $x \sim y$ if there exists an integer $k$, such that $x - y = 2\pi k$. Verify that this is indeed an equivalence relation. Representatives of its equivalence classes are then elements of $\mathbf{R} \mod{2 \pi}$.
Notice that this is analogous to defining modulo integers.
Comment: What is the common between equivalence relation and this modulo operation. I have not encountered this before is this number theory?
Comment: Same thing, except $x,y \in \mathbf{Z}$ and $2\pi$ would be replaced by an integer.
Answer: It means that $x\equiv y$ if and only if $x=y+2k\pi$ for some integer $k.$ It is the same when you watch your clock. Then hour $13$ is equal to hour $1$ just because you understand hours mod $12.$ That is $13-1=12.$
The model for your $\mathbb{R}\: \mathrm{mod}\: 2\pi$ is a circumference of radius $1.$ There you can identify $1$ with $1+2\pi,$ $1-2\pi,$ etc.
Comment: But what is this set? Does $S  = \mathbb{R}$ mod $2\pi$ mean $S = \{y | x = y + 2k\pi, for x \in \mathbb{R}, k \in \mathbb{Z}\}$
Comment: As I have said you can identify this set with a circumference of radius $1.$ As @Prospect says in his/her answer this set is obtained as the set of equivalence classes of an equivalence relation. In his/her answer he/she gives explicitly the equivalence relation. I think that the clock is a good model.
Answer: $\Bbb{R}\mod M$ means real numbers ($\Bbb{R}$) such that $0\leq x < M$.  So for example $\Bbb{R}\mod  2\pi$ means all real numbers in the half-open interval $[0,2\pi)$, an interval often used when talking about angles or the modulus of a complex number.
Although in set theory that is the end of the story, usually when such a set is used, we are going to also have rules of arithmetic modulo $2\pi$, that is, for example, $3 \cdot \frac{4\pi}{5} = \frac{2\pi}{5}$.
Comment: so $x \in \mathbb{R}$ mod $M$ is $x \in [0, M)$. This is simpler to understand...


Paylocity API get employee department

Question: Does anyone know how to retrieve department from the Employee API? As per the online documentation, the Employee structure does not have a property for department?
I need this to be able sync some data into Azure AD.
Answer: It depends on how your company implemented departments, but this worked for us:
<code>DepartmentCostCenter1 = employee.Value.departmentPosition == null ? null : employee.Value.departmentPosition.costCenter1,
DepartmentCostCenter2 = employee.Value.departmentPosition == null ? null : employee.Value.departmentPosition.costCenter2,
DepartmentCostCenter3 = employee.Value.departmentPosition == null ? null : employee.Value.departmentPosition.costCenter3,
DepartmentPositionCode = employee.Value.departmentPosition == null ? null : employee.Value.departmentPosition.positionCode,
</code>

Paylocity API get employee department


How do you open an MS Word file with php?

Question:
Possible Duplicate:
Create Word Document using PHP in Linux

I am trying to open Word files and edit them on linux based operating system.
is there any PHP API that enables me to open and edit word file?
I want to read and edit these files and view the images and the text formating.
Comment: There are [many many questions](http://stackoverflow.com/search?q=%5Bphp%5D+edit+word+document) addressing this...
Comment: http://stackoverflow.com/questions/124959/create-word-document-using-php-in-linux look here...
Answer: We used COM objects to open up MATLAB using PHP on a Windows machine. We were able to control it pretty decently, pass scripts and such. You might want to take a look at that.
Comment: http://support.microsoft.com/kb/257757


Find oldest post — WordPress

Question: Thanks to some answers on here, I've managed to distinguish my posts into the latest post and all the rest. However, it needs to be the oldest post. Here is my current loop:
<?php if (have_posts()) : ?>
<?php $post = $posts[0]; $c=0;?>
<?php while (have_posts()) : the_post(); ?>

<?php $c++;
if( $c == 1) :?>

                <a href="<?php the_permalink();?>">
                    <?php the_title(); ?>

        <?php the_content(); ?>

a

<?php else :?>

                <a href="<?php the_permalink();?>">
                    <?php the_title(); ?>

        <?php the_content(); ?>

b

<?php endif; ?>`

I saw somewhere that you can use a while loop to target the last post from a post.length. However, I am unsure how to implement this.
Comment: Do you need to style ONLY the oldest post or the oldest post and the posts just before it? In essence, if there are only 10 posts (10 being ID of the oldest), do you want to retrieve 10{special styling} then 9,8,7,etc{normal styling} or do you ONLY want 10?
Answer: Yes, you're right. Use count.
Suppose the total posts is 5 for $total_posts = count($posts);.
You'll have to check your $counter for total - 1 as the array is $posts[0], $posts[1], $posts[2], $posts[3], $posts[4].
<?php
if ( have_posts() ) :
    $counter = 0;
    $total_posts = count($posts) - 1;

    while ( have_posts() ) :
        the_post();
        if( $counter == $total_posts ) {
            ?>

<?php // CUSTOM CODE FOR LAST ARTICLE ?>

            <?php
        } else {
            ?>

<?php // CUSTOM CODE FOR THE REST OF ARTICLES ?>

            <?php
        }
        $counter++;
    endwhile;
endif;

Note that you only need to open <?php and close ?> when changing from PHP to HTML, using them at every line is very confusing.
Comment: Thanks. Where would I put my content if I were to use this method? (`` etc.)
Comment: Updated the answer with the basics, just adapt it to match your original code.

Find oldest post — WordPress


Can't create a new view

Question: I am having trouble creating a new View. I am just testing out the module, but when I click "Save" after setting everything up, I receive the following error:

PDOException: SQLSTATE[HY000]: General error: 1267 Illegal mix of
  collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT)
  for operation '=': SELECT s.uid, c.updated FROM {ctools_object_cache}
  c INNER JOIN {sessions} s ON c.sid = s.sid WHERE s.sid <> :session_id
  AND c.obj = :obj AND c.name = :name ORDER BY c.updated ASC; Array (
  [:session_id] => 3nTvCCvx2_Zopg07JqIBReKxL3TzvilIkwmHjFKZ93o [:obj] =>
  view [:name] => recently_posted_jobs ) in ctools_object_cache_test()
  (line 145 of
  /home1/mt/public_html/mtnet/sites/all/modules/ctools/includes/object-cache.inc).
  The website encountered an unexpected error. Please try again later.

Any ideas why this is happening?
Answer: Clear all your caches and try again.
You db seems to become corrupted or misconfigured. Your ctools module is using a different collation to store values in the db. So most of your site is utf8_general_ci and the ctools is using utf8_unicode_ci.
I gathered all of that from this line:

(utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '=': SELECT s.uid, c.updated FROM {ctools_object_cache}

If the clearing of caches fails then...
If you have phpmyadmin installed, go to the site's db and check what the Collate value is. Try changing it to utf_8 or something.

NOTE: I would create a backup of the db before you play with any collate value stuff.
Comment: I followed your advice, and it worked! For posterity, I changed the "Collation" field for the ctools_css_cache, ctools_custom_content, and ctools_object_cache tables in my database to utf8_unicode_ci. Make sure the Collation value is the same for all tables in your database, otherwise you'll experience the same issues I did. So it doesn't have to be "utf8_unicode_ci", that's just what the Collation value was for all of the other tables in my DB, so it's what I settled on. As long as there's consistency, you'll be good!

Can't create a new view


Importing Django Custom User Model From Another App Model

Question: So I have an app called profiles and it has model named Profile
from poros.abstracts.models import Model
from django.db import models
from poros.users.models import User

class Profile(Model):
    user = models.OneToOneField(
        to=User,
        on_delete=models.CASCADE,
        related_name='profile', )

the Profile model has a field name user which has OneToOneField relationship with my Django custom user User. The problem now is it returns me an error:
ImportError: cannot import name 'User'

How can I solve this issue?
Comment: Don't import; use a string, in the format `appname.ModelName`, in the field definition
Answer: Don't refer to the user model directly, it is recommended by django by refer to the settings.AUTH_USER_MODEL.
Document
from django.conf import settings

class Profile(Model):
    user = models.OneToOneField(
        to=settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='profile', )


SQL dúvida em consulta

Question: Alguém pode me dar uma orientação nessa consulta? Como encontrar a quantidade de possíveis shows assistidos?
Para os espectadores do dia "24/07/2020" que passaram na catraca antes do horário de início do show, liste o número do ingresso, a hora de entrada, o nome do espectador e quantidade de possíveis shows assistidos (considerando apenas o horário de entrada).
<code>SELECT i.numero, i.horaentrada, p.nome
FROM pessoa P
INNER JOIN espectador E ON e.cpfpessoa = p.cpf
INNER JOIN ingresso I ON e.cpfpessoa = i.cpfespectador
INNER JOIN show S ON s.datalineup = i.datalineupentrada
WHERE i.pertencedatalineup = '24/07/2020' and i.horaentrada < s.horainicio;
</code>
Tabelas

Pessoa {cpf, nome}

Espectador {cpfpessoa, codigo}

Ingresso {numero, valor, datalineupentrada, horaentrada, cpfespectador, pertencedatalineup}

Lineup {datalineup}

Show {nomelocal, horainicio, datalineup}

Banda {nome, ordemapresentacao, nomelocalshow, datalineupshow, horainicioshow}

Saída
NUMERO HORAENTRAD NOME

<code>   3   21:00      Corina Brandan
   3   21:00      Corina Brandan
   8   22:00      Cristovao Aranha
</code>
Preciso que mostre a quantidade de shows assistidos com base no horário de entrada.
Comment: Pelo que você postou não existe o campo `pertencedatalineup` na tabela `ingresso`. Talvez se você informasse um exemplo do resultado obtido e o resultado desejado alguém possa orienta-lo. Creio que a função de agregação `count` juntamente com a cláusula `GROUP BY` possa ajuda-lo.
Comment: Qual a diferença entre as colunas `pertencedatalineup` e `datalineupentrada`?
Comment: Acrescente o que contém cada coluna das tabelas, principalmente daquelas que serão utilizadas no código sql.
Comment: realmente, 'pertencedatalineup' e 'datalineupentrada' são iguais
Answer: Eis uma possível solução:
<code>-- código #1
-- © José Diz (Porto SQL)

with Comparecimento as (
SELECT numero, datalineupentrada, horaentrada, cpfespectador
  from Ingresso
  where datalineupentrada = convert (date, '24/7/2020', 103)
)
SELECT C.numero, C.horaentrada, P.nome, count(*) as [Shows assistidos]
  from Comparecimento as C
       inner join Pessoa as P on P.cpf = C.cpfespectador
       inner join Show as S on s.datalineup = C.datalineupentrada
  where S.horainicio >= C.horaentrada
  group by C.numero, C.horaentrada, P.nome;
</code>
A CTE Comparecimento seleciona os ingressos que foram apresentados na data desejada. A partir dessa relação são obtidos o nome da pessoa e os shows que iniciariam após a entrada da pessoa.
Há fatores que podem confundir no momento de manipular datas no SQL Server, acarretando em erros na execução quase sempre relacionados ao desconhecimento de como o SQL Server interpreta os literais (strings) contendo data. Assim, sempre que fornecer datas como literal fique atento para utilizar de forma que não gere interpretações erradas, dependendo de como esteja configurado o LANGUAGE e/ou o DATEFORMAT da sessão. Exemplos de erros que podem ocorrer, e respectivas soluções, estão no artigo "Dominando datas e horas no SQL Server".
Comment: Muito obrigado pelo exemplo e explicação, ajudaram muito mesmo!

SQL dúvida em consulta


Objective-C Automatic Reference Counting (ARC) and Key-Value Observing

Question: I'm writing an Objective-C application using ARC and it's definitely a great improvement even though I never really minded retain counts. However, there's one case I couldn't find in the documentation on first glance.
If, in my init method, I call [self addObserver:self forKeyPath:…] to get notifications of when an ivar declared using an @property directive, do I need to explicitly call removeObserver… in the dealloc method, or does ARC handle key value observer cleanup? Similarly if I add my object to a NSNotificationCenter, does that need to be explicitly removed in dealloc?
Answer: You need to call removeObserver, ARC only automates retain counts.  removeObserver does not impact the retain count
Comment: Thanks! That's what I initially thought but I wasn't sure.


Height of a Normal distribution curve

Question: For a Normal distribution 'bell-shaped' curve, one would have thought that the height should have an ideal value. Knowing this value may be one quick indicator to check if the data is normally distributed.
However, I could not find its formal value. Most places, the shape is shown but not the y-axis measurements. http://www.stat.yale.edu/Courses/1997-98/101/normal.htm
In some graphs where it is mentioned, it is 0.4. http://en.wikipedia.org/wiki/File:Normal_Distribution_PDF.svg . But on the main page (http://en.wikipedia.org/wiki/Normal_distribution), value of 0.4 is not mentioned anywhere.
Is this the correct value and what is its mathematical basis? Thanks for your insight.
Edit:
The three curves shown in @Glen_b 's answer and on the wiki page (with mean=0) have same mean but different SDs. All tests would show that no significant difference between them. But they are clearly from different populations. Which test can we then apply to determine the difference in standard deviations of two distributions?
I checked on net and found it to be the F-test.
But is there a specific name for a distribution curve that is similar to one with mean of 0 and standard deviation of 1 (and peak at 0.4)?
Answered by Aleksandr Blekh in comments: "standard normal distribution or the unit normal distribution denoted by N(0,1)".
However, it is not emphasized that, if the means are not different, F-test or the KS test (as suggested by Glen_b in the comments) should be done to determine if the standard deviations are different, indicating different populations.
Comment: Your claim "all tests would show no significant difference between them" is false. At reasonable sample sizes, an F test for variance (testing if the ratio of variances differs from 1) would find the difference easily, as would a simple Kolmogorov Smirnov test.
Comment: Re: your last question. Definition from [corresponding Wikipedia article](http://en.wikipedia.org/wiki/Normal_distribution): "If $\mu = 0$ and $\sigma = 1$, the distribution is called the **standard normal distribution** or the **unit normal distribution** denoted by $N(0,1)$" (emphasis mine; the standard normal distribution is the one that peaks at ~0.4).
Comment: It's not clear what function "bell shaped" serves in your question. A normal density has a bell shape (but one can have a distinctly-bell shaped density that's non normal). If you removed it, so the question just said "normal distribution", would that change the intent of the question?
Comment: I meant height of the density curve of normally distributed data.
Comment: I was thinking of all tests of comparing means, as is generally done. Thanks for your explanations.
Comment: Thanks. I should have read the article more carefully. However, it is usually not emphasized while recommending comparison of groups that F-test should also be done along with tests to compare means. Alternatively, is it recommended that the KS test should be done in almost all comparison of groups so that difference in standard deviation is also picked up even if the means are not different?
Comment: rnso -- don't ask new substantive questions in comments. That's actually a question that's been asked a number of times, you should be able to find some good posts on it.
Answer: The height of the mode in a normal density is $\frac{1}{\sqrt{2\pi}\sigma}\approx \frac{.3989}{\sigma}$ (or roughly 0.4/$\sigma$). You can see this by substituting the mode (which is also the mean, $\mu$) for $x$ in the formula for a normal density.
So there's no single "ideal height" -- it depends on the standard deviation
edit: see here:

Indeed the same thing can be seen from the wikipedia diagram you linked to -- it shows four different normal densities, and only one of them has a height near 0.4
A normal distribution with mean 0 and standard deviation 1 is called a 'standard normal distribution'
Comment: It depends on how you're defining 'peakedness'. If you mean "height of peak, without regard for relative spread" then no, as you can see from the diagram in your question, or the one in my answer. If you adjust for the spread (i.e. standardize), then all normal densities standardized to have $\sigma=1$ have the same height at the mode, but an infinite number of unimodal (but non-normal) distributions could have exactly the same height at the mode (it's trivial to construct one, for example via finite mixture distributions).
Comment: So peakedness does not indicate normality or otherwise? Apologies of a very basic question.
Comment: Please see the edit in my question above.
Comment: @Glen_b Where did you get the mode height formula from? I'm having trouble finding a derivation.
Comment: Never mind, I figured it out. You just set $x = \mu$ and find the value of the PDF. If you really want to, you can also confirm that $x=\mu$ is a maximum via differentiation, but in this case that seems overkill.

Height of a Normal distribution curve


R: Setting an F-statistic to determine variables for a multiple linear regression model

Question: I am trying to understand the steps behind the linear regression process. I already have a linear model like:
lmodel1 <- lm(y~x1+x2+x3, data=dataset)
for which R calculates several different things (Coefficients, Intercept, Residuals, F-statistic and p-value) among  others.
At this point, I am mostly interested in F-statistic and p-value.
So far, I have concluded to the following:
The process is iterative and begins taking under consideration every variable. In order to achieve an optimal y some x variables have to be "taken out". This comes as a result of calculating F-statistic, which quantifies the importance of each xi and the dependent variable y.
When F value is smaller than p-value(?) that variable is removed.
Next step of the process is to compare that F-statistic of a xi independent variable, with an F-to-enter and F-to-remove in order see if the removed variable will be re-inserted to the equation.(?)
Now, please do correct me if i am wrong regarding the steps described above.
Is that what happens under lm()'s hood. Are those the right variables?
R-wise speaking how does these values can be shown, inserted or calculated in a multiple linear regression model.?
How is ANOVA related to the above?
I am afraid R's summary and help  take too much for granted.
Answer: The lm function calculates the coefficients, but it does not calculate F-statistics or p-values, you need to run another function (summary, anova, etc.) on the results to see p-values.  What the p-values mean depend on which function calculated them and how it was called.  You seem to have run at least some of these functions based on your question, but it is not clear which ones and how they were run.
You first need to decide what question or questions you are trying to answer.  Then based on those questions you can decide on which functions to run on your regression and which tests to examine (sometimes (often) additional tests are included which should just be ignored).
Also, the F-statistic (or t-statistic) is a step to a p-value, we don't compare p-values to F-statistics, we compute p-values from F-statistics.
When you run summary on a linear regression it computes an overall F-test (reported near the bottom) that compares the full model to an overall mean.  This answers the question of if any subset (including the whole set) of the potential predictors are significantly related to the response.  The summary function also does an adjusted t-test for each predictor testing if that predictor adds significantly to the prediction above and beyond the effect of all other predictors in the model.
The anova function when given a single regression object does a set of sequential tests.  Reading from top to bottom the first test is that the first predictor is significant by itself, then the second predictor is significant above and beyond the 1st (but ignoring the others), the 3rd test is that the 3rd predictor adds significantly above and beyond the 1st 2, etc.  These tests are really only meaningful if you put the predictors in a specific order to begin with because of the tests of interest.  This functionality is mainly left over from the days when a single analysis took hours or even days.  Now we can just fit a new model with a couple keystrokes and a few seconds, so the tests of interest don't need to be as planned out ahead of time.
If the anova function is given 2 or more (nested) regression models then it does a full and reduced model F-test where the null hypothesis is that the simpler model fits just as well as the fuller model and the alternative is that the full model adds information beyond what is in the simpler model (if more than 2 models then it compars 1 vs. 2, then 2 vs. 3, etc.).  This tests all the terms in the full model but not the reduced simultaneously.
I have not figured out what question stepwise regression answers, just that it does not answer any of the questions that I am interested in.  The consensus is moving away from doing automated stepwise regression.
Comment: i am reading your question, trying to comprehend it. Give me a bit more please
Comment: @KapelNick, which question?
Comment: Scratch that, I meant your answer..
Comment: @KapelNick, so which parts don't you understand or need more explanation about?
Comment: alright i will post another question, including some of the things your answer is implying and i will make sure notifying you.


Total of multiple computed elements

Question: I am trying to create a quote form where I can add two computed twig elements together to give a total of the two. I have created the two computed elements to give a total based on the user inputs but when I then create the third computed element it doesn't add the two together. It just gives me a value of two. Below is the export of the Webform. What am I doing wrong please or am I going about this wrong? Any help to resolve this would be greatly appreciated :)
Drupal version 8.9.13 - Webform Version: 6.0.2

<code>uuid: b6d7a837-6396-4fe5-af62-9a15bbf50cb2
langcode: en
status: open
dependencies: {  }
open: null
close: null
weight: 0
uid: 1
template: false
archive: false
id: quote_builder
title: 'Quote builder'
description: ''
category: ''
elements: |
  how_many_sockets_:
    '#type': textfield
    '#title': 'How many sockets?'
  cost_per_socket:
    '#type': hidden
    '#title': 'Cost per socket'
    '#default_value': '45'
    '#prepopulate': true
  total_cost_of_sockets:
    '#type': webform_computed_twig
    '#title': 'Total cost of sockets'
    '#display_on': view
    '#template': '{{( data.how_many_sockets_ * data.cost_per_socket )}}'
    '#store': true
  how_many_light_fittings_including_down_lights_:
    '#type': textfield
    '#title': 'How many light fittings? (including down lights)'
  cost_per_light_fitting:
    '#type': hidden
    '#title': 'cost per light fitting'
    '#default_value': '35'
    '#prepopulate': true
  total_cost_of_light_fittings:
    '#type': webform_computed_twig
    '#title': 'total cost of light fittings'
    '#display_on': view
    '#template': '{{( data.how_many_light_fittings_including_down_lights_ * data.cost_per_light_fitting )}}'
    '#store': true
  total_cost_of_sockets_and_light_fittings:
    '#type': webform_computed_twig
    '#title': 'Total cost of sockets and light fittings'
    '#template': '{{( data.total_cost_of_sockets + data.total_cost_of_light_fittings )}}'
    '#store': true
    '#ajax': true
css: ''
javascript: ''
settings:
  ajax: false
  ajax_scroll_top: form
  ajax_progress_type: ''
  ajax_effect: ''
  ajax_speed: null
  page: true
  page_submit_path: ''
  page_confirm_path: ''
  page_theme_name: ''
  form_title: both
  form_submit_once: false
  form_exception_message: ''
  form_open_message: ''
  form_close_message: ''
  form_previous_submissions: true
  form_confidential: false
  form_confidential_message: ''
  form_disable_remote_addr: false
  form_convert_anonymous: false
  form_prepopulate: false
  form_prepopulate_source_entity: false
  form_prepopulate_source_entity_required: false
  form_prepopulate_source_entity_type: ''
  form_reset: false
  form_disable_autocomplete: false
  form_novalidate: false
  form_disable_inline_errors: false
  form_required: false
  form_unsaved: false
  form_disable_back: false
  form_submit_back: false
  form_autofocus: false
  form_details_toggle: false
  form_access_denied: default
  form_access_denied_title: ''
  form_access_denied_message: ''
  form_access_denied_attributes: {  }
  form_file_limit: ''
  share: false
  share_node: false
  share_theme_name: ''
  share_title: true
  share_page_body_attributes: {  }
  submission_label: ''
  submission_log: false
  submission_views: {  }
  submission_views_replace: {  }
  submission_user_columns: {  }
  submission_user_duplicate: false
  submission_access_denied: default
  submission_access_denied_title: ''
  submission_access_denied_message: ''
  submission_access_denied_attributes: {  }
  submission_exception_message: ''
  submission_locked_message: ''
  submission_excluded_elements: {  }
  submission_exclude_empty: false
  submission_exclude_empty_checkbox: false
  previous_submission_message: ''
  previous_submissions_message: ''
  autofill: false
  autofill_message: ''
  autofill_excluded_elements: {  }
  wizard_progress_bar: true
  wizard_progress_pages: false
  wizard_progress_percentage: false
  wizard_progress_link: false
  wizard_progress_states: false
  wizard_auto_forward: true
  wizard_auto_forward_hide_next_button: false
  wizard_keyboard: true
  wizard_start_label: ''
  wizard_preview_link: false
  wizard_confirmation: true
  wizard_confirmation_label: ''
  wizard_track: ''
  wizard_prev_button_label: ''
  wizard_next_button_label: ''
  wizard_toggle: false
  wizard_toggle_show_label: ''
  wizard_toggle_hide_label: ''
  preview: 0
  preview_label: ''
  preview_title: ''
  preview_message: ''
  preview_attributes: {  }
  preview_excluded_elements: {  }
  preview_exclude_empty: true
  preview_exclude_empty_checkbox: false
  draft: none
  draft_multiple: false
  draft_auto_save: false
  draft_saved_message: ''
  draft_loaded_message: ''
  draft_pending_single_message: ''
  draft_pending_multiple_message: ''
  confirmation_type: page
  confirmation_title: ''
  confirmation_message: ''
  confirmation_url: ''
  confirmation_attributes: {  }
  confirmation_back: true
  confirmation_back_label: ''
  confirmation_back_attributes: {  }
  confirmation_exclude_query: false
  confirmation_exclude_token: false
  confirmation_update: false
  limit_total: null
  limit_total_interval: null
  limit_total_message: ''
  limit_total_unique: false
  limit_user: null
  limit_user_interval: null
  limit_user_message: ''
  limit_user_unique: false
  entity_limit_total: null
  entity_limit_total_interval: null
  entity_limit_user: null
  entity_limit_user_interval: null
  purge: none
  purge_days: null
  results_disabled: false
  results_disabled_ignore: false
  results_customize: false
  token_view: false
  token_update: false
  token_delete: false
  serial_disabled: false
access:
  create:
    roles:
      - anonymous
      - authenticated
    users: {  }
    permissions: {  }
  view_any:
    roles: {  }
    users: {  }
    permissions: {  }
  update_any:
    roles: {  }
    users: {  }
    permissions: {  }
  delete_any:
    roles: {  }
    users: {  }
    permissions: {  }
  purge_any:
    roles: {  }
    users: {  }
    permissions: {  }
  view_own:
    roles: {  }
    users: {  }
    permissions: {  }
  update_own:
    roles: {  }
    users: {  }
    permissions: {  }
  delete_own:
    roles: {  }
    users: {  }
    permissions: {  }
  administer:
    roles: {  }
    users: {  }
    permissions: {  }
  test:
    roles: {  }
    users: {  }
    permissions: {  }
  configuration:
    roles: {  }
    users: {  }
    permissions: {  }
handlers: {  }
variants: {  }
</code>
Answer: Unfortunately, computations cannot draw values from other computed elements. You always have to go back to the original elements.
Here is the working Twig code for the "Total cost of sockets and light fittings" element:
<code>{{
  data.how_many_sockets_ * data.cost_per_socket +
  data.how_many_light_fittings_including_down_lights_ * data.cost_per_light_fitting
}}
</code>

Total of multiple computed elements


What is the maximum advantage from first to last qualified in a FIS slalom first half?

Question: What is the maximum delay with a skier is qualified for the second half in a slalom race?
Today (2018 Jan 3rd) at Zagreb ladies Slalom Mikaela Shiffrin is leading 4"61 on the last qualified (Moellg and Truppe ex equo), is this a record in FIS Alpine Ski World Cup?
Answer: As far as I can tell, there is no such limit. The official Rules for the FIS Alpine Ski World Cup define only:

3.6 Limitation for SL / GS / DH in 2 runs
Limitation for the 2nd run (Slalom / Giant Slalom / DH): Only the first 30 competitors from the 1st run are qualified. This limitation is not valid for the Alpine Combined (see art. 9.5.1).

(And as noted, the Alpine Combined does not have even that limit:

9.5.1 Alpine Combined
All competitors who complete the 1st run correctly have the right to start in the 2nd run.

)
I did not find any more stringent criteria. The more general International Ski Competition Rules define the following for slalom races (and similarly for the other race types):

806.2 Limitations in the Second Run
The Jury has the right to reduce the number of competitors for the second run to half on the first run start list. The decision has to be made no later than one hour before the start of the first run.

But again, no specific time limit.
However, note that competitors who have more than 108% of the total time of the winner will receive no World Cup points:

10.2 Time difference from the winning time
If a competitor's overall time (at combined events the total running times of both events counting for the Combined) is more than eight (8) percent greater than the winning time, irrespective of the rank achieved, no points will be awarded


Expected type 'Number' got 'list[list]' instead

Question: I have some nodes who transmit power and I have their positions in a list that I then use to calculate the power receiver from every node to the other so that's what I do:
Node_positions = [[0,100],[100,0],[0,0],[100,100]]
distances_Ascending = [[]] * len(list(itertools.combinations(Node_positions , 2)))
Counter = 0
for p0, p1 in itertools.combinations(Node_positions , 2):
    distances_Ascending[Counter] = (math.sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2))
Counter += 1

Powers_Ascending = [[]] * len(list(itertools.combinations(Node_positions , 2)))

counter = 0
row = 0
next_no = sheet.nrows - 1
for elements in range(len(list(itertools.combinations(Node_positions , 2)))):
Powers_Ascending[elements] = 10 * (math.log10((sheet.cell_value(row, 0) * 1e-3))) - 20 * (
    math.log10((4 * math.pi * distances_Ascending[elements] * 2.4e9) / 3e8))
counter += 1
if counter == next_no:
    row += 1
    counter = 0
    next_no -= 1

Pycharm for python highlights this part:
(4 * math.pi * distances_Ascending[elements] * 2.4e9)

and says:
 Expected type 'Number' got 'list[list]' instead

What does that mean?Isn't distances_Ascending already a number which represents the distances between nodes and all the inside the log is a number already?
Where is the problem?
Answer: Looks to me that distances_Ascending is a list of lists
>>> foo = [[]] * 3
[[], [], []]

so it is complaining because you are mulitiplying a list and a float.
From your code seems that you are incrementing the counter Count only after the end of the loop so you are only assigning to the first element of the list.
All the other elements are still lists from how the variable is initialised and you get the error on access.
The minimal change that you need to do is move the Counter variable inside the loop:
Node_positions = [[0,100],[100,0],[0,0],[100,100]]
distances_Ascending = [[]] * len(list(itertools.combinations(Node_positions , 2)))
# if you want to intialise the list it is better to do
# [0] * len(...your_calculations...)
# otherwise use the append() method of the list in the loop
Counter = 0

for p0, p1 in itertools.combinations(Node_positions , 2):
    distances_Ascending[Counter] = math.sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2)
    Counter += 1 # <--- this was not properly indented, hence the error

Powers_Ascending = [[]] * len(list(itertools.combinations(Node_positions , 2)))
# same init comment as for distances_Ascending
counter = 0
row = 0
next_no = sheet.nrows - 1

for elements in range(len(list(itertools.combinations(Node_positions , 2)))):
    Powers_Ascending[elements] = 10 * (math.log10((sheet.cell_value(row, 0) * 1e-3))) - 20 * (math.log10((4 * math.pi * distances_Ascending[elements] * 2.4e9) / 3e8))
    # this part was also badly indented
    counter += 1
    if counter == next_no:
        row += 1
        counter = 0
        next_no -= 1

A few pointers for your coding:

You don't really need to allocate lists, you can just use them in the loop by appending data to them.
try not to change the type of data you are storing unless you ensure that the reader can easily follow up.
try to use the standard python style conventions, it will help you a lot in coding with other people (see PEP 8)
Comment: but im saying `distances_Ascending[elements]` and this represents a number not a list of lists.
Comment: The definition of distances_Ascending generates a list of lists, this confused me since I was assuming that you were using it that way. The whole list allocation is not needed there since lists are dynamic, you can just assign the values in the loop. Now I see that the problem might be that you are incrementing the counter `Count` outside the loop, so you only set the first value as a number.
Comment: So what exactly should I change in my code so that the error goes away I don't quite get it.
Comment: It should be sufficient to put the counter inside the loop, let me update the answer with a snippet.


Web scrapping com python não traz a informação completa da pagina html

Question: Saudações pessoal, estou tentando utilizar python para poder pegar as informações da pagina http://www.nfce.se.gov.br/portal/painelMonitor.jsp , é uma pagina da sefaz onde tem o status de ping dos envios da NFC-e, porém ao usar o soup com python pra puxar as informações da pagina, ela nao me traz as informações que estão la em tempo real, ele não ta me trazendo todas as informações que eu consigo ver com o inspect F12 do browser, alguem teria alguma ideia do que pode ser ? Segue abaixo o código que estou utilizando:
#!/usr/bin/env python

# -*- coding: UTF-8 -*-

import requests
from bs4 import BeautifulSoup

page = requests.get('http://www.nfce.se.gov.br/portal/painelMonitor.jsp')
soup = BeautifulSoup(page.text, 'html.parser')

autorizador = soup.find(id='tabDados')

print(autorizador.prettify())

Answer: As informações da página são preenchidas por código em Javascript que é executado depois que a chave é carregada. Esse codigo faz as requisições em tempo real aos vários servidores, e etc...
Com tecnologias de web-scrapping normais não é possível obter esses dados. Quando é assim, você tem duas opções:
Tnetar olhar o código da página (como baixado pelo Python - com requests ou o framework de scrapping que estiver usando) ,  e fazer a engenharia reversa das URLs consultadas pelo Javascript e tentar fazer as mesmas consultas a partir do seu código em Python . Nesse caso, estaria até favorável fazer algo assim já que o Javascript que faz as operações não está obfuscado. Além de um pouco de código na própria página que você carrega, a maior parte do código em Javascript está na URL http://www.nfce.se.gov.br/portal/framework/js/nfce/nfc-e.js .
Essa opção, dependendo de quais dados você precisa e de quanto complexo é o código pode ser muito complicada (se for uma página com Javascript obfuscado nem tente começar por aí).
A outra opção é usar em vez do beautifulsoup, o Selenium - O selenium usa um browser "real" (embora, na configuração atual, sem uma janela visível), e roda todo o javascript da página como numa navegação normal, inclusive efetuando outros requests de HTTP. E ele expõe uma API que permite que você veja o HTML gerado pelo javascript executado.
Perceba que a grande diferença é que o Selenium realmente inclui um navegador completo, com um engine javascript (por padrão ele usa o firefox, mas isso é configurável) - e permite que seu programa em Python veja a página como ela ficou enquanto o Javascript está em execução.
Esta segunda opção definitivamente é mais apropriada para você seguir, uma vez que não vai estar sujeito a ficar horas analizando o código Javascript da página e tentando replicar o seu comportamento, apenas para em algumas semanas ou meses, os autores mudarem o código e você ter que refazer todo o trabalho. Com Selenium você pega o HTML já renderizado da página e pode proceder a isolar os dados que precisa com o Beautfulsoup normalmente.
Answer: O código abaixo usa lxml para parsear a página diretamente da URL:
import requests, lxml.html

resp = requests.get('http://www.nfce.se.gov.br/portal/ConStatusAuto?Origem=1')
doc = lxml.html.fromstring(resp.text)
for tr in doc.xpath('//tr'):
    nome = tr[0].text_content().strip()
    print(nome.ljust(25), '|'.join('{: >7}'.format(td.text_content().strip())
        for td in tr.xpath('.//td')[1:]))

Resultado:
SEFAZ Amazonas                   |  783ms|  900ms|  361ms|    0ms|  900ms|  661ms|    0ms|  806ms|   50ms|  783ms|  783ms|  196ms|    0ms|    0ms|    0ms
SEFAZ São Paulo                  |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Paraná                     |  429ms|1s808ms|  559ms|  433ms|1s808ms|  620ms|  429ms|  799ms|  495ms|  512ms|  521ms|  518ms|    0ms|    0ms|    0ms
SEFAZ Goias                      |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Mato Grosso                |    0ms|  896ms|  310ms|  609ms|  861ms|  301ms|    0ms|  896ms|  325ms|    0ms|  476ms|  159ms|    0ms|    0ms|    0ms
SEFAZ Rio Grande do Sul          |  852ms|1s886ms|  974ms|  852ms|1s166ms|  964ms|  871ms|1s886ms|  986ms|  867ms|  986ms|  940ms|    0ms|    0ms|    0ms
SEFAZ Virtual RS                 |  761ms|5s854ms| 1s11ms|  830ms|1s245ms|  964ms|  761ms|5s854ms| 1s65ms|  899ms|  969ms|  925ms|    0ms|    0ms|    0ms
SEFAZ Mato Grosso do Sul         |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Ceará                      |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Minas Gerais               |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Pernambuco                 |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms

Comment: salvou minha vida cara, valeu, era isso mesmo que eu queria, agora vc saberia dizer como trazer somente o SEFAZ Virtual RS ?
Comment: outra coisa, como vc chegou nesse link http://www.nfce.se.gov.br/portal/ConStatusAuto?Origem=1 ?
Comment: @RafaelXavierSuarez ao solicitar a url, o servidor da SE retornará todos os dados. Cabe a você filtrar os que você quer
Comment: @RafaelXavierSuarez o link eu cheguei inspecionando a página no navegador através da aba "Network"


How to download a PDF document from Google Docs and display it in the browser?

Question: Using the code shown below, the PDF document seems not to be a valid PDF format. The browser displays the message, "Failed to load PDF document." If I save the download to a file and open it in Adobe Reader, it gives the message, "There was an error opening this document."
I can open and download the document manually within Google Docs. So, it is a valid PDF document.
I'm using C#, ASP.NET, and Google.Documents.
<code>        // get the document to download
        Feed<Document> feed = request.GetEverything( );
        foreach( Document entry in feed.Entries )
        {
            if( entry.AtomEntry.AlternateUri.ToString( ) == DocumentAltUri )
            {
                document = entry;
                break;
            }
        }

        using( Stream stream = request.Download( document, Document.DownloadType.pdf ) )
        {
            StreamReader reader = new StreamReader( stream );
            string content = reader.ReadToEnd( );
            reader.Close( );

            Response.ClearContent( );
            Response.ContentType = "application/pdf";
            Response.AddHeader( "Content-Length", content.Length.ToString( ) );
            Response.AddHeader( "Content-Disposition", "inline;" );
            Response.Write( content );
            Response.Flush( );
            Response.Close( );
            Response.End( );
        }
</code>
UPDATE: Resolved. code shown below.
Answer: You might take some ideas from the following post:
code to download PDF file in C#
It uses an additional header: content-disposition.
Comment: There is a Content-Disposition header. I have used the "Response" code successfully to display a PDF file that is stored locally.
Answer: The problem was that the file content was being read in as text, it needs to be Byte[].
Updated code:
<code>        using( Stream stream = request.Download( document, type ) )
        {
            long length = 0;
            Response.ClearContent( );
            Response.ContentType = contentType;

            int nBytes = 2048;
            int count = 0;
            Byte[] arr = new Byte[nBytes];
            do
            {
                length += count = stream.Read( arr, 0, nBytes );
                Response.OutputStream.Write( arr, 0, count );
            } while( count > 0 );

            Response.AddHeader( "Content-Disposition", "inline;filename=" + filename + fileext);
            Response.AddHeader( "Content-Length", length.ToString( ) );
            Response.Flush( );
            Response.Close( );
            Response.End( );
        }
</code>


exponents of rational numbers close to integers

Question: I'm not sure how you can prove the base case for the answer to this question. The base case states:
Lemma. If $x \ge 1$ is a rational number and $\alpha\ne 0$ is a real number such that $\lim_{n\to\infty}\alpha x^n-m_n=0$ where $m_n\in\mathbb{N},$ then $x\in\mathbb{Z}$.
Does it also hold if $x$ can be real instead of just rational?
Some attemps:
I've thought about raising $m_n$ to some power $p$ and then doing the reverse by raising to power $1/p$ so it gives a tighter bound around $m_n$, but this doesn't appear to work since there may be a lot of integers besides $m_n^p$ within the bound.
Comment: I don't have a handle on $m_n$.  Where does it come from or how is it defined?
Comment: @B.Goddard It can be anything, if the limit does exist then for large enough $n$ it should always be the closest integer, by taking $\epsilon = 0.5$.
Answer: Here's a proof assuming $x$ is rational.  Write $x=\frac{a}{b}$ for $a,b\in\mathbb{N}$ in lowest terms.  Choose $\epsilon>0$ such that $x\epsilon<\frac{1}{2b}$ and $\epsilon<\frac{1}{2b}$ (actually, the latter is automatic since $x\geq 1$).  Choose $N$ such that $|\alpha x^n-m_n|<\epsilon$ for all $n\geq N$ and such that $m_N\neq 0$ (the latter is possible since $x\geq 1$ and $\alpha\neq 0$).  In particular, for any $n\geq N$, we can write $$\alpha x^n=m_n+\delta$$ where $|\delta|<\epsilon$ ($\delta$ depends on $n$).  Multiplying by $x$, we get $$\alpha x^{n+1}=xm_n+\delta x.$$  Note that $xm_n$ is a rational number with denominator $b$, and $|\delta x|<\frac{1}{2b}$.  If $xm_n$ were not an integer, then it would be at least $\frac{1}{b}$ away from an integer, and so $xm_n+\delta x$ would be at least $\frac{1}{2b}$ away from an integer.  But by hypothesis, $\alpha x^{n+1}$ is within $\epsilon$ of $m_{n+1}$, and $\epsilon<\frac{1}{2b}$.  Thus $xm_n$ must be an integer, and clearly in fact we must have $xm_n=m_{n+1}$.
Thus $xm_n=m_{n+1}$ for all $n\geq N$.  But this means $x^km_N=m_{N+k}$ is an integer for all $k\in\mathbb{N}$.  This implies $m_N$ is divisible by $b^k$ for all $k$.  Since $m_N\neq 0$, this is only possible if $b=1$, i.e. if $x$ is an integer.
Answer: Here is a proof for more general statement: http://artofproblemsolving.com/community/c6h4556p334225
It's given as a lemma in the solution to problem 27 (section 4.1) in Russian 1987 book
 В.А.Садовничий, А.А.Григорьян, С.В.Конягин "Задачи студенческих математических олимпиад"
("Problems of mathematical olympiads for university students")


Can I use this attentuator to attentuate a passive stage monitor

Question:
I have a power amp that connects to a passive monitor which connects to a second passive monitor (I don't know if saying they're connected in series is the right terminology). I'd like to attentuate the second monitor without changing the volume of the other, so I figured putting an attentuator in between the two that can pass power may work. But as I don't want to waste money/damage equipment, I'm asking for a second opinion. Would connecting this in between work?
If not, how can I make the second monitor quieter than the first?
Shure A15AS Switchable Attenuator (15, 20, 25 dB), Passes Phantom Power https://www.amazon.ca/dp/B0002J1JKY/ref=cm_sw_r_cp_api_wpPyzbXXG21T8
Comment: That attenuator is meant for small signals, line level or microphone level.  It isn't going to be happy connected to the output of a power amplifier.
Comment: Short answer: nope.
Answer: No, that attenuator will not work. It's designed to connect to a mic, which will push out a very small electrical signal compared with that of an amp going to a speaker. That apart, with XLRs, chances are it won't fit physically.
To attenuate the signal, you are going to need something bigger that will dissipate heat produced while trying to sap the power to that speaker. It's possible with a big pot., which will do that and be adjustable, too.
A far more workable system is to either use a speaket with a high impedence - but watch the overall impedence match to the amp., or use another mixer/amp to feed that speaker. A lot of mixer amps will already have the facility to re-mix signals to another monitor/powered monitor.


JQuery Não permitir Click em um Botão que tenha uma determinada Classe CSS

Question: Bom dia Pessoal, tenho uma aplicação com JQuery EasyUI, e sempre chamo as ações de click dos botões com o JQuery, conforme exemplo abaixo:
<code>$("#btnEditar").click(function(){
  ...
});
</code>
Acontece que quando ao se clicar no botão e o mesmo estiver desabilitado, continua executando a ação de Click do JQuery.
Gostaria de saber se seria possível executar o CLick do Botão apenas se o mesmos estiver sem determinada classe css, no meu caso .l-btn-disabled. Efetuei o teste conforme abaixo porém não funcionou:
<code>$("#btnEditar").not(".l-btn-disabled").click(function(){
  ...
});
</code>
Grato pela atenção.
Comment: esse elemento `#btnEditar` é um `button` ou um `input[type=button]`?
Answer: Podes usar assim, fazendo uso do <code>:not()</code>:
<code>$("#btnEditar:not('.l-btn-disabled')").click(function(){
</code>
Porem repara que estás usar um ID no teu seletor, e ID têm de ser únicos. Usa classes nos buttons que queres selecionar em vêz de ID.
Exemplo: https://jsfiddle.net/my78aLr1/


Port number required after url name?

Question: I have followed along a digital ocean tutorial to deploy my node.js app onto VPS. Everything is working, but instead of reaching the app from myDomain.com, it's only available through myDomain.com:3700. myDomain.com only shows "Success! Virtual host is set up!"
/etc/nginx.sites-available/default:
server {
    listen 3700;

server_name myDomain.com;

location / {
    proxy_pass http://127.0.0.1;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    }
  }

Oddly, if I change it to:
server {
    listen 80;

server_name myDomain.com;

location / {
    proxy_pass http://127.0.0.1:3700;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    }
}

and enter sudo nginx -s reload, nothing changes.
in my node app, I have:
...
var port = 3700;
...

Comment: Have you tried changing your apps port variable to 80 instead of 3700 to match your nginx config?
Comment: You may need to restart nginx after changing the set of ports that are being listened on.
Answer: The message about the successful setup you are getting is from Apache web server, which is already running on port 80. Nginx is actually failing to bind to port 80 in your case.
I'm not exactly sure how you're setting up node.js and if Apache is supposed to play a role, but you have to either remove apache2 if it's not needed or reconfigure it to run on a different port.

Port number required after url name?


Como carregar uma página dentro de uma div com Angular

Question: Fala galera!!!
Estou com uma mega dúvida e não consigo solucionar. Estou desenvolvendo uma aplicação para o TCC da minha faculdade em Angular. Possuo um menu e dentro desse menu há opções para navegar pelo site, porém ao invés de mudar de página, gostaria que essa nova página fosse carregada em uma div que está no mesmo conteúdo, vou postar o código.
Aqui está o meu arquivo com nome de index.component.html que possui o menu.

Cadastro Tele

Configuracoes

    Tem um texto aqui pra teste

Gostaria de saber como faço pra ao clicar na Opção de Menu Cadastro Tele carregar o conteúdo dentro da div carregaPaginas.
Tks!!

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpModule } from "@angular/http";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { DataFormModule } from './pages/data-form/data-form.module';
import { HttpClientModule } from '@angular/common/http';
import { LoginComponent } from './pages/login/login.component';
import { Error404Component } from './pages/error404/error404.component';
import { IndexComponent } from './pages/index/index.component';

@NgModule({
  declarations: [
   AppComponent,
   LoginComponent,
   Error404Component,
   IndexComponent,
 ],
 imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule,
HttpModule,
ReactiveFormsModule,
DataFormModule

],
  providers: [],
  bootstrap: [AppComponent]
     })
  export class AppModule { }
e o meu app.component.html
<router-outlet></router-outlet>

Eu preciso que inicie no /login que vem do LoginComponent e que ao logar vá para o IndexComponent (/index) e dentro do index eu consiga utilizar a opção de rota que eu perguntei lá em cima pra carregar dentro da div carregaPaginas.
meu arquivo app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DataFormComponent } from './pages/data-form/data-form.component';
import { LoginComponent } from './pages/login/login.component';
import { IndexComponent } from './pages/index/index.component';
import { Error404Component } from './pages/error404/error404.component';

const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'login'},

{ path: 'login', component: LoginComponent },
{ path: 'dataForm', component: DataFormComponent },

{ path: '**', component: Error404Component }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Answer: Isso mesmo, esta faltando a directiva router-outlet,
Uma saída para roteador emitir um evento de ativação sempre que um novo componente estiver sendo instanciado.
routerLinkActive permite você adicionar um seletor css, caso seja ativado.

Cadastro Tele

Configuracoes

    <router-outlet></router-outlet>

Comment: Eu teria que colocar o meu principal como o app-module ? se eu não colocar o router outlet lá ele some tuudo
Comment: O meu  está dentro do arquivo app.module.ts, se eu tirar ele de lá some todo o código da página, eu gostaria que o aplicativo iniciasse no localhost:4200/login e ao logar ir para o index.html onde eu configuraria todas essas rotas, porém se tirar o router outlet de dentro do app module some todo o código
Answer: Troque essa div pela tag <router-outlet></router-outlet>, é nela que vai ser carregada o seus componentes
No seu módulo, configure as rotas e importe
const appRoutes: Routes = [
  { path: 'cadTel', component: cadTelComponent },
  { path: 'config', component: configComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ]
})
export class AppModule { }

De uma olhada na documentação
Comment: Não funcionou :(
Comment: Eu teria que colocar o meu principal como o app-module ? se eu não colocar o router outlet lá ele some tuudo
Comment: O meu  está dentro do arquivo app.module.ts, se eu tirar ele de lá some todo o código da página, eu gostaria que o aplicativo iniciasse no localhost:4200/login e ao logar ir para o index.html onde eu configuraria todas essas rotas, porém se tirar o router outlet de dentro do app module some todo o código
Comment: Poste o código do seu `app-module.ts` por favor
Comment: Fiz um novo post (respondi minha pergunta) pra você pode ver. Da uma olhadinha se possível@@@


C#: How many bytes to read from a NetworkStream of a chat using a Unicode encoding?

Question: I've followed a tutorial of a chat using the ASCII encoding to send/receive messages, and it used to read 4096 bytes in a row to write on the chat client. But now I've changed the encoding to unicode and I know that Unicode use more bytes per character.
My code is the following:
taskOpenEndpoint = Task.Factory.StartNew(() =>
        {
            while (true)
            {
                serverStream = tcpClient.GetStream();
                byte[] message = new byte[4096];
                int bytesRead = 0;
                try
                {
                    bytesRead = serverStream.Read(message, 0, 4096);
                }
                catch (Exception ex)
                {
                    if(flag_chiusura == false)
                        MessageBox.Show(ex.Message);
                    return;
                }
                UnicodeEncoding encoder = new UnicodeEncoding();
                AddMessage(encoder.GetString(message, 0, bytesRead));
                Thread.Sleep(500);
            }
        });

Should I change the number of bytes read, now that I'm using the Unicode encoding?
Comment: Unfortunately this implementation is naive and faulty (you might not see anything bad happen, but it's a classic case of "most of the time it will seem to work fine"). The problem is that `Read` won't necessarily give you back what `Write` sent, so messages sent in one go might be delivered in any number of pieces. If this does happen, the Unicode version will break harder than the ASCII one. There is no correct answer to your question because the question is based on the false premise that there is some "correct" amount of bytes to read.
Answer: Switching to Unicode certainly will have an impact on this code.  It is buggy code, it assumes that you'll read a "packet" of data from the socket.  This is only the case if you use a UDP socket, TCP sockets implement a stream.  Where the number of bytes you read from a socket is entirely unpredictable and will not match the number of bytes transmitted at the other end of the network connection.
Your Thread.Sleep() call is a workaround of sorts.  It is however an extremely evil kind of fix.  For one, it is placed at the wrong spot, sleeping after you read instead of before you read.  Much worse, it provides no guarantee that the bug is actually fixed, it the app on the other end of the wire also suffers a delay, when the machine is heavily loaded for example, then you still won't read a "packet".  This doesn't happen nearly often enough to ever have a shot at debugging the problem.  And that this is a problem on a machine that's a thousand miles away of course makes it entirely impossible.
So using Unicode increases the odds that your app will crash.  The Encoder will throw when it is asked to decode a partial byte sequence.
You need to fix the bug.  Delete the Thread.Sleep() call.  Turn a TCP stream in a stream of packets by first transmitting the number of bytes in the packet.  The receiver can now read the length and knows how often to loop, repeatedly calling Read() until it has received all the bytes.  After this, decoding can of course never cause any trouble.
Comment: Thanks. How to turn a tcp stream into a stream of packets? Which library should I use?

I've updated the code regardind the task.
Comment: Wow, TCP doesn't use packets?  Guess I better turn in my copy of "Illustrated"...  Seriously.  4096 is a bit big, Hopefully an 8-byte message length will never ever get split up eh Hans?  If he could wait for the read buffer to reach n chars (or bytes) he ought to be OK.  Unfortunately `NetworkStream.Length`, glaringly, isn't supported.  I seem to recall available from WINSOCK, knowing window size, but apparently accepted wisdom says reading 1 byte at a time is the only way to avoid blocking.  A sledgehammer: Fill a raw byte[16384] 1 byte at a time re-decoding till 4096 characters are counted.
Comment: @user3603880 4096 may be too big for a "real" packet... (sure you could use IP fragmentation, but why?)
Comment: @ebyrob I haven't understood what you are saying, is it ok or not?
Comment: @user3603880 The 4096 (or larger 16384) and comment about fragmentation is more about UDP.  TCP is generally the simpler implementation to deal with in most scenarios.
Comment: "The Encoder will throw when it is asked to decode a partial byte sequence."  - Does that mean the three-parameter constructor with `bool throwOnInvalidBytes` doesn't work?
Answer: Something like the following would work without changing your protocol:
Note: It's good to have some notion of record/start/end other than just block size.
taskOpenEndpoint = Task.Factory.StartNew(() =>
    {
        UnicodeEncoding enc = new UnicodeEncoding(false, false, false);
        while (true)
        {
           serverStream = tcpClient.GetStream();
           byte []message = new byte[16384];
           int bytesRead = 0;
           try {

     // --------- first version may avoid blocking:
               while( encoder.GetCharCount(message, 0, bytesRead) < 4096
                  && bytesRead < message.Length )
               {
                  if( serverStream.DataAvailable /* && !timed_out */ )
                      message[bytesRead++] = serverStream.ReadByte();
                  else
                      Thread.Sleep(10);  // Better to wait than sleep...
               }

     // --------- second version will fully block:
               while( encoder.GetCharCount(message, 0, bytesRead) < 4096
                      && bytesRead < message.Length)
                   bytesRead += server.Read(
                        message,
                        bytesRead,
                        168384 - message.Length);

           catch (Exception ex)
           {
               if(flag_chiusura == false)
                   MessageBox.Show(ex.Message);
               return;
           }
           AddMessage(encoder.GetString(message, 0, bytesRead));
           Thread.Sleep(500);
        }
    });

It could be more efficient by figuring out GetByteCount(decoded) and only re-decoding the portion that hasn't already been fully decoded.


How to refresh a page or refresh ngOnInit() in ionic 2

Question: i'm wondering if there is a way to refresh the ngOnInit() function or refresh the component. i don't wanna use the pull to refresh method. i want to do it on button click or tap. Thank you
home.ts file
  checkNetwork() {
  console.log("check internet");
this.platform.ready().then(() => {
  if(this.network.type == "none"){
    this.shouldHide = false;
    this.dividerHide = true;
  }
    let alert = this.alertCtrl.create({
        title: "Connection Status",
        subTitle: <string> this.network.type,
        buttons: ["OK"]
    });
  alert.present();
});
}

home.html file
<ion-card [hidden]="shouldHide">
<ion-card-header>

</ion-card-header>
<ion-card-content>
  <ion-card-title style="text-align:center">
    No INTERNET!
  </ion-card-title>
  <button ion-button full (click)="refreshPage($event)">Retry</button>
</ion-card-content>

when the connection will be available i want the page to refresh
Comment: so call the load data function on button click.. not sure what is the problem here
Comment: i; using the ionic loading plugin for a function that downloads data from server but sometimes the data downloading fails but the spinner keep on. i want a function that would restart the page so the function and the loading modal
Comment: can you share the relevant code and edit the question?
Comment: im also using a function that checks the networks avaibility if its none i want a function that would refresh the page when the connection is available
Comment: `refreshPage` function can call the loadData
Comment: suraj Good idea i did it it is working
Answer: Thank you all, this is how i managed it
home.ts file
ngOnInit(){
 this.LoadData();}

checkNetwork() {
  console.log("check internet");
this.platform.ready().then(() => {
  if(this.network.type == "none"){
    this.shouldHide = false;
    this.dividerHide = true;
  }else{
    this.shouldHide = true;
    this.dividerHide = false;
    this.presentLoading()
  }
});
}

refreshPage()
  {this.LoadData();
}

public LoadData(){...}

Home.html file
<ion-card [hidden]="shouldHide">
<ion-card-header>

</ion-card-header>
<ion-card-content>
  <ion-card-title style="text-align:center">
    Pas de connexion internet!
  </ion-card-title>
  <button ion-button full (click)="refreshPage()">Reessayer</button>
</ion-card-content>

Answer: Use this code
refreshPage() {
   this.navCtrl.setRoot(this.navCtrl.getActive().component);
}

Answer: My workaround for this was to present a toast (ToastController). Toast shows, toast disappears, then angular refreshes the data like it's supposed to. Toast can say "Refreshing data" or whatever is relevant for you -- in my case "New message from blah@blah". Or perhaps only show the toast for 1 ms if you don't want to clutter the UI.
Doing this.navCtrl.setRoot(this.navCtrl.getActive().component); "works" but has the side effect of totally reseting the nav stack, which is usually totally unacceptable.
Answer: You may need to refactor your code structure that so it doesn't need the page refresh, using an init method or Rx's subscriptions.
In case if you need the page reload, why don't you use reload method?

window.location.reload();

Edited:
Are you using network.onConnect subscription?

// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');

  // We just got a connection but we need to wait briefly
   // before we determine the connection type.  Might need to wait

  // prior to doing any api requests as well.
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});
Comment: does it work on ionic 2? will it reload the whole app or only the component?
Comment: Yes it would work, since ionic2 app is running under chrome browser
Comment: This is a very bad practice since the whole application would be reloaded. Also any session data will be lost.
Comment: JoeriShoeby do you have any suggestion?
Comment: You may need to refactor your code structure that so it doesn't need the page refresh, using an init method or Rx's subscriptions
Answer: you can re-initialise the page with calling to ngOnInit() :
this.ngOnInit();


Dúvida/problema ao scanear QR Code com javascript e exibir o resultado no input

Question: Estou tentando fazer com que o QR code ao ser scaneado ele imprima o valor dele no input, mas não estou conseguindo, utilizei algumas funções que eu conheço mas o qr code não é impresso no input de nenhuma forma, sou novato nisso.
<!DOCTYPE html>

    <title>Instascan</title>

    <video id="preview"></video>

    <input type="text" id="myText" value=""> </input>

<button onclick="myFunction()" id="meuElemento">QR CODE</button>

Answer: Utilizo também o Instascan com o mesmo objetivo.
Dentro do método addListener, no lugar ou até junto do alert, utilize o seguinte, substituindo o "id_campo_de_envio" pelo id do elemento que receberá o dado de leitura:
$("#id_campo_de_envio").trigger("click");
Seu código ficaria assim (substitua o id para funcionar!!!):

<!DOCTYPE html>

    <title>Instascan</title>

    <video id="preview"></video>

    <input type="text" id="myText" value=""> </input>

<button onclick="myFunction()" id="meuElemento">QR CODE</button>

O ".trigger("click")" executará o vulgo "enter no final".
Comment: No caso, você se referia a pegar o ID do input?
Comment: Isso. Se você não está utilizando id, seria bom colocar para discriminar o elemento.
Comment: Realize alguns testes com o reconhecimento mas não tive sucesso, aparentemente não sei oque aconteceu, sou bem novato nesse ramo. Mas irei usar uma "gambiarra" de momento para que eu possa estar incluindo o valor na base de dados.
Comment: Após trocar a ID #id_campo_de_envio por #myText, não funcionou, o console apresentou o seguinte erro, "ReferenceError: $ is not defined"
Comment: O id tem que ser o do "input", talvez seja isso. eu sofri também no começo.
Comment: Valeu amigo, você conseguiu abrir minha mente para uma questão que era simples. Deixei o código abaixo caso deseje dar uma olhada
Answer: Para quem estava com a mesma duvida consegui descobrir uma solução, onde era bem simples, segue o código abaixo do QR Code sendo reconhecido e logo após o valor sendo exibido no input.
<!DOCTYPE html>

    <title>Instascan</title>

    <video id="preview"></video>

<input type='text' id='yourInputFieldId' />


How can I translate the menu item?

Question: I have installed the Internalization module and after that edit the Main menu setting and select the translate and locale.
and add translate as per menu item. But when I switch the language its all the menu item still shows in english
Have a look I have only these options:
Answer: Below is how I resolved this before, for a multilingual D7 site with menus in multiple languages. In this case for the "main menu", but you can do this for any menu.
Step 1
Use a single "main menu" that contains all menu items for all languages, so not 1 main menu for only EN menu items and another main menu for only (e.g) FR menu items.
Step 2
Configure the multilingual options of the menu via the Menus administration page and follow the "edit menu" link to the menu in question. For the Main menu that would be admin/structure/menu/manage/main-menu/edit.
For "Translation Mode", use the option "Translate and Localize". So that
menu items with language will allow translations, and menu items without language will be localized.
Step 3
Add the links for any of your languages to the single menu, but make sure to specify for each of these links for which specific language you want the link to be shown. Or as an alternative, if you have menu items that should be shown for all languages, make sure such link is marked as "Language Neutral".
Summary
For any language the very only (single) "Main menu" is shown. However based on the selected language, only those menu items in it will be shown that match the selected language.
Not sure if it is the best/most elegant way to make this work, but IMHO it works like a charm ...
Comment: I did same but when I click on hindi only the content change in hindi language but the menu name remain same in English see the screen shot
Answer:
Did you check those checkboxes? This screen you will find at this URL admin/config/regional/language/configure
Please checked those option after you need to create a menu in both languages like create menu in a single language after using translate tab translate it.
When you check your site in your language, Please check that language postfix is added in URL Like(/en = English, /de = German)
Comment: Please see the edit question I have attached the screen shot
Comment: Unbelievable, but real - enabling the URL recognition method made the menu entries translatable ...

How can I translate the menu item?