Retornar apenas o primeiro dado de um array em JSON e JAVA

Question: Tenho um projeto onde busco no banco de dados via JSON, para exportar esses dados em formato Excel. Estou adicionando uma nova busca, porem tenho um array de string, mas não consigo trazer os dados do banco de forma que me retornasse apenas o primeiro dado desse array.
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject js = jsonArray.getJSONObject(i);
    JSONObject js2 = js.getJSONObject("cliente").optJSONObject("enderecoList").getJSONObject("municipio");
    JSONObject jsUnidade = js.getJSONObject("unidade");
    JSONObject jsUnidadePai = jsUnidade.getJSONObject("unidadePai");
    JSONObject jsCliente = js.getJSONObject("cliente");
    JSONObject jsApl = js.getJSONObject("apl");
    JSONObject jsSetor = js.getJSONObject("setor");

Eu gostaria que ele me retornasse apenas o primeiro dado que encontrasse no array getJSONObject("municipio")
Não está escrito getJSONArray("municipio"), pois não consigo dar um getString para mostrar o valor retornado.
Sou iniciante em java e JSON.
Comment: Poderia mostrar a estrutura deste JSON? Mas se quer apenas o primeiro item da lista tente assim: **JSONObject js = jsonArray.getJSONObject(0);**
Comment: mas se você quer que ele te retorne apenas o primeiro dado encontrado no array não da pra fazer algo tipo `for(int i = 0; i < 2; i++)` assim só faz o loop uma vez e te retorna só o primeiro?
Comment: Mas eu preciso do for para me retornar os outros dados.
Comment: Mas no for você esta determinando que o Objeto **js** recebe **jasonArray.getJSONObject(i)** então se no seu for o i for apenas **for (int i = 0; i < 1; i++)** o valor de **I** será apenas **0** assim pegando o primeiro registro encontrado
Comment: Fiz isso, porem ele exporta o arquivo Excel sem nem um dado.
Answer: O que você precisa fazer é alterar o código para obter o municipio como um JSONArray, e se for sua necessidade pegar apenas o primeiro elemento, usar o método getJSONObject, conforme o exemplo abaixo:
JSONObject js2 = js.getJSONObject("cliente").optJSONObject("enderecoList")
           .getJSONArray("municipio").getJSONObject(0);

Mas ainda seria melhor trazer cada elemento por vez. Algo assim:
JSONObject endList = js.getJSONObject("cliente").optJSONObject("enderecoList");
if(js != null) {
    JSONArray jsMunicipios = endList.getJSONArray("municipio");
    if(jsMunicipios.length() > 0) {
        JSONObject primeiroMunicipio = jsMunicipios.getJSONObject(0);
        // Imprime ou usa o primeiro Municipio aqui
    }
}

Pois desta forma você tem mais controle sobre o código e depuração de possíveis erros que podem acontecer ao ler o JSON.
Comment: Perfeito, funcionou!


Como passar pela página de alerta de Conexão Insegura do Firefox com GeckoDriver?

Question: Como passar pela tela de erro de certificado (conexão insegura) com o WebDriver GeckoDriver para Firefox?
Estou batendo em uma URL que apresenta esse alerta.
Já adicionei nas exceções do browser, mas o problema continua.
Se desmarco a opção "Consultar servidores OCSP para confirmar a validade atual dos certificados" continua o problema após o WebDriver iniciar uma sessão do browser.
Carrego o profile do mesmo pelo padrão do sistema:
private static IWebDriver GetWebDriver(string path)
{
    const string firefoxPath = @"...firefox.exe";

    var service = FirefoxDriverService.CreateDefaultService(@"...GeckoDriver\");
    service.FirefoxBinaryPath = firefoxPath;

    var options = new FirefoxOptions
    {
        Profile = GetFirefoxProfile(path),
    };

    var driver = new FirefoxDriver(service, options, TimeSpan.FromMinutes(1));

    return driver;
}

Mas mesmo assim não funciona.
Inclusive tentei setar:
options.Profile.AcceptUntrustedCertificates = true;
options.Profile.AssumeUntrustedCertificateIssuer = true;

profile.SetPreference("acceptInsecureCerts", true);

Comment: Poste uma foto da página.... talvez se você clicar em "Avançado" no final da página, e depois em "Continuar mesmo assim", você possa acessar a página.
Comment: @dot.Py olá, é esse tipo de página mesmo que aparece. Mas como fazer isso com o WebDriver? Em exceções do browser já está. Grato!
Comment: Encontrei essa solução para python dê uma fuçada no código pra ver se encontra algo parecido:

profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
Comment: Resolvi o problema momentaneamente fixando a versão do Firefox na 47.0.2
Answer: Não entendo muito de Selenium em C#, pois sou mais adepto da versão para o Python, mas a ideia serve para os dois. Tente absorver a ideia e descobrir como reproduzir em C#.
Como adicionar o website às exceções de segurança não funcionou, você pode fazer o seu WebDriver clicar no link "Avançar" e depois em "Continuar mesmo assim".
Mas... como fazer isso?

Você precisa descobrir qual o caminho do elemento na página para indicar ao WebDriver onde ele deve dar um .click()
Clique com o botão direito no link "Avançar" e selecione "Inspecionar elemento"
Descubra qual identificador "único" você pode utilizar para mostrar ao seu WebDriver onde encontrar o link "Avançar". Essa etapa é uma questão de estratégia e paciência!
Após encontrar um identificador único, como um id, class, name ou text, por exemplo, faça seu WebDriver encontrar este elemento e depois, clicar nele.

Docs
Encontrar 1 elemento
Encontrar todos os elementos

Repita os passos de 2 a 4 para o link "Continuar mesmo assim."

Códigos:

Encontrar elem: links = driver.FindElements(By.TagName("a"));
Clicar no elem: links.First(elem => elem.Text == "Avançar").Click();

ps: não testei pois não consegui reproduzir seu erro.

Como encontrar o identificador único:
Exemplo utilizando o botão de descartar post no SOpt.
1ª etapa:

2ª etapa:

3ª etapa:
Posso utilizar como identificar único:

class = btn-clear discard-answer
a
text = descartar

Qual estratégia será a mais eficiente? Talvez a 1ª, mas pode-se utilizar qualquer uma das 3 estratégias para encontrar o botão.
Comment: @JamesTK veja [essa resposta](http://stackoverflow.com/a/12745015/3846228) e a logo abaixo dela. O Selenium tem um 'alert handler', isto é, ele pode manipular alerts do navegador! No entanto, quando o alert é do sistema operacional, isto não é possível (como por exemplo as caixas que aparecem quando há o uso de certificado digital).
Comment: Obrigado pelos detalhes.
No Firefox é uma janela do próprio, como um alert.
Já vi algo sobre como selecionar um botão específico de um alert, mas não encontrei nada a respeito de outras janelas que não sejam o Alert. Ainda a procura. Obrigado!


Beginner confused about module structure in Express and socket.io

Question: I use default Express.js project structure, main js files involve my confuse are:
app.js:  define request handler and use module.exports = app; as a module.
bin/www:  require app.js,  setup and configure http server.
Everything seems modularized great.
But when it comes to Socket.io integration, this structure begins to confuse me:
From Socket.io Docs:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Since socket.io needs server variabe, so I figure out this code should be in www file, however I also want to modularize the io event handling part into a module, but I do not know how to export that io variable to www since it need a variable server from www.
I wonder: does that mean I have to keep all socketio event handling code in www file? Could anyone give me some code to show how to modularize this?
Answer: The organization of socket code is not necessarily intuitive but you could think of it as similar to the http side of things and the way that functions are often provided to routes.
Notice that you are just providing a function to "io.on". So, you could do something like this. In a separate file create a module for your socket functions...
// File named socket_funcs.js
module.exports.connection = function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
    console.log(data);
});

Then in your app.js file you can do this...
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var sf = require('./socket_funcs.js');

server.listen(80);

app.get('/', function (req, res) {
    res.sendfile(__dirname + '/index.html');
});

io.on('connection', sf.connection);


Spring 5 - HTTP Status 500 – Internal Server Error

Question: I'm doing Website from tutorial and I'm using Spring. Sadly code from video is not working in my IDE.
There is pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>Travel</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>Travel</name>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <release>17</release>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>6.0.3</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>
  <version>3.0.11.RELEASE</version>
</dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
        <version>3.1.1.RELEASE</version>
    </dependency>
  </dependencies>

</project>

And WebConfing.
package main.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

@Configuration
@EnableWebMvc
@ComponentScan("main")
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private WebApplicationContext context;

    @Bean
    public ServletContextTemplateResolver templateResolver() {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context.getServletContext());
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        return templateEngine;
    }

    @Bean
    public ThymeleafViewResolver viewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        return viewResolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

When I try to put it in localhost i can see error 500 in browser and then this is from IDE:
sty 07, 2023 7:36:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet [dispatcher]
java.lang.Error: Unresolved compilation problems:
ServletContextTemplateResolver cannot be resolved to a type
ServletContextTemplateResolver cannot be resolved to a type
ServletContextTemplateResolver cannot be resolved to a type
The method getServletContext() from the type WebApplicationContext refers to the missing type ServletContext

at main.config.WebConfig.templateResolver(WebConfig.java:31)
at main.config.WebConfig$$SpringCGLIB$$0.CGLIB$templateResolver$1(<generated>)
at main.config.WebConfig$$SpringCGLIB$$2.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:258)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
at main.config.WebConfig$$SpringCGLIB$$0.templateResolver(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:139)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:491)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1324)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1161)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:561)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:706)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:583)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:537)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:169)
at jakarta.servlet.GenericServlet.init(GenericServlet.java:158)
at jakarta.servlet.http.HttpServlet.init(HttpServlet.java:140)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:995)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:696)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:128)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)

So for sure this lines are wrong:
    @Bean
    public ServletContextTemplateResolver templateResolver() {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context.getServletContext());
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".html");
        return resolver;
    }

I tried to change it in this way:
    @Bean
    public ServletContextTemplateResolver templateResolver() {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver((ServletContext) context.getServletContext());
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".html");
        return resolver;
    }

Still same, 500 error.
Answer: As you can see in the changelogs, Spring migrated to Jakarta EE in the 6.0 release.
In your pom.xml, you are using version 6.0.3 of spring-webmvc (which requires Jakarta EE) but also javax.servlet-api which is part of Java EE.
You basically have two options:
Migrate to Jakarta EE
Replace
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>

with
<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.0.0</version>
    <scope>provided</scope>
</dependency>

This will then use version 6.0.0 of the Jakarta Servlet API instead of version 4.0.1 of the Java EE servlet API.
Alternatively, you can use an older version like 5.0.0.
Similarly, you would need to upgrade thymeleaf to 3.1.x as this version supports Spring 6 and Jakarta EE.
For doing so, replace
<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>
  <version>3.0.11.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>

with
<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>
  <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring6</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>

so that Thymeleaf is compatible with your Spring version as well.
Aside from updating dependencies, it is also important to replace the use of ServletContextTemplateResolver with something else as these were changed in Spring 3.1.
Since it is a Spring application, you might be able to use SpringResourceTemplateResolver as described in this Tutorial for Thymeleaf 3.1:
@Bean
public SpringResourceTemplateResolver templateResolver(){
    // SpringResourceTemplateResolver automatically integrates with Spring's own
    // resource resolution infrastructure, which is highly recommended.
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");
    // HTML is the default value, added here for the sake of clarity.
    templateResolver.setTemplateMode(TemplateMode.HTML);
    // Template cache is true by default. Set to false if you want
    // templates to be automatically updated when modified.
    templateResolver.setCacheable(true);
    return templateResolver;
}

Alternatively, you might be able to use WebApplicationTemplateResolver which can work with both Java EE (using JavaxServletWebApplication) and Jakarta EE (using JakartaServletWebApplication):

    @Bean
    public WebApplicationTemplateResolver templateResolver() {
        WebApplicationTemplateResolver resolver = new WebApplicationTemplateResolver(JakartaServletWebApplication.buildApplication(context.getServletContext()));
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".html");
        return resolver;
    }

Downgrade Spring
Another possibility is to use a version of Spring Webmvc before 6.x.
For doing that, replace
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>6.0.3</version>
    </dependency>

with
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.24</version>
    </dependency>

However, when using 5.x versions of Spring, you would miss the other features of Spring 6.x (including possible future features).
Comment: First of all, thanks for quick respond. So I decided to migrate to Jakarta EE. Sadly ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context.getServletContext()); is still red. Can you prove me more details to fix it? Thanks! (It shows: The constructor ServletContextTemplateResolver(ServletContext) refers to the missing type ServletContext).
Comment: Also make sure to change `thymeleaf-spring5` to `thymeleaf-spring6` and update your project in your IDE (Alt+F5 in Eclipse) after that change. In case the error persists, did the error message change in any way?
Comment: So i changed pom.xml thymeleaf-spring6 and jakarta.servlet. Just "new ServletContextTemplateResolver(context.getServletContext());" is red and message shows "The constructor ServletContextTemplateResolver(ServletContext) refers to the missing type ServletContext". I updated all couple of times, even i turned off and on Eclipse. Still not working.
Comment: For Jakarta EE, you need to [update thymeleaf itself to `3.1.x`](https://www.thymeleaf.org/doc/articles/thymeleaf31whatsnew.html) as well (e.g.`3.1.1-RELEASE`). However, this might result in `ServletContextTemplateResolver` not existing any more. You might be able to use [`SpringResourceTemplateResolver`](https://javadoc.io/doc/org.thymeleaf/thymeleaf-spring6/latest/org/thymeleaf/spring6/templateresolver/SpringResourceTemplateResolver.html) instead.
Comment: See [this section of the Thymeleaf docs](https://www.thymeleaf.org/doc/tutorials/3.1/thymeleafspring.html#the-springstandard-dialect) on how to use `SpringResourceTemplateResolver`.
Comment: Alternatively, you could create a [`WebApplicationTemplateResolver`](https://javadoc.io/doc/org.thymeleaf/thymeleaf/latest/org/thymeleaf/templateresolver/WebApplicationTemplateResolver.html) using `new WebApplicationTemplateResolver(JakartaServletWebApplication.buildApplication(context.getServletContext()))`.
Comment: You are awesome! Real legend! It is working! I spend 1.5 days to try to solve it. Thanks. So for future guys. Yes, ServletContextTemplateResolver is not longer working. You have to use SpringResourceTemplateResolver instead.


Support integer or float values as an attribute on a Drupal Commerce "Add to Cart" form

Question: I have created a product type which has integer and float fields. I would like to store my data as the correct data type and allow users to make decisions about which product to buy based on those fields. These are ineligible to become part of the commerce "Add to Cart" as defined by the following commerce function:
function commerce_cart_field_attribute_eligible($field) {
  // Returns TRUE if the field is single value (i.e. has a cardinality of 1) and
  // is defined by a module implementing hook_options_list() to provide an array
  // of allowed values structured as human-readable option names keyed by value.
  return $field['cardinality'] == 1 && function_exists($field['module'] . '_options_list');
}

It looks like the concept of implementing hook_options_list is hardcoded into a few places, including the field config forms:
if ( ... && function_exists($form['#field']['module'] . '_options_list')) {
  // Enable this field to function as an attribute field on Add to Cart forms.
}

By looking at how this has been setup, it seems reasonable that if you want commerce to cooperate with a field type, it must implement the hook.
I have considered implementing this hook for the "number" module and returning the entire dataset of values defined on the website for the specific field (this seems to work without any issues from what I can tell with 5 products).
I'm not sure if this will cause issues with Commerce or core down the track, perhaps with:

Too much data grinding things to halt.
The core "options" module not playing nicely with float/int fields.
Other modules assuming the field is a list of data?
The weirdness around implementing another modules hook.

Looking for some advice on the best way to move forward with the problem.
Answer: I ran into the same problem (and asked a similar question which I ended up answering myself  here)
Basically with the knowledge you gave I was able to implement a new module which installs a widget for the "list integer" and "list float" types that uses a textfield for input and on POST it sanitizes and adds the value of the textbox to the "allowed_values" setting on the field allowing it to pass the standard list field validation and use the standard list field storage.
This allows you to enter and display a "number" and use the value as a product attribute.  Best part is I did not have to alter another modules code, which addresses the majority of your concerns as:

The core "options" module not playing nicely with float/int fields.

The options module defines the widget, since you are doing this, you don't need to worry about it.

Other modules assuming the field is a list of data?

Since you defined your own widget and are not using the standard "options", other modules will not know it exists so you don't have to worry.

The weirdness around implementing another modules hook.

Again, by adding the sanitized field into the allowed_values setting on POST you pass validation and this allows you to use the "LIST" modules standard implementation of hook_options_list and you don't have to modify someone else's code
As far as your first point on too much data, this is possible that you will have a problem here if you have a multitude of products OR if you are added and removing products all the time (which would continuously add to your "allowed_values" list). For the first point, you could probably also implement a field type in your module and do your own implementation of hook_options_list to follow your logic and just return all the values in your database (i don't have that much so didn't bother).  For the second point, you could implement hook_cron and clean up on the allowed values setting based on the values for the field in the database.
hope this helps and if you have any questions let me know!


Contour integral of inverse square root.

Question: I want to calculate the below complex integral on the upper-semi-circle which its radius goes to infinity:
$$ \oint \frac{dz}{\sqrt{1+z^2}}$$
I tried with the substitution $z = R e^{i \theta}$ where $0<\theta<\pi$, and then took the limit where $R$ goes to infinity, but I counldn't find sensible result.  Is it due to the fact that my substitution crosses the branch cut? (Either the cut taken from $i$ to infinity or to connect $-i$ and $i$.) If this is the case, how can one evaluate this integral, by the way if it converges.
Answer: Idea:
Note that for large $R$ we have that $\sqrt{1+z^2} \approx z$. This result is analytic without any branch cut. So it is useful for integration.
Formal:
We have to branch points of $\sqrt{1+z^2}$ at $z=\pm i$. We may choose the branch cut between between these branch points. With this choice, we have that (for $|z| > 1$)
$$ \sqrt{ 1+z^2} = z \sqrt{1+1/z^2}$$
where on the right hand side the branch cut does not play a role [as $\operatorname{Re}(1+1/z^2)>0$].
With that we have for the upper semi-circle ($z= R e^{i\theta}$)
$$\int  \frac{dz}{\sqrt{1+z^2}} = \int  \frac{dz}{z \sqrt{1+1/z^2}}  = i \int_{0}^{\pi} d\theta + O(1/R) \to \pi i \quad (R\to \infty).$$
To this, we add the contribution of the integral along the real line. For this we obtain
$$\int_{-\infty}^{\infty}\frac{dx}{\pm\sqrt{1+x^2}}$$
where the sign $+$ has to be chosen for $x>0$ and $-$ for $x<0$ (given that the branch cut is between $+i$ and $-i$). Due to the fact that we integrate an odd function, this part of the contour vanishes and we have that
$$\oint \frac{dz}{\sqrt{1+z^2}} = i \pi\;.$$
Comment: Thanks. If we choose the branch cut between $\pm i$, how can we also add the contribution of the contour integral on the bottom (horizontal) line of the semi-circle? (It crosses the cut.)
Comment: Oh, I thought that you want to integrate only over the semi-circle (without the part along the real line). If you include the part of the real line, the integral still is not closed as you necessarily end up in the second Riemann sheet (by having encircled a branch point). In this case, the result of course depends on the branch cuts chosen. So you should specify in which branch cut you are interested. (initially I wrote the answer for the complete circle at $R \to \infty$ in which case the branch cut does not matter)
Comment: The branch cut as you have already chosen. Another question: How can one make this integral closed? That is, if we start from $- \infty$ on the real axis, then move on and encircle the branch point $i$ and continue and move on the semi-circle, we don't come back to our initial point, indeed we are on the second sheet. How can we make it closed, that is: coming back to our initial point?
Comment: You can encircle the branch point (at $z=+i$) a second time. Another choice would be to encircle the other branch point (at $z=-i$) in the opposite direction.
Comment: Now that the final result is $i \pi$, can one say that if we encircle the branch point $+ i$ for a second time in order to end up in our starting point, the result becomes $2 i \pi$?
Comment: @Simple: no, the second time, you are on the second branch. So the integrand is minus the integrand in the first case. So encircling the branch point again, leads to $-i\pi$ and thus  the total result is 0.


In any $\triangle ABC$, prove that: $\frac {\cos B-\cos C}{\cos A +1}=\frac {c-b}{a}$

Question: In any $\triangle ABC$, prove that: $\dfrac {\cos B-\cos C}{\cos A +1}=\dfrac {c-b}{a}$
My Attempt:
$$\begin{align}
\text{R.H.S.}&=\dfrac {c-b}{a} \\[4pt]
&=\frac {a\cos B+b\cos A-a\cos C-c\cos A}{b\cos C+c\cos B} \\[4pt]
&=\dfrac {a(\cos B-\cos C)+(b-c)\cos A}{b\cos C+c\cos B}
\end{align}$$
Comment: There is a brute-force way of solving the problem: use the cosine law to write all cosines into side lengths, and compare both sides.
Answer: We have$$a\cos B+b\cos A=c,$$$$a\cos C+c\cos A=b.$$Subtracting gives$$a(\cos B-\cos C)-(c-b)\cos A=c-b,$$which on rearranging yields the required result.
Comment: Can you provide a proof for the first equations ?
Comment: @S.H.W: For the first one, drop the perpendicular from vertex $C$ onto the side $AB$, and similarly from $B$ to $CA$ for the second. I did not include a proof, because these results were already used by the OP: See the second line of "My Attempt" in the question.
Comment: Okay , thanks a lot .
Answer: Obvious if $B=C$
Otherwise  using this $$\dfrac{\cos B-\cos C}{\sin C-\sin B}=\cot\dfrac A2$$
$$\dfrac{1+\cos A}{\sin A}=?$$
Answer: For $\triangle ABC$,
$$\frac{\sin\left(A\right)}{a}=\frac{\sin\left(B\right)}{b}=\frac{\sin\left(C\right)}{c}=\frac{1}{k}$$
therefore,
$$k\sin\left(A\right)=a,\:k \sin\left(B\right)=b,\:k\sin\left(C\right)=c$$
\begin{align*}
RHS= &\frac{k\sin\left(C\right)-k\sin\left(B\right)}{k\sin\left(A\right)}\\&=\frac{\sin\left(C\right)-\sin\left(B\right)}{\sin\left(A\right)} \\&=\frac{2\cos\left(\frac{B+C}{2}\right)\cdot \sin\left(\frac{C-B}{2}\right)\cdot \cos\left(\frac{A}{2}\right)}{2\sin\left(\frac{A}{2}\right)\cdot \cos\left(\frac{A}{2}\right)\cdot \cos\left(\frac{A}{2}\right)}\\&=\frac{2\sin\left(\frac{A}{2}\right)\cdot \sin\left(\frac{C-B}{2}\right)\cdot \cos\left(\frac{A}{2}\right)}{2\sin\left(\frac{A}{2}\right)\cdot \cos^2\left(\frac{A}{2}\right)+1-1}\\&=\frac{2\sin\left(\frac{B+C}{2}\right)\cdot \sin\left(\frac{C-B}{2}\right)}{\cos\left(A\right)+1}\\&=\frac{\cos\left(B\right)-\cos\left(C\right)}{\cos\left(A\right)+1}
\end{align*}


How to prove $n^x \in o(a^n)$ for $x>0$ and $a>1$? formally, without using limits.

Question: What is a clever and robust argument to show that for any $x>0$ and $a>1$, $n^x \in o(a^n)$, or equivalently; for all $c>0$, there is a $n_0 >0$ such that $n \geq n_0 \Rightarrow n^x < ca^n$?
Here's my argument; Since $\log_n(ca^n)$ is an increasing function for any $a,c >0$, there is always a $n_0$ such that  $\log_{n_0}(ca^{n_0}) > x$. As a result, for all $n \geq n_0$, $ca^n = n^{\log_{n}(ca^{n})} \geq n^{\log_{n_0}(ca^{n_0})} > n^x $.
I'm not really happy with this because it doesn't really give a precise and nice definition of $n_0$. Is my proof correct and is there a better/more clever way?
Comment: Why do you need "for all $c > 0$"? Are you trying to prove that $n^x$ is $o(a^n)$ or $O(a^n)$? (Both happen to be true, but the definition of $O$ only requires there to exist such a constant $c$.)
Comment: Sorry, I want to prove $o$, I'll edit it. Ty.
Comment: The way your question is worded, you are asking to show that $n^x$ is $O(a^n)$. If you want little $o$, then you are asking to prove that $\lim_{n\to\infty} n^x/a^n = 0$.
Answer: You need your $\log_n(ca^n)$ not only to be increasing, but to actually go to infinity. Apart from that, your proof looks fine.
Here's how I would prove it. Lightly tweaking the notation a little*, we want to prove that $n^b = o(a^n)$ (for fixed constants $b > 0$ and $a > 1$), or in other words that for any given constant $c > 0$, we have $n^b < c a^n$ for sufficiently large $n$.
Just solve for $n$. Note that $n^b = e^{b \ln n}$, and $a^n = e^{n \ln a}$. So we want $e^{b \ln n} < e^{\ln c + n \ln a}$, or $b \ln n < \ln c + n \ln a$, or equivalently $n \ln a - b \ln n > -\ln c$. This is something you can see clearly is true for sufficiently large $n$: the LHS goes to infinity, while the RHS is a fixed constant. This you can now prove.

If you wanted a "precise and nice definition for $n_0$" (but really you shouldn't want it: note that the whole point of the $O$ notation is to suppress such information as nonessential), you could probably do the following: pick $n_0$ to be large enough such that:

$b \ln n_0 < 0.5n_0 \ln a$ (this just means $n_0 / \ln n_0 > 2b/\ln a$)
and such that

$0.5n_0 \ln a > -\ln c$ (this just means $n_0 > -2\ln c/\ln a$)

(That is, pick $n_0$ to be the maximum of the points where the two conditions hold.) Then for $n \ge n_0$, we have
$$ n \ln a - b \ln n > n \ln a - 0.5 \ln a > 0.5n \ln a > -\ln c$$
and therefore $c a^n > n^b$ as required.
(The way I arrived from "$n \ln a - b \ln n > -\ln c$" to this trick is to see that the LHS was basically $O(n)$, so the pesky thing being subtracted could be bounded by say $0.1n$ or $0.5n$… and carrying the factors along.)

If you want something even more explicit: to prove that $n^b < ca^n$ for sufficiently large $n$, assume without loss of generality that $c \le 1$ (otherwise if $c > 1$ we could just prove the stronger inequality with $c = 1$), pick
$$n_0 = e + \left(\frac{b + \ln(1/c)}{\ln a}\right)^2$$
so that, for all $n \ge n_0$, we have:

$\dfrac{n}{\ln n} > \sqrt{n}$ (true for all $n > 1$), and
$\sqrt{n} > \dfrac{b + \ln(1/c)}{\ln a}$

which together give
$$ \frac{n}{\ln n} > \frac{b + \ln(1/c)}{\ln a}$$
or
$$ n \ln a > b \ln n + \ln(1/c)\ln n > b \ln n + \ln(1/c) $$
and therefore
$$a^n > n^b (1/c)$$
which is the same as $n^b < c a^n$ that we wanted to prove.

But if you don't want a "precise and nice definition for $n_0$", then the nicer way to prove this (and to think about this) would be to write something like:
$$n^b = e^{O(\ln n)} = e^{o(n)} = o(a^n)$$
after proving that each of these (one-way) equalities is generally valid. That is the whole power of the notation (or the idea of asymptotic analysis): to avoid having to thinking about specific constants where things happen, while still being completely formal and rigorous.

[* Footnote on notation: I used $b$ instead of $x$ to indicate that it is a constant. And I don't like the subset notation for $O$, so I will not indulge in that misguided pedanticism. You can read the treatments by de Bruijn and by Knuth to see that we lose much of the value of $O$ notation by definining $O(x)$ as a set; for example, statements like $e^{O(1)} = O(1)$ become harder to write. See also the "four reasons" for preferring "$=$" over "$\subseteq$", on pp 446–447 of Concrete Mathematics: actually just work through the whole Asymptotics chapter and see if you still prefer thinking of $O(\ldots)$ as sets.]
Comment: For the footnote, you may want to weigh in at https://math.stackexchange.com/questions/86076/what-are-the-rules-for-equals-signs-with-big-o-and-little-o
Comment: @HenningMakholm Nice question and answers :-) There's a clear (IMO) line indicated by de Bruijn: we simply refuse to assign any formal meaning to $O(f(n))$ in isolation (such as declaring that it denotes a set of functions) (we do retain an informal/intuitive meaning), and we only assign meanings to full statements (including an $=$ sign) in which an $O$ occurs on either side. I think it's closer to your answer than to Srivatsan's. (I also think it will be clearer to start with the $L$ or $A$ examples.) Let me know if you'd like me to post an answer at that question along those lines. :-)
Comment: I accepted your answer. I didn't think of splitting the inequality into one half > first part and one half > second part, it was way too clever for me to think of. Though, this is still not entirely what I'm looking for.  $n_0/ \ln n 0 >2b/\ln a $ still does not give $n_0$ in explicit form.
Comment: @VeryNoobCSStudent Added an explanation for how I arrived at the trick… and I've just added an even more explicit expression for $n_0$ for you. :-) (Even though I think such explicit expressions miss the point and obfuscate what is going on.)
Comment: I like the new method much more; instead of switching bases, we take the logarithms, make a $\ln n$ appear (which is too clever for me), then find $n_0$ by going through a simpler, smaller function (which is also too clever for me). At least I'm able to understand this, sigh. I will never understand how people think of clever tricks like those.
Comment: @VeryNoobCSStudent I can tell you how I thought of it: (1) Whenever there is exponentiation (something is raised to another power), take logarithms. This immediately turns $n^b < ca^n$ into $b\ln n < \ln c + n\ln a$ and there is no longer any exponentiation to think about. (2) Actually think about the asymptotics, how "big" the different terms are. The term $b\ln n$ is $O(\ln n)$. The term $\ln c$ is a constant $O(1)$ and you can almost ignore it. The term $n\ln a$ is $\sim n$. So all you're trying to prove is that something that is $O(\ln n)$ is less than something that is $\sim n$.
Comment: @VeryNoobCSStudent More concretely, I looked at $b \ln n < \ln c + n \ln a$, tried to get all the $n$s in one place (like middle-school algebra), and ended up with $$\frac{b}{\ln a} < \frac{\ln c}{\ln a \ln n} + \frac{n}{\ln n}$$ -- next I realized that the $\ln n$ in the denominator of the $c$ term can be ignored (fortunately) as larger $n$ only makes the inequality "easier" (by making that term smaller), so we're left with trying to prove that $\frac{n}{\ln n} > \mathrm{something}$. If we want this explicitly, we can replace $\frac n{\ln n}$ with something easier, and I thought of $\sqrt n$.
Comment: @ShreevatsaR: I had hoped you might post an answer with a formalism backed by more authority than my own synthesis-from-practice.
Answer: Hint:
Let $k=\lceil x\rceil$. To prove $n^x=o(a^n)$, it is enough to prove $n^k=o(a^n)$.
Denote $u_n=\dfrac{n^k}{a^n}$. A standard argument to show $(u_n)\to 0$ consists in proving $\;\dfrac{u_{n+1}}{u_n}$ has a limit $\ell <1$.
Indeed, if this is the case, take any $r$ such that $\ell<r<1$. There exists an integer $N>0$ such that $\dfrac{u_{n+1}}{u_n}<r$ for all $n\ge N$. By a trivial induction there results that
$$0<u_n<u_N\, r^{n-N}=\frac{u_N}{r^N}r^n,$$i.e. if $n$ is large enough, $(u_n)$ is bounded from above by a geometric series of ratio $r<1$, which therefore converges to $0$. Hence, by the squeezing principle, $(u_n)$ converges to $0$.
Last step: let's check  $\dfrac{u_{n+1}}{u_n}$ conerges to a limit $<1$:
$$\frac{u_{n+1}}{u_n}=\frac{(n+1)^k}{a^{n+1}}\frac{a^n}{n^k}=\Bigl(1+\frac1n\Bigr)^k\frac1a\to 1\cdot\frac 1a<1\quad\text{by hypothesis.}$$


I cannot enable firestore on a project although I'm not using AppEngine nor Datastore

Question: I'm trying to activate firestore on a project on which I'm not using AppEngine nor Datastore and having this error message.
Cannot enable Firestore for this project
Currently Firestore cannot be enabled in projects already using Cloud Datastore or App Engine
To be more precise, I used to use datastore but now there is no entities in my project datastore. So maybe there is something that I need to disable explicitly
Thx in advance for your help
Comment: Sorry Frank but it is not. Besides when I posted my question in that feed I was asked to open a new question. thx !
Comment: Voted to reopen since it's subtly, but meaningfully, different and not really a dup. @Frank
Comment: Great ! Thank you @Frank
Answer: Unfortunately since you have previously used Cloud Datastore in that project, you cannot create a Cloud Firestore instance. Our ability to switch it currently only works if it was never used in the past.
Comment: Is there any workaround for GCP support to delete the old Cloud Datastore meta trail from project entirely if no longer in use?
Comment: Thank you Dan for your feedback !
Comment: Well, a Beta of anything is normal to some functionality not working out as it seems to be... Rest assure we'll wait for Stable one.
Comment: Yes as @vgrafe mentioned an even in a fresh project not able disable Datastore to use Firestore. Throws error like "Following service(s) depend on service(s) to be deactivated: cloudapis.googleapis.com"
Comment: I fixed it by disabling it in the GCP console then clicking create in the Firebase console. After that I got the error again but when I refreshed it was there.
Answer: go to the Project Settings and add Default GCP resource location:

Then try to create database


Warning: Expected server HTML to contain a matching  in

Question: I get the above mentioned warning in the console. I don't understand why. I have two matching  tags in index.js file. The complete warning is -
Warning: Expected server HTML to contain a matching  in
.
    in body (at pages/index.js:12)
    in div (at pages/index.js:11)
    in div (at pages/index.js:7)
    in Index (at _app.js:8)
    in MyApp
    in Container (created by AppContainer)
    in AppContainer

Following the index.js file I'm using. I'm using Next.js with tailwindcss.
import Head from "next/head"
import SideNavbar from "../components/SideNavbar"
import MainPage from "../components/MainPage"

const Index = () => {
  return (

        <title>Manchester United</title>

          <SideNavbar />
          <MainPage>

              Manchester United

          </MainPage>

  )
}

export default Index

The warning goes away if I replace the  tag with a
 tag. The two custom components I use, <SideNavbar /> and <MainPage />, don't use any  tags.
Comment: I don't have a `_document.js` file. I created this app using `npm init next-app`. I do have an `_app.js` file which I had to create to use tailwindcss.
Comment: Inside your _document.js you must have div i.e.

`

`

so the `Main` can't have another body tag via your _app.js
Answer: Your HTML isn't correct. You cannot have a body-Tag inside a div-Tag. A basic HTML-Structure looks like this

<title>Page Title</title>

My First Heading

My first paragraph.

Comment: I see. But in react, the return statement should be wrapped in one `` element. Other wise I'll get a compile error. I remove the topmost `` in the `Index` component in the code above and then I got the following error - `SyntaxError: /home/akshaj/projects_js/man-utd-explorer/pages/index.js: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...? (10:6)
`.
Comment: @theairbend3r  you cannot return *more than one* top level html tag/component from a react component. to solve this, you **can** use `...` to wrap the multiple tags in an effectively, 'no-op' tag.
Answer: As React works, your React application is "injected" to HTML element which you define at ReactDOM.render:
ReactDOM.render(<App />, document.getElementById('root'));

But, this element is already a child of  element.

Warning: validateDOMNesting(...):  cannot appear as a child of
.

Your error is just a variation of the same thing but as server-side rendering (Next.js) error.

By using Next.js, this HTML is hidden from you (check the HTML in the "vanilla" example in codesandbox attached).
Also, you can inspect the DOM tree at source tab in dev tools, there you will notice that two  elements exist.
Here is a small codesandbox code which demonstrates the error:


Why isn't $y=(x^6)^{1/3}$ a polynomial function?

Question: I've been told that $y=(x^6)^{1/3}$ isn't a polynomial function because of the radical but I believe that the equation could be simplified to $y=x^2$ which fits the definition of a polynomial function.
Comment: Are you sure they said polynomial *function* and not polynomial *expression* or polynomial *form*? If the latter, then it is a distinction between *syntax* (language) and *semantics* (meaning, denotation).
Comment: Perhaps you can ask the person who told you this what it means for two functions to be equal, e.g. the meaning of $f=g$ when $f:{\mathbb R} \rightarrow {\mathbb R}$ and $g:{\mathbb R} \rightarrow {\mathbb R}$ are two given functions from the reals to the reals, and whether "polynomial" is a property that is invariant under equality of functions.
Comment: so @Daniel actual problem is :is your believe correct or other assumption? :D it is just for  funy
Comment: Who has told you $x\mapsto (x^6)^{1/3}$ is not a polynomial function? For real numbers, it is identical to $x\mapsto x^2$.
Answer: Raising to non integer exponents poses some problems. One might define $x^{1/3}$ also for negative values of $x$, because this is essentially the cubic root; but while $\sqrt[3]{x}$ is non ambiguous, a fraction doesn't change according to its representation:
$$
\frac{1}{3}=\frac{2}{6},
$$
but writing $x^{1/3}=x^{2/6}$ at least raises some doubts.
My personal opinion is that powers with non integer exponents should always be bound to positive values of the base, thus making algebraic manipulations possible without restrictions. So, if we bind $x$ to be positive, we have the true identities
$$
x^{1/3}=x^{2/6}=(x^2)^{1/6}=(x^{1/6})^2,
$$
which would be plainly false if $x<0$ were allowed.
I acknowledge that others don't think this way and define $x^{p/q}$ ($p$ and $q$ integers, $q\ne0$) also for negative values of $x$ provided $p$ and $q$ are coprime and $q$ is odd.
What's the convention used in a textbook should be clearly expressed from the beginning. There is no law cast in the stone about this (and most of mathematics, either). Different fields of math use different conventions; just think to the concept of function itself: in several fields functions must have a well defined domain and codomain, while in Analysis this is not strictly enforced. It's not a problem, provided one is made aware of the convention used.
In your case there is no doubt: the function $x\mapsto(x^6)^{1/3}$ assumes, for every real $x$, the same value as the function $x\mapsto x^2$. Thus the two functions are equal and, being $x\mapsto x^2$ clearly a polynomial function, the conclusion is obvious.
On the other hand, $x\mapsto(x^2)^{1/2}$ is not a polynomial function, because it is the same as $x\mapsto|x|$ and there's no polynomial form of this function: polynomial functions are everywhere differentiable, $x\mapsto|x|$ is not differentiable at $0$.
Comment: Let $\,f\,$ be you favorite hairy transcendental function that is invertible. Maybe so hairy that it is not even provable that $\,f\,$ is total or invertible without using very strong set-theoretic axioms. Then do you consider $\,f^{-1}\! f(x)\,$ to be a polynomial function of $\,x\,?\ \ $
Comment: @BillDubuque If I don't *prove* that $f^{-1}$ exists, I'm not allowed to use it; if I know it exists, then $f^{-1}\circ f$ is the identity by definition. What "exists" mean can be object of a discussion. In any case, the function under examination is polynomial; for other functions I might say "I don't know".
Answer: sAt least in $\mathbb{C}$ the functions $f(x) := (x^6)^\frac{1}{3}$ and $g(x) := x^2$ are not equal, as $f(\sqrt[3]{i}) = (i^2)^\frac{1}{3} = -1$ and $g(\sqrt[3]{i}) \not\in \mathbb{R}$.
Edit: Oops. As the comments stare $f$ is not well defined in $\mathbb{C}$, so my answer does not work out so easy. Sorry
Comment: Over $\mathbb{C}$ the function is not even defined, as  the cubic root isn't a function (at least in the usual sense of "one valued functions").
Comment: For complex numbers, $(i^2)^{\frac{1}{3}} = (-1)^{\frac{1}{3}}$ has multiple values.
Comment: There are three (entire) branches of $\left(z^6\right)^{1/3}$. They are $z \mapsto \omega^k\cdot z^2$ with $\omega\neq 1$ a third root of unity and $k\in \{0,1,2\}$.
Answer: Salman Khan talks about that in one of his (many) videos.
It's at the beginning of this video:
About polynomials
Hope it helps you understanding polynomials.
Answer: I'm going to be a little pedantic (but that's my job).
I want to distinguish between a function and the way that the function is specified. The functions
$$
f_1 : \mathbb R \to \mathbb R: x \mapsto x \\
f_2 : \mathbb R \to \mathbb R: x \mapsto (x+1) - 1
$$
are identical as functions (they have the same domain, codomain, and relation), but they've been specified differently.
Most often, we see functions specified by relatively simple expressions, i.e., strings of characters that we recognize as syntactically correct and semantically valid stuff. But sometimes they're specified by tables, or by "cases" (one expression gets used for $x > 2$, another for $x \le 2$, for instance), etc.
Certain expressions are called "polynomials in $x$"; they consist of a finite sum of terms, each term being either (a) a constant, or (b) the product of a constant (which may be omitted if it's $1$) and a positive integer power of $x$. Terms where the constant is negative can have an "addition" replaced by a subtraction, so that $4 + -2x^2$ can be written $4 - 2x^2$.
The expression $(x^6)^{\frac{1}{3}}$ doesn't meet the criteria for being a polynomial. The expression $x^2$ does meet the criteria. If I had been the one talking to you about this thing (which would have meant that I was in a very formal mood), I would have said "The function description $y = (x^6)^\frac{1}{3}$ does not define the function via a polynomial expression. It is, however, identical, as a function, to one that can be defined via a polynomial expression."
In practice, this almost never matters.
We tend to be sloppy and say that the function "isn't polynomial" when we mean that the description's not a polynomial, and everyone kinda gets it, and we move on. In the same way, we sometimes say "The vector $v$ is a linear combination of the vectors $x_1$ and $x_2$." What we really mean is that there's a linear-combination-expression whose value happens to be $v$, but the distinction almost never matters in much of mathematics. I'm guessing that in logic and formal semantics, it matters quite a lot, but those aren't my areas, so I cannot say.


Debug Eclipse - Classes com nomes iguais em projetos diferentes

Question: Estava fazendo o debug aqui e me deparei com uma situação curiosa. Já fucei, mas não consegui êxito em descobrir o problema.
Em um projeto, tenho a classe EntidadeDAO no projeto1. Em outro projeto, no mesmo workspace, tenho uma classe com o mesmo nome, EntidadeDAO, no projeto2.
Ao fazer o debug no projeto1, nessa classe, o eclipse aponta para a classe do projeto2.
obs: As duas classes são bastante diferentes, somente os nomes são iguais. Somente os nomes mesmo. O nome do projeto e pacotes são todos diferentes.
Mais alguém já passou por essa situação e sabe me dizer o motivo?
edit: Estou usando o Eclipse Neon, esqueci de avisar.
Comment: Pode ser o import de `EntidadeDAO` aponte para o projeto dois. Como vc adicionou essa classe no projeto? como arquivo normal ou library?
Comment: Mesmo que o projeto 2 esteja fechado acontece isso? veja também se no projeto 1 não tem nenhum tipo referência para o projeto 2. Verifica o build path.
Comment: está no mesmo pacote, o `package faturamento;`
Comment: Não, não tem nenhuma referência ao outro projeto no build path.
Comment: Não testei fechá-lo.
Answer: Esse problema ocorre pois na configuração de debug do eclipse o projeto1 esta primeiro que o projeto2, isso é meio que um bug do eclipse mesmo e muita gente que tem classes que tem o mesmo nome em vários projetos tem esse problema de vez em quando, eu já consegui resolver isso de duas formas:
1º Opção: Alterar a ordem do Source Lookup no debug.

Em seguida

2º Opção: Em vez de alterar a ordem remova um dos projetos do Source Lookup temporariamente
Comment: Valeu cara!!!

Verifiquei `Run/Debug Settings`, onde tem a lista de classes que estão no Debug e achei outra solução.

Posso editar a `launch configuration properties` da classe e apontar para o projeto que eu quero e a classe que eu quero.


calling WCF client function doesn't work on IIS

Question: I made a service using the WCF discovery. Everything works fine when it is deployed on a specific port (using VS2010 debug), but when I try to deploy it to IIS it finds the service but can't run any of the methods.
This is the code:
 DiscoveryClient discoverclient = new DiscoveryClient(new UdpDiscoveryEndpoint());
 FindResponse response = discoverclient.Find(new FindCriteria(typeof(IService)));
 EndpointAddress address = response.Endpoints[0].Address;
 ServiceClient client = new ServiceClient(new BasicHttpBinding(), address);
 Console.WriteLine(client.getMsg()); //some test function
 Console.ReadKey();

When tring to run the client.getMsg() method I get the following error:

EndpointNotFoundException:
  There was no endpoint listening at
  http://computerName.domain/services/Service.svc that could accept the
  message. This is often caused by an incorrect address or SOAP action.
  See InnerException, if present, for more details.

But I got the address, meaning it found it. And if I use the debug deployer (not to iis) I find it in http://localhost:port/services/Service.svc and it runs perfectly fine. How can I have it deployed to iis with no problems?
OS : win7 64 bit
config file :

<services>
  <service behaviorConfiguration="RemoteDeploy.Service1Behavior"
    name="RemoteDeploy.Service">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration=""
      contract="RemoteDeploy.IService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint name="udpDiscoveryEpt" kind="udpDiscoveryEndpoint" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>

</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="RemoteDeploy.Service1Behavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
      <serviceDiscovery>

        </serviceDiscovery>
    </behavior>
  </serviceBehaviors>
</behaviors>

Comment: Perhaps you need to add the svc mappings to the IIS? (ServiceModelReg.exe -i)
Comment: Could you please post your web.config file, at least where you configure your endpoints. With WCF services more times than not, all issues are related to its configuration.
Answer: First try to GET http://computerName.domain/services/Service.svc in your browser - either you get an error or service description..
Comment: going to that link in the browser doesn't work also, but going to: localhost/services/Service.svc does work. The findCriteria gives me the wrong address (gives me the full computer location)
Comment: I get same result in browser with computer domain name and localhost - as part of the URI - are you positive computerName.domain is correct, or maybe it's only fragment?


Mostrar aspas vindas do MySQL

Question: Em MySQL tenho uma tabela com o seguinte dado:
"Cavalo dado não se olha os dentes", disse a professora

Segunda linha

Estou pegando esse campo assim:
$sql = $pdo->prepare('SELECT texto FROM noticia');
$sql->execute();
$resultadoSql = $sql->fetchAll();
foreach($resultadoSql as $valorSql){
    $texto = nl2br($valorSql['texto']);
}

Mas está me retornando isso:

Porque entra esses quadrados? Como mostrar as aspas?
Comment: Caro Caio, esta com cara de que isso não são aspas, pelo menos não aspas do ASCII, pode ser um UNICODE, pode ser erro de codificação da página, pode ter sido problema no INSERT (creio que o mais provavel);
Comment: @GuilhermeNascimento obrigado pela ajuda. Esses dados vieram de um banco de dados em Wordpress, estou acessando a tabela post do Wordpress. Realmente se eu edito o conteúdo e recoloco as apas, aparece. O que pode ser? E como resolver?
Comment: Me parece provavel ser alguma conversão das aspas ASCII em algum unicode, talvez o proprio WP esteja convertendo na hora de salvar, tornando em `"` (`U+201C`) quando a aspas `"` forem a esquerda e `"` (`U+201D`)... Note que apesar de semelhantes aos da tabela ASCII não se tratam do mesmo codepoint. Sua página PHP deve estar em iso-8859-1 ou windows-1252 (ambos assumidos pelo apache ou pelo navegador), ou se seu PHP estiver mesmo em UTF-8 então significa que esses caracteres não são aspas tradicionais, mas sim aspas criadas pela propria turma do WP para usar codepoints e emojis proprios.
Comment: Realmente são essas aspas. Está tudo em UTF-8. Mas vê alguma fora de contornar isso? Pois preciso listar mais de 7000 textos, e muitos estão assim...
Answer: Como eu já comentei, me parece provável ser alguma conversão das aspas ASCII em algum unicode, talvez o próprio Wordpress esteja convertendo na hora de salvar, tornando em " (U+201C) quando a aspas (") forem a esquerda e " (U+201D) quando forem a direita de algum texto
Note que apesar de semelhantes aos da tabela ASCII não se tratam do mesmo codepoint. Sua página PHP deve estar em iso-8859-1 ou windows-1252 (ambos assumidos pelo apache ou pelo navegador), ou se seu PHP estiver mesmo em UTF-8 então significa que esses caracteres não são aspas tradicionais, mas sim aspas criadas pela própria turma do WP para usar codepoints e emojis próprios.
Não vou afirmar que esta é a melhor solução, mas como está trabalhando com outro banco e não com a API do Wordpress diretamente (talvez ele próprio forneça algo que "decodifique" o que eles mesmos fizeram) o iconv (precisa estar ter libiconv, a maioria dos servidores PHP tem - são "compilados" com isto):
<?php

$exemplo = '"Cavalo dado não se olha os dentes", disse a professora
Segunda linha';

$exemplo  = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $exemplo);

$texto = nl2br($exemplo);

echo $texto;

outra solução provisória seria str_replace (provavelmente terá que usar utf8_decode), assim:
<?php

$exemplo = '"Cavalo dado não se olha os dentes", disse a professora
Segunda linha';

$exemplo  = str_replace(array('"', '"'), '"', $exemplo);

$texto = nl2br($exemplo);

echo $texto;

Vale lembrar que o documento PHP que usar isto terá que ser salvo em "Utf-8 sem BOM".
Você também pode começar a usar header('Content-Type: text/html; charset=utf-8'), mas isso realmente só se desejar e claro que as aspas ali continuarão a ser os UNICODEs " (U+201C) e " (U+201D)
Comment: Valeu, colocando para repor " não funciona. Mas acabei descobrindo que os valores das aspas são  e (< 0x94 >e < 0x93 >). Me ajudou muito, obrigado!
Comment: @caiocafardo o iconv funcionou? Copiei da string que colou na sua pergunta, no teste que fiz ele funcionou: https://ideone.com/yO1Wsh, vale notar que tudo isto eu presumi que você esta usando ISO88591 ou windows1252 com codec em sua página.

Mostrar aspas vindas do MySQL


Probability Generating Functions and Discrete Time Queuing Chains

Question: I've been learning about Markov Chains for a reading course I'm doing and I've become stuck on some of the notes I was given. It defines a discrete time queuing chain for a server by $$X_{t+1}=\begin{cases} X_{t}+Y_{t+1}-1 & , X_{t}>0\\Y_{t+1} &, X_{t}=0\end{cases}$$ where $X_{t}$ is the number of job requests in the queue and $Y_{t}$ is the number of job requests that join the chain at time $t$ which follows a Poisson distribution with parameter $\lambda$. There is only one server and it can can only complete one job at each time $t$ (if there are jobs in the queue).
From this we have the transition matrix $P$ with entries defined by $P(0,y)=f(y)$ and $P(x,y)=f(y-x+1)$ where $f$ is the probability density function of $Y_{t}$, $x$ is the current state, and $y$ is the future state.
My issue is that the notes claim that if we have some distribution $q(i)$ defined for integer $i\geq0$ that satisfies $qP=q$ then the probability generating function of $q$ is given by $$\Phi_{q}(s)=\frac{q(0)\Phi_{Y}(s)(s-1)}{s-\Phi_{Y}(s)}$$ where $\Phi_{Y}(s)$ is the probability generating function of $Y_{t}$.
I have no idea how to even derive this expression. I tried using the basic pgf formula of $\Phi_{q}(s)=E\left(s^{q}\right)=\sum_{i} q(i)s^{i}$ and then substitute in the relationship given, but this doesn't appear to help. Could anyone please explain either how to derive this expression, or give me a large shove in the right direction please?
Answer: Here's the shove. We can agree that the number of job requests $Y_t$ has probability generating function (pgf) $\Phi_Y(s)$ regardless of $t$, right? Then obtain $\Phi_{q,t+1}(s)=\text{E}[s^{X_{t+1}}]$, the pgf of the number of jobs in the queue at $t+1$ as follows using the system equations you provide, where it is understood that $\Phi_{q,t}(0)=\text{Prob}[X_t=0]$,
\begin{align}
\Phi_{q,t+1}(s)=\text{E}[s^{X_{t+1}}] & = \text{E}[s^{X_{t+1}}| X_{t}>0] \text{Prob}[X_t>0] + \text{E}[s^{X_{t+1}}| X_{t}=0] \text{Prob}[X_t=0]\\
& = \text{E}[s^{X_t+Y_{t+1}-1}| X_{t}>0] (1-\Phi_{q,t}(0)) + \text{E}[s^{Y_{t+1}}| X_{t}=0] \Phi_{q,t}(0)\\
& = \Phi_Y(s)\frac{1}{s}\text{E}[s^{X_t}| X_{t}>0] (1-\Phi_{q,t}(0)) + \Phi_Y(s) \Phi_{q,t}(0)
\end{align}
where the independence between $Y_{t+1}$ and $X_t$ was used in both terms. The implicit assumption is made that the queue reaches an equilibrium as $t\to\infty$ which means that the distribution of the number of jobs in the queue no longer changes with time. In other words, after some time we have that $\Phi_{q,t+1}(s) = \Phi_{q,t}(s) = \Phi_{q}(s)$. Now see what you get if you substitute that in the above relation.
Comment: Thanks for the shove! It really helps and I think I've got it now.


Flutter não encontra pubspec.yaml quando executo run

Question: Fiz a instalação do dart + flutter pela primeira vez hoje, fiz a configuração orientada pelo Getting Start do próprio site oficial, porém na hora de dar RUN no projeto, aparece esse erro:

No pubspec.yaml file found.

Já tentei executar o flutter upgrade porém ainda assim não resolveu, no flutter doctor não aparentou problemas e também é a ultima versão instalada.
Como posso resolver?
Comment: Verifique se o diretório que vc está é a raiz do projeto. Para isso pode simplesmente abrir a pasta pelo `explorer` do windows ou então utilizar o comando `dir` no terminal e ver os arquivos que estão listados. O erro que está recebendo fala que vc não está na raiz do projeto.
Comment: Foi isso mesmo @LeonardoPaim, acabei me confundindo com as pastas e por isso o erro. A dica da lista de arquivos no terminal foi importante, não sabia dessa ferramenta. Obrigado!
Comment: Postei como resposta para que possa ser consultada mais facilmente.
Answer: O diretório onde está rodando o comando não é o diretório raiz do projeto. O comando flutter run precisa ser executado em uma pasta que contenha os arquivos do projeto flutter e o pubspec.yaml é um desses arquivos.
Uma dica que pode ser usada é listar os arquivos da pasta. No Windows por exemplo, pode facilmente verificá-los através do comando dir.
Quando posicionar dentro da pasta o comando funcionará.


why does response codes returned by httplib and urllib not match?

Question: I'm writing a dead link detector and wondering which lib i should use, httplib and urllib, so I tried both.
def http_response_code(url):
    host = urlparse(url)[1]
    req = '/'.join(urlparse(url)[2:5])
    conn = httplib.HTTPConnection(host)
    conn.request('HEAD', req)
    res = conn.getresponse()
    return res.status, res.reason

def urllib_response_code(url):
    a = urllib.urlopen(url)
    return a.getcode()

def main():
    url = 'http://1010wins.com/content_page.php?contenttype=4&contentid=6077355'
    print http_response_code(url)
    print urllib_response_code(url)

But I'm confused about the mismatch of results returned by the above 2 methods, which are:

(302, 'Found')
  200

I think maybe it's because urllib automatically detect the redirect and fetch the final destination page, and then return the response code?
Thanks.
Answer: 302 is the HTTP status code for a redirect (see for example here), and httplib (the lower-level library) returns it faithfully, while urllib is automatically following the redirect and giving you the final resulting status code (200 for "everything OK").
Pick the library that best suits the abstraction layer you want to work at -- httplib gives you a lot more control, but it's less general (won't do anything with URLs with other protocols such as ftp:, etc, for example) and lower-level (so you have to do a bit more work!-).


Error while compiling statement: FAILED: ParseException line 1:49 cannot recognize input near '(' 'stock_status_id' ',' in statement

Question: Hive version : Hive 1.1.0-cdh5.7.1
While executing the insert into statement, I am getting the below error

Error while compiling statement: FAILED: ParseException line 1:49
  cannot recognize input near '(' 'stock_status_id' ',' in statement

INSERT INTO table tgt_ebr_stores_physical_counts (stock_status_id,stk_no,description,avg_unit_cost,phy_cnt_date,issue_date,rcpt_date,adj_date,review_date,on_reqst_only_flag,row_bin,primary_flag,new_qty,cap_qty,user_code,description_1) SELECT EIM_STOCK.STOCK_STATUS_ID,EIM_STOCK.STK_NO,EIM_STOCK.DESCRIPTION,EIM_STOCK_COSTS.AVG_UNIT_COST,EIM_STOCK_HISTORY.PHY_CNT_DATE,EIM_STOCK_HISTORY.ISSUE_DATE,EIM_STOCK_HISTORY.RCPT_DATE,EIM_STOCK_HISTORY.ADJ_DATE,EIM_STOCK_HISTORY.REVIEW_DATE,EIM_STOCK_LOCATION.ON_REQST_ONLY_FLAG,EIM_STOCK_LOCATION_QUANTITIES.ROW_BIN,EIM_STOCK_LOCATION_QUANTITIES.PRIMARY_FLAG,EIM_STOCK_LOCATION_QUANTITIES.NEW_QTY,EIM_STOCK_LOCATION_QUANTITIES.CAP_QTY,TSW_CODES.USER_CODE,TSW_CODES.DESCRIPTION FROM AAA_ORCL_SLK_M003P.EIM_STOCK EIM_STOCK JOIN AAA_ORCL_SLK_M003P.EIM_STOCK_LOCATION EIM_STOCK_LOCATION ON EIM_STOCK.STK_NO=EIM_STOCK_LOCATION.STK_NO JOIN AAA_ORCL_SLK_M003P.TSW_CODES TSW_CODES ON EIM_STOCK.ISSUE_UOM_ID=TSW_CODES.CODE_ID JOIN AAA_ORCL_SLK_M003P.EIM_STOCK_LOCATION_QUANTITIES EIM_STOCK_LOCATION_QUANTITIES ON EIM_STOCK_LOCATION.STK_NO=EIM_STOCK_LOCATION_QUANTITIES.STK_NO AND EIM_STOCK_LOCATION.LOC_CODE=EIM_STOCK_LOCATION_QUANTITIES.LOC_CODE JOIN AAA_ORCL_SLK_M003P.EIM_STOCK_HISTORY EIM_STOCK_HISTORY ON EIM_STOCK_LOCATION_QUANTITIES.STK_NO=EIM_STOCK_HISTORY.STK_NO AND EIM_STOCK_LOCATION_QUANTITIES.LOC_CODE = EIM_STOCK_HISTORY.LOC_CODE JOIN AAA_ORCL_SLK_M003P.EIM_STOCK_COSTS EIM_STOCK_COSTS ON EIM_STOCK_HISTORY.LOC_CODE=EIM_STOCK_COSTS.LOC_CODE AND EIM_STOCK_HISTORY.STK_NO=EIM_STOCK_COSTS.STK_NO;

Can someone please help?
Answer:
"As of Hive 1.2.0 each INSERT INTO T can take a column list like INSERT
INTO T (z, x, c1)."
LanguageManualDML-Synopsis.1

Hive 1.1 does not support column list.
You should insert all columns by their order in the destination table.
INSERT INTO table tgt_ebr_stores_physical_counts SELECT ...


Do attribute assignment operators need to be declared in NAMESPACE? How?

Question: I have a package with a function foo which uses rlang::fn_fmls() and rlang::fn_fmls()<-:
#' @importFrom rlang fn_fmls missing_arg
foo <- function(x) {
  args <- rlang::fn_fmls(x)
  args <- c(args, bar = rlang::missing_arg())
  rlang::fn_fmls(x) <- args

  return(x)
}

Using roxygen2, I obviously need to document this function with an @importFrom rlang ... in order to get those functions declared in my NAMESPACE. However, does the inclusion of fn_flms there also handle the declaration of fn_fmls<-? Or does it also need to be included separately? If so, how? @importFrom rlang fn_fmls<-? "fn_fmls()<-"?
Answer: fn_fmls<- is an entirely separate function, an example of what is a called a replacement function, which you can read more about at the link. The gist is it must take the form function_name<-, and always returns a modified version of its first argument.
We can see in the rlang documentation that fn_fmls<- takes two arguments, fn and value. The function is used to replace the formal arguments of fn with value. Using a very simple example, if we only import fn_fmls, we get:
#' @importFrom rlang fn_fmls
foo <- function(values) {
  fn <- function(a = 1, b = 2) A + B
  fn_fmls(fn) <- values
  fn()
}

foo(list(A = 10, B = 20))
#> Error in fn_fmls(fn) <- values : could not find function "fn_fmls<-"

Instead, if we import fn_fmls<-, we get:
#' @importFrom rlang `fn_fmls<-`
foo <- function(values) {
  fn <- function(a = 1, b = 2) A + B
  fn_fmls(fn) <- values
  fn()
}

foo(list(A = 10, B = 20))
#> [1] 30

Note that we didn't have to import fn_fmls. This is because again, the similar naming is just a convention of convenience, since fn_fmls is a function to retrieve formal arguments of a function, it makes logical sense to name a function to replace formal arguments of a function fn_fmls<-, since it will be written as fn_fmls(fn) <- value.


Polynomial extrapolation

Question: If $p(x)$ is a polynomial of degree $n$ and $p(k) = k/(k + 1)$ for $k = 0, 1, 2, \ldots,n$, find $p(n + 1)$.
I'm not looking for a solution, I just want help starting it.
*Edit: Typo in original post,
Comment: You write "p(k)=k=(k+1)." What does that mean?
Comment: Apologies, this is a typo! p(k) = k/(k+1) for k = 0; 1; 2; : : : ; n, find p(n + 1).

I feel like simply saying p(n+1) = n+1/(n+2) is not exactly what I'm looking for.
Answer: I present a method of solution, but it might not be what you're looking for because it is tedius. Using the standard way to solve these kinds of problems, let
$$p(x)=a_0+a_1x+\cdots+a_nx^n$$
You can see using $p(0)=0$ that $a_0=0$. For the remaining $n$ coefficients we have a system of equations
$$a_1+a_2+\cdots+a_n = \dfrac{1}{2}$$
$$2a_1+2^2a_2+\cdots+2^na_n = \dfrac{2}{3}$$
$$\vdots$$
$$na_1+n^2a_2+\cdots+n^na_n = \dfrac{n}{n+1}$$
Or
$$\left[\begin{matrix} 1 & 1 & 1 & \cdots & 1\\
2 & 2^2 & 2^3 & \cdots & 2^n\\
\vdots & \vdots & \vdots & \cdots & \vdots\\
n & n^2 & n^3 & \cdots & n^n\end{matrix}\right]\left[\begin{matrix} a_1\\a_2\\ \vdots\\ a_n\end{matrix}\right] = \left[\begin{matrix} 1/2 \\ 2/3 \\ \vdots\\ n/(n+1)\end{matrix}\right] $$
The matrix here is the transpose of a Vandermonde matrix, and an inverse formula is known for it (but quite messy). Using the fact that $\left(A^{-1}\right)^T=\left(A^T\right)^{-1}$, we can find what $a_1,...,a_n$ are by multiplying the inverse to both sides, and finally evaluate the polynomial at $n+1$.
Answer: $q(x)=(x+1)p(x)-x$ is a polynomial of degree $n+1$ and has the $n+1$ roots $x=0,1,...,n$, i.e.,
$$q(x)=(x+1)p(x)-x=cx(x-1)...(x-n)$$
Inserting $x=-1$ results in a value for $c$, which determines the solution.

$$q(-1)=1=c(-1)(-1-1)...(-1-n)=c(-1)^{n+1}(n+1)!$$
Now setting $x=n+1$ gives
$$q(n+1)=(n+2)p(n+1)-(n+1)=c(n+1)(n+1-1)...(n+1-n)=c(n+1)!=(-1)^{n+1}$$
Answer: There may be a slicker way of doing this, but I'd look into Lagrange interpolation. Since you have $n+1$ points of a polynomial of degree $n$ it should be uniquely specified.

Polynomial extrapolation


Getting TypeError while including multiselect option using Angular.js

Question: I am getting the following error while trying to integrate angular multiselect.

Error:

TypeError: _.contains is not a function
I am explaining my code below.

Selected Model: {{example14model}} | json

Here suppose user clicked on drop down list and then clicked on outside to close that list or get back to normal state of the list at that time this type error is coming in console.
My controller side code is given below.
var app = angular.module('myApp', ['angularjs-dropdown-multiselect']);

app.controller('AppCtrl', function ($scope) {
    $scope.example14model = [];
    $scope.example14settings = {
        scrollableHeight: '200px',
        scrollable: true,
        enableSearch: true
    };
    $scope.example14data = [{
    'id':1,
    'label':'aaa'
  },{
    'id':2,
    'label':'bvc'
  },{
    'id':3,
    'label':'rtcv'
  },{
    'id':4,
    'label':'uytg'
  }
  ];
    $scope.example2settings = {
        displayProp: 'id'
    };
});

That opened drop down list also not closing after click on outside.My Total code is here. Please help me.
Answer: This is an issue with the lodash version. You have used a version that doesn't have contains method
Refer this
https://github.com/mgonto/restangular/issues/1298
Try using a lower version.


Arbitary plane curve.

Question: Does an arbitrary curve in the plane necessarily pass through a rational point? That is, a point of the form $(a,b)$ where $a$ and $b$ are rational numbers.
Comment: line $y=x+ \pi$
Comment: Some don't; the rest almost never do.  (In $ \ \mathbb{R}^n \ $ , "almost nothing" is a rational point.)
Comment: You should clarify what you mean by *arbitrary* and by *curve*. For example, are you considering algebraic, smooth, or continuous (or maybe some other kind of) curves? And by arbitrary do you mean every curve or do you mean "almost every" curve (in some sense to be specified)?
Comment: Every continuous non constant function from an interval into $R^2$
Comment: I don't know if there is a way to put a topology or a measure on $\mathcal{C}^0([0,1],\Bbb{R}^2)$ (which are the only two ways I know of that give a precise meaning to the term *arbitrary*), but I would guess that by most standards almost all those functions don't have a rational point, as they can be quite ill-behaved.
Answer: Set $\{(\sqrt{2},y):y\in\Bbb R\}$ is a line, thus a curve, yet it passes through no rational point, as $\sqrt{2}\not\in\Bbb Q$.
Comment: I may be reading too much into this, but I think that the OP is asking weather the generic plane curve (if there is a way to formalise this notion) must have some rational points.

Arbitary plane curve.


ASP.NET Dynamic menu creation with sql data base

Question: just wondered what are the steps for a
role based menu using sitemap and sql server database..
Answer: I found this tutorial very useful for building a database driven ASP.net menu.
http://aspalliance.com/822


Is 'Include /path/to/*/live.conf' possible with Apache?

Question: We store VirtualHost entries in (dev|staging|live).conf files within the SVN repository for the site.
For example:
/var/www/vhosts/site1.com/live.conf
/var/www/vhosts/site2.com/live.conf

It'd be handy to be able to include them automatically, such as:
Include /var/www/vhosts/*/live.conf
But that doesn't seem to work.
We've worked around it with a simple PHP script:
$vhosts = '';
foreach (glob('/var/www/vhosts/*/vhost/dev.conf') as $filename) {
    $vhosts .= "\nInclude $filename";
}

file_put_contents('/var/www/vhosts/vhosts.conf', $vhosts);

However, I'd love to simplify and get Apache (2.2.3) to do the job without requiring the PHP step.
Possible?
Answer: apache2 does not support wildcards in includes.
However, you could arrange it a bit in the following manner:

create some directory for your configs (such as /etc/apache2/myconfigs)
symlink your configuration dynamically to apache2:

rm -f /etc/apache2/myconfigs/*
for i in $(find /var/www/vhosts/*/live.conf); do \
tempfn=$(echo $i|cut -d/ -f5-6|sed s,/,_,);  \
ln -s $i /etc/apache2/myconfigs/$tempfn.conf \
done

add a "Include /etc/apache2/myconfigs" in your apache2.conf

Note: on cut, i used -f5-6 for delimiter joining (to provide something like site1.com_live.conf symlink name), but you might have to adjust that according to your own fs path.
Note on note: the above is for bash, might need adapting for other shells.
Answer: I've tested, it through the below error when checking syntax:

httpd: Syntax error on line 211 of /etc/httpd/conf/httpd.conf:
  Wildcard patterns not allowed in Include /etc/httpd/*/pr.conf

According to the documentation, from version 2.0.41, it supports the wildcard matching follow shell-style (fnmatch()). But it seems that it only works with the file (or the last component in the path), not the directory.
Testing with python, it returns true:
In [1]: import fnmatch

In [2]: fnmatch.fn
fnmatch.fnmatch      fnmatch.fnmatchcase

In [2]: fnmatch.fnmatch('/etc/httpd/site1.com/live.conf','/etc/httpd/*/live.conf')
Out[2]: True

Comment: According to my apache 2.2.19:
apache2: Syntax error on line 229 of /etc/apache2/apache2.conf: Wildcard patterns not allowed in Include /etc/apache2/conftest/*/a.conf
Comment: My 2.2.12 on Ubuntu and 2.2.3 on CentOS 5 gives me `Wildcard patterns not allowed in Include`
Comment: It looks like wildcards are only allowed in the last component of the path.
Answer: mod_perl allows for the following construct:
<Perl>
    foreach $file (glob '/etc/httpd/conf.d/vhosts/*/live.conf') {
        push @Include, $file;
    }
</Perl>

This can be used in place of the Include directive.
Answer: I have had this problem for a while and have written a blog post on how to fix it by applying some patches to apache, I hope it helps.  I works for me :)
http://wes.limethinking.co.uk/2011/09/07/apache-include-directive-wildcards-in-directory-names/


Git fatal: unable to write new_index file

Question: We are a web development company that is transitioning to Git.
Eventually we intend to run it fully locally but at the moment we have development websites hosted on a Linux server, which is also where the Git repos are (which I create via Tower on my own machine).
Our developers connect to this server via either AFP (Mac) or Samba (Windows / Linux) and use a combination of Tower and Sourcetree to check in these changes.
Our web development folder on this server is shared and permissioned so that all read / writes are done as the www-data user. Not ideal by any means and not something I'd do in production but it works for us. Mostly....
Every so often when attempting to stage modified files or commit them, this error message is received:
fatal: unable to write new_index file

Sometimes it's just "index", with no "new_" prefix.
I have found that SSHing to the server as the www-data user, cd'ing to the .git folder within the project, and then renaming index to something else and back again often fixes this problem. The permissions (660) are correct on the file before and after this, but the rename trick seems to work.
Apart from the obvious long term goal of having Git / websites running on the developer's own machines, is there a solution to this - or is it simply that managing a Git repo remotely isn't recommended?
Answer: Sounds like you're actually sharing the same working repo across multiple users, which is in general not a good idea:

you're opening up to conflicts in the repo control - the errors could very well indicate such conflict, the file renaming would simply mask it but I guess changeset loss or even serious corruptions may happen especially if different machines use different versions of git
you're losing the identity of the author in the repo history

I'd suggest creating a group-shared bare git repo (specifically designed for sharing) on that very same partition, accessible to the developer machines in the same way as the current repo (plenty of info out there, you could start at https://stackoverflow.com/questions/7632454/how-do-you-use-git-bare-init-repository):

developers would git clone/git pull from this bare repo into their own local working repos where they make git commit their changes and then git push them back into the shared repo
another repo would be pulled by www-data from the bare repo on the linux server for serving the development websites; a git pull in this one would 'refresh' the content with all commits pushed in the bare repo since the last git pull (a httpd restart may be needed as well after that)
Answer: I know this is old, but I still experience this same problem.
It doesn't work over AFP. Instead, connect to the share on SMB and it'll work.


MongoDB dynamic query with javascript, working static, not with variable

Question: I've been writing an app in express, using a standard mongodb driver, version 3.2.6. I need to make a query to my database, and I'd like to make it for 5 years and count entries for each year. When I write the code statically it works without problem, if I so much put the same exact value into a variable and insert it into the query, it refuses to work.
I apologize if this is something obvious I missed, but I fail to find a solution. Thanks for everyone attempting to help :)
This code works. The output is bellow
router.get("/test", (req, res) => {
    result = {
        title : "Somethings through time",
        data : []
    }
    for(let i = 4;i<9;i++) {
        const query = `/2014/`;
        db.getDB().collection("somethings").find({"date_of_something": /2014/}).count().then(numOf => {
            console.log(query +"\n"+numOf);
        });
    }
    res.json({
        success: false
    });
});

Output:
[0] /2014/
[0] 24263
[0] /2014/
[0] 24263
[0] /2014/
[0] 24263
[0] /2014/
[0] 24263
[0] /2014/
[0] 24263

This code does not work.
router.get("/test", (req, res) => {
    result = {
        title : "Somethings through time",
        data : []
    }
    for(let i = 4;i<9;i++) {
        const query = `/2014/`;
        db.getDB().collection("somethings").find({"date_of_something": query}).count().then(numOf => {
            console.log(query +"\n"+numOf);
        });
    }
    res.json({
        success: false
    });
});

Output:
[0] /2014/
[0] 0
[0] /2014/
[0] 0
[0] /2014/
[0] 0
[0] /2014/
[0] 0
[0] /2014/
[0] 0

Comment: Also, I'm using the backticks (`) because I eventually want the query to look like `$201{i}`, to loop through years. The query does not work with " or ' either :/
Answer: This is a regex
/2014/

But this one with back ticks is just a normal string
`/2014/`

To create a new regex from a string you can do it like this
const query = new RegExp(`201${i}`)

In MongoDB to match using a regex you should use $regex operator
{"date_of_something": {$regex: query}}

Also worth noting you're returning the result res.json without waiting for the queries to finish, you should await for the queries, and the request handler should be async
router.get("/test", async (req, res) => {
    ...
    const numOf = await db.getDB().collection("somethings")
                   .find({"date_of_something": {$regex: query}}).count();
    console.log(query +"\n"+numOf);
})

Comment: Yes, this solves it! Thank you sir, you've enabled me to sleep tonight :)
Comment: Thanks, now I know what I've been doing wrong. But this still does not work for me. I still get 0 results if I use what you've written.
Comment: `date_of_something` is a date type field? how is the data look like
Comment: This is what the data looks like, "03.01.2014". it is a date in our format, written as a string, not an actual date type. Unless mongo automatically detected it, from importing a json file.
Comment: Where should I put the async? The await part is underlined red if I just use that.
The regex is not working if I keep it how it was though. If I type out the regex in the $regex: field it works, as a variable, not so much.
Comment: The async and await work now. The regex still getting no hits as a variable. Working flawlessly typed out.
Comment: oh sorry, updated, creating a regex from a string doesn't need to add the extra / , like this RegExp(`201${i}`)


Mosquitto isolated users

Question: Is it possible to configure mosquitto when user have the same topic name, but values will be isolated.
For example userA writes to topic "temperature"
And userB writes to topic "temperature"
userA should not see values from userB, etc
Answer: No, the topic space is shared between all users.
The best you can do is to use a ACL with a username substitution e.g.
pattern readwrite %u/temperature

This would set up a acl that allows the any user to publish/subscribe to [username]/temperature.
Comment: thank you, i thought that online services provide the one broker with separated user spaces
Comment: Cloud broker services may have separate topic spaces, but these are custom brokers, not mosquitto (which is the broker you asked about)
Comment: No publicly available ones that I am aware of. The concept is against the pub/sub model
Comment: could you please give me product names or services? i'll investigate it
Comment: @alexya CloudMQTT providing isolated user spaces.
It uses mosquito as a base and looks like this service generates mount_point for every user and user messages visible only in mount point space.

Mosquitto isolated users


Can HTTP GET be used if there are small side-effects?

Question: As far as I understand, GET has to be idempotent - it cannot change anything in the system and repeating it should always return the same unless something else changed the state of the application.
Problem is, on my website, there should be a lot of little changes based on whether some content has been already seen before by the user. I mean, like notifications, new message alerts, content sorting based on whether user saw it or not, how many users saw the content counters... For example when user clicks on notification, the notification should disappear from his notification panel and never be seen there again, so it changes something - state of the notification, but I can press F5 as many times as I want and it always returns the same page with same info, same buttons etc.
Can I ignore this kind of side-effect as too small and I can use GET or do I have to make most links and buttons on the website use POST like I do with links and buttons which lead to more "serious" changes? I do that by making forms around each of them with those links as form actions and original buttons as submit buttons of the form which seems a little messy to me and I don't want it almost everywhere (or is there a better way?).
Comment: The more important question is whether the request is *safe*, see https://greenbytes.de/tech/webdav/rfc7231.html#safe.methods
Comment: [This related answer](https://stackoverflow.com/a/58013757) provides some insights based on RFC 7231.
Answer: This can be tackled from several points of view, I'll illuminate it from this angle:
The end result here is always the same, hence the request is idempotent.
The user visits the URL, the end result is that the notifications are cleared. They can visit the page again and again, the end result is that the notifications are cleared. They're not going to get an error message because the notifications have been previously cleared (that would not be idempotent). Yes, they will see different content each time they visit the page, but nothing says that the page content must be identical each time the resource is requested (that would put half the web in a bind).
Contrast that with a POST request to /questions (which creates a new question, for example): each time you repeat that POST request, a completely new resource is being created. You POST once, and /questions/12345 is being created. You repeat the same request, /questions/12346 is being created. That is not idempotent.
No, you do not need to make all those requests into POST requests.


Missing modules after fresh generation with Yeoman's angular-fullstack

Question: So, I generated a fresh angular-fullstack with TypeScript, MongoDB, Bootstrap, Bootstrap UI, Authentication Boilerplate, Twitter and Google OAuth, Grunt, Jasmine, HTML, CSS, and UI-Router for the settings.
After I ran npm install and bower install. There were some unmet dependencies, so I installed

TypeScript, locally
Mocha, locally
Tslint, locally

Also, I was getting an error during build that was resolved by installing
firstname.lastname@example.com, locally.
Now, when I run "grunt serve" It all works just fine, except when I go to the Admin page at http://localhost:9000/admin. There is no list of users. Instead it says, "The delete user and user index api routes are restricted to users with the 'admin' role." All of the links on the navigation bar are dead, except for the app title.

When I check the console I get these two errors:

Uncaught Error: [$injector:nomod] Module
  'perfectAlgorithmDrillsApp.auth' is not available! You either
  misspelled the module name or forgot to load it. If registering a
  module ensure that you specify the dependencies as the second
  argument.
Uncaught Error: [$injector:nomod] Module
  'perfectAlgorithmDrillsApp.admin' is not available! You either
  misspelled the module name or forgot to load it. If registering a
  module ensure that you specify the dependencies as the second
  argument.

I triple-checked. They are not misspelled and they are correctly included in the list of module dependencies.
Further errors arise because the module isn't loaded. Obviously, it can't find the controllers, since those modules aren't loaded.
At this point, I have not added or changed any code.
I've tried a couple things to resolve the situation:

updating yo and angular-fullstack and then recreating the project from scratch.
wrapping those "missing" modules in IFFE's.
I updated node.js to the latest LTS version

More Details:

I am running everything on OSX El Capitan 10.11.2
I'm running node version 4.2.6, npm version 2.14.12, yeoman 1.6.0
in the yo.rc file it says the generator version is "3.3.0-beta.0"
I have mongod running.
I'm doing my work in WebStorm, but I haven't used anything that's built in. It's all been command line.
The TypeScript is being compiled correctly, as the .tmp directory looks good.
I made sure grunt-cli is installed.

Thanks so much for the help. Let me know if you need any more details.
Answer: I too had this exact problem. The long answer (plus some other answers to questions you might not be asking for yet or possibly ever) is here, but in short, replace var module = /\.module\.js$/; with var module = /[\w/]+.module.ts$/; inside Gruntfile.js.
If that doesn't work, try going here to see the whole thread on this issue.


NameError: global name is not defined when calling @staticmethod in python

Question: I am making a small project and I have a main file, called blog.py and a separate file called users.py in a folder called source.
The layout of the project so far is:
MainFolder
    |_blog.py
    |
    |_source
        |_user.py

So, my user.py is very simple and it has a @staticmethod:
from google.appengine.ext import db

class User(db.Model):
    username = db.StringProperty(required = True)
    pwd_hash = db.StringProperty(required = True)
    email = db.StringProperty()

    @staticmethod
    def searchByUsername(anUserName):
        usersList = db.GqlQuery("select * from User where username='" + anUserName + "'")
        user = None
        for theUser in usersList:
            user = theUser
        return user

In my blog.py file I try to call that method by making User.searchByUsername(anUserName), however when I do so everythning blows up and I end up with an error (check last 2 lines):
Traceback (most recent call last):
  File "/home/pedro/google_appengine/google/appengine/runtime/wsgi.py", line 266, in Handle
    result = handler(dict(self._environ), self._StartResponse)
  File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1519, in __call__
    response = self._internal_error(e)
  File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1511, in __call__
    rv = self.handle_exception(request, response, e)
  File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1505, in __call__
    rv = self.router.dispatch(request, response)
  File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1077, in __call__
    return handler.dispatch()
  File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 547, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "/home/pedro/google_appengine/hw5/blog.py", line 202, in post
    user = User.searchByUsername(username)
NameError: global name 'User' is not defined

I am using from source import user in my blog.py file, and the sources folder also has the __init__.py blank folder, so I know that file is being correctly imported.
Further more, if I just copy/paste the contents of the user.py file into the blog.py file everything works fine (but the I the code gets big and not organized). how can I fix this?
Answer: By doing from source import user, you are importing the module user, not the class User inside it.  If you want to import that class, you should do from source.user import User.  Or you can do from source import user and then refer to the class as user.User.
The staticmethod has nothing to do with it.  As the error message suggests, the issue is that it does not know what User is, so it can't even begin to call a method of that class.
Comment: Wow, I had not idea about the module thing. Thanks !
Answer: Sounds like you may have forgotten to import User into blog.py:
from source.user import User


Some trouble autopath

Question: I have some trouble with user path aliases. I want that every user has a small page under /member/username. To enforce that I build in the settings (/admin/config/search/path/patterns) under user path the plattern: member/[user:name].
This seems to work fine but if I look at the contact link I get the link /user/1/contact I expect the link http://example.com/member/username/contact.
I have the same problem for some other links like editing any node. E.g. I have a link in my menu called Updates which is aviable under /updates but when I try to edit this one I see the url /node/123/edit.
I know that there is a module called Extended Path Aliases but this one breaks one of my own modules.
The problem there is that I use taxonomy to build paths for topics e.g. photography and sports. Normal posted news are then aviable under /photography/a-great-day or /sports/scores that will work with Extended Path Aliases, but it compleatly breaks my module with this pathes sports/event/%date (notation from menu_hook). That one seems to be routed to /sports.
Answer: I got the solution via IRC. Simply install and activate Sub-pathauto.

Some trouble autopath


groups and owners with ftp

Question: When a user "U" who is part of group "G" uploads a new file to the server with ftp , the permissions are set as U:U instead of U:G . I know the user is also part of his own group called "U" but how do I have them upload a file with the group "G". I don't see anyhthing in any FTP software.
Thanks
Comment: See: http://serverfault.com/q/93894/984
Comment: and: http://serverfault.com/questions/184548/ftp-and-apache-permission-issues
Answer: Generally you do this when you want all files in a directory to be owned by a certain group.  To make this happen set the SETGID bit on the directory chmod g+s.  Then any file created in that directory will belong to the group that is associated ith the parent directory.

groups and owners with ftp


Is it possible to determine what attachments (JS libraries, CSS, etc.) are required by a node form?

Question: I'm developing a solution which allows users to create content through a custom AJAX-driven UI. The first step in the process requires users to pick a content type from a dropdown list, which will then trigger the relevant node form to be loaded in to the page via AJAX. The HTML for the node form is being built correctly, but the issue I'm experiencing is that required JavaScript libraries are not included in the page, e.g. system libraries such as drupal.ajax and jquery.form, and libraries provided by contributed modules such as CKEditor and the media browser provided by the Media module.
Is there an elegant way of determining what libraries are required by node forms for a range of content types before the form is loaded? My intention would be to include all of the libraries using drupal_add_library, drupal_add_js and drupal_add_css in the page callback function for the UI.
Thanks in advance to anyone who has any ideas!
Answer: The most elegant way to do that is define attachments in hook_form_FORM_ID_alter. You can specify css files, js files or libraries:
$form['#attached']['library'][] = array('system', 'jquery.cookie');
$form['#attached']['js'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.js';
$form['#attached']['css'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.css';

Comment: Thanks for your reply, but unfortunately it doesn't answer my question. I don't need to _add_ additional attachments to the form, I'd like to know if there's a way of finding out what libraries etc. are _already_ attached based on all of the fields that make up the node form for a specific content type.