Verificar intervalo entre duas datas

Question: Preciso verificar se o intervalo entre duas datas não ultrapassa 12 meses, para isso fiz o seguinte em javascript:
var dataFinal = new Date();
var dataInicial = new Date();

dataFinal.setMonth($data.formInput.dataSelecionada.getMonth() +12);
dataInicial.setMonth($data.formInput.dataSelecionada.getMonth() -12);

var situacao = true;
if ($data.formInput.dataSelecionada02 >= dataFinal || $data.formInput.dataSelecionada02 <= dataInicial){
    situacao = false;
} else {
    situacao = true;
}

return (dataInicial+' | '+dataFinal);

Porém se eu seleciono a data 01/01/2017 inicialmente funciona normalmente, me é exibido 01/01/2016 e 01/01/2018 porém se eu mudo a data para 01/02/2016 ao invés das datas passarem a ser 01/02/2015 e 01/02/2017 me é retornado 01/02/2016 e 01/02/2018, ou seja, o dia e o mês até alteram porém o ano não, como poderia resolver isso?
Comment: Existe uma biblioteca javascript chamada moment.js ela faz examtemnte o que vc esta querendo fazer https://momentjs.com/
Comment: @GuilhermeXavier, não recomende o uso da biblioteca `Moment.js.` essa biblioteca foi descontinuada e é mantida apenas para suprir projetos legados. Os próprios autores da biblioteca recomendam a [não utilização dessa biblioteca em novos projetos](https://momentjs.com/docs/#/-project-status/).
Answer: Espero que isso possa ajudar:
var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
  month1++;
  month2++;
}
var numberOfMonths;

1.Não considerando os meses month1 and month2:
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;

2.Considerando apenas um dos meses:
numberOfMonths = (year2 - year1) * 12 + (month2 - month1);

3.Considerando ambos os meses:
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;

Qualquer dúvida, segue o link para auxiliar
Answer: Acredito que o erro está na maneira como calcula a diferença entre datas. Um abordagem mais simples é a seguinte:

var date1 = new Date(2018, 01, 01);
var date2 = new Date(2019, 02, 25);

var umDia = 1000*60*60*24;
var diasNoMes = 30;
var meses = Math.round((date2 - date1)/umDia/diasNoMes);

if (meses > 12){
  console.log("Superior a 12 meses!")
}
console.log(meses);

:)

Verificar intervalo entre duas datas


Query SQL, Mostrar sempre primeiro registro de um campo que se repete

Question: Estou com dificuldade de listar somente uma linha de cada processo.
A query precisa trazer sempre os protocolos com a ultima revisao.

Ex: Mostrar somente o processo de numero 2 da ultima revisão 2
e   Mostrar somente o processo de numero 1 da ultima revisão 3
Select
Numero_Processo Processo
, Numero_Revisao Revisao
,Titulo
,Id
,Data_Criacao
 FROM Qualidade_Insp_Inj_Processo
 WHERE Data_Exclusao is null

order by Numero_Processo desc, Numero_Revisao desc

Ja tentei o Group By, mas como o campo revisao é sempre é diferente ele traz todos os protocolos com todas as revisões
Comment: Tem várias maneiras> usar row_number aggregando pela coluna que você quiser ou um self-join ou mesmo uma subqueri p/ retornar o max segundo algum critério e dai retornar só os registros que satisfaçam a sub-query. Favor ao postar uma pergunta sobre query taggear com o SGBD pois vários recursos não são SQL Ansi
Answer: Tente usar assim:
SELECT
   Numero_Processo Processo
   , Numero_Revisao Revisao
   , Titulo
   , Id
   , Data_Criacao
FROM
   Qualidade_Insp_Inj_Processo
WHERE
   Id = (
      SELECT
         aux.id
      FROM
         Qualidade_Insp_Inj_Processo aux
      WHERE
         aux.Numero_Revisao DESC LIMIT 1
   )
   AND Data_Exclusao IS NULL
ORDER BY
   Numero_Processo DESC
   , Numero_Revisao DESC

Comment: Não funcionou, ele continua listando todos os processos pois a Numero_Revisao é diferente.
Answer: Você pode filtrar pela Id com um sub-select ordenando pelo número da revisão:
SELECT
    p.processo,
    p.revisao,
    p.titulo,
    p.id,
    p.data_criacao
FROM
    processos p
WHERE
   p.id = (
      SELECT top 1 x.id
      FROM processos x
      WHERE x.processo = p.processo
      ORDER BY revisao DESC
   );

Coloquei no SQLFiddle
Answer: Consegui usando select MAX dentro do where
SELECT Numero_Processo, Numero_Revisao Revisao,Titulo ,Id ,Data_Criacao
                                    FROM Qualidade_Insp_Inj_Processo Qproc
                                    WHERE Data_Exclusao is null
                                    AND   Numero_Revisao = (select Max(Numero_Revisao) processo
                                                                from Qualidade_Insp_Inj_Processo
                                                                where Numero_Processo = Qproc.Numero_Processo)


Pyspark SQL: How to left join dataframe A and dataframe B on two columns where dataframe B columns are NULL

Question: I am writing a script for a daily incremental load process using Pyspark and a Hive table which has already been initially loaded with data.
I've been trying to create a UC dataframe by left outer joining an INC dataframe and BASE dataframe on two PK columns src_sys_id & acct_nbr where INC dataframe columns are NULL.
I've tried the following syntax:
uc_df = base_df.join(base_df, inc_df("src_sys_id") == base_df("src_sys_id") &
inc_df("fleet_acct_nbr") == base_df("fleet_acct_nbr"),"left_outer").filter(inc_df("*").isNull).show(false)

But I keep getting syntax errors whenever I attempt to run the code block above...stating that a dataframe object is not callable
I don't have much experience running sql functions or queries w/Pyspark, so any suggestions or help is appreciated guys.
Comment: You are clearly not ready to use pyspark. Are you familiar with SQL?
Comment: & You clearly have your panties in a bunch for whatever reason snowflake. Either answer the question, offer some useful advice, or keep scrolling.

But so you know.. I'm working on a ETL script with pre-existing code for which TempViews & TempTables cant be used because of the nature of the data set and the code before this block which can't be shown.
Comment: You killed me with that "snowflake":-)) obviously my comment didn't land right... sorry for that. There where so many syntax errors in the provided code, therefore I was trying to guide you in another direction that might have suit you better. Also provided you with a detailed answer. Good luck with that ETL!
Answer: Sample dataset
base_df = spark.createDataFrame([(1,10,100),(2,20,200),(3,30,300),(4,40,400),(5,50,500)], 'id int, src_sys_id int, fleet_acct_nbr int')
inc_df  = spark.createDataFrame([(1,20,200),(2,40,400)], 'id int, src_sys_id int, fleet_acct_nbr int')

1st option (PySpark)
uc_df = base_df.join(inc_df, ['src_sys_id','fleet_acct_nbr'], "leftanti")

2nd option (Spark SQL)
base_df.createOrReplaceTempView('base')
inc_df.createOrReplaceTempView('inc')

sql_stmt = '''
select *
from   base left anti join inc using (src_sys_id, fleet_acct_nbr)
'''

uc_df = spark.sql(sql_stmt)

Results
uc_df.show()

+----------+--------------+---+
|src_sys_id|fleet_acct_nbr| id|
+----------+--------------+---+
|        10|           100|  1|
|        30|           300|  3|
|        50|           500|  5|
+----------+--------------+---+

As for your attempted solution:

You cannot use dataframe like this: df(...). It is not a function, therefore it is not callable. That is the reason for the error you get. You can reference a column by using df.col or df['col']
& has precedence over =. You should surround your equality conditions with brackets.
inc_df['*'].isNull() Is not a valid use for *. You should use a column.
Assigning show(...) to a dataframe will give you None.
.show(false) is wrong for 2 reasons: (1) The first parameter should be integer. (2) false literal in Python is uppercased: False. You should read the doc.

Here are a couple of options to fix your original code
uc_df = (base_df
         .join(inc_df,
               (inc_df.src_sys_id == base_df.src_sys_id) & (inc_df.fleet_acct_nbr == base_df.fleet_acct_nbr),
               "left_outer")
         .filter(inc_df.src_sys_id.isNull())
        )

uc_df = (base_df
         .join(inc_df,
               (inc_df['src_sys_id'] == base_df['src_sys_id']) & (inc_df['fleet_acct_nbr'] == base_df['fleet_acct_nbr']),
               "left_outer")
         .filter(inc_df['src_sys_id'].isNull())
        )

and a similar solution in Spark SQL
base_df.createOrReplaceTempView('base')
inc_df.createOrReplaceTempView('inc')

sql_stmt = '''
select  *

from                base as b

        left join  inc   as i

        on         b.src_sys_id     = i.src_sys_id
              and  b.fleet_acct_nbr = i.fleet_acct_nbr

where   i.src_sys_id is null
'''

uc_df = spark.sql(sql_stmt)


Como funciona Symbol no ES6?

Question: Na nova especificação do Javascript ECMAScript (ES6) foi criado um novo tipo primitivo chamado Symbol() qual é a utilidade dele?
Answer: Symbol() é um novo primitivo. Como Function, Object e Number.
O que é especial é que ele gera algo de único. Um Symbol é sempre único. Há quem diga que gera tokens (por serem únicos), sempre diferentes.
Ou seja:
var a = Symbol(123);
var b = Symbol(123);
console.log(a == b, a === b); // false, false

es6fiddle: http://www.es6fiddle.net/ihpaffj0/
Isto é verdade curiosamente até em nomes de propriedades de objetos.
var obj = {};
var a = obj[Symbol('prop')] = 'foo';
var b = obj[Symbol('prop')] = 'bar';
console.log(a, b, obj[Symbol('prop')]); // 'foo', 'bar', <vazio>

es6fiddle: http://www.es6fiddle.net/ihpapvuv/
Onde poderá ser útil?
É dificil adivinhar todos os casos de uso, mas alguns que imagino:

gerar Symbols unicos para ids e/ou sessões
evitar choques de nomes de propriedades de objetos

Boa leitura em Inglês

Blog Axel Rauschmayer: http://www.2ality.com/2014/12/es6-symbols.html
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
Comment: +1, legal, mas em quais cenários ele vai ser útil?
Comment: Bruh, isso sim é uma resposta +1
Comment: @mgibsonbr tens razão. E usando `Symbol.for('str');` ainda é mais fácil com `Symbol.keyFor(instancia)` ([jsfiddle](https://jsfiddle.net/v3ou4hzd/)). Bom ver-te! Se andasses por aqui mais vezes as respostas estariam ainda mais em ordem :)
Comment: @GabrielRodrigues juntei ideias, se surgirem mais vou juntar.
Comment: Acho que a ideia principal é que sejam usados como nomes de propriedades (Chaves). As chaves dos objetos nativos só são strings por motivo de compatibilidade com ES5-
Comment: Essa questão de só poder acessar a uma propriedade se tiver a chave correspondente me parece estranha. Afinal, as propriedades cujas chaves são `Symbol`s ainda são enumeráveis, não? Usando esse seu último código como exemplo, não seria o caso de fazer `var mensagemSecreta = obj[Object.getOwnPropertySymbols(obj)[0]];` e assim ter acesso ao valor mesmo sem conhecer a chave?

Como funciona Symbol no ES6?


$f : \mathbb{N} → \mathbb{R}$, f(x)= $\sqrt{x+4}$ - what is the range?

Question: For a revision task that I'm confused whether a solution is formal enough.
$f : \mathbb{N} → \mathbb{R}$
$f(x) = \sqrt{x+4}$
What is the range of this function?
Given $f(0) = \sqrt{4} = 2$ my initial guess is to say $\{\sqrt{x+4} \in \mathbb{N}\}$ or something like,
$X = \{y \in \mathbb{R} : y \in I\}$
$I = \{\sqrt{x+4} \in \mathbb{N}\}$
Meaning the range is any real number, such that it's equal to the square root of any natural number (non-negative integer) + 4, however I'm not sure if this is a formal enough way of defining the range.
Thanks for any help.
Comment: You should write $\{\sqrt{x+4} : x \in \mathbb N \}$.
Comment: Thanks @Desperado
Answer: The function maps from natural numbers to real number. Since it is increasing with increase in x, your lowest closed number should be f(1)=√5, and not f(0) since 0 is not a natural number. Your range becomes [√5, infinity)
Comment: Many people define $0$ to be a natural number; in my experience the two definitions are about equally common.


Can I put information from an API to another page?

Question: The title is the best I can really phrase it, however, heres my Microsoft Paint version of what I'm trying to do. If you guys know how to do it feel free to reply.
Heres what it is doing

Heres what I want it to do

Sorry for the bad drawings not the most artistic.
Comment: Does the API get called from the `index.html` and the process data will load to `2ndPage.html`?
Comment: @Francisaskquestion No, the API gets called from my app.js file, I have the form.js as a  in my index.html.
Answer: React basically is a single page application so one way in doing what you want is to use react-router-dom when the submit button is clicked, you send the form data to the backend and then dispatch a new route that will display the component that has the API data. inside the componentDidMount life cycle of the component that will display the api data you make a fetch to get the data.
Answer: I'm not sure whats the use case you are trying to solve, but I will assume that it is something similar to how search could work. ie: You enter something in input fields, push submit button -> hide form you are currently in and show results in next page.
Pseudo code could look like this
class Search extends React.Component {
  state = {
    query: "",
    results: null
  }

  handleOnChange = e => {
    this.setState({query: e.target.value})
  }

  formSubmit = () => {
    //do your request to api
       .then(response => this.setState({results: response}))
  }

  render() {
    return(
      this.state.results === null ? (
        <form>
           <input type="text" value={this.state.query} onChange={this.handleOnChange}/>
           <button type="submit" onClick={this.formSubmit}>Submit</button>
        </form>
      ):(

{this.state.results}

      )
    )
  }
}

Comment: Your answer was the most informative, however, I still dont quite understand how I'd implement this. Also sorry for the lack of information I gave, I'm making a weather app as a little project, this is how I have it setup, I have an app.js that calls the API, then the form.js which is just simple JSX of a form setup, and then weather.js which is also JSX that just has the format in which the information gets placed. In the end, I have an index.html which has a div class as root to have the forms in the html. If you have a Discord I can send you a few screenshots.
Comment: @looskie If you would add you code to codeSandbox, I could probably help you out.


'RatingControlChanged' is not a member of 'ASP.default_aspx'.

Question: net using VB. I followed this tutorial for doing my ratings controller
But I am getting the following error
Error   1   'RatingControlChanged' is not a member of 'ASP.default_aspx'.   C:\Users\raj\Documents\Visual Studio 2013\WebSites\WebSite13\Default.aspx   46
Error   2   'ratingControl' is not declared. It may be inaccessible due to its protection level.    C:\Users\raj\Documents\Visual Studio 2013\WebSites\WebSite13\Default.aspx.vb    16  48  WebSite13
Error   3   'ratingControl' is not declared. It may be inaccessible due to its protection level.    C:\Users\raj\Documents\Visual Studio 2013\WebSites\WebSite13\Default.aspx.vb    33  13  WebSite13
Error   4   'lbltxt' is not declared. It may be inaccessible due to its protection level.   C:\Users\raj\Documents\Visual Studio 2013\WebSites\WebSite13\Default.aspx.vb    34  13  WebSite13

I have no idea which one is causing the error My DB name is Test and Table name is ratings
This is my default.aspx
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Ajax Rating Sample</title>

<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ScripManager1" runat="server"/>

<asp:UpdatePanel ID="pnlRating" runat="server">
<ContentTemplate>

Average Rating:

<ajax:Rating ID="ratingControl" AutoPostBack="true" OnChanged="RatingControlChanged" runat="server" StarCssClass="ratingEmpty" WaitingStarCssClass="ratingSaved" EmptyStarCssClass="ratingEmpty" FilledStarCssClass="ratingFilled">
</ajax:Rating>
 <asp:label ID="lbltxt" runat="server"/>

Testing

</ContentTemplate>
</asp:UpdatePanel>

</form>

This is default.aspx.vb code
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient

Partial Class _Default
    Inherits System.Web.UI.Page
    Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("test").ConnectionString)
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindRatingControl()
        End If
    End Sub
    Protected Sub RatingControlChanged(ByVal sender As Object, ByVal e As AjaxControlToolkit.RatingEventArgs)
        con.Open()
        Dim cmd As New SqlCommand("insert into rating(rate)values(@Rating)", con)
        cmd.Parameters.AddWithValue("@Rating", ratingControl.CurrentRating)
        cmd.ExecuteNonQuery()
        con.Close()
        BindRatingControl()
    End Sub
    Protected Sub BindRatingControl()
        Dim total As Integer = 0
        Dim dt As New DataTable()
        con.Open()
        Dim cmd As New SqlCommand("Select Rate from rating", con)
        Dim da As New SqlDataAdapter(cmd)
        da.Fill(dt)
        If dt.Rows.Count > 0 Then
            For i As Integer = 0 To dt.Rows.Count - 1
                total += Convert.ToInt32(dt.Rows(i)(0).ToString())
            Next
            Dim average As Integer = total \ (dt.Rows.Count)
            ratingControl.CurrentRating = average
            lbltxt.Text = dt.Rows.Count & "user(s) have rated this article"
        End If
    End Sub
End Class

So can any Help me how to solve this issuse.
Answer: Your default.aspx page (front end) appears to be missing the needed page declaration - this is what tells it which codebehind to use.
It should be at the very top line of the default.aspx file.
An example default page declaration:
<%@ Page Title="Home Page" Language="VB.net" MasterPageFile="~/Site.Master"
AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTest._Default" %>

The important pieces are:
CodeBehind="Default.aspx.cs"
Inherits="WebTest._Default"

This tells the ASP.net engine which file and class name to associate with the page.
Are you sure you didn't accidentally erase that line and save the file?
This should be easy to restore, just copy from another file and fix the CodeBehind and Inherits (and Title) attributes to have the proper values.


Views, Contextual Filters, and Path Alias

Question: First, a disclaimer:  I am less than a year into learning Drupal just to give you a frame of reference.  I am probably using incorrect terminology in my searches so if there is an answer out there, a point in the right direction would be greatly appreciated.
I am building a site that will have multiple "categories."  In each category, there will be page content.  So, my URL will (should) look like this:
www.example.com/category/page

All of my pages have been put into their respective subdirectories which are named for their categories.  For example:
widgets/page1  (node 10)
widgets/page2 (node 13)
widgets/page3 (node 24)
services/page1 (node 12)
services/page2 (node 15)
services/page3 (node 17)

If I type the url /widgets/page1 I get the "article" not the view.  If I type in the url with node id:
www.example.com/widgets/13

The view works perfectly and shows me widgets/page2
I created a page view for widges and set its path to "widgets"  so the url would be:
www.example.com/widgets

I have created a view that displays all my relevant info.  I also created an "attachment" that shows me related content from the same category.  This actually works quite well - it displays all the relevant content with linkable titles.
The problem that I am running into is when I click on one of the titles (or type the link directly) it no longer goes through the page view.
How do I structure this so that all links go through the views?  I am missing something, I just don't know what.
Screenshot of my Views Page
Comment: Can you clarify the question - are you trying to fix the paths so that when a user goes to URL widgets/page2 it shows the view, or are you just trying to fix the links on the master view to point to the right "subview"? two very different issues...
Comment: Yes, I am trying to fix/figure out the paths so they all go through the view.  But that creates another question.... What are subviews?
Comment: Sorry, used subviews but meant the views/pages the master view links to. In your view, you can customize the URL pattern in your links to, check out the answer in this post: http://drupal.stackexchange.com/questions/45668/custom-links-in-views  Another option would be to look at the view that generates your pages, and see if you specified the right path to the view (first option "Path" under Page Settings). If you can attach a screengrab of your view, can try to provide more concrete instructions
Comment: I attached a screen shot..I have used (from my site)  .com/little and .com/little/%
Comment: Ok, under Fields, click on the Title, then tick "Link this field to the original piece of content", then under "Rewrite results" tick "Output this field as a link", then in Link Path below it try "widgets/[nid]" then save obviously!
Comment: I see where you went with this...I applied the changes you suggested and was able to have the content processed through the view.  Awesome!  I am now trying to get the view to use path alias instead of the node ID.  If you want to see what I am trying to do, the url is http://urlgone.com/718a35/   It is only good for 1 day (security purposes).
Answer: Ok, under Fields, click on the Title, then tick "Link this field to the original piece of content", then under "Rewrite results" tick "Output this field as a link", then in Link Path below it try "widgets/[nid]" then save obviously!
Comment: Awesome, but now I have more questions, but I am going to experiment with rewriting the output.  I see that %1 is the node title and would prefer to use that rather than a simple node number.
Comment: You can use other tokens to play around with the paths/links/URLs, like the title etc. This is a handy ref: https://www.drupal.org/node/390482#drupal7tokenslist
Comment: @Allan, if you are trying to point to the page's alias instead of the nid, try to use this 'widgets/[node:menu-link:url:alias]' in the link path as instructed above.


The way to evaluate level of significance for coefficient of eta correlation?

Question: How I can check the significance level of eta correlation?
To assay to see the significance of Pearson correlation, we compare the coefficient with r table, but for eta correlation what can I do?
Comment: [Some similar Qs with answers](https://stats.stackexchange.com/search?q=eta+corr*+answers%3A1+). Do some help?
Answer: The easiest is to use a computer package such as SPSS or STATA to evaluate the significance, I don't think you can easily use tables for this.
If you are a programmer you can use the permutation test (which I think is implemented in some computer packages). With observations $(x_1,y_1),\ldots(x_n,y_n)$, randomly generate $m$ permutations $(y_{(1)},\ldots,y_{(n)}$) and compute eta for $(x_1,y_{(1)}),\ldots(x_n,y_{(n)})$. So you get $m$ permutation values of eta, and the proportion of these that are bigger than the observed eta value is the $p$-value.
Note this is called an exact conditional $p$-value, where the conditioning is done on the observed marginal distributions. You can also do this for the Pearson correlation, and for small samples that may give more accurate p-values than significance tables.
Comment: Dear WicherThanks for the reply. Your mean is to compare the computed Eta coefficient with the statistical table of the Pearson correlation coefficient.
Comment: You can't use the same tables, in fact I don't think you can use tables for the eta coefficient because it depends on several quantities of the data, so you'll need a statistical computer package such as SPSS or STATA.


Proving a maximum and minimum inequality

Question: I'm trying to show that $\min{(x,y)} \le \frac{a}{a+b}\cdot x + \frac{b}{a+b} \cdot y \le \max{(x,y)}$, for all $a$, $b$, $x$, $y$ $>0$.
Any ideas?
Comment: Assume $x\le y$. Use $1-\frac{a}{a+b}=\frac{b}{a+b}$ and arrive at $y< x$ if the equality does not hold.
Comment: Thanks for your help! Awesome solution.
Comment: If you expect people to put in the effort to answer a question, then it is polite to put in some effort yourself. For example, simply telling us where you got the problem from or explaining what you tried would be a big step forward! (For further feedback/help with asking questions, you can ask [here](https://chat.stackexchange.com/rooms/43593/constructive-feedback).)
Answer: $x,y\ge\min(x,y)\implies\frac{ax+by}{a+b}\ge\frac{a\min(x,y)+b\min(x,y)}{a+b}=\min(x,y)~~\because a,b>0$
Similarly use the fact $x,y\le\max(x,y)$ to prove the other part.
Comment: Thank you very much. It was really helpful!
Comment: You are welcome :)


Changing the currency sign in mvc

Question: I'm currently new to asp.net MVC and I have this
[Range(1, 1000)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }

Now, it displays the dollar sign as an output. Is there any way I could change it into Php (Philippine Peso)?
Comment: Set the culture in your app and it will be displayed in the format for that culture
Comment: https://stackoverflow.com/questions/12408530/is-it-possible-to-force-the-currency-for-an-mvc3-field-with-datatype-as-datatype check this out.
Answer: According to ISO-639/ISO-3166 country-language codes, the proper value for Filipino culture stored in CultureInfo is fil-PH, hence you need to configure the UI/site culture code in web.config file to show its currency in view (this configuration apply for entire application):
<configuration>
    ...
    <system.web>
        <globalization culture="fil-PH" uiCulture="fil-PH" />
    </system.web>
    ...
</configuration>

As an alternative, creating custom attribute to include culture & language code on currency input can be used as given in this post using same language code provided above.
Similar issue:
Change the Currency Symbol thoroughout the Application

Changing the currency sign in mvc


Bootbox moving DIV tags outside of table

Question: I'm using Bootbox to display a modal.
Using JS, I'm creating a string as the message :
display = "Notes";
display += "

";

display += "
";
display += "
";
display += "
";
display += "...";
display += "
";
display += "
";
display += "
";

Then I call the modal :
bootbox.alert( {
    message: display,
    buttons: {
        ok: {
            label: 'Close'
        }
    }
    //Example.show("Hello world callback");
});

Logging display in the console, I get:
Notes

...

However, when I inspect the DOM, I get:
Notes

...

Why are the DIV tags no longer wrapping the table?
Answer: That happen because putting
 tag directly inside a
 tag is not a valid HTML structure, so the browser will rectify that automatically and return the valid expression by putting the
 tag out of the table.
Hope this helps.


Putting Roman numeral chord notation into practice

Question: I was reading the wiki page on chords [en.wikipedia.org/wiki/Chord_(music)], specifically the Roman numeral notation section, and they have an example chord progression [C: vi6 ii V6 I] along with a midi file (midi). As a self test exercise, I opened up Ableton and blind recreated it to the best of my knowledge.
This is what I ended up with:

After realizing it sounded off, I imported the original midi file to compare and I was definitely incorrect. I'm wondering if someone could help me correct my mistakes, and more importantly understand where I went wrong.
Thanks!
Comment: Can you read standard notation?
Comment: Without giving more information about what your knowledge currently (such as @Dave asked) and how you tried to recreate it, the only answer we'd be able to give as to where you went wrong is that you put the wrong notes in, and that to correct it you should put the right notes in.
Answer: Roman numeral notation consists of two parts:

The Roman numeral itself, which tells you the root of the chord; and
The figured bass (the numbers that occasionally appear to the right of the Roman numeral) that tell you the inversion of the chord (ie, the intervals above the lowest pitch).

Let's start with the Roman numeral, which tells you the root. Since your example is in C, this entire post will focus on C major.
Now, think through the C major scale: C D E F G A B C. In music we often assign "scale degree numbers" to these pitches, so C is "scale-degree one" in C, D is "scale-degree two," ... and B is "scale-degree seven." (The next C is not "scale degree eight," but rather it returns to "scale degree one.")
The Roman numeral is thus the scale degree written in Roman numerals. This means that your chord progression of vi6 ii V6 I is based on chords whose roots are scale degrees six, two, five, and one. Your chords are thus built on A, D, G, and C.
Important to know is that uppercase Roman numerals indicate a major chord while lowercase indicates minor. (If you ever see a lowercase with a circle next to it, that means diminished.) Thus now we know the chords are A minor, D minor, G major, and C major.

vi = A C E
ii = D F A
V = G B D
I = C E G

So, now let's talk about the 6 that shows up occasionally; as we said, we call this "figured bass." For triads, there are only three possibilities:

No figured bass at all means the chord is in "root position." In other words, the root of the chord (ie, the Roman numeral number) is the lowest sounding pitch. (Occasionally you might see this written as 53.) So your vi and I chords are in root position.
A 6 indicates the chord is in "first inversion," meaning the pitch a third above the root is in the bass. So vi6 should have the chordal third in the bass. A is the root, which means C is the chordal third, so your vi6 chord will actually have C in the bass. (A similar thought process will address the V6.)
A 64 means the chordal fifth is in the bass, putting the chord in "second inversion."

With this knowledge, then, your progression should be what I give below; the lowest pitch is always given on the left. The remaining two pitches can be in any order, but the order I've given is the smoothest "answer" to this progression:

vi6 = C E A
ii = D F A
V6 = B D G
I = C E G

(As an explanation of your error, you may have been counting half-steps. Thus your ii6 is a minor chord built on the second half-step of the scale, C#. Similarly, your V6 is a major chord built on the fifth half-step of the scale, E. But this doesn't explain your first chord, so maybe that wasn't what you did. Or perhaps you read the vi as a iv, which is actually a really common mistake!)
Answer: To answer your question, you simply entered the wrong notes.  Is this the example you were working from?  The first chord is C, E, A.   You entered D#, F#, A#.  The next two chords are way out too, but you got the last one right!
If you want to study harmony, Ableton isn't the best tool.  You need a notation-based program.  Look at MuseScore.  It's free!


Can we create certificate sign request (CSR) using HSM?


integrate the following integral

Question: Can anyone help with integrating the following integral:
$$I=\int{\frac{\ln(\tan(x))}{\sin(x)+\cos(x)}}dx$$
I tried with mathematica,matlab, all wouldn't come out as a simple answer.
Just wonder if anyone can work out here.
Many thanks!
Comment: There is more hope of getting a definite integral. Was this given as an indefinite integral or a definite one?
Comment: I cannot speak for certain, but if mathematica did not have a simple answer, then it is unlikely that MSE has one
Comment: I subscribe to WolframAlpha and I have to say that it's rare to see it not provide _any_ description of an anti-derivative whatsoever (which is what happened with this integrand).  I do not hold out much hope for you that there is any convenient (and it is certainly _non_-elementary) function for the anti-derivative.  What are the circumstances for which you are asked to find a result?
Comment: Where did the integral come from? Is it from some kind of workbook or tutorial sheet so we might expect it to have an answer, or did someone just throw it together, or is it related to some kind of model?
Comment: @ASKASK can you possibly think about a way to start this one?
Comment: I've tried writing the numerator as $ \ \ln(\sin x) \ - \ \ln(\cos x) \ $ and asking about the integral for just $$   \int \  \frac{\ln(\sin x)}{\sin x \ + \ \cos x } \ \ dx \ \ , $$ or making the substitution $$ \rightarrow \ \int \  \frac{x}{e^x + \sqrt{1 - e^{2x}}} \ \ dx   $$  to see if WA could provide a _hint_ of what the anti-derivative might be related to.  No dice...
Comment: Rewriting $\sin x+\cos x$ in terms of $\sin\bigg(x+\dfrac\pi4\bigg),~$ and then substituting $x=2t,~$ we get [this result](http://i.stack.imgur.com/3894R.png).
Comment: Another argument for adding polylogarithms to the general curriculum... ;)
Answer: You won't obtain a general answer since the integral is not defined. The tangens is negative on $(\frac{1}{2}\pi,\pi)$, $(\frac{3}{2}\pi,2\pi)$ and so on. More precisely it is negative in $(\frac{2n+1}{2}\pi,n\pi), n\in \mathbb{Z}$. But the logarithm is not defined for negative numbers! So the function over which you integrate is not defined everywhere.
So let us have a look where it is defined. That is $(n\pi,\frac{2n+1}{2}\pi), n\in \mathbb{Z}$. Let's have a special look at $(0,\frac{\pi}{2})$. The function is antisemetric to the point $\pi/4$ thus:
$$\int_0^{\frac{\pi}{2}}{\frac{\ln(\tan(x))}{\sin(x)+\cos(x)}}dx = 0$$
On the other side
$$\int_{\frac{\pi}{4}}^{\frac{\pi}{2}}{\frac{\ln(\tan(x))}{\sin(x)+\cos(x)}}dx \approx 0.792737,$$
which I obtained with Wolfram Alpha (It was probably numerically evaluated).
It might be possible to obtain an expression for the antiderivative
$$\int_{\frac{\pi}{4}}^{y}{\frac{\ln(\tan(x))}{\sin(x)+\cos(x)}}dx \text{, where } y\in (0,\tfrac{\pi}{2}) .$$
But I don't directly see how. Why are you interested in this integral?

integrate the following integral


How are these two angles equal?

Question: I am reading about the geometrical derivation of the centripetal acceleration formula.  And the only thing I don't understand is the angles.
For example, here is a picture.

The assertion is that angle $BCD$ = $\theta$
However, I cannot understand this at all.  The lines aren't parallel.  There's no way they can prove this.  What am I not understanding or missing here?
Answer: Notice that $OACB$ is a 4 sided polygon, so all interior angles add up to $360^{\circ}$. We have that $\angle OAC=\angle OBC =90^{\circ}$. Hence $\angle ACB=180-\theta$ and hence $\angle BCD=\theta$.

How are these two angles equal?


Finding the inverse of a function by swapping x with y and vice-versa

Question:
The professor explained the following steps were required to finding the inverse and the step was to swap x with y and y with x.
Why it is so? Well, I can follow the steps and applied it, but I couldnt understand the need for the swap.
Comment: there is no need. you can perfectly well end up with $x=(y-1)^2$ so that $f^{-1}(y) = (y-1)^2$ if you prefer. If a question asks for $f^{-1}(x)$ then you can change y to x at that point.
Answer: Note that in $y=\sqrt{x}+1$, $x$ is an input variable and $y$ is an output variable. The question of finding the inverse function is to make $y$ input and $x$ output variables.
For this one must rearrange the equation of the function and express $x$ in terms of $y$, that is: $x=(y-1)^2$. Then for convenience the variables are swapped to make it look like a function $y=f(x)$. However, it may not be allowed. For example, consider the cost function $C=2Q$, where $Q$ is the quantity of a good and $C$ is the cost. If a customer buys $10$ products, it will cost $20$ units of money. If a customer has $30$ units of money, he can buy at most $15$ products. So, the inverse cost function is $Q=\frac{C}{2}$. Note that swapping the variables here is meaningless.
Answer: This is simply because, for the initial function, $x$ is the variable (its values are represented on the abscissae axis) and $y$ is the value of the function (its values are represented on the ordinates axis.
For the inverse function, $y$ is the variable, so its values have to be represented on the abscissae axis, $x$ is now the value of the inverse function, and its values have to be represented on the ordinates axis.
A similar point of view says that, having the graph of a function (with the axes) on a sheet of paper, to see the graph of the inverse function, turn the sheet over and rotate it 90° clockwise.


Picking cards at random

Question: I want to know if my reasoning is correct for following problem.
I have 5 cards, 2 are marked with an X. What is the probability of getting a "hit" with increasing numbers of guesses?
My solution is reasoned like this:
With 1 pick, I have a 2 in 5 chance of picking a marked card. So 40% chance.
For 2 picks, it's as above plus (prob. I didn't pick it yet) * prob. to pick one = 2/5 + (1-2/5)*2/4 = 70%
For 3 picks, by extension of above argument = 7/10 + 3/10 * 2/3 = 90%
Extending to last case of a 4th pick which must get one of them, it's 9/10 + 1/10 * 2/2 = 100%
Is this correct?
Comment: That is correct, assuming you can't pick the same card twice.
Answer: Yes.  A way of checking your answer is by subtracting the chance of "miss" from 100%.
$$1-\frac{3}{5}=\frac{2}{5}\\1-\frac{3}{5}\times\frac{2}{4}=\frac{7}{10}\\1-\frac{3}{5}\times\frac{2}{4}\times\frac{1}{3}=\frac{9}{10}\\1-\frac{3}{5}\times\frac{2}{4}\times\frac{1}{3}\times0=1\\$$
But your way of solving it is solid.
Comment: Ah excellent. I was wondering how to get there directly without having to calculate all the previous steps.

Picking cards at random


How to install WTForms? Gettiing import error when trying to import forms

Question: I'm trying to follow the Flask Mega Tutorial for which I need to use WTForms. As is suggested in the tutorial, I use a virtualenv in which I installed WTForms like this:
flask/bin/pip install flask-wtf

This seemed to work fine, and when I now run it again I simply get this:
Requirement already satisfied (use --upgrade to upgrade): flask-wtf in ./flask/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): Flask in ./flask/lib/python2.7/site-packages (from flask-wtf)
Requirement already satisfied (use --upgrade to upgrade): WTForms>=1.0 in ./flask/lib/python2.7/site-packages (from flask-wtf)
Requirement already satisfied (use --upgrade to upgrade): Werkzeug>=0.7 in ./flask/lib/python2.7/site-packages (from Flask->flask-wtf)
Requirement already satisfied (use --upgrade to upgrade): Jinja2>=2.4 in ./flask/lib/python2.7/site-packages (from Flask->flask-wtf)
Requirement already satisfied (use --upgrade to upgrade): itsdangerous>=0.21 in ./flask/lib/python2.7/site-packages (from Flask->flask-wtf)
Requirement already satisfied (use --upgrade to upgrade): markupsafe in ./flask/lib/python2.7/site-packages (from Jinja2>=2.4->Flask->flask-wtf)
Cleaning up...

But when I try to import forms using from forms import LoginForm I get an error saying: ImportError: cannot import name LoginForm.
Does anybody know what I'm doing wrong here, and how I can solve this? All tips are welcome!
Answer: You need a module named forms that contains LoginForm,
from flask.ext.wtf import Form
from wtforms import TextField, BooleanField
from wtforms.validators import Required

class LoginForm(Form):
    openid = TextField('openid', validators = [Required()])
    remember_me = BooleanField('remember_me', default = False)

This is the example taken from Part iii.
Comment: Stupid stupid me. I did create that file and pasted the code in, I just didn't save the file yet. Excuse me for bothering you guys, and thanks for answering.
Comment: How does this `Form` class compare with
`from flask_wtf  import FlaskForm`. I thought I came across this usage from one of Miguel Grinberg's pycon talks.


Accidentally Deleted Admin Menu Items

Question: Hi i hope someone can offer me a bit of advice here. I seem to have deleted all my admin menu items. Is there a way to restore them without losing any data on my site?
thanks
Answer: Your menu items are probably still there but disabled. In Drupal 6, navigate to admin/build/menu-customize/navigation and check if your administrative menu items are enabled. In Drupal 7 the path is admin/structure/menu/manage/management.
If you re-enable any menu items, make sure you scroll to the bottom of the page and hit the Save Configuration button to save your changes.
Comment: The OP is saying that he seems to have deleted the administrative menu items. In which way does clearing the cache help?
Comment: Thanks. I was imagining the OP damaged menu links and resetting the menu cache would fix it. That would be unlikely from the UI though, so the menu items are probably just disabled, in which case resetting the cache will not help. I'll change the answer.
Comment: Thanks Keith. you where right. they where still there. i found them again. I think clearing the cache helped. thanks for your input too kiamlaluno.

Accidentally Deleted Admin Menu Items


Posterior distribution of normal with gamma prior on the precision

Question:
Find the posterior distribution when
$$x|\sigma\sim \mathcal N(0,\sigma^2),\:\:\: 1/\sigma^2\sim \mathsf{Gamma}(1,2)$$

I'm stuck in this exercise, I know that $$\pi(x|\sigma)\approx f(x|\sigma)\pi(\sigma)\cdot\frac{1}{m(x)}$$
Maybe I am thinking wrong, but I would not have to find a prior of $\sigma$?
Comment: Could you explain what the symbols "$m$", "$f$", and "$\pi$" mean to you?
Comment: Please add the `[self-study]` tag & read its
[wiki](http://stats.stackexchange.com/tags/self-study/info).
Comment: Is that the quotient of $x, \sigma$, or $x$ given $\sigma$?
Comment: @SeanEaster the pdf is given and the other is $\frac{1}{\sigma^2}$
Comment: @amoeba, I believe I voted to close as SS, although I don't really remember anymore. You can vote to reopen if you like.
Answer: In effect, you know the prior on $\sigma^2$: It's inverse gamma. After expressing the posterior as the product of normal likelihood and inverse-gamma prior, one can manipulate the posterior until it's recognizable as another inverse gamma. (Left as an exercise, but confirmed in Michael I. Jordan - The Conjugate Prior for the Normal Distribution)


How to use arguments, defined in a custom event, for an action

Question: I've just defined this event with the two arguments: number and message. I want to use them to verify the message and send a response back to the number. I have an action for that but I don't know how to pass the arguments.
function sms_rules_rules_event_info() {
  return array(
      'sms_rules_sms_received' => array(
         'label' => t('SMS received'),
         'module' => 'sms_rules',
         'arguments' => array(
            'number' => array('type' => 'text', 'label' => t('Number from where the message was received.')),
            'message' => array('type' => 'long text', 'label' => t('Contents of message.')),
         ),
      ),
  );
}

Answer: In your action you might have something like
function mymodule_rules_action_info() {
  return array(
    'my_action' => array(
      'label' => t('Label'),
      'module' => t('My module'),
      'arguments' => array(
        'number' => array('type' => 'text', 'label' => t('Number from where the message was received.')),
        'message' => array('type' => 'long text', 'label' => t('Contents of message.')),
      ),
      'base' => 'mymodule_my_action',
    ),
  );
}

The 'base' property indicates the callback for the action. You can also use the key of your action as the callback if you choose not to set a 'base'. In this case it would be function my_action(). The arguments defined in the action will automatically be passed to that function. Now, whether the action is available is dependent upon which arguments your event makes available and which arguments your action requires. So, if I had an event that passes a 'type' => 'user' and 'type' => 'node' then only actions that have arguments 'user' and 'node' would be available. This is how Rules 1 works. Alternatively, by using a simple 'text' data type the actions will always be available because the data type is not unique. You can specify your own data types by implementing hook_rules_data_type_info().
Anyways, I got off track. So, with your base being mymodule_my_action:
function mymodule_my_action($number, $message) {
  // Do stuff here.
  return $number;
}

Another addition you can make if necessary is adding a settings form to your action.
function mymodule_my_action_form($settings, &$form) {
  $form['settings']['my_options'] = array(
    '#type' => 'select',
    '#title' => t('Select an option'),
    '#options' => array(
      'this' => t('this'),
      'that' => t('that'),
      'also' => t('also'),
    ),
    '#default_value' => $settings['my_options'],
    '#required' => TRUE,
  );
}

In this case, you would just add the settings array to your action callback as the last argument:
function mymodule_my_action($number, $message, $settings) {
  if ($settings['my_options'] == 'this') {
    // Do stuff.
  }
}

Hmm... I don't even know if I answered your question, but I tried to provide as much info as possible. If I completely missed it please give me some guidance. I maintain three Rules modules, so I've been around that module for a while and I'm glad to help.
Comment: Looks very good. Unfortunately I won't be needing it for a few weeks so I can't give you feedback on the answer, but I'll vote it and come back when I do.
Comment: Oh, I remembered what my initial problem was. I needed to know how to write an event that gives me variables so I can use them for an action.


Oracle Insert de várias linhas

Question: Preciso fazer o insert de vários registros em uma tabela onde apenas um deles mudará, os outros são constantes.
Por exemplo:
Insert into processo (ID, status, descricao) values (1, 'X01', 'lorem ipsum dolor')

Tenho que fazer centenas de inserts como esse acima, onde o status e a descrição será sempre o mesmo mas para ID's diferentes.
Da pra fazer isso com um único insert ou preciso criar uma função? Como?
Comment: qual a versão do oracle?
Comment: @MarllonNasser 11g
Answer: Utilize o INSERT ALL:
INSERT ALL
  INTO processo (id, status, descricao) VALUES (1, 'X01', 'lorem ipsum dolor')
  INTO processo (id, status, descricao) VALUES (2, 'X02', 'lorem ipsum dolor2')
  INTO processo (id, status, descricao) VALUES (3, 'X03', 'lorem ipsum dolor3')
SELECT * FROM dual;

Você também pode fazer insert em outras tabelas se quiser :)
Comment: Essa é a unica forma com insert? Vou precisar de centenas de linhas mudando o ID apenas.
Comment: Com insert sim, amigo..... A outra forma seria através de pl/sql.
Answer: Se você quer apenas fazer um incremento no ID de 1 em 1, pode fazer uma Stored Procedure(conjunto de comandos) com um while e o insert.
Como Exemplo:
CREATE TABLE tbCliente(
 id int NOT NULL AUTO_INCREMENT,
 numero int,
 nome varchar(50),
 PRIMARY KEY(id)
);

DELIMITER $$
DROP PROCEDURE IF EXISTS myProc$$
CREATE PROCEDURE myProc()
BEGIN
DECLARE i INT default 1;
WHILE i<=100 DO
    INSERT INTO tbCliente(nome,numero) values ('Nomes',i);
    SET i=i+1;
END WHILE;
END$$

DELIMITER ;
call myProc();

Com esse código será incrementado de 1 em 1 o valor i em cada insert de 1 até 100, onde 'i' faz referência ao campo 'numero' da tabela tbCliente.
O DELIMITER onde diz para o sql, onde o código da procedure inicia e termina.
call muProc() executará sua procedure, depois é apenas necessário fazer o select para ver se tudo deu certo.
Lembre de executar o DELIMITER$$ junto com a procedure e depois o DELIMITER; junto com o call myproc().
Comment: Na verdade não é sequencial. As IDs são de outra consulta e precisava dar um insert em outra tabela que tem esse ID como FK.
Sei que é possível com PL/SQL, mas como não domino acabei conectando com uma aplicação só pra criar uma função pra fazer isso.

Oracle Insert de várias linhas


systemd drop-in order in debian jessie

Question: I have several debian 8 servers shipped with a default configuration.
They have on board apache2 and i want to add monit ( https://mmonit.com/monit/ ) for extra availability.
To manage operator-driven stops and starts of apache, i would love to add monit monitor and unmonitor actions to the apache systemd unit.
I thought about shipping this drop-in file in the systemd apache configuration (/etc/systemd/system/apache2.service.d/ folder):
[Service]
ExecStartPost=-/usr/bin/monit monitor apache2
ExecStop=-/usr/bin/monit unmonitor apache2

The ExecStartPost command works great.
Unfortunately I have some problems with the ExecStop command because it is executed after the actual stop of the service.
I figured out that there is another ExecStop defined in /run/systemd/generator.late/apache2.service (a file automatically generated by systemd-sysv-generator). Of course there is no problem in having multiple ExecStop commands, the problem here is about order:
root@debianjessie:~# systemctl show apache2 | grep ^ExecStop
ExecStop={ path=/etc/init.d/apache2 ; argv[]=/etc/init.d/apache2 stop ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }
ExecStop={ path=/usr/bin/monit ; argv[]=/usr/bin/monit unmonitor apache2 ; ignore_errors=yes ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }

I found a workaround redefining all the ExecStop sequence in my drop-in file:
[Service]
ExecStartPost=-/usr/bin/monit monitor apache2
ExecStop=
ExecStop=-/usr/bin/monit unmonitor apache2
ExecStop=/etc/init.d/apache2 stop

but i think it's not a very "clean" solution in my opinion.
Reading here the drop-ins in /etc/ should be the ones with the highest priority, so i don't get why my drop-in ExecStop action is executed last.
Am I missing anything?
Thanks in advance.
S.
Answer: Why not turning it around (without modifying any systemd units!) by using monit to start/stop your apache?
If you use /bin/systemctl start apache2.service as start program in monitrc and the same for stop, you can simply use monit with monit stop apache to do it "all inclusive" ;)
Comment: That works in general @boppy, and i like the approach.
Unfortunately, that means i have to change the procedure that a lot of operators already know for stopping/starting apache2 (and for a few other services, not mentioned here, as for them the drop-in works pretty great)
Thank you though!

systemd drop-in order in debian jessie


Is it ever a good idea to use results of multiple algorithms as features?

Question: Let's say that I have a vector of features that I use to get a single result back using some machine learning algorithm.
I thought about using multiple variations of that algorithm to get multiple results back and then simply concatenating them together into one big features vector for a new algorithm to give me that one result back.
Would that enhance accuracy or make it worse?
Answer: This is widely used method, called stacking, see e.g.
Bagging, boosting and stacking in machine learning
To answer your question: yes, it is very useful in some cases.
If you cook it properly with folding, it almost sure to have quality no worse than a single model.


Is it possible to create a function where [[prototype]] refers to another function

Question: I would like to create function objects (yes, all functions are objects) with some control over the prototypal inheritance, that is, I would like one function to inherit from another.
I can make objects that have prototypal inheritance, and know to set the prototype property of a function performing as a constructor to initialize the [[prototype]] property of the object.
However, when creating a function, I must use the function operator or the Function constructor. I could try to swizzle Function.prototype, but (1) don't know if that is writable, and (2) that just seems quite dangerous [still, I should try doing that].
btw: I only care to do this for V8 within node.JS, so if there are means that work only for that environment, that would be acceptable.
For the record, I have seen this:
Is it possible to create a function with another prototype than Function.prototype?
Comment: To help clarify, can you add an example describing why you want to do this? e.g. I need this because I'm ____________________.  Before getting into the nitty gritty, I think we'd want to make sure we are solving your problem, and not just creating "Astronaut Architecture"
Comment: Because I want to have prototypal inheritance for functions, and not have to resort to adding methods to Function.prototype, because the added methods won't work on arbitrary native types and objects.
Comment: That said, more specifically, I have a Constructor that produces function objects. I want to have methods that work only for those function objects. Presently, I can refer to  instance.constructor.prototype to get to the methods that act on these function objects, e.g.:
instance.constructor.prototype.method();
But it sure would be nice to modify the [[prototype]] chain so that I could simply write instance.method();
Comment: I think adding some (pseudo-)code to your question would clarify what you mean.
Comment: Anybody reading my question: If you are not sure of what I'm asking, you may want to be sure you have a solid understanding of [[prototype]], \_\_proto\_\_, and the way that Function instances don't inherently behave like Object instances even though they are Object instances.  Some good background on this page: http://javascript.info/tutorial/inheritance
Answer: In V8 (and most other browsers/engines except IE) you can change an object's prototype by setting the __prototype__ __proto__ attribute. Setting the prototype attribute will instead change the prototype that is used to create an object if the function is invoked as a constructor function. This should not be what you want.
Afaik there currently is no standard conform way to directly "subclass" a function (or array for that matter). There's only Object.create, but there is no Function.create or Array.create.
EDIT: I just realized that function objects do not have the __prototype__ attribute and changing / setting it will not turn an object into a function.
I believe though that I just recently watched a talk by Brendan Eich (the creator of JavaScript) in which he talked about Function and Array equivalents of Object.create. And infact, googling for "Function.create brendan eich" reveals the following blog post by Eich in which he talks about his wish to implement Function.create and Array.create.
EDIT 2: Ok, I screwed up. Pretty much. The non-standard attribute is of course __proto__ and not __prototype__. Setting __proto__ works fine for functions with some restrictions, which are:

To be able to call aFunction you must initialize it with an actual function, eg:
var aFunction = function () {};

This is important. Calling a function does not access the prototype chain, so if you define aFunction as an object and simply set the  __proto__ attribute, you will not able to call aFunction.
You can now assign any other function to aFunction.__proto__ and reading any members (including methods) will correctly delegate to the prototype chain if the porperty is not found on aFunction itself.
Calling aFunction() will always invoke the function that was originally declared when aFunction was defined and will never invoke aFunction's prototype function. So the body of the function is not subject to inheritence.

Sorry for screwing up first with the name of the attribute. Hope this helps you nevertheless.
Comment: Interesting how many write-ups state that functions are first class objects. Well, they may inherit from Object, but they aren't really first class objects in the sense that they don't have a [[prototype]] chain. I haven't read read Brendan's blog post, but I suspect your spot on about his understanding the need for inheritance with Functions and Arrays. Thanks for the link... I'm off to read now.
Comment: This looks promising Daniel -- I will give it a try. I know you meant \_\_proto\_\_ -- but good of you to correct for others who may visit here.
Comment: Daniel -- setting \_\_proto\_\_ works like a charm. Alas, I have cold feet, because doing this is non-standard and I suddenly feel like the library I am developing could be useful in the Browser, and so would like to find a cross-browser solution, but suspect there isn't one. Anyway, thanks for your diligent research and reporting!
Comment: There is no cross browser solution. IE does not support modification of the special `[[prototype]]` attribute at all.
Comment: Will just have to wait for Harmony :-) Another way to handle this is by proxies, which are proposed for Harmony (see: http://wiki.ecmascript.org/doku.php?id=harmony:proxies). Isaac Schlueter has implemented this (non-standard!) as a CC-coded extension for V8 under node.JS (see: https://github.com/isaacs/node-proxy)
Comment: Posting the above comment inspired me to write a very simple proxy (actually, a method forwarder and invoker). I have explained this in an answer I posted below.
Answer: I came up with a solution that solves my needs. It is not cross-browser, but can be used cross-browser. My most important use case is as a module for node.JS. In that case, the mechanism of setting __proto__ works just fine, in which case I can call methods on the base function object
f.method(args...);

and it executed by code in the "super" function. Because the method is invoked by the method invocation pattern, "this" is set to the base function object, and so the proper properties are accessed even though the method resides in the "super."
Now for the in-Browser case: when I use my library client-side, I provide a proxy mechanism. Alas, code intended for the browser must be written differently. The invocation is:
f.proxy(methodName, args...);

The proxy method in the base function object is:
f.proxy = function (methodName) {
    var p = this.constructor.prototype;
    return p.proxy(this, methodName, arguments);
};

The proxy in the "super" object's prototype is:
proxy: function (instance, methodName) {
    var args = Array.prototype.splice.apply(arguments, [2]),
        method = this[methodName];
    return (method) ? method.apply(instance, args) : undefined;
}

I probably should have named this "forward" or some such, but "proxy" is good enough.
Perhaps this mechanism might be useful to someone...
Comment: Note: that code is sloppy -- the super.proxy should either (1) examine the type of the supplied methodName (because it is really just a property name), and apply if a function, otherwise return the value; or (2) enforce use of methods and have getter methods for any properties that should be exposed.
Answer: I think I understand what you're trying to do.  In short, there's no way to really do it natively.  You'd have to access the Function constructor, which for function expressions and definitions (i.e. anything using the 'function' keyword), isn't possible as far as I can tell.  You could overwrite Function and just always use new Function([args], string) but I doubt you (or any JS programmer) want to do that.
Your best bet would probably be to send your function expressions to another function that returns the function object with your custom methods dynamically added:
wrapFunc = function(f){
  f.customFunc = someCustomFunc;
  return f;
}

var myNewFunc = wrapFunc(
  function(){
    //do something
  }
);

myNewFunc.customFunc();

Comment: Thanks for your thoughts, but that won't do what I want as you are still using the function operator to create the function.


How to prove that $ 1- \frac{x^2}{n} \leq (1+\frac{x}{n})^n\cdotp(1-\frac{x}{n})^n$

Question: How would I prove this inequality (assuming its true, its from a textbook)
$$1 - \frac{x^2}{n} \leq (1+\frac{x}{n})^n\cdotp(1+\frac{-x}{n})^n$$
if $n > |x|$, $x\in R$ and $n\in N$
I first rewrote the inequality to
$$1 - \frac{x^2}{n} \leq (1-\frac{x^2}{n^2})^n$$I then tried to manipulate the inequalities by saying the right hand side was greater than a smaller expression however I was unable to prove the above. I also tried induction where the base case works however I was unable to show that a case being true implies the next also being true.
Any help would be appreciated
Comment: Good first step. Now Bernoulli's inequality would help.
Comment: How would you use the Bernoulli inequality?
Comment: What does the Bernoulli inequality say? How can you relate that to the expression $\left(1-\frac{x^2}{n^2}\right)^n$?
Comment: So, $(1-\frac{x^2}{n^2})^n > 1 - n\frac{x^2}{n^2} = 1-\frac{x^2}{n}$ ?
Comment: Observe that the function $$ f (x)=(1-\frac{x^2}{n^2})^2-(1-\frac {x^2}{n}) $$ is increasing for all $|x|\ge n $.
Comment: No, $\left(1-\frac{x^2}{n^2}\right)^n < 1 < 1 + \frac{x^2}{n}$, unless $x = 0$. But Bernoulli's inequality says $(1+y)^n \geqslant 1+ny$ for $y \geqslant -1$, so what could you take for $y$ here?
Comment: I let $y = \frac{-x^2}{n^2}$ but I made a mistake is correct now?
Comment: Yup, now it's correct.
Comment: I made a typo. I mean show that function increasing for $|x|\le n $.
Answer: $$1-\frac{x^2}{n}\overset{?}{\leq}\left(1-\frac{x^2}{n^2}\right)^n$$
is a good starting point. You can assume $|x|<\sqrt{n}$, since otherwise the inequality is trivial, with the LHS being non positive and the RHS being positive.
Consider the logarithm of both sides. Then:
$$\log\left(1-\frac{x^2}{n}\right)\leq n\log\left(1-\frac{x^2}{n^2}\right)$$
is a consequence of the inequality:
$$\forall z\in[0,1),\qquad \log(1-z)\leq n\log\left(1-\frac{z}{n}\right)$$
that follows from the fact that:
$$\int_{0}^{z}\frac{dx}{1-x}\geq\int_{0}^{z}\frac{dx}{1-\frac{x}{n}}$$
since $(1-x)\leq 1-\frac{x}{n}$.
Comment: Sorry, I can't understand why the last inequality is a Jensen's inequality.
Comment: @Shine: I modified my argument in order to avoid it, I think it is more elementary now.
Answer: Deriving both sides on $x$, $$-\frac{2x}{n}\le-n\frac{2x}{n^2}(1-x^2)^{n-1},$$ or
$$-1\le-(1-\frac{x^2}{n^2})^{n-1}.$$
The latter relation is obviously true for $|x|<n$, so that the LHS of the initial relation decreases faster than the RHS, while they are equal for $x=0$.
(If you prefer, $l'(x)\le r'(x)\implies l'(x)-r'(x)\le0\implies l(x)-r(x)$ is decreasing $\implies l(x)-r(x)\le l(0)-r(0)=0\implies l(x)\le r(x)$.)
Comment: No you cannot differentiate the "inequality" (not equality) this is not true mathematically even your solution correct or not.
Comment: What if $C^1$ continuity is guaranteed ?
Comment: No. Example: it is well know that $\log (1+x)-1$, $ x\ne 0$. If you differentiate both sides we get $ \frac {1}{1+x}< 1$ for all $ x>-1$ which is not true take $ x=-1/2$
Comment: The logics goes the other way: $\frac1{1+x}>1$ for $x<0$, so that $\log(1+x)-x$ increases until $0$, where it equals $0$. Hence, $\log(1+x)-x$ is negative and $\log(1+x)g'(x)\implies f(x)>g(x)$, I am saying $f'(x)>g'(x)\implies f(x)-g(x)$ is increasing.
Comment: You wrote $\frac{1}{x+1}>1$ for $ x <0$, this is not true take $ x =-1-\frac {1}{3}$
Comment: Values $x\le-1$ are outside the domain (and if you considered $\log|x+1|$, you would be past the singularity, violating the $C^1$ assumption). Actually $C^0$ and differentiability should be enough.
Comment: OK, right.  But in your solution you said deriving both sides and kept the $\le $ " this false srarement". You cannot differentiate  any inequality.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/16009/discussion-between-mwomath-and-yves-daoust).


Besides 2023-24 AFC Champions League are there any tournaments with this kind of group stage?

Question: When the total number of teams is 2^n (e.g. 32), there is no problem. Because when two top teams in each group promote to the next round we will have two teams for the final match.
But when the total number of teams isn't 2^n (e.g. 24) we can't reach two teams in the final match by only promoting two top teams in each group. In the 24 case we have to promote 4 of the best third teams in addition to the two top teams.
But the 2023-24 AFC Champions League has 40 teams in total. So they need to promote 10 first teams in each group in addition to 6 of the best second teams.
My Question: Are there other tournaments with groups of 4 teams each (a total of 40 or other numbers) with some of the second teams eliminated?
Comment: @defaultlocale as I understand it, the OP is asking when some _second_ place teams might not qualify.
Comment: Something similar happened to third-placed teams on [Euro 2020](https://en.wikipedia.org/wiki/UEFA_Euro_2020#Ranking_of_third-placed_teams). There were six groups, so all first, all second and four best third-placed teams qualified to the round of 16.
Answer: One obvious answer here is the NFL - each conference has 4 divisions of 4 teams, with the 7 playoff teams from each conference being made up of:

The winner of each division
The three "best of the rest" (wild cards) - which could even be from the same division, meaning three second place teams can in theory miss out on the playoffs.

This was more likely before the 2020-21 season when there were only two wild cards rather than three.


Expectation of $X$ given $X < c$

Question: Let $X$ be a random variable with PDF $f(\cdot)$ and CDF $\Phi(\cdot)$. I want to compute $E(X \mid X < c)$, where $c$ is some constant.
Using definition of the expected value
$$E(X \mid X < c) = \int_{-\infty}^{+\infty}xf(x\mid x<c)dx.$$
I know that conditional density should simplify to
$$f(x\mid x<c) = \frac{f(x)}{\Phi(c)},$$
but I can't derive it. I found that question similar, but I am still confused.

Using (Kolmogorov) definition of conditional probability I get
$$P(X=x \mid X<c) = \frac{P\left(\{X = x\}\cap\{X<c\}\right)}{P(X<c)}.$$
But I don't see how $P\left(\{X = x\}\cap\{X<c\}\right)$ simplifies to $P(X=x)$.
Comment: What definition of conditional probability are you working with?
Comment: What happens when you apply it to your situation?  This definition writes every conditional probability as a quotient, so by inspecting the intended answer you should easily be able to identify the events that are involved.  For instance, the presence of $\Phi(c)$ in the denominator is a strong hint that the conditioning event is $X\le c$.
Comment: Do you have a specific density $f$ given to you, or is this a general question for any $f$?
Comment: @Greenparker, now I work with a case where $X$ is normally distributed, but I also would like to know an answer to the general case.
Comment: @whuber, I guess with Kolmogorov definition.
Comment: @whuber, I added an edit. I used definition of conditional probability for discrete RV. For continuous case, I guess I have to replace $P(X=x)$ with $P(X=x+\delta x)$ or $P(X\in B_0)$.
Comment: Consider the distribution function $F$ rather than the density, let $x$ be any number, and consider the events $X \le x$ and $X \le c$: your definition of conditional probability gives the desired result immediately, assuming $p(X\le c)$ is nonzero. This basically is the approach taken by Zen, albeit with more formal language.
Answer: A general solution: let $X$ be a random vector with density $f$ and $A=\{X\in B_0\}$, for some $n$-dimensional Borel set $B_0$, with $\Pr(A)>0$. The conditional density denoted by $f(x\mid A)$ must be such that
$$
  \Pr\{X\in B\mid A\} = \int_B f(x\mid A)\,dx \, \qquad (*)
$$
for every $n$-dimensional Borel set $B$. From this it's clear that
$$
  f(x\mid A) = \frac{f(x)}{\Pr(A)}\,I_{B_0}(x) \,
$$
almost everywhere, in which $I_{B_0}$ is the indicator function of $B_0$: $I_{B_0}(x)=1$ if $x\in B_0$, and $I_{B_0}(x)=0$ if $x\notin B_0$.
Here is why: the left hand side of $(*)$  is just
$$
  \Pr\{X\in B\mid X\in B_0\} = \frac{\Pr\{X\in B\cap B_0\}}{\Pr\{X\in B_0\}},
$$
and integrating the right hand side of $(*)$ we have
$$
  \int_B \frac{f(x)}{\Pr(A)}\,I_{B_0}(x)\, dx = \frac{1}{\Pr(A)} \int_{B\cap B_0} f(x)\,dx = \frac{\Pr\{X\in B\cap B_0\}}{\Pr\{X\in B_0\}}.
$$
In your specific case
$$
  f(x\mid X \leq c) = \frac{f(x)}{\Phi(c)}\,I_{(-\infty,c]}(x).
$$
Comment: Sorry, but it is not really clear for me how you get an expression for $f(x\mid A)$. Also, what $I_{B_0}(x)$ stands for?
Comment: Details added. To do Probability properly it's important that you get comfortable with the use of indicators. An excellent book is *Basic Probability Theory* by Robert Ash.
Comment: Ash is kind of unique. He was a brilliant expositor. His "trio" Basic Prob + Measure Theoretic Prob + Stochastic Processes is amazing. For more recent books, I like Grimmett and Stirzaker. David Williams "Weighing the Odds" is also amazing, because Williams is such a brilliant guy.
Comment: @DeltaIV: In this case you can, of course. But if you think about it, this reverse order has the merit of giving a little flavor of the general descriptive definition of conditional probability/expectation given a $\sigma$-field. In the general case there is no universal constructive recipe/procedure, but to verify that the integral equation holds for your candidate (which you may have to guess). With that said, your one-liner is probably much more adequate as an explanation to a beginner than my answer. Maybe this is why the OP didn't accept the answer... Thank you very much for your comment!
Comment: 1) Yes, your formula misses the indicator. 2) I didn't make this claim, because it's wrong. Please, read the answer carefully.
Comment: very nice! But instead than having to remember the final result $f(x\mid A) = \frac{f(x)}{\Pr(A)}\,I_{B_0}(x)$, and then proceed backwards by verifying that it is correct, wouldn't it be easier to just note that $\Pr\{X\in B\cap B_0\} = \int_{B\cap B_0} f(x)\text{d}x = \int_{B} I_{B_0}(x)f(x)\text{d}x$?
Comment: You're welcome! I don't know much about conditional probabilities given a $sigma-$field (my bachelor and Ph.D. are neither in Math or Stats), but I get your point. BTW, since you were mentioning Ash's book, do you have a similar suggestion of a more recent book? I studied probability from an old edition of https://www.amazon.it/Probability-random-variables-stochastic-processes/dp/0071226613 and I was wondering if there was something of similar complexity to Ash and Papoulis, but a bit more modern in exposition.
Comment: Thank you for your answer, it is helpful and I can follow it. So, in the end I have that $f(x\mid X<c) = \frac{f(x)}{\Phi(c)}I_{(\infty ; c]}(x)$ and hence for expectation $E[X\mid X<c] = \frac{1}{\Phi(c)}\int_{-\infty}^{\infty}xf(x)I_{(\infty ; c]}(x) = \frac{1}{\Phi(c)}\int_{-\infty}^{c}xf(x)dx$ without further simplification? Hence my formula in the question for $f(x\mid x<c)$ is incorrect?
Comment: I also wanted to ask on the validity of the claim that $f(x\mid A) = Pr\{X\in B\mid X\in B_0\}$. If I remember it correct, $f(x)$ is defined as $f(x) = \frac{Pr(x\in x+\Delta x)}{\Delta x}$ for infinitesimally small $\Delta x$. Why does $\Delta x$ term drop out in $Pr\{X\in B\mid X\in B_0\}$?
Answer: Here is another approach for a continuous random variable, less rigorous than Zen's beautiful solution.
Fix $x:x< c$, then
$P(X\leq x|X<c)=\frac{P(X\leq x,X <c)}{P(X<c)}\overset{x<c}{=} \frac{P(X <x)}{P(X<c)}=\frac{F_X(x)}{F_X(c)}$
Fix $x:x>c$, then
$P(X\leq x|X<c)=\frac{P(X\leq x,X <c)}{P(X<c)}\overset{x>c}{=} \frac{P(X <c)}{P(X<c)}=1$
Then, the conditional pmf is $ f_{X|X<c}(x|x<c)=\frac{f_X(x)}{F_X(c)}I_{(-\infty,c]}(x)$
Therefore, the conditional expectation is
$E(X|X<c)=\int_{- \infty}^{+\infty}xf_{X|X<c}(x|x<c)dx=\int_{- \infty}^{c}xf_{X|X<c}(x|x<c)dx$

Expectation of $X$ given $X < c$


How to run multiple async method in sequence then execute normal function in JavaScript?

Question: I have 3 async functions and a synchronous one. How to run these methods serially?
async function Method1(obj) {
    let url = 'https://www.googleapis.com/';
    let obj = await (await fetch(url)).json();
    console.log('seq 1');
}

async function Method2(obj) {
    let url = 'https://www.googleapis.com/';
    let obj = await (await fetch(url)).json();
    console.log('seq 2');
}

async function Method3(obj) {
    let url = 'https://www.googleapis.com/';
    let obj = await (await fetch(url)).json();
    console.log('seq 3');
}

function Method4 ()
{
    //Some Non-Async Code
    console.log('seq 4');
}

It should give:
seq 1
seq 2
seq 3
seq 4

What is the correct way to achieve this?
Answer: Just wrap it in another async function and use await to call these other async functions.
Example using anonymous wrapper:
(async () => {
    await Method1(foo);
    await Method2(foo);
    await Method3(foo);
    Method4();
})();

Comment: Happens to this too, it ran in sequence but it didnot wait for Methods to finish. What I wanted is first finish Method1 then execute Method2 and so on...
Comment: Then you do something funny. It does wait for `Method1` to finish and calls `Method2` after that.
Answer: Your code has a problem:
You've redeclared variable obj in Method1, Method2 and Method3.
Since you don't use the argument at all, just remove it, like this:
async function Method1() {
    let url = 'https://www.googleapis.com/';
    let obj = await (await fetch(url)).json();
    console.log('seq 1');
}

async function Method2() {
    let url = 'https://www.googleapis.com/';
    let obj = await (await fetch(url)).json();
    console.log('seq 2');
}

async function Method3() {
    let url = 'https://www.googleapis.com/';
    let obj = await (await fetch(url)).json();
    console.log('seq 3');
}

function Method4 ()
{
    //Some Non-Async Code
    console.log('seq 4');
}

Another problem is that https://www.googleapis.com doesn't return a valid JSON (it returns the string Not Found), so all fetch requests will fail. For testing, I've replaced all URLs with JSONPlaceholder's.
And now, to the question:
You can build an asynchronous promise-chainer function:
async function executeSequence(seq){
  for(const fn of seq) await fn();
}

executeSequence([
  Method1,
  Method2,
  Method3,
  Method4
])

This will work with synchronous functions as well (await doesn't mind).
Working example:

async function Method1() {
    let url = 'https://jsonplaceholder.typicode.com/posts/1';
    let obj = await (await fetch(url)).json();
    console.log('seq 1');
}

async function Method2() {
    let url = 'https://jsonplaceholder.typicode.com/posts/1';
    let obj = await (await fetch(url)).json();
    console.log('seq 2');
}

async function Method3() {
    let url = 'https://jsonplaceholder.typicode.com/posts/1';
    let obj = await (await fetch(url)).json();
    console.log('seq 3');
}

function Method4 ()
{
    //Some Non-Async Code
    console.log('seq 4');
}

async function executeSequence(seq){
  for(const fn of seq) await fn();
}

executeSequence([
  Method1,
  Method2,
  Method3,
  Method4
]).catch(console.error)
Comment: It ran in sequence but it didnot wait for Methods to finish. What I wanted is first finish Method1 then execute Method2 and so on...
Comment: How is that more readable than putting `await` in front of each method? Keep it simple.
Comment: @JamshaidAlam The problem was with your functions. I've edited my post, check it now
Comment: If it's less readable and more verbose, then what's the point?
Comment: That it can be reused. But did you notice my phrasing: "*You **can** build an asynchronous promise-chainer function*". The OP can choose your solution if they want, that's another version.
Comment: There's a name for that: overengineering. Try avoiding it, you're not becoming a better programmer by abstracting everything. There is literally zero reasons to do it like you did. Especially that it's also wrong, as you ignored OP's parameters.


schm-reduplication (yiddish) morphological process

Question: By definition, schm-reduplication is a form of reduplication in which the original word or its first syllable (the base) is repeated with the copy (the reduplicant) beginning with shm-.
baby -> schmaby
sprinkler -> schminkler
artist -> schmartist

So all of the letters up till the first vowel of the word are removed with a 'schm' prepended to it.
How do translate this into code?
I'm thinking..
(1) Get the list. (2) Remove all elements until the first vowel is detected. So I'm thinking this will be useful: vowel(X):- member(X,[a,e,i,o,u]). So I would need to scan first element to the end and once I get to a vowel, I keep that and prepend a 'schm'.
I'm having trouble with the removing all elements till vowel part. Can someone help?
I have:
yiddish(A,B):-
append([s,c,h,m],A,B).

?- yiddish([h,o,u,s,e],X).
X = [s, c, h, m, h, o, u, s, e].

Answer: your schema could be implemented like
yiddish(A,B) :- after_first_vowel(A,AFV), append([s,c,h,m],AFV,B).

% here some decision should be taken about data correctness
after_first_vowel([C|Cs],[C|Cs]) :- memberchk(C,[a,e,i,o,u]), !.
after_first_vowel([_|Cs],Rs) :- after_first_vowel(Cs,Rs).

basic test:
?- atom_chars(baby,Cs),yiddish(Cs,L).
Cs = [b, a, b, y],
L = [s, c, h, m, a, b, y]

Comment: @lurker: so sad `Last Changed: 1999/06/14`, and still no agreement on basic features...
Comment: Thank you. Also, what can i do to increase the 'length capacity'? For example, `atom_chars(trousers,Cs),yiddish(Cs,L).
Cs = [t, r, o, u, s, e, r, s], L = [s, c, h, m, o, u, s, e, r|...].` but it doesn't truncate if it's just `trouser`. I don't see the restriction of 7 characters in your code, so I'm curious what it could be.
Comment: no problem, it's a user interface feature of the interpreter: when a list is longer than a configurable limit, only the first elements are shown. Try for instance `?- atom_chars(trousers,Cs),yiddish(Cs,L),write(L).`
Comment: Ah ok, you're right. It displays differently between SWI-Prolog and gprolog. I've also noticed that some libraries in SWI-Prolog do not work with gprolog; the predicate 'intersection' for example. Anyway, I appreciate the help.
Comment: @am3decoy different implementations of Prolog (SWI, GNU, SICStus, ...) have their own libraries. They have many in common, but many unique ones as well. There is an [ISO standard](http://www.iso.org/iso/catalogue_detail.htm?csnumber=21413) for Prolog (also described [here](http://www.deransart.fr/prolog/docs.html) which the various implementations have different degrees of compliance to.
Comment: @CapelliC indeed. Lack of a strong standards base, in part, encourages the diversity of implementations.


Webpack pass a variable into the start/build script

Question: I have a React app which is built inside a Docker container when deployed. It all works as it should, no issues. I have an .env file for development with an API_URL variable and an .env.prod file for deployment with a different API_URL. The .env files get passed directly inside the start/build scripts, like this (for yarn start):
"start": "cross-env NODE_ENV=development env-cmd .env node server"

So, the API_URL variable is inside the .env file used in this script. My question is - can I somehow pass the variable to yarn start or yarn build? When I tried, for testing, adding the variable directly in the script, it didn't get picked up, like so: "start": "cross-env NODE_ENV=development API_URL="my api url" env-cmd .env node server".
Answer: The usage is correct except that env_cmd is overriding that key.
You should use the --no-override flag so it won't.
The final line should like: API_URL="my api url" env_cmd .env --no-override node server"
Comment: This sounds like a solution to half of my problem - I still need a way to pass the variable directly from the terminal. Pseudocode: `yarn start VARIABLE=value`. So if I add `--no-override` to the script itself inside package.json, can I somehow pass the variable from the terminal?
Comment: I tried: `cross-env VARIABLE=value yarn start` but it didn't get picked up
Comment: I forgot to add the new variable to `process.env`. Your solution with the `--no-override` flag is correct. On top of that, the line above worked directly from the terminal.


Dynamically Set Database Parameters For RAD Server

Question: I have developed an application that uses RAD Server over IIS. So far I have successfully created my Server and client applications. The app provides some information that needs to be verified against a MSSQL database on the Server Side. Everything works fine in a test environment as my Database Connection parameters are set in my FDConnection component.
However, I would like to change the Connection parameters by reading an ini file when the Server is accessed.
On my development system I can place the ini file in the directory where my bpl output is located. (ie. C:\Users\Username\Projects\Application\Server\Win32\Debug). The server then reads the ini file correctly and updates the component parameters.
I have created the directories on the server in accordance with the RAD Server documentation and have placed the required EMS files in the directory. (ie: C:\inetpub\RADServer\EMSServer) Since this is where the emsserver.ini file resides, I thought this would be the correct place to put my ini file. If I launch the EMSDevServer.exe from this directory, the ini file gets read properly and FDConnection parameters get updated.
However, when I launch the RAD Server through IIS using the ISAPI dlls, it appears the ini file is not found as my database connections fail.
I have tried putting the ini file in the C:\Users\Public\Documents\Embarcadero\EMS directory and that did not work either.
Following is my code to access the ini file which is called on DataModuleCreate.
procedure TdmSecurity.DataModuleCreate(Sender: TObject);
begin
  SetConnectionStr(FDConnectionSTIKS);
end;

procedure SetConnectionStr(var FDConnectionSTIKS: TFDConnection);
var ConfigIni: TInifile;
    DBServerName, DBName, Path: string;
begin
  Path := GetCurrentDir;
  ConfigIni := TIniFile.Create(System.IOUtils.TPath.Combine(Path, 'Config.ini'));
//  ConfigIni := TIniFile.Create(System.IOUtils.TPath.Combine(System.IOUtils.TPath.GetDocumentsPath, 'Config.ini'));
//  ConfigIni := TIniFile.Create('C:\Users\leonard\Projects\LumberNowEMS\Server\Win32\Debug\config.ini');
  DBServerName := ConfigIni.ReadString(AppNode, 'ServerName', 'ZEUS');
  DBName := ConfigIni.ReadString(AppNode, 'DataBase', 'NOTHING');

//  showmessage(configini.FileName);

  with FDConnectionSTIKS.Params as TFDPhysMSSQLConnectionDefParams do
  begin
    DriverID := 'MSSQL';
    Server := DBServerName;
    Database := DBName;
    UserName := DBUserID;
    Password := DBPassword;
  end;

  ConfigIni.Free;

//  showmessage(Path + '; DBName:' +DBName);
//  Result := Format('DriverID=MSSQL;Server=%s;Database=%s;User_name=%s;Password=%s', [DBServerName, DBName, DBUserID, DBPassword]);
end;

I expected that the IIS would read the ini file from the same place but it does not appear to be so. Can someone tell me where I should put the ini file so IIS can access it correctly or perhaps a better way of setting the database connection in Rad Server? Perhaps I could put my parameters in the emsserver.ini if there is a variable I can access.
Comment: @nolaspeaker - I don't know how to determine what the PATH variable contains when running IIS. I can't use showmessage() and I'm not sure how I show the value when it is contained in a package. When I run the EMSDevServer.exe the path variable is C:\inetpub\RADServer\EMSServer. I will see if I can write the value of the PATH variable to a text file.
Comment: What value does the `Path` variable have when you are running under IIS? That will answer your question for you immediately.
Comment: Go to the root node from the Connections panel and double-click ISAPI and CGI Restrictions. Select Edit Features Settings from the Actions panel and check the two options [image](https://imgur.com/a/rVqU7Jj) and  Return to the root node and double-click Handler Mappings. Go to the Actions panel, select Edit Feature Permissions and check Execute. [image1](https://imgur.com/a/p3EBGkL) could you please share the permisiion of the .ini file. in my opnion, you need to give IIS_iusrs and iusr full control.
Comment: @JalpaPanchal I only loaded the ISAPI Extensions and not the CGI and have checked 'Allow unspecified ISAPI modules' at the root node.  I enabled Execute permission on the RADServer node but not the Root node. I have since enabled Execute permission at the root node as well with no change in results. iUSR already has full permissions.
Answer: @nolaspeaker - I would give you credit for the answer but you only posted a comment. Your response prompted me to find a way to determine the path that was being used. So I wrote the value of the path variable to a known text file.
Path := GetCurrentDir;
AssignFile(F, 'C:\Temp\Data.txt');
Rewrite(F);
WriteLn(F, Path);
CloseFile(F);

The path that is being used is 'C:\Windows\SysWOW64\inetsrv';
I moved my Config.ini file to this directory and it was found and read correctly.
Thanks for the responses.
Answer: Quite late, still posting an answer.
Functions in System.SysUtils will be helpful here.
following function call would give you the path to the directory where the .bpl file resides.
ExtractFilePath(GetModuleName(HInstance));

place the ini along with .bpl file, combining the above function's result with the Ini filename will help you to target an ini.


Python. Playsound "TypeError: sequence item 3: expected str instance, bytes found"

Question: I've working about small script that must play 1 of my sounds. It's about 1,5 sec.
<code>import playsound

mp3_sound = "audio.mp3"
playsound.playsound(mp3_sound)
</code>
And it gives this error:
<code>"TypeError: sequence item 3: expected str instance, bytes found"
</code>
Help, pls.
Answer: I assume your file is not in your run time folder. I would run the following code to verify you are providing the correct file path.
<code># one of many ways
import os.path
os.path.exists(path_to_file)
</code>
Comment: It's a rely good advice, but I've copied the path from the Explorer. And I ran your code and it showed me the same path.
Comment: Looks like that is not the problem. I do not have any experience with this library but I might have time to look more into it later today.


Line equation and distance between a line and a point in 3D space

Question: I've looked for many similar questions but could not find an answer that helps.
I have a point $p$ $(x,y,z)$ on a plane, and a normal to the plane $n$ $(a,b,c)$. I need to find the equation of a line defined by the point $p$ and normal $n$.
Then I would like to know how to find the distance from any arbitrary point $p_a$ $(x_a,y_a,z_a)$ and the line defined above.
Comment: By a line defined by the point $p$ and normal $n$ do you mean _the_ line through $p$ parallel to $n$ ?
Comment: @Abramo NO, outside the plane
Comment: "..a line defined by $\;p\;$ and the normal $\;n\;$" ? There shall be infinite such lines...
Comment: But I know the point $ p $.
Comment: It doesn't matter, @SalamKh :I'm assuming you know both the normal and the point. Still, there are infinite lines that can be traced from that point through (some point of) that line.
Comment: I am afraid that I don't understand your issue here.
Comment: given one point and one line not through the point (in 2 or 3 dimensional space) , there is an infinite number of lines through the point and a point of the line. This is what I understand when you write "A line defined by a point and a (normal) line". Just do a little drawing.
Comment: isn't this the case all the time? even if there are infinite number of lines what stops me from getting an equation?
Comment: Nothing at all stops you: you even have infinite choices...:)
Comment: @TonyPiccolo yes
Answer: A line through a point $p$ which is parallel to the plane normal $n$ (or in other words - the line through a point $p$ normal to the plane with  normal $n$) is simply:
$${\bf p} + {\bf n} \cdot t$$
Where $t$ is the line parameter. To find the distance between a third point $q$ and this line, you may want to use the following formula:
$$d = \left|({\bf q}-{\bf p})\times({\bf q}-{\bf p}-{\bf{n}}/|{\bf n}|)\right|$$
Where $\times$ is the cross product.
Comment: Yes, and then what about the distance between any other point and this line?
Comment: @SalamKh - this should answer your question.
Comment: the second part of the distance equation, is it supposed to be $((q-p-n)/|n|)$ or $(q-p-(n/|n|))$ ?
Comment: @SalamKh - option two. that is only meaning possible given the precedence division has over subtraction.
Comment: I know that, I just wanted to make sure I'm not missing something. sry.


Interagindo todos os itens de uma lista

Question: tenho a seguinte situação:
Possuo 4 listas numéricas que vão de 1 a 30. Ex.:
AP_X = [1,2,3,4,5...30]
AP_Y = [1,2,3,4,5...30]
demanda_X = [1,2,3,4,5...30]
demanda_Y = [1,2,3,4,5...30]

Possuo uma outra lista, vazia, chamada distancia que receberá o resultado dessas interações.
distancia = []

As listas AP_X e AP_Y representam as coordenadas de um ponto e as listas demandas_X e demanda_Y, representam as coordenadas de outro ponto.
Preciso fazer que cada ponto AP(x,y) combine com cada ponto demanda(x,y).
Por exemplo:
distancia = [1,1,1,1 | 1,1,2,2 | 1,1,3,3 |...| 2,2,1,1 | 2,2,2,2| ...| 30,30,1,1 | 30,30,2,2 ]

Não sei se fui claro, mas preciso combinar todos os item AP(x,y) com todos demanda(x,y).
Desde já grato pela ajuda.
Comment: De fato não deu para entender que tipo de combinação você precisa. Consegue explicar melhor?
Comment: Por exemplo: Digamos que eu tenha uma lista com [ a,b,c]  e outra lista com [e,f,g]. Preciso que o resultado seja [ae,af,ag,be,bf,bg,ce,cf,cg].
Comment: Porém, no meu exemplo o abcdefg = coordenadas xy,
Comment: Desculpe-me se não estou claro. Estou me esforçando.
Answer: AP_X = [1,2,3,4,5,30]
AP_Y = [1,2,3,4,5,30]
demanda_X = [1,2,3,4,5,30]
demanda_Y = [1,2,3,4,5,30]

ap = list(zip(AP_X, AP_Y))
demanda = list(zip(demanda_X, demanda_Y))

distancia = []

for i in ap:
  for j in demanda:
    distancia.append((i, j))

print(distancia)

Esse código imprime o seguinte resultado:
[((1, 1), (1, 1)), ((1, 1), (2, 2)), ((1, 1), (3, 3)), ((1, 1), (4, 4)), ((1, 1), (5, 5)), ((1, 1), (30, 30)), ((2, 2), (1, 1)), ((2, 2), (2, 2)), ((2, 2), (3, 3)), ((2, 2), (4, 4)), ((2, 2), (5, 5)), ((2, 2), (30, 30)), ((3, 3), (1, 1)), ((3, 3), (2, 2)), ((3, 3), (3, 3)), ((3, 3), (4, 4)), ((3, 3), (5, 5)), ((3, 3), (30, 30)), ((4, 4), (1, 1)), ((4, 4), (2, 2)), ((4, 4), (3, 3)), ((4, 4), (4, 4)), ((4, 4), (5, 5)), ((4, 4), (30, 30)), ((5, 5), (1, 1)), ((5, 5), (2, 2)), ((5, 5), (3, 3)), ((5, 5), (4, 4)), ((5, 5), (5, 5)), ((5, 5), (30, 30)), ((30, 30), (1, 1)), ((30, 30), (2, 2)), ((30, 30), (3, 3)), ((30, 30), (4, 4)), ((30, 30), (5, 5)), ((30, 30), (30, 30))]

Onde cada item é do formato ((AP_X, AP_Y), (demanda_X, demanda_Y))
Lhe serve ou precisa necessariamente ser no formato AP_X, AP_Y, demanda_X, demanda_Y?
Comment: Perfeito, Anderson!
É exatamente como eu preciso.
Muito, Muito Obrigado.

Abraço amigo.

Interagindo todos os itens de uma lista


How to use Zend Cache with SimpleXML objects?

Question: I'm trying to cache the user timeline of a Twitter feed using Zend_Service_Twitter which returns its results as a SimpleXML object. Unfortunately the regular serialize functions (which Zend Cache uses) don't play nice with SimpleXMl objects. I found this http://firstname.lastname@example.com/msg18133.html.
So it looks like I'll need to create some kind of custom frontend for Zend Cache to be able to change the serialize function used. Anybody ever done this already or can point me where to look to start?
Comment: Looks like Zend_Service_Twitter actually returns a Zend_Rest_Client_Result which then contains a SimpleXML object.
Answer: Instead of trying to cache the SimpleXML object, I chose to loop through Twitter posts returned and save that data as a string. I then save that string to the cache. Works for me!
Answer: Or you can call asXML() function:
<code>$simpleXml = @simplexml_load_file($xml_url);
$cache->save($simpleXml->asXML(), 'name_of_cache');
</code>

Definition and Usage
The asXML() function returns the XML document, from a SimpleXMLElement
  object, as a string.
  This function returns FALSE on failure.


Golang package that must also be useable standalone from cli

Question: I would like to create a package that has a main function and uses the flag package to specify arguments.
Additionally, I want to be able to include this package in other packages, and call it's methods with a similar syntax to passing args on the cli. Possibly something like
err := myPackage.setFlags(args ...string)
out, err := myPackage.exec()

Some of the reasons I want the included package to have a main function is:

It enables me to distribute the package as a standalone executable. My users might not need the complete system
It could make manual troubleshooting easier

Should I keep everything separate and use os\exec?
Should I create standalone wrappers (maybe these can be generated?) for each package and call exported functions directly from the complete system without doing the setFlags thing?
Is there a good design pattern I could follow to do this?
Or am I conjuring up an anti-pattern?
Answer: A common pattern is to have a cmd pkg in your project that has executables.
Something like this
cmd/
   foo/main.go
pkg/
   foo/foo.go

cmd/foo imports pkg/foo and handles the command line flags. pkg/foo is the package with all of the library code. This pattern lets others import pkg/foo and cmd/foo gives you an executable called foo as well.


Calculation of confidence interval for estimation of demand curve - how many degrees freedom?

Question: I'm trying to understand how uncertain an estimation of a demand distribution of a good is. If I take a random sample of n people from the representative consumer population who give me their personal cutoff/choke prices (assuming they accurately report them), I can construct a demand curve with n points representing an estimation of the proportion of the population who would buy the good at that price.
Given that I used n independent pieces of information to calculate n points, should I be using a t-distribution with 1 degree of freedom to calculate the confidence interval for each point? And, if I want to reduce this interval by increasing the degrees of freedom, I either need to take more samples, or increase the granularity of the demand curve to get more d.f. at each point?
Comment: Could you clarify how you would construct a demand curve?  Do your n points constitute the "curve", or would you having calculated the n points use regression to fit a smooth curve to them?
Comment: n "choke price" points can be aggregated into a bar chart (the "demand curve"), where each bar represents the proportion of people in the sample who would buy the good at that price. It is a cumulative distribution. You can, of course, smooth this discrete bar chart into a smooth continuous curve, but as it doesn't add new information (and the application I'm using this for doesn't require it) I don't bother.
Comment: A regression doesn't add new information, but it could perhaps make more effective use of the information you have.  However, I have answered your question on the basis that each estimated point simply reflects the sample proportion of people who would buy the good at that price.
Answer: You should use a $t$-distribution with $n-1$ degrees of freedom (or if $n$ is large the normal distribution which provides a good approximation to the $t$-distribution).  A larger sample, increasing $n$, would narrow the confidence interval both because it increases the degrees of freedom (although once $n$ increases beyond 30 this effect is quite small) and because it reduces the standard error.
For a given price the sample contains, say, $m$ people who would buy the good at that price. Thus the proportion of the population who would buy the good at that price can be estimated as $m/n$.  This applies to any price, not just to the $n$ cutoff prices given by the people in the sample. So you can calculate any number of points, taking a point to be identified by a price and its associated estimated proportion.
The number of points that are or could be calculated has no relevance to the degrees of freedom used in calculating a confidence interval for the proportion at any one price (the situation is quite different from a regression in which $n$ observations are used to jointly estimate $k$ parameters, implying $n-k$ degrees of freedom).  The degrees of freedom here depend only on the size $n$ of the sample used to estimate that proportion and its standard error, from which we deduct 1 because use of the same sample to estimate both the proportion and its standard error implies a loss of 1 degree of freedom.
The value of $t_{n-1}$ at the desired confidence level times the estimated standard error gives the half-width of the confidence interval.


Questionario de setores em php mysql

Question: Aqui eu vejo quantas perguntas que tem em cada setor:
SELECT
    a.area_id   AS ID_AREA,
    a.area_desc AS AREA_DESC,
    count(sb.sub_area_cod) AS TOTAL
      FROM
        relacaoperg AS rp
         INNER JOIN area     AS a  ON rp.id_area = a.area_id
         INNER JOIN sub_area AS sb ON rp.id_subgrupo =  sb.sub_area_cod
              WHERE
                   id_area <> '1' GROUP BY AREA_DESC ASC;

Retorna da seguinte forma:
id  desc        total
2   FRENTE      18
3   FRIOS       36
4   ACOUGUE     35
5   MERCEARIA   27
6   HORTIFRUTI  31
7   PADARIA     33

Aqui vejo as respostas:
SELECT
       a.area_id   AS ID_AREA,
       a.area_desc AS AREA_DESC,
       count(resp_area) AS TOTAL
             FROM respostas as r
               INNER JOIN area     AS a  ON r.resp_area     = a.area_id
               INNER JOIN sub_area AS sb ON r.resp_subgrupo =  sb.sub_area_cod
                  WHERE
                    resp_area <> '1'
                    AND resp_questionario='3'
                        GROUP BY resp_area;

Retorna da seguinte forma:
id  desc       total
3   FRIOS      32
5   MERCEARIA  27

Ou seja somente frios e mercearia que responderam.
No parte do select onde coloco: resp_area <> '1'  esse setor é a gerencia.
Preciso que o gerente só possa responder quando as respostas estiverem iguais as perguntas (mesma quantidade),ou seja,ele só pode responderem quando todos os setores já tiverem respondido.
Como poderia criar essa regra ?
Comment: mano não sei bem como ficaria a consulta, mas basicamente vc tem que somar o total das perguntas de todos os setores, tipo 18+36+35... e comparar com o total geral das perguntas, se for igual vc libera pra gerencia rs. Vc quer fzr isso no php ou no sql?
Comment: PHP.assim daria sim,mais eu queria também exibir para ele,qual setor não respondeu ainda.
Answer: Salve o resultado das duas consultas em um array e utilize
http://php.net/manual/pt_BR/function.array-diff-assoc.php
para compara-las, dependendo do resultado você deixa ou não a gerencia responder

Questionario de setores em php mysql