Popular List c#

Question: Estou tentando retornar dados de um list em um foreach. No primeiro foreach, ele está retornando os dados corretos, mas não está gravando na variavel nflist do primeiro foreach, então, assim que passa por ele novamente, perde os dados anteriores e substitui pelos dados atuais.
    public void UpdateNFE()
    {
        List<NFE> nfeList = new List<NFE>();
        NFEDB nfeData = new NFEDB();
        SAPBAPI sapBAPI = new SAPBAPI();
        NFE nfeTeste = new NFE();

        DataTable NFSap =  sapBAPI.SearchNFbyDate();

        foreach (DataRow item in NFSap.Rows)
        {
            int index = NFSap.Rows.IndexOf(item);

            nfeList = nfeData.ListNFEForUpdate(NFSap.Rows[index]["J_1BNFDOC-NFENUM"].ToString(), NFSap.Rows[index]["J_1BNFDOC-CREDAT"].ToString());

    //está retornando todos os dados corretamente, mas é necessário "gravar"
    //os dados retornados

        }

        foreach (NFE nfe in nfeList)
        {
            StructureNFEAccessKey nfeAccessKey = new StructureNFEAccessKey();

            nfeAccessKey.REGIO = nfe.Region;
    }

Comment: Se você faz `nfeList = ...` dentro do `foreach` naturalmente que perde os valores anteriores. Se a ideia é ir adicionando coisas à lista terá que utilizar o método `Add` da lista para isso
Comment: Obrigada! Deu certo com nfeList.AddRange..
Answer: Você precisa usar o método nfeList.Add(item) ou nfeList.AddRange(items) para adicionar itens na sua lista, senão os valores antigos serão perdidos mesmo.
substitua:
  nfeList = nfeData.ListNFEForUpdate(NFSap.Rows[index]["J_1BNFDOC-NFENUM"].ToString(), NFSap.Rows[index]["J_1BNFDOC-CREDAT"].ToString());

Se o nfeData.ListNFEForUpdate for uma lista, insira isso:
nfeList.AddRange(nfeData.ListNFEForUpdate(NFSap.Rows[index]["J_1BNFDOC-NFENUM"].ToString(), NFSap.Rows[index]["J_1BNFDOC-CREDAT"].ToString()));

Se o nfeData.ListNFEForUpdate for um objeto unico do tipo NFE, insira isso:
nfeList.Add(nfeData.ListNFEForUpdate(NFSap.Rows[index]["J_1BNFDOC-NFENUM"].ToString(), NFSap.Rows[index]["J_1BNFDOC-CREDAT"].ToString()));

Popular List c#


A question on the argument : $\delta f(p) \le C$

Question: I'm confusing for the following argument is true or not:
Let $f(p) = \frac{1}{2-p}$. Then for any $1<p<2$, there exists a constant $C>0$ independent of $p$ and $\delta$ such that $$\delta f(p) \le C$$
if $\delta>0$ is small enough.
Answer: since $C>0$ is independent of $p,δ$ we can move it outside of the quantifiers for $p$, so your statement is equivalent to the assertion
$$∃ C>0 : ∀ p∈ (1,2), ∃ δ =δ(p ) :\quad f( p) \leq \frac{C}{δ(p)} $$
and this is true, In fact, any $C>0$ works, since then we can choose $δ( p) \geq \frac{C}{f( p)}$.
Comment: Thank you for your comment. But I could not understand clearly. For example, if $p=1.99$ then it seems I can take $\delta$ very small that the inequality holds. I think this process works for any $p<2$. Is there something wrong?
Comment: @Kumarta I'm sorry, I misread your statement as well!
Comment: Thanks. I can now understand this. I can adopt your answer may be tomorrow because I used another account at the work.
Comment: OK. Glad to help :)


Menu Block shows both languages

Question: I'm using the i18n module for translating nodes and menu items.
I have a bunch of menu-items and am now trying to put that into the header with a menublock.
But unfortunately all menu-items in all languages appear instead of just the items in the current language and language-neutral.
Does anyone know how to fix that.
The only solution I have is to create a menu for every language.
Answer: Okay sorry ... it took some time, but I found the solution.
First I had the themed menu within the template, now I have the main menu direct as a block.
The solution was to edit the main menu and set the following option:

Translate and Localize. Menu items with language will allow
translations. Menu items without language will be localized.

That's it.

Menu Block shows both languages


Has there ever been a complete game in which the pitcher never threw 3 balls in one at-bat?

Question: During his perfect game in Game 5 of the 1956 World Series, Don Larsen went to 3 balls in a count against only one batter. (source)
Has there ever been a complete game in MLB history in which the pitcher never threw 3 balls during one at-bat?  (Meaning that the count against any one batter never reached 3-0, 3-1, or 3-2.)
Answer: Per an SI article, Len Barker did not allow three balls to anyone in his 1981 perfect game.

He struck out 11 batters—all swinging—and didn't go to a single three-ball count. Only eight Toronto batters got as much as a two-ball count.


Eigen values of a block diagonal matrix of a specific form (resulting from an adjacency matrix)

Question: The question is as framed below

Let G be a graph on $p$ vertices. Let the eigen values be $\lambda_1,...,\lambda_n$. Create a new graph G' from G as follows. Corresponding to each vertex $v$ of G, add a new vertex $v{'}$ such that $v'$ has degree 1 and is connected via an edge to $v$. In all, the new graph G' has $2p$ vertices with $p$ number of edges more than that in $G$. Show that the eigen values of G' are $$\frac{\lambda_i\pm\sqrt{\lambda_i^2+4}}{2}$$

This question is from algebraic combinatorics by Stanley. This is related to number of closed walks of length $l$ but the hint says that an algebraic proof is quicker and better and hence I am trying to find one.
Ordering the vertices as $\{v_1,v_2,...,v_p,v_1',...,v_p'\}$, we get that the adjacency matrix is of the form
$$\begin{bmatrix}
A & I \\ I & 0
\end{bmatrix}$$
where all matrices in the block matrix are of size $p\times p$ and
$A$ is the adjacency matrix of the original graph G
To get the eigen values of this, we use $$det\begin{bmatrix}A&B\\C&D\end{bmatrix}=det(AD)-det(CB)$$ because $A$ and $C$ commute
Thus, we end up with,
$$x^p det(A-xI)=1$$ where $x$ is the eigen value of the bigger block matrix.
After this I am stuck. How do I relate $x$ and $\lambda$ ?
Comment: No!  You can only get $\det\begin{pmatrix}A&B\\C&D\end{pmatrix}=\det(AD-CB)$ from $AC=CA$.  You can easily see $\det(AD-CB)\neq\det(AD)-\det(CB)$ in general.
Answer: Let $(v,w)'$ be an eigenvector of the extended matrix with eigenvalue $\mu$. That is,  $$ \begin{bmatrix} A & I \\ I & 0\end{bmatrix} \begin{bmatrix} v \\ w\end{bmatrix} = (Av + w, v)' = \mu (v,w)'$$
Then
\begin{cases}
 Av + w = \mu v \\
 v = \mu w.
\end{cases}
Substituting $w = v/\mu$ into the first equation
$$ Av + v/\mu = \mu v \iff Av = (\mu - 1/\mu) v$$
so $ \mu - 1/\mu = \lambda$ where $\lambda$ is an eigenvalue of $A$. Solving this equation for $\mu$ gives the desired equation.
Note that this only proves that if an eigenvalue for $G'$ exists then it has the desired form. Therefore there is still a little work to do in order to obtain a full proof of the statement.


How to fetch a tag value from Test step response file (REST request's response) in SOAP UI

Question: I am a newbie to SOAP UI, I need to fetch a tag value from Test step response file (REST request's response) and set it as testsuite property.
My Request file looks like;
<xdata created_by="XXXX" created_at="Wed Mar 16 08:45:39 EDT 2016" app="" profile="" app_version="" env="DEV" tran="" service="1234">
   <rows start_index="0">
      <row basketId="1234566" basketVersionId="11" basketName="ORDERS_1505" basketDescription="ORDERS" createdUserName="XXXX" updatedUserName="XXX" __errorMsg="{"errors":[],"success":true}" totalApprovedOrderCount="0"/>
   </rows>
</xdata>

I need to fetch basketVersionId attribute, please help.
Note: All the examples I read are dealing with Soap Response, property transfer using namespace and xpath. but that is not woking here I guess.
Comment: 1. there seems to be duplicated data, is that correct? 2. can you show which did not work as that will help better. 3. you were saying need to extract value from response and but you provided the request, would you like to provide response and tell which data to be extracted?
Answer: SOAPUI converts practically all to Xml, so despite the fact that you've a REST service you can use anyway and XPath in the property transfer testStep.
The only difference is that in property transfer you've to select:

ResponseAsXml as a property for the REST service with a Json response.
Response as a property for a SOAP service with Xml response.

So you can use: //*:row/@basketVersionId as XPath to get your attribute value.

Hope it helps,
Comment: Thanks, the above xpath mentioned worked. So it was the xpath that i was giving wrong. Thanks :)
Comment: @SandyQAProffessional glad to help you `:)`


Linksys VOIP System Layout

Question: I am completely new to VOIP systems and I want to learn how to setup a small business VOIP system. I understand that for a small business, there is 1 physical phone line that comes in with phone and adsl traffic on it. I am looking at the Linksys SPA9000 to use for the VOIP service, but can someone please explain how a network diagram goes together exactly? Ie:
------> Phoneline/Internet ------> Modem/Router ------> Switch ------> SPA9000
Thanks.
Answer: The diagram that you showed would be how it should be connected.

Linksys VOIP System Layout


Azure SQL Authentication Active Directory Default Slow

Question: We are transitioning from using usernames and passwords in Visual Studio to "Authentication=Active Directory Default" in our Azure SQL connection strings for EF Core.
We are experiencing startup times taking 3 times as long since this change as it appears the token acquisition is really delaying things, possibly down to attempting to authenticate different ways that are unavailable.
There appears to be ways to add settings to environmental variables to disable mechanisms other than Visual Studio as the method but I haven't gotten them to improve things.
Is anyone aware of a fix for this issue?
https://github.com/Azure/azure-sdk-for-net/blob/e9cbf9b31df595b2b34268fa91e14be9d57bdfd3/sdk/identity/Azure.Identity/src/Credentials/DefaultAzureCredentialOptions.cs#L213
https://learn.microsoft.com/en-us/sql/connect/ado-net/sql/azure-active-directory-authentication?view=sql-server-ver16#using-active-directory-default-authentication
https://github.com/dotnet/SqlClient/issues/1473
UPDATE
In case it's of any use to anyone, I started to build out an interceptor. I haven't fully implemented this yet but in case it's helpful I'll leave it here.
You can register this as like this:
https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors#registering-interceptors

public class AadAuthenticationInterceptor : DbConnectionInterceptor
    {
        public override InterceptionResult ConnectionOpening(
            DbConnection connection,
            ConnectionEventData eventData,
            InterceptionResult result)
            => throw new InvalidOperationException("Open connections asynchronously when using AAD authentication.");

        public override async ValueTask<InterceptionResult> ConnectionOpeningAsync(
            DbConnection connection,
            ConnectionEventData eventData,
            InterceptionResult result,
            CancellationToken cancellationToken = default)
        {
            var sqlConnection = (SqlConnection)connection;

            var token = await GetAzureTokenCache();
            sqlConnection.AccessToken = token;
            return result;
        }

        public static async Task<string> GetAzureTokenCache()
        {
            AzureTokenItem tkn = new AzureTokenItem();

            var AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YourFolder\\";
            if (File.Exists(AppDataFolder + "AzureTokenCache.txt"))
            {
                var tokenText = File.ReadAllText(AppDataFolder + "AzureTokenCache.txt");
                var tmpTkn = JsonSerializer.Deserialize<AzureTokenItem>(tokenText);
                if (tmpTkn.ExpiresOn > DateTime.Now)
                {
                    return tmpTkn.Token;
                }
            }

            var tokenCredential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
            {
                // Disable the token credential that we don't use
                ExcludeEnvironmentCredential = true,
                ExcludeInteractiveBrowserCredential = true,
                ExcludeAzurePowerShellCredential = true,
                ExcludeSharedTokenCacheCredential = true,
                ExcludeVisualStudioCodeCredential = true,
                ExcludeManagedIdentityCredential = true,
                ExcludeAzureCliCredential = true,
            });

            var azureTkn = await tokenCredential.GetTokenAsync(new TokenRequestContext(new[] { "https://database.windows.net/" }));

            tkn = new AzureTokenItem
            {
                ExpiresOn = azureTkn.ExpiresOn.LocalDateTime,
                Token = azureTkn.Token
            };

            Directory.CreateDirectory(AppDataFolder);
            File.WriteAllText(AppDataFolder + "AzureTokenCache.txt", JsonSerializer.Serialize(tkn));

            return tkn.Token;
        }
    }
    public class AzureTokenItem
    {
        public DateTime ExpiresOn { get; set; }
        public string Token { get; set; }
    }

Comment: Has anyone any ideas on this as it's taking over 20 seconds for our first requests to go through now?
Comment: You're caching the access token, in plain text, on disk. This makes me nervous because the point of AAD auth is to avoid developer secrets sitting on the machine. This is my motivation anyway. DefaultAzureCredential is also meant to refresh tokens, and here it looks like it's going to be forced to auth every time a token expires rather that simply refreshing. Which is ultimately quicker? Hard to tell tho without some proper testing.
Comment: Absolutely and this is obviously a decision to be made. I would hope most developers have some form of disk encryption enabled on their machines. This is the same way the user secrets operates, so if you're using that it's not necessarily an extra issue. In my experience the slowness comes from the first request so it would appear caching is done in memory.
Answer: I feel you pain. I got it ok-ish by implementing a custom authentication provider and explicitly configuring the auth sources to use:
public class MySqlAuthenticationProvider : SqlAuthenticationProvider
{
    public override async Task<SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters)
    {
        var context = new TokenRequestContext(new[] { "https://database.windows.net/" });
        var options = new DefaultAzureCredentialOptions() {
            ExcludeManagedIdentityCredential = true
            // Exclude more..
        };
        var token = await new DefaultAzureCredential(options)
            .GetTokenAsync(context, default);
        return new SqlAuthenticationToken(token.Token, token.ExpiresOn);
    }

    public override bool IsSupported(SqlAuthenticationMethod authenticationMethod)
        => authenticationMethod.Equals(SqlAuthenticationMethod.ActiveDirectoryDefault);
}

You wire this up in program start-up by:
SqlAuthenticationProvider.SetProvider(
    SqlAuthenticationMethod.ActiveDirectoryDefault,
    new MySqlAuthenticationProvider()
);

This way I got initial connection speed on VS auth from ~15+ sec to ~6 sec.
This is still slow, but bearable, especially if warmed up asynchronously while other parts of app start up.
Comment: Thanks for your comment. I've actually just updated my original post with the Interceptor I built out. I haven't fully tested it or anything yet but the concept is sound. I added file system based caching for the token to persist restarts which you could probably do too.


Sampling without replacement from a population

Question: While counting number of ways to select a sample of size n, from a small(<=60 elements) population, we use combinations to count. For example, number of ways to select a sample of size 3 from a population of size 60, let's say is: 60C3 or 60 choose 3 i.e the usual combinations formula.
My question is:
Why the order does not matter while counting the number of ways we can sample without replacement from a population ? or why don't we use permutations to calculate number of ways to sample? If someone could elaborate with simple example would be nice.
Note: I am studying hypergeometric random variable.
Comment: You'll want to familiarize yourself with something called the sampling table, which has as rows With Replacement and Without Replacement and as its columns Order Matters and Order Does Not Matter. All 4 questions make sense and have useful applications: With Replacement & Order Matters, With Replacement & Order Does Not Matter, Without Replacement & Order Matters, Without Replacement & Order Does Not Matter. Check out Joseph Blitzstein's Harvard STAT 110 course on YouTube. He discusses the sampling table starting with minute 42 of his first lecture: Probability and Counting.
Comment: "Order doesn't matter" is just a convention of sampling. If I'm throwing dice, a 1-6 is the same as a 6-1. Just the same, if I deal a blackjack hand to you of A-K, it's the same as K-A.
Answer: Does not matter to whom and for what?
The number of possible ordered samples of $n$ items from a population of $N$ items is indeed $N!/n!$, and the number of possible unordered samples of $n$ items from a population of $N$ items is ${N \choose n}$.  Both of these are legitimate counts of the number of possible outcomes of a certain aspect of the sample.  As to whether or not the order matters, that begs the question: matters to whom and for what?
When we sample via simple-random-sampling without replacement, this means that samples containing the same items (in any order) are equally likely, which means that we will typically use procedures on the sample that are invariant to their order.  If we use the sample in ways that are order invariant, then the order doesn't matter to the way in which we use the sample.  In such cases, it is quite natural for us to ask the number of possible unordered samples we can get and to perform probability calculations on this basis.  Contrarily, if we use the sample in ways that are not order invariant, then the order matters to the way in which we use the sample, and we would therefore have to consider order.  Even in the latter case, we know that the probability of the unordered sample is $(N-n)!$ times the probability of any ordered sample of the same items, so the conversion is quite simple.
Answer: Hi: You use combinations when its without replacement but there's a multiplication involved also.  Say you had numbers 1,2 and 3 and you wanted to calculate the number of ways you could pick 2 of these numbers without replacement.  Then, you could pick 3 numbers on the first trial and 2 numbers on the second trial so the total ways of picking two numbers without replacement is 3 * 2 = 6.
But this is (3 choose 1) * ( 2 choose 1 ). So, you're using combinations through the choose function but you're multiplying two of them because, in the second trial, you only have 2 numbers left.
If it was with replacement, then it would be (3 choose 1) * (3 choose 1 ) = 9 ways because, since you're putting them back, you still have 3 numbers to pick from on the second attempt.
Does that make sense ?
Answer: Because when sampling—with or without replacement—all we are interested in is are the distinct items selected—not the order in which they were selected. All combinations really are is permutations where order doesn't matter. So you can start with permutations but then must address the lack of interest in the order by treating each "sampling-identical" set as the same. This is done by dividing the total number of permutations by the number of permutations each sample may have. For example, when choosing 3 items from a pool of 4, selecting $(A, B, C)$ is functionally equivalent for sampling purposes as selecting any of $(A, C, B), (B, A, C), (B, C, A), (C, A, B)$ or $(C, B, A)$. There are six such items because there are $k!$ ways to distinctly order $k$ items.
Let's enumerate the possibilities:

A, B, C (1)
A, B, D (2)
A, C, D (3)
A, C, B (1)
A, D, B (2)
A, D, C (3)
B, A, C (1)
B, A, D (2)
B, C, D (4)
B, C, A (1)
B, D, A (2)
B, D, C (4)
C, A, B (1)
C, A, D (3)
C, B, A (1)
C, B, D (4)
C, D, A (3)
C, D, B (4)
D, A, B (2)
D, A, C (3)
D, B, A (2)
D, B, C (4)
D, C, A (3)
D, C, B (4)

Note all of the above can be broken into four categories (listed by numerals) which correspond to using the same letters regardless of order. Which is what we expect ${4\choose 3} = \frac{4!}{3!\cdot(4 - 3)!} = 4$


why they have the same first coordinate in torus?

Question: Note: It humble request to everyone please don't downvote  my post .Im not  genius or intelligent.Im new  to the  Algebraic Topology.Try to understand my level of understanding.I feel discourage   whenever  i get  downvote
I have  some confusion in this  answer
Question : Is the Borsuk-Ulam theorem valid for a torus? In other words, for any map $f: S^1 \times S^1 \rightarrow \mathbb{R^2}$ there is a point $(x,y) \in S^1 \times S^1$ which $f(x,y)=f(-x,-y)?$

Here  is the  outlined  of the  given answer

No. With the usual torus embedded in $\mathbb{R}^3$, lying on the $OXY$ plane, one has a natural projection onto that plane, $p:S^1×S^1\to \mathbb{R}^2$, which is continuous.

Two points on the torus have the same image if they are one above the other,
in the same vertical line. In particular, they are in the same meridian of
the torus, i.e. they have the same first coordinate. So, if $p(a,b) = p(c,d)$,
$a = c$. This implies that the Borsuk-Ulam theorem fails on the torus because if $x=-x$, and then $x=0\notin S^1$.

My confusion : Im not getting the  statement "they are in the same meridian of
the torus, i.e. they have the same first coordinate".
My  attempt :If they are in the same meridian of
the torus  then  $p(\theta_1, \theta_2)=p(\theta_1 +\frac{1}{2}   , \theta_2 +\frac{1}{2})$
Now take  $a=\theta_1$ and  $c=\theta_1 +\frac{1}{2} $
$\theta_1=\theta_1 +\frac{1}{2} \implies \theta_1-\theta_1 =\frac{1}{2} \neq 0 \implies  a \ne c$
and $\theta_1=\theta_1 +\frac{1}{2} \implies  \frac{1}{2}  \in S^1$
My question : why they have the same first coordinate in torus ?
Comment: You are assuming that the downvotes on your previous questions have something to do with your intelligence. I don't think that is accurate. When you place your cursor over the down arrow it says "This question does not show any research effort; it is unclear or not useful." Having seen some of your questions, I think its reasonable to assume that some users agreed with that statement. I recommend you visit the [Constructive Feedback chatroom](https://chat.stackexchange.com/rooms/43593/constructive-feedback) to discuss how you can improve your future questions.
Answer: Imagine projecting this torus on the horizontal plane:

Points that are mapped on the same point on the plane lie one above another, and so they have to both be on the same little circle (like the red one).  E.g. here the upper point of the red circle will have the same image as its lower point. Points of other small circles, however, will have different projections on the plane.
The first coordinate of a point on a torus is specifying exactly the meridian (small circle) on which the point lies.


Você tem um erro na sintaxe do seu SQL

Question: Estou aprendendo php e estou tentando fazer um combobox, ele está puxando os dados do banco corretamente porém na hora de exibir o resultado apresenta este erro:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'and imovel_categoria = '2' and imovel_bairro = '2'' at line 1

PHP

      <?php

       $tipo = new Conexao();
       $tipo->ExecSQL("select * from tipo ");

        ?>

       Finalidade:
       <select id="tipo">

        <?php

         while($tip = $tipo->ListarDados()){

            ?>

         <option value="<?php echo $tip['tipo_id']?>"><?php echo        $tip['tipo_nome']?></option>

<?php

}//fecho o laço

?>

 </select>

  Tipo:

    <select id="cb_categoria">

     </select>

PHP combo_categoria:

<?php
require './app/Config.php';

if (!empty($_GET['cod'])):

    $cod = $_GET['cod'];

else:
    $cod = 0;
endif;

$categoria = new Conexao();
$categoria->ExecSQL("select * from categoria where categoria_tipo = '$cod' ");
?>

    <?php
    while ($cat = $categoria->ListarDados()) {
        ?>

        <option value="<?php echo $cat['categoria_id'] ?>"><?php echo $cat['categoria_nome'] ?></option>

    <?php
}//fecho o laço
?>

Bairro:
<select id="cb_bairro">

</select>

PHP combo_bairro:
<?php

require './app/Config.php';

if (!empty($_GET['cod'])):
    $cod = $_GET['cod'];

else:
    $cod = 0;
endif;

$bairro = new Conexao();
$bairro->ExecSQL("select * from bairro where bairro_categoria = '$cod'");

?>

    <?php

    while($bai = $bairro->ListarDados()){

    ?>

    <option value="<?php echo $bai['bairro_id']?>"><?php echo $bai['bairro_nome']?></option>

    <?php

    }//fecho o laço

    ?>

PHP resultado:
<?php
require_once './app/Config.php';

$imovel = new Conexao();

if (!empty($_GET['cod'])):
    $cod = $_GET['cod'];
else:
    $cod = 0;
endif;

$sql = 'select * from imoveis, tipo, categoria, bairro';
$sql .= ' where imovel_categoria = categoria_id and imovel_bairro = bairro_id';
$sql .= ' and imovel_tipo = tipo_id order by imovel_id desc limit 6';

$sql .= " and imovel_categoria = '$cod' ";
$sql .= " and imovel_bairro = '$cod' ";

$imovel->ExecSQL($sql);

echo '
';
while ($imv = $imovel->ListarDados()) {

    //pego a foto
    $i = new Conexao();
    $f = $imv['imovel_id'];
    $i->ExecSQL("select * from imoveis_fotos where foto_imovel = '$f' limit 1");
    $foto = $i->ListarDados();

    //mostrando conteudo
    echo '
';
    echo Fotos::Exibir($foto['foto_nome'], 150, 150);
    echo '
';
    echo '
' . $imv['tipo_nome'] . '
';
    echo '
 ' . $imv['categoria_nome'] . '
';
    echo '
R$ ' . Sistema::GetReal($imv['imovel_valor']) . '
';
    echo '
 ' . $imv['bairro_nome'] . '
';
    echo '
';
    echo 'saiba mais';
    echo '
';
    echo '
';
    echo '
';
}
echo '
';
?>

Comment: Do jeito que esta montando seu select, esta ficando assim: `select * from imoveis, tipo, categoria, bairro where imovel_categoria = categoria_id and imovel_bairro = bairro_id and imovel_tipo = tipo_id order by imovel_id desc limit 6 and imovel_categoria = '$cod' and imovel_bairro = '$cod'`. Percebe onde esta o erro?
Comment: A estrutura deve **sempre** seguir mais ou menos essa ordem: `SELECT campos FROM tabela JOIN (JOIN, LEFT, RIGTH, OUTER, FULL, ETC) tabela WHERE condição GROUP BY condição ORDER BY campos LIMIT numero` podendo possuir todas, mais de uma, ou nenhuma dessas estruturas
Comment: Você não pode ter um `LIMIT` no meio da consulta ele sempre vai no final o mesmo vale para o `ORDER BY`
Answer: No PHP resultado, os filtros por imovel_categoria e imovel_bairro na consulta SQL vêm a seguir ao " order by ", daí o erro Podes fazer assim:
if (!empty($_GET['cod'])):
    $cod = $_GET['cod'];
else:
    $cod = 0;
endif;

$sql = 'select * from imoveis, tipo, categoria, bairro';
$sql .= ' where imovel_categoria = categoria_id and imovel_bairro = bairro_id';
$sql .= ' and imovel_tipo = tipo_id';
$sql .= " and imovel_categoria = '$cod'";
$sql .= " and imovel_bairro = '$cod'";
$sql .= ' order by imovel_id desc limit 6';

$imovel->ExecSQL($sql);

Atenção, aparentemente não estás a limpar os dados enviados pelo utilizador que vêm na variável $_GET ! É mais seguro usar prepared statements, por exemplo. Mais info (em Inglês): https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php

Você tem um erro na sintaxe do seu SQL


Default shares need to be hidden from normal domain users

Question: I have installed windows server and it produces default shared folders that users can see when they are looking at other folders I have shared for them. Is there a way to hide these system folders or at least stop the domain users from seeing them without breaking the server. Microsoft suggest that you should not remove these shares.
Some of the folders are listed below,

clients
NETLOGON
SYSVOL
tsclient
Users

The hidden shares are below also:

C$
print$
Resources$

How do most people change these folders after installation?
From what I can see most people remove the C$ share and thats about it.
Comment: John, I get what you're saying but sometimes you just need to tell users that's the way it is. Modifying, deleting or otherwise manipulating the default shares is only going to lead to frustration. I don't know how a car engine works but that doesn't stop me from driving one and I don't get confused by looking at all of the engine components. I assume that all of the components are necessary to make the car work and I concern myself with only those components that I'm required to interact with in order to drive it.
Comment: What are you trying to accomplish by "hiding" these shares? They all server a purpose, do you understand what purposes each serve and are you prepared to break that functionality? Most people do **not** modify these shares in any way. Except `Users` and `clients` - those are not default share, to my knowledge. Someone must have shared those out without your knowledge.
Comment: Maybe you could use group policy to map shares for them and train them to look at what's mapped on their computer instead.
Comment: They might be SBS 2011 defaults.  (Guessing.)
Comment: When domain users browse to the server they are complaining about the excess number of shares (they appear to have read permissions for everyone). They were expecting one or two folders but see many, for me its not a big deal, but is causing confusion. I am not prepared to break functionality simply looking for a way to make the folders less visible.
Comment: This seems like tilting at windmills.
Comment: Yes it is and it isn't as I have read many posts about this issue on forums, the non I.T. person doesn't get the reason why these shares exist and trying to educate them is like hitting your head against a break wall
Answer: Why are your users browsing somewhere that they can see this in the first place? There are a few things I'd like to address, so bear with me.

It appears you're using a domain controller as a file server if your users are seeing NETLOGON and SYSVOL. Don't do this. Have your domain controllers run AD DS, DNS, and nothing else if at all possible.
You don't want to modify permissions on NETLOGON/SYSVOL unless you really know what you're doing. This will likely result in broken Group Policy processing on clients.
You probably don't want to modify the C$ share. By default, only administrators can access C$. Certain applications like the SCCM client and ADMT use it for software/agent delivery to the client.  Only disable this share if you really know what you're doing - in it's default state it's not dangerous since only Administrators can use it.
Consider mapping the shares that your users will need using GPO. Then, they don't need to browse to any servers and enumerate these additional shares that you don't want them to see. This is very easy to do using Group Policy Preferences (GPP).
If your users really must browse to a UNC to get these shares, set up a DNS namespace like <code>\\example.com\shares\</code> and have each share listed there. This will have the benefit of only displaying the shares that you configure as part of the namespace.

Really though, don't go fiddling with things unless you really understand their purpose, otherwise you might end up breaking things that you didn't anticipate breaking. Very few people have a reason to modify these shares (except for Users and clients which I don't believe are default shares).
Comment: I suspect the OP is using SBS.  It's set up by default with shares on the DC.
Comment: That was my thought as well, but it's tagged [tag:windows-server-2003]
Comment: Huh, you're right, I missed that.  There was an SBS 2003, though.
Answer: Rather than worrying about "hiding" them, you should put appropriate permissions on them.  It doesn't matter whether or not people see they exist.  What matters is whether people can access things they shouldn't.
Comment: I'll add that you really shouldn't modify the permissions on NETLOGON/SYSVOL unless you *really really really* know know you're doing.


Multi-line and spanned rows with pandas

Question: found a solution for a problem with multi-line headers.
import pandas

headers = [
    ('data1', 'value1'),
    ('data1', 'value2'),
    ('data2', 'value1'),
    ('data2', 'value2'),
    ('data3', 'value1'),
    ('data3', 'value2'),
    ('data4', 'value1'),
    ('data4', 'value2'),
]

data = [
    (1, 2, 3, 4, 5, 6, 7, 8),
    (11, 12, 13, 14, 15, 16, 17, 18),
]

df = pandas.DataFrame(data, columns=pandas.MultiIndex.from_tuples(headers))

multiheaders
I don't understand how to add multilines
multirows
I tried to transpose and add new multi-line headers - nothing happened. does anyone have a solution?
Answer: You can create horizontal multiindex the same way as columns, but using index argument of pd.DataFrame:
import pandas

headers = [
    ('data1', 'value1'),
    ('data1', 'value2'),
    ('data2', 'value1'),
    ('data2', 'value2'),
    ('data3', 'value1'),
    ('data3', 'value2'),
    ('data4', 'value1'),
    ('data4', 'value2'),
]

index = [
    ('key1', 'val1'),
    ('key1', 'val2')
]

data = [
    (1, 2, 3, 4, 5, 6, 7, 8),
    (11, 12, 13, 14, 15, 16, 17, 18),
]

df = pandas.DataFrame(
    data,
    columns=pandas.MultiIndex.from_tuples(headers),
    index=pandas.MultiIndex.from_tuples(index)
)
df

Output:
           data1         data2         data3         data4
          value1 value2 value1 value2 value1 value2 value1 value2
key1 val1      1      2      3      4      5      6      7      8
     val2     11     12     13     14     15     16     17     18

Multi-line and spanned rows with pandas


Why sharing session to implement SSO is not good?

Question: Why sharing session to implement SSO is not good? I'm learning SSO system.
Thinking about this scenes:
Assume that all http requests to business services is required Login, the business services need verify the requests is login or not by asking SSO service in CAS or SAML. If there are 10 business services, and each service's request is 1k req/s, so the SSO service's request is 10k req/s. It's hard to image the SSO service can hold on.
SO, may be there is a cache mechanism in the business services to verify login token. But when user logout, the SSO service need remove the verify info, and the business services need remove the cache verify info also. I think that's too complicated. The SSO service need tell the business services some people was logout. So why don't all service sharing the login token verify info? Let SSO service write, and other business read. It remind me the sharing the session to implement SSO. And I thought if I can sharing the login token verify info by redis distributed cluster. But I have hear sharing session is not good? So why?
Answer: Whether the SSO server can handle that many requests depends on your deployment of it. There are very large deployments of CAS that handle hundreds of thousands of requests. It varies.
In general, the SSO session is entirely separate from your application session. Once you have logged onto the application via SSO, you have established a session for that application that will last for as long as you configure it to last. When it expires, your application may decide to authenticate against your SSO server again. If the SSO server has still an SSO session, it will simply re-issue the appropriate data and your app will recreate the session. If not, it will challenge the user for credentials, whatever they may, and redo the same.
Session concerns of the application are entirely yours and application's concerns. The SSO server should never get involved. If your application has a requirement to share sessions because it's clustered, then you should share sessions. Nobody said it's a bad idea. However, you generally want to make sure your application is as stateless as possible since that will make clustered deployments easier.
When you log out from your application, your app session is gone, but the SSO session may still exist. As a result, you will get right back into the app because there is no need to provide credentials. If you wish, you could log out of the app AND your SSO server.
If you have all other applications logged in via SSO, and you wish to log out of all by logging out of one, this is called SLO. Your SSO server will need to reach out to every app that it has created a ticket for and contact them to logout. Or, you could destroy the shared sessions for all apps assuming they are all part of the same suite.


Pydev debugger stopped working in PyCharm after Python upgrade

Question: I use PyCharm. I had previously built the pydev debugger under Python 3.3 using
python /Applications/PyCharm.app/Contents/helpers/pydev/setup_cython.py build_ext --inplace.
I then had to update my project to use a new virtual environment under Python 3.5, and now the debugger won't run, with the following message:
/<venv_path>/bin/python3.5 /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --multiproc --save-signatures --qt-support --client 127.0.0.1 --port 58286 --file /Applications/PyCharm.app/Contents/helpers/pycharm/pytestrunner.py -p pytest_teamcity <pytest_root> <options>
Testing started at 10:25 AM ...
pydev debugger: process 94521 is connecting

Connected to pydev debugger (build 163.8233.8)
Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1596, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 956, in run
    time.sleep(0.1)  # busy wait until we receive run command
KeyboardInterrupt

I tried rerunning setup_cython.py build_ext --inplace under the updated Python version, invalidating my caches, restarting, deleting my .idea folder, but nothing manages to resolve the message above.
Comment: I was able to reclaim use of the debugger by creating a project off of a newly cloned repository, which implies that there's some other cached object that all of the aforementioned steps I took together are not sufficient to truly clear a PyCharm project of its references outside of the source files. I am still curious to know if someone else has ever solved this problem.
Answer: I resolved this issue by clearing all saved breakpoints.
Setting the environment variable PYCHARM_DEBUG=True in the launch lead me to this resolution.
Comment: I since remade the project and deleted the old one, but thank you for posting this for posterity. I did notice since that there are some stale reference bugs around breakpoints in PyCharm, the likes of which I haven't seen in Intellij.
Comment: I solve the same problem by adding: `# -*- coding: utf-8 -*- ` in second line


using QuaZip on Windows with VS2008

Question: I'm using QT4.7.3, VS2008 and trying to add QuaZip library.
I got QuaZip, Zlib and compile it, and then I can make "quazip.lib" file.
I added quazip.lib to "Project property->Configuration Properties->Linker->Input->Additional Dependencies" and include pathes.
I wrote the source code as below.
<code>#include "Updater.h"
#include "quazip.h"

Updater::Updater(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);

    QuaZip *qZip = new QuaZip();
}
</code>
but, here, I stuck in problem.
Error message is shown as below.

Updater.obj : error LNK2019: unresolved external symbol
  "__declspec(dllimport) public: _thiscall QuaZip::QuaZip(void)"
  (_imp_??0QuaZip@@QAE@XZ) referenced in function "public: __thiscall
  Updater::Updater(class QWidget *,class QFlags)"
  (??0Updater@@QAE@PAVQWidget@@V?$QFlags@W4WindowType@Qt@@@@@Z)
  1>.\updater.exe : fatal error LNK1120: 1 unresolved externals

I know this error occurs when declaration exists but definition doesn't exists.
As a result of find QuaZip constructor, I found as below.
<code>QuaZip::QuaZip():
  p(new QuaZipPrivate(this))
{
}
</code>
How can I make it correct?
Thank you for any comment.
Answer: I have found the following message in Quazip's README file:

If you want to include QuaZIP sources directly into your project or if
  you want to use QuaZIP compiled as a static library using
  "qmake CONFIG+=statliclib", you have to define the QUAZIP_STATIC macro,
  otherwise you're likely to run into problems as QuaZIP symbols will be
  marked as dllimported.

Maybe that will help you.

using QuaZip on Windows with VS2008


Merge non empty values from a table to one result row

Question: I have a MYSQL table which has about 350 columns. There are most 'empty' values and I need to merge several rows in one and replace 'empty' values by a non empty value. My table looks like this:
id|col1|col2|col3|cola|col_b|...|col350
1 |12  |4   |3   |-77 |-77  |...|-77
2 |12  |-77 |-77 |2   |-77  |...|-77
3 |12  |-77 |-77 |-77 |6    |...|-77
4 |12  |-77 |-77 |-77 |-77  |...|6
5 |13  |3   |-77 |-77 |-77  |...|-77
6 |13  |-77 |5   |-77 |-77  |...|-77
...

-77 is a replacement for empty values. In col1 is an id of datasets witch belongs together.
I need a select query to merge non 'empty' values to one result row per col1-id. For col1-id 12 it should looks like this:
1 | 12 | 4 | 3 | 2 | 6 | ... | 6

Does someone have an idea how to do this?
Comment: 350 columns in a table, and they're all alike like this? You really need to normalize the schema.
Comment: It is a csv import from 3rd party software.
Answer: SELECT col1,
       MAX(CASE WHEN col2 <> -77 THEN col2 END) AS col2,
       MAX(CASE WHEN col3 <> -77 THEN col3 END) AS col3,
       MAX(CASE WHEN cola <> -77 THEN cola END) AS cola,
       MAX(CASE WHEN col_b <> -77 THEN col_b END) AS col_b,
       ... and so on
       MAX(CASE WHEN col350 <> -77 THEN col350 END) AS col350
FROM YourTable
GROUP BY col1

Comment: Would not work, becouse column names are not numeric. For example: there is no col4, cola instead.
Comment: Just use whatever the actual column names are. I thought those were just examples.


Connecting to Oracle database with gorm in golang

Question: Previously i was using godror package to connect to oracle database client. And now i want to implement ORM in my system and want to connect to oracle using GORM package but it seems i am unable to do it though.
I did found out a package https://github.com/CengSin/oracle but the package installation seem to fail. Trying:
go get github.com/cengsin/oracle
I seem to be stuck on this.
Comment: Can you add the error log please?
Answer: So, it seems that while installing package go get github.com/cengsin/oracle , gorm package needed to be of version less than or equal to v1.20.1. I downgraded my gorm package to version 1.20.1 and it solved my issue.


Can I disable the printing page x of y dialog?

Question: I am developing a full screen kiosk application using c#. I need to print tickets and receipts. I use the PrintDocument class for the printing. Printer prints perfectly, but i need to disable the pop-up dialog shown during printing.

I heard it can be disabled with Printers and Faxes in control panel, but i do not have Printers and Faxes in control panel.
Can i disable the dialog shown? If i could, how can i do it?
Answer: I believe setting your PrintDocument's PrintController to StandardPrintController should solve this.
PrintDocument printDocument = new PrintDocument();
PrintController printController = new StandardPrintController();
printDocument.PrintController = printController;

Hope this helps some.
Comment: @Krankoloji No problem, glad to have helped!
Comment: @SeeSharp : This works fine if you are calling printDocument.Print, but not if you call printDocument.DisplayDialog. There is no dialogController equivalent. Any ideas?
Comment: This did not do anything to prevent the Paging pop-up dialog.  Visual Studio 2017 C# .NET Framework 4.6.2, Windows 10 Ent 2016 LTSP.
Answer: Great question and answer. Here is the VB.Net version googling for vb.net wasn't returning any meaningful results.
  Dim printDocument As New System.Drawing.Printing.PrintDocument
  Dim printController As New System.Drawing.Printing.StandardPrintController
  printDocument.PrintController = printController

Answer: Windows 10, 8, 7, & Server 2012
Note: This option is not available in the Home versions of Windows.
Press and hold the Windows Key, then press "R" to bring up the Windows Run dialog box.
Type "printmanagement.msc", then press "Enter".
Expand "Printer Servers", then right click the name of the computer and select "Printer Server Properties".
Select the "Advanced" tab.
Uncheck "Show Informational Notifications for Local Printers" and "Show Informational Notifications for Network Printers".
Comment: This did have any affect on the issue.  Dialog still displays.  Windows 10 Enterprise 2016 LTSB all current updates
Answer: This Worked for me. You can try this
PrintDocument document = new PrintDocument();
        PrintDialog dialog = new PrintDialog();
        PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
        private  Font printFont;
        private string stringToPrint;
      //  private int linesPerPage=9;
        private Font printFont1;
        QRCode qrCode1;
        private string stringToPrint1;
        private string databasePath;
        int i=1;
        public Form1()
        {
            InitializeComponent();

            //document.DefaultPageSettings.PrinterSettings.PrinterName = "GODEX500";
            //  document.DefaultPageSettings.Landscape = true;
            document.DefaultPageSettings.PaperSize = new PaperSize("75 x50 mm", 300, 200);
            document.DefaultPageSettings.Margins = new Margins(1, 1, 1, 1);
            printFont = new Font("Arial", 10);
            // printFont1 = new Font("NewBarcodeFont", 12);

            //    document= new Font("GODEX-NewBarcodeFont", 12, FontStyle.Regular);
            // document.OriginAtMargins = true;
            //This PrintController worked fine and not showing printing this document using window
            PrintController printController = new StandardPrintController();
            document.PrintController = printController;
            document.PrintPage += new PrintPageEventHandler(document_PrintPage);

        }


Would this method to eliminate extraneous solutions be correct?

Question: In algebra I, they taught us that when solving equations with radicals, you just had to plug the solutions you received back into the original equation to check if they were legit solutions or extraneous solutions. However, this can be time consuming. This is my method.
Take an equation like $\sqrt{10-x}$ = $3x$. If you square both sides, you get $10-x$ = $9x^2$. Then, you get the polynomial $9x^2+x-10$. Solving this polynomial, you get solutions $x=1$ & $x= -\frac{10}9$. However, if you plug the negative solution, the answers do not match up. Here's my way to solve this equation without checking for extraneous solutions.
First, note that $\sqrt{10-x}$ $\geq$ $0$ for all real x because square root is positive. $3x$ $\leq$ $0$ for all negative x. Since $\sqrt{10-x}$ $\geq$ $0$ for all real x, but $3x$ $\lt$ $0$ for all negative x, that means our solution can't be negative or the sides won't be equal. Thus, we can eliminate all negative solutions easily without plugging them in to check.
This method will save a lot of time for higher degree polynomials where you have to check more solutions. So, is this method mathematically valid? If so, why don't we learn it in school?
Comment: Incidentally, I propose calling extraneous roots "weeds". (I'm probably not the first.)
Comment: Your logic is indeed valid. For higher degree polynomials, though, it becomes correspondingly harder to decide when the functions are positive or negative.
Comment: *"So, is this method mathematically valid?"* Sure, but it's highly specialized. If you had, say, $\sqrt{10-x}=3x^7-1x^5+41x^2-5$, it'd take a lot more effort to articulate conditions that make the right-hand side negative than it would just to substitute-in candidate values and see what happens. Computers can make (in)validation-by-substitution instantaneous, so that this isn't a hassle. That said, it *can* be worthwhile to give some thought to (in)validity conditions that let you rule-out bad values; doing so might well provide insights into the problem that gave rise to the equation at hand.
Answer: Yes, it is valid. However, it is a lot harder to use this in a lot of cases than to simply plug things in, because the equation may be way more complicated, so you can't tell if the functions are positive or negative. Also, $x^2$ stays positive everywhere.


Ignore magento admin directory in GeoIP Htaccess Rewrite

Question: I've got a magento install that is using the htaccess mod_geoip to redirect people from specific countries to other store fronts. It's working like a charm (after I got it to ignore javascript and skin files), but I'm going to be having someone from Australia input some orders into the backend of magento.
The issue is that they can't access the main backend at store/index.php/admin (they are rewritten to austore/index.php/admin) and when they go to put orders in, they are missing some integral components of the order process which I think is due to the url being rewritten to austore/index.php/admin. Wondering if there is a way that if the request uri is store/index.php/admin that they won't get rewritten. My code is below from my htaccess:
RewriteRule ^(skin|js) - [L,NC]

RewriteCond %{ENV:GEOIP_COUNTRY_CODE}     ^(AQ|AU|MY|BV|BN|BN|MM|KH|CN|CX|CC|CK|GQ|FJ|PF|GU|GW|HM|HK|ID|KI|KR|KP|KR|LA|MO|MY|MH|FM|MM|NR|NC|PG|NZ|NU|NF|PG|CN|PH|PN|WS|SG|SB|KR|LK|BN|TW|TW|AU|TH|TL|TK|TO|TV|VU|VN|VN|WF)$
RewriteCond %{REQUEST_URI} ^/store(/.*)$ [NC]
RewriteRule ^ /austore%1 [L,R]

Thanks for the help!
Answer: Taken from this, http://www.sonassi.com/knowledge-base/magento-kb/secure-your-magento-admin/ you can use the same rewrite logic in what you want to do.
RewriteCond %{REQUEST_URI} !^/store/(index.php/)?(admin|custom_extensions_go_here)/ [NC]
RewriteCond %{REQUEST_URI} !^/store/downloader/ [NC]

RewriteCond %{ENV:GEOIP_COUNTRY_CODE}     ^(AQ|AU|MY|BV|BN|BN|MM|KH|CN|CX|CC|CK|GQ|FJ|PF|GU|GW|HM|HK|ID|KI|KR|KP|KR|LA|MO|MY|MH|FM|MM|NR|NC|PG|NZ|NU|NF|PG|CN|PH|PN|WS|SG|SB|KR|LK|BN|TW|TW|AU|TH|TL|TK|TO|TV|VU|VN|VN|WF)$
RewriteCond %{REQUEST_URI} ^/store(/.*)$ [NC]

RewriteRule ^ /austore%1 [L,R]

Just bear in mind, doing this through .htaccess could potentially cause some bizarre issues in the long run with 3rd party extensions, that have custom admin routes (that are not prefixed with /admin) break. So just be mindful of this.
I would advocate the use of a Magento extension (PHP based), mod_geoip store switcher - as then you can make it apply only to the frontend area of the Magento store (to prevent the potential errors I've described above)
Comment: Thanks for the quick answer. It doesn't seem to be working though, the base login page for the store is still changing to the region specific store. Does it matter that my store isn't in the root but in root/store? We did initially look at some php store switchers, but we weren't satisfied with their implementation.
Comment: Well the code is right, so I can only assume your `RewriteBase` is potentially causing an issue with the store being in a subdirectory. PHP based is the far more reliable method - assuming your PHP developer is competent.
Comment: This is our RewriteBase /store/. We'll take a look at php based redirect again. Do you feel there is any degradation in speed for the php based lookup?
Comment: PHP is fast enough. But your bottleneck will be that a **good** PHP implementation should be in a custom Magento extension, so it requires the Mage instance to be created (`Mage::run()`) before it can carry out your modules requirements, this will add a small overhead, probably noticeably (slightly) slower than `.htaccess`. I realised I might have typo'ed in my comment, try replacing the `NC,OR` with `NC` and try again - seems a shame if your "simpler" current implementation otherwise works well.
Comment: Bummer, still doesn't seem to be working. Feel like it's really close, but just can't figure it out.
Comment: @coloradohiker I've edited the answer above, changed ordering and added `/store/` - give that a try ;)
Comment: That worked! Seems like once it hit the geoIP redirect it was too late to ignore those directories. Nice work!


Prove $\binom{n}{2}+\binom{n}{3}\cdot7+\binom{n}{4}\cdot7^2+....+7^{n-2}\in \mathbb{Z}$ for all $n\geq 2$

Question:
If $X=\{8^n-7n-1:n\in \mathbb{N}\}$ and $Y=\{49(n-1):n\in \mathbb{N}\}$ then show that $X⊂Y$

While solving the problem
$$8^n-7n-1=(1+7)^n-7n-1\\
=49\bigg[\binom{n}{2}+\binom{n}{3}\cdot7+\binom{n}{4}\cdot7^2+...+\binom{n}{n-1}.7^{n-3}+7^{n-2}\bigg]\\
$$
How do I know that the expression inside the bracket is an integer for all $n\geq 2$ ?
Comment: The expression in the bracket is a sum and product of integers, hence an integer.
Comment: @vadim123 ohh is it because the number of combinations, ie. each binomial coefficient must be an integer right ?
Answer: Another way to expand using
$$a^n-b^n=(a-b)\left(a^{n-1}+a^{n-2}b+a^{n-3}b^2+...+a^2b^{n-3}+ab^{n-2}+b^{n-1}\right) \tag{1}$$
is
$$8^n-7n-1=8^n-1-7n=\color{red}{(8-1)}\left(8^{n-1}+8^{n-2}+...+8+1\right)-\color{red}{7}n=\\
7\left(8^{n-1}+8^{n-2}+...+8+1-\color{blue}{n}\right)=...$$
there are $\color{blue}{n}$ terms $8^{n-1},8^{n-2},...,8,1$, thus
$$...=7\left(8^{n-1}-\color{blue}{1}+8^{n-2}-\color{blue}{1}+...+8-\color{blue}{1}+1-\color{blue}{1}\right)=\\
7\left[\color{red}{(8-1)}\left(8^{n-2}+8^{n-3}+...+8+1\right)+\color{red}{(8-1)}\left(8^{n-3}+8^{n-4}+...+8+1\right)+...+\color{red}{7}\right]=\\
49\left[\left(8^{n-2}+8^{n-3}+...+8+1\right)+\left(8^{n-3}+8^{n-4}+...+8+1\right)+...+1\right]$$
Your version is a lot shorter and, as per the comments, correct one (binomial coefficients are integers). Sometimes it's good to have more versions to validate the answer.


Dúvida: Função de geradores

Question: Escreva sua própria função de gerador que funciona como a função interna enumerate.
Recorrendo à função assim:
lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"]

for i, lesson in my_enumerate(lessons, 1):
    print("Lesson {}: {}".format(i, lesson))

deve resultar na saída:
Lesson 1: Why Python Programming
Lesson 2: Data Types and Operators
Lesson 3: Control Flow
Lesson 4: Functions
Lesson 5: Scripting

" Então pessoal, estou com muita dificuldade nesse assunto(Geradores), não consigo compreender como posso resolver esse problema , acredito que devo usar a função enumerate() , mas a minha falta de compreensão do assunto esteja comprometendo as minhas tentativas. "
lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"]

def my_enumerate(iterable, start=0):
    # Implement your generator function here

for i, lesson in my_enumerate(lessons, 1):
    print("Lesson {}: {}".format(i, lesson))

Comment: Você pode incluir qual erro está impedindo você de obter êxito com o código?
Comment: @WilliamLio na verdade eu não estou conseguindo nem sequer pensar como devo criar esse código , repito , por eu não compreender o assunto relacionado a geradores .
Comment: Quando li pela primeira vez entendi uma coisa bem diferente, quando reli entendi seu ponto. Achei bem interessante. Ficarei de olho, também quero saber a resposta ;)
Comment: @Barbetta , eu também , eu não estou conseguindo de forma alguma achar ou bolar um código para resolver isso.
Answer: Não precisa de saber a fundo de geradores para fazer uma replica do enumerate, pois esse é simples. A sua implementação seria algo como:
def my_enumerate(iterable, start=0):
    current = start  # começa no numero passado como segundo parametro
    for elem in iterable:
        yield current, elem  # gera uma nova tupla
        current += 1  # aumenta o numero corrente

O yield é o responsável pela geração de cada tupla com a posição e o elemento do iterável.
Veja o exemplo a funcionar no Ideone
Este é um tópico de que deve de seguir com alguma calma e de preferência quando já domina os básicos do Python, pois é mais complicado, e ainda tem bastantes pormenores.
Comment: entendi . Perfeito

Dúvida: Função de geradores


How to use Rules to send an email after a user submits a first node and grant a new role after 5 nodes?

Question: I want to send a congratulations email to user on submitting his/her first node.
I want to implement this through the Rules module. But I am confused and think that there is no such option except PHP evaluation which seems bad to me due to eval().
And I also want to assign a special role to a user after a user submitted (= Save new content) 5 nodes.
Any suggestions?
Comment: Does submit mean published or unpublished save. Currently there is not Rules event for published/unpublish so you will have to work around it.
Comment: submit mean After new content save .
Comment: Yo will need to do a fetch entity by property (uid) to check for previous submissions. Best in my opinion is to set a hidden integer field on user object and via rules update and check it.
Comment: setting integer field option is suitable i think. thanks for giving time :)
Comment: Thank you for the accept! Sorry it took a few years to notice your question ...
Answer: This can be implemented perfectly by using the Goals module (disclosure: I'm its maintainer), as further detailed below.
Part 1 - Configure 2 goals
You'd start by configuring the appropriate set of Goals and related Tasks. For a basic introduction about Goals, have a look at:

How to implement gamification in a Drupal site and award incentives?
Its video tutorial.

Here is what it would take:

Goal1 = "New user", with only 1 Task = "Save 1 node" (say with machine name = save_a_node).
Goal2 = "Mature user", with Task = "Save 5 nodes".

Part 2 - Create a rule to record progress on the tasks
Create a rule using Rules Event "After saving new content". The purpose of this rule is to make Goals automatically track the progress on completing the tasks (which you can do via an appropriate Rules Action to record that progress).
The interesting part of this is that you can reuse the same rule (related to that machine name = save_a_node) to keep track of the progress of any user to become a New/Mature customer (check the video for a similar sample).
Part 3 - Trigger your rules after a goal is achieved
Together with what is above, you should write these 2 rules to implement what your question is actually about:

a rule with these specs:

Rules Event: "After a user completed Goal1"
Rules Action: "Send an eMail"

a rule with these specs:

Rules Event: "After a user completed Goal2".
Rules Action: "Assign role to user".
Answer: I would use Rules and I would set up multiple roles.

Role 1: new user
Role 2: after Role 1 New User creates new content, they get their role changed to Role 2
Role 3: after Role 2 creates new content, they get their role changed, etc.

I would think about a different # than 5 if possible, just to start, to keep roles down. This is the easiest way to handle this without custom code. Also, having multiple roles makes it easy to target for other things, like notices or other email campaigns.
Comment: The best would be to include views in rules, and execute a view that returns the node count for the user. Rules Bonus pack has a nice solution for that. But I am sure it can be done with just rules and views.


Add product fields to cart form through line items

Question: So I have a Product field called "Quantity Per Box". It's a field that says how many items (in this case, screws, nuts, and bolts) come in each box. I want to display this number in the view when the customer goes to cart.
I have the field as part of the product already. What I have done so far is added the existing field to line items, and checked the box to add that field to the cart. Then I edited the view to add that item. The label shows up "Quantity Per Box" but there is no value in the field from the product. I've tried this several different ways with no success. Can someone help me out here, what am I missing?
Answer: To be absolutely clear, you want the "Quantity Per Box" field present on product entities to display on the cart view?  For that you'll need to add I believe the "Commerce Line Item: Referenced Products" relationship in the view.  That should give you access to the product fields, with no need to copy a field from product entities to line item entities.
Since the cart is a Commerce Order view:
Relationships needed to reach products can be visualized as:
commerce_order->commerce_line_items->commerce_product


How to prove $e^x\left|\int_x^{x+1}\sin(e^t) \,\mathrm d t\right|\le 1.4$?

Question: Related question asked by me on MathOverflow: How to prove $e^x\left|\int_x^{x+1}\sin(e^t) \,\mathrm d t\right|\le 1.4$?
This is a follow-up question to the question How to prove $ \mathrm{e}^x\left|\int_x^{x+1}\sin\mathrm e^t \mathrm d t\right|\leqslant 2$?, in which a weaker bound is proven using a nice trick.
Now my question is how to maximize and minimize $$f(x)=e^x\int_x^{x+1}\sin(e^t) \,\mathrm d t$$
or at least to prove $-1.4\le f(x)\le 1.4$.
Some observations, using the substitution $y=e^t$:
$$f(x)=e^x \int_{e^x}^{e^{x+1}} \frac{\sin(y)}y\,\mathrm dy=g(e^x),$$
where I have defined $$g(z)=z \int_z^{e z} \frac{\sin(y)}y\,\mathrm dy = z (\operatorname{Si}(e z)-\operatorname{Si}(z)).$$
($\operatorname{Si}$ is the Sine integral.)
So the question reduces to: What are the maxima/minima of $g(z)$ for $z\geq 0$ ?
Using the series of $\mathrm{Si}(z)$, we get
$$g(z)=\sum_{k=1}^\infty (-1)^{k-1} \frac{z^{2k}(e^{2k-1}-1)}{(2k-1)!\cdot(2k-1)}$$
and here is a plot of $g(z)$, which seems to be periodic:
Comment: Would the downvoter care to explain the downvote ?
Comment: $g(z)$ is certainly not periodic. Nice problem, by the way!
Comment: I don't know if it helps anybody but the x-value of the critical points of the function $f(x)$ must satisfy the equation $\sin(e^{x+1})-\sin(e^x) = \operatorname{Si}(e^{x})-\operatorname{Si}(e^{x+1})$, again where $\operatorname{Si}(x)$ denotes the Sine Integral. [Wolfram|Alpha gives numerical approximations](https://www.wolframalpha.com/input/?i=sin%28e%5E%28x%2B1%29%29-sin%28e%5Ex%29%3DSi%28e%5Ex%29-Si%28e%5E%28x%2B1%29%29)
Answer: By the result of [1], we have
$$\left|\mathrm{Si}(y) - \frac{\pi}{2}\right| \le \frac{1}{y}, \ y > 0.\tag{1}$$
Thus, we have, for $z > 0$,
$$\frac{\pi}{2} - \frac{1}{z} \le \mathrm{Si}(z) \le \frac{\pi}{2} + \frac{1}{z}$$
and
$$\frac{\pi}{2} - \frac{1}{\mathrm{e}z} \le \mathrm{Si}(\mathrm{e}z) \le \frac{\pi}{2} + \frac{1}{\mathrm{e}z}.$$
Thus, we have, for $z > 0$,
$$-1 - \frac{1}{\mathrm{e}} \le z(\mathrm{Si}(\mathrm{e}z) - \mathrm{Si}(z)) \le 1 + \frac{1}{\mathrm{e}}.$$
Also, $1 + \frac{1}{\mathrm{e}} \approx 1.367879441$. We are done.
Reference
[1] Upper bound for the sine integral
Remark: The following stronger inequality holds, which implies (1):
$$\left|\mathrm{Si}(y) - \frac{\pi}{2}\right| \le \arctan \frac{1}{y}, \ y > 0.$$
See: Graham Jameson, Nick Lord and James McKee, An inequality for Si(x), Math. Gazette 99 (2015).
https://www.maths.lancs.ac.uk/jameson/siineqnotes.pdf
Answer: This question has received some answers on MathOverflow.

Fyodor Petrov solves with integration by parts
Iosif Pinelis suggests a method that allows arbitrarily accurate bounds with interval arithmetic


In which condition the Test-match declared TIE?

Question: When can a test-Match results in tie (not-draw)?
What are the factors affecting to such result to be declared?
Answer:
A test match can only be declared as a tie when the innings second
  batting team bowled out(losing all the wickets or no batsmen available
  to bat due to injury) for the second time, with scores level.
  - Wikipedia

If the second batting captain declares the innings after the score gets level, then the match will get tie. But,this will not happen forever in an international cricket match.
All the other factors will affect the result to be declared as tie.
In the history of cricket, only two test matches got tied.

One was between Australia and West Indies.
And the other was between Australia and India.


Pass query parameters through local response

Question: I'm trying to pass query parameters received on a controller from an external redirect through TrustedRedirectResponse or LocalRedirectResponse. None of the options seem to be working.
Comment: Probably need to see some code to comment further.
Comment: Welcome to Drupal Answers! Since the question is about code, we need to see the code you wrote so far. In this way, the answers could eventually point out what is wrong in the code.
Comment: Seeing the code would also help to understand what _seems to be working_ exactly means. Generally speaking, _it doesn't work_ isn't a much helpful phrase, in a question. Questions should make clear what exactly the issue is, or what exactly the OP doesn't understand in achieving the task described in the question.
Answer: Receive the query parameters through the request you've added as parameter to the controller and pass them via the URL of the redirect.
Caching is a bit tricky because generating an absolute local URL bubbles up cacheable metadata which you need to collect by Url::toString(TRUE):
<code>public function view(Request $request) {

  $url = Url::fromRoute(
    '<front>',
    [],
    [
      'query' => $request->query->all(),
      'absolute' => TRUE,
    ]
  )->toString(TRUE);

  $redirect = new LocalRedirectResponse($url->getGeneratedUrl());
  $redirect->addCacheableDependency($url);
  $redirect->getCacheableMetadata()->addCacheContexts(['url.query_args']);

  return $redirect;
}
</code>


drush sql-sync structure tables in alias dont work

Question: It seems that the structure tables dont work on a sql sync from my live site to my dev. Using the following comman:
drush sql-sync @example.live @example.dev
The search_api_server is every time overritten, so it gets synced. So i think also my cache tables get synced. Whats wrong with my aliases?
/**
 * Dev/Local alias
 */
$aliases['dev'] = array(
  'root' => '/var/www/example_dev',
  'uri'  => 'example.dev',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'source-command-specific' => array (
    'sql-sync' => array (
      'no-cache' => TRUE,
      'structure-tables-key' => 'common',
    ),
  ),
  // No need to modify the following settings
  'command-specific' => array (
    'sql-sync' => array (
      'sanitize' => TRUE,
      'no-ordered-dump' => TRUE,
      'structure-tables' => array(
       // You can add more tables which contain data to be ignored by the database dump
        'common' => array('cache', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions', 'watchdog','search_api_server'),
      ),
    ),
  ),
);

/**
 * Live alias
 */
$aliases['live'] = array(
  'remote-host' => '000.000.00.00',
  'remote-user' => 'username',
  'root' => '/var/www/html/example-live',
  'uri'  => 'example.net',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
);

Answer: There are three places you can reference aliases when using sql-sync:
drush @site sql-sync @prod @dev
@site - Where the sql-sync will execute. If this is a remote site, then the other two aliases must be defined in files that reside on the remote machine.  Options from 'command-specific' will be applied to the command.
@prod - The source for the sync.  Options from 'source-command-specific' will be applied to the command.
@dev - The target for the sync.  Options from 'target-command-specific' will be applied to the command.
The alias @site is not usually used with sql-sync; most people just run drush sql-sync @prod @dev.
Drush is going to look for different 'command-specific' records depending on the position of the alias appears on the commandline.
@site - The alias that appears before the command name will have options from the 'command-specific' -> 'sql-sync' record added to the evaluated options list.
@prod - The alias that appears in the first position after the command name will have options from the 'source-command-specific' -> 'sql-sync' record used.
@dev - The alias that appears in the second position after the command name will have options from the 'target-command-specific' -> 'sql-sync' record used.
In the typical case (drush sql-sync @prod @dev), the 'command-specific' record is not used at all, the 'source-command-specific' record from @prod is used, and the 'target-command-specific' record from @dev is used.
Try using alias records more like the following set:
/**
 * Dev/Local alias
 */
$aliases['dev'] = array(
  'root' => '/var/www/example_dev',
  'uri'  => 'example.dev',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'target-command-specific' => array (
    'sql-sync' => array (
      'no-cache' => TRUE,
      'structure-tables-list' => 'cache,cache_admin_menu,cache_block,cache_bootstrap',
      ),
    ),
  ),
);

/**
 * Live alias
 */
$aliases['live'] = array(
  'remote-host' => '000.000.00.00',
  'remote-user' => 'username',
  'root' => '/var/www/html/example-live',
  'uri'  => 'example.net',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'source-command-specific' => array (
    'sql-sync' => array (
      'sanitize' => TRUE,
      'no-ordered-dump' => TRUE,
    ),
  ),
);

Comment: Thanks for the answer but i dont understand all of it.
Comment: In the documentation of drush sql-sync the command is   described like this:
`drush sql-sync @prod @dev`
So what is?
`drush @site sql-sync @live @dev`

In my case live is remote and dev is the local machine, as you can see in the alias file.

And what do you mean with:
It is unusual for anyone to use the alias in the first position with sql-sync.
Comment: I expanded my answer for better clarity.


Create an image slideshow with multiple image fields per node

Question: I'd like to create an image slideshow using views slideshow. I see a few ways of doing it, like this one create-an-easy-jquery-slideshow-in-drupal-7, but they all require a single image per node.
I would like to have a content type that accepts multiple images and still retains similar functionality. So there is a list of thumbnails at the bottom, as a pager, and a single image above that is activated by hovering the thumbnails below.
I'm sure there is a way to do this. possibly with a few more modules? I'd love to know.
EDIT: This is drupal 7
Answer: You can achieve this using Views Slide Show.... See this example I've done here http://www.cnngo.com/hong-kong/visit/hong-kongs-temporary-june-4-memorial-museum-568132 which is using Views Slideshow (ThumbnailHover) + Simply Scroll Jquery Plugin. See images below...
Answer: In drupal 7 for the very basic slideshow you will need views and views slideshow.
You will need to create two imagestyles for the slideshow, a large image, and a small image that will be used for the pager.
next for the view Fields you will need two image fields. One, the first, you will choose the larger imagestyle setting. For the second image filed you will use the smaller imagestyle that will be used for the pager, also on this one you will need to 'exclude from display.'
For the view format choose slideshow. These settings you can use most of the default settings but for the pager type you will be choosing fields and also you will choose the second image type (the pager image.)
For the view contextual filters you'll choose content:nid and choose 'provide default value' with the value being 'content id from url.'
I realise those are very blunt directions but as long as you're looking at your view display you should be able to follow it.


Transforming an arc-based point together with other points to target considering angle

Question: If have a point on an arc and other points related to it. I now want to move the point on the arc to a given target and rotate everything so that the arc-based-point has a vertical angle as the new position (like the if the arc-center would now be just below (on y-axis) the target.
Example: I have an arc-center $R(0;-233.7)$, radius $250$ and arc-point $P(9.9;16.1)$. That point is at about $2.27°$ of the arc. The other point is $Q(0;0)$, so $P$ and $Q$ are a "shape". Now if I move $P$ to target positon $T(0;16.3)$ in a way so that the midpoint $R$ would be on the y-axis, where is $Q$ in that case? This is not just vector movement but we need to rotate as well which gives me headaches.

Edit: Maybe the single problem is easier in the context. The complete problem is that I have a shape defined by 3 arcs. Here you see it with three different colors for each arc (the blue one is quite small at $0°$ and $90°$. I can calculate the shapepoints. In fact I am calculating a quarter of the shape and mirror the remaining parts.

For each of the points I calculate I want to know where the midpoint (of the shape) is if I put the point to a targetpoint where it is not only moved to but the shape must be aligned at the target point so that the tangent on the point (based on the initial arc) is parallel to x-axis like shown here:

As you can see it is not as easy as the midpoint is always directly below the target point, it needs to be moved so the correct angle is set.
I know each shapepoint $P$, the radii $r1$, $r2$ and $r3$, the arc lengths $s1$, $s2$, $s3$, the angle where each arc starts and ends, The width $A$ and height $B$ of the shape.

2nd edit: What I am currently doing:
I start at the top (middle of green part) at 90° with the first point there, going clockwise. I take the counter-angle of the current angle where the point was generated $\alpha = 90° - currentAngle$. At the beginning the midpoint of the shape is at $SM(0,0)$. I know the current arc-center $R_1$ and $r_1$ which defined the shape point.
So my current rotation center $RC$ is $R_1$. I just rotate $SM$ by $\alpha$ around $RC$.
This works great until I come to the point where the shape point was generated by the next arc defined by $R_2$ and $r_2$. When it comes to that point, I rotate $R_1$, $R_2$, $R_3$ as well around the (old) $RC$. Then I switch $RC$ to the rotated $R_2'$. $\alpha$ will now be decreased by the alread done angle, so here $\alpha$ becomes 0° again and I start to rotate again.
From here on, the outcome starts to get wrong. I also recognized that I am rotating around a $RC$ whose x-coordinate is no longer $0.00$ so it is not directly below my target position anymore.
Comment: I suppose what you name "midpoint" is just the center of the associated circle. If so, I'd suggest to change "midpoint" to "center", because the midpoint of an arc is something different.
Comment: You're right. I changed it to make it more clear. Thanks for pointing me to this potential issue in my description.
Comment: My current approach calculated bad values after switching from the first arc to the next arc, but only for Y-axis as it looks like (I have some reference values from an older calculation from the past). Maybe that helps as well.
Answer:
where is $Q$ in that case?

When you move $P$ to $T$, then $R$ moves to $R'$ where $\vec{RR'}=\vec{PT}$ implies $R'_x=R_x+T_x-P_x=-9.9$ and $R'_y=R_y+T_y-P_y=-233.5$.
The equation of the circle whose center is $R'$ with radius $250$ is given by
$$(x+9.9)^2+(y+233.5)^2=250^2$$
So, the slope of the tangent line at $T$ is given by
$$\frac{-T_x-9.9}{T_y+233.5}=-\frac{99}{2498}$$
So, the angle $\alpha$ between the tangent line and the $x$-axis is given by
$$\alpha\approx 177.7304^\circ$$
Therefore, we can get $Q''$ by rotating $Q'(-9.9,0.2)$ by $180^\circ-177.7304^\circ=2.2696^\circ$ around $T$.
Since
$$\begin{pmatrix}Q''_x-T_x\\Q''_y-T_y\end{pmatrix}=\begin{pmatrix}
\cos(2.2696^\circ) & -\sin(2.2696^\circ) \\
\sin(2.2696^\circ) & \cos(2.2696^\circ)
\end{pmatrix}\begin{pmatrix}
Q'_x-T_x \\
Q'_y-T_y\end{pmatrix}$$
we have
$$\begin{align}Q''_x&=T_x+(Q'_x-T_x)\cos(2.2696^\circ)-(Q'_y-T_y)\sin(2.2696^\circ)
\\\\&\approx -9.2547\end{align}$$
and
$$\begin{align}Q''_y&=T_y+(Q'_x-T_x)\sin(2.2696^\circ)+(Q'_y-T_y)\cos(2.2696^\circ)
\\\\&\approx -0.1794\end{align}$$

Added 1 :

May I ask to elaborate how $\alpha$ is calculated and how did you calculate $Q′$?

Since $-\frac{99}{2498}$ is negative, we see that $\alpha$ is obtuse. So, $\alpha$ (in radians) is given by
$$\arctan\bigg(-\frac{99}{2498}\bigg)+\pi$$
(The reason why we add $\pi$ is that $-\frac{\pi}{2}\lt \arctan(x)\lt\frac{\pi}{2}$. See here.)
According to WolframAlpha,
$$\arctan\bigg(-\frac{99}{2498}\bigg)+\pi\approx 3.10198$$
So, $\alpha$ (in degrees) is given by
$$3.10198\times \frac{180}{\pi}\approx 177.7304$$

Since $\vec{QQ'}=\vec{PT}$, we have
$$Q'_x=Q_x+T_x-P_x=-9.9$$
$$Q'_y=Q_y+T_y-P_y=0.2$$

Added 2 :
Let us prove the following claim.
Claim : Let $A$ be a point on the circle whose center is $B$ with radius $r$. When we move everything such that $A$ moves to $C$, the point $B$ moves to $B'$, and the point $D$ moves to $D'$. Moreover, when we rotate everything such that the tangent line at $C$ is parallel to the $x$-axis and the circle is below the tangent line, the point $D'$ moves to $D''$. Then,
$$D''_x=C_x+(D_x-A_x)\cos\beta-(D_y-A_y)\sin\beta$$
$$D''_y=C_y+(D_x-A_x)\sin\beta+(D_y-A_y)\cos\beta$$
where $\beta\ $ ($\color{red}{\text{in radians}}$, not in degrees) is given by
$$\beta=\begin{cases}\dfrac{\pi}{2}&\text{if $A_y=B_y$ and $A_x\gt B_x$}
\\\\\dfrac{3\pi}{2}&\text{if $A_y=B_y$ and $A_x\lt B_x$}
\\\\ 0&\text{if $A_x=B_x$ and $A_y\gt B_y$}
\\\\ \pi&\text{if $A_x=B_x$ and $A_y\lt B_y$}
\\\\ -\arctan\bigg(\dfrac{B_x-A_x}{A_y-B_y}\bigg)&\text{if $B_x\lt A_x$ and $A_y\gt B_y$}
\\\\ \pi-\arctan\bigg(\dfrac{B_x-A_x}{A_y-B_y}\bigg)&\text{if $B_x\not= A_x$ and $A_y\lt B_y$}
\\\\ 2\pi-\arctan\bigg(\dfrac{B_x-A_x}{A_y-B_y}\bigg)&\text{if $B_x\gt A_x$ and $A_y\gt B_y$}\end{cases}$$
Proof :
Since $\vec{DD'}=\vec{AC}$, we have $D'_x=D_x+C_x-A_x$ and $D'_y=D_y+C_y-A_y$.
Since $\vec{BB'}=\vec{AC}$, we have $B'_x=B_x+C_x-A_x$ and $B'_y=B_y+C_y-A_y$.
The equation of the circle whose center is $B'$ with radius $r$ is given by
$$(x-B'_x)^2+(y-B'_y)^2=r^2$$
If $C_y=B'_y$ and $C_x\gt B'_x$, then we can get $D''$ by rotating $D'$ by $\frac{\pi}{2}$ [rad] around $C$.
If $C_y=B'_y$ and $C_x\lt B'_x$, then we can get $D''$ by rotating $D'$ by $\frac{3\pi}{2}$ [rad] around $C$.
In the following, $C_y\not=B'_y$.
The slope of the tangent line at $C$ is given by $$s:=\frac{-C_x+B'_x}{C_y-B'_y}$$

If $s=0$ and $C_y\gt B'_y$, then we can get $D''$ by rotating $D'$ by $0$ [rad] around $C$.

If $s=0$ and $C_y\lt B'_y$, then we can get $D''$ by rotating $D'$ by $\pi$ [rad] around $C$.

If $s\lt 0$ and $C_y\gt B'_y$, then we can get $D''$ by rotating $D'$ by $-\arctan(s)$ [rad] around $C$.

If $s\lt 0$ and $C_y\lt B'_y$, then we can get $D''$ by rotating $D'$ by $\pi-\arctan(s)$ [rad] around $C$.

If $s\gt 0$ and $C_y\gt B'_y$, then we can get $D''$ by rotating $D'$ by $2\pi-\arctan(s)$ [rad] around $C$.

If $s\gt 0$ and $C_y\lt B'_y$, then we can get $D''$ by rotating $D'$ by $\pi-\arctan(s)$ [rad] around $C$.

Let $\beta$ [rad] be the angle by which we rotate everything.
Since
$$\begin{pmatrix}D''_x-C_x\\D''_y-C_y\end{pmatrix}=\begin{pmatrix}
\cos\beta & -\sin\beta \\
\sin\beta & \cos\beta
\end{pmatrix}\begin{pmatrix}
D'_x-C_x \\
D'_y-C_y\end{pmatrix}$$
we have
$$D''_x=C_x+(D'_x-C_x)\cos\beta-(D'_y-C_y)\sin\beta$$
and
$$D''_y=C_y+(D'_x-C_x)\sin\beta+(D'_y-C_y)\cos\beta$$
Comment: @ZoolWay : See the claim written in **Added 2** in my answer. You can use the claim not only for $R_1$ but also for $R_2$ and $R_3$.
Comment: Why does $P'$ (as $P$ gets moved to $T$, so alternative why does $T$) not influence this? It is more to it than rotating $Q$ around $R$ as also $P$ gets moved on $T$.
Comment: Looks promising. I am trying to follow and reproduce this in an algorithm. Will come back.
Comment: May I ask to elaborate how $\alpha$ is calculated and how did you calculate $Q'$?
Comment: So the slope for the $arctan$ calculation is $(-T_x+R'_x)/(T_y-R'_y)$? I can replay this sucessfull for points where the center of the arc is $R_1(0, -233.7)$ like in the question but is does not seem to work with my other to centers $R_2(-1.5, 0)$ and $R_3(15, 0.32)$. The Y-coordinate always seems to be off...
Comment: Thank you for the whole support, it works and I have learned a lot!


Array and pointers input

Question: I'm facing a problem here. It is about inputs.
Edit: The program crashes everytime after i enter values to allocate them to each season. Btw, i'm self-learning c++ so…
#include <iostream>

const int Seasons = 4;
const char * Snames[Seasons] = { "Spring", "Summer", "Fall", "Winter" };

void fill(int*  a[], const int);

int main()
{
    int * expenses[Seasons];
    fill(expenses, Seasons);

    return 0;
}

void fill(int*  pa[], const int x)
{
    for (int i = 0; i < x; i++)
    {
    std::cout << "Enter " << Snames[i] << " expenses.";
    std::cin >> *pa[i];
    }
}

I know I can use string instead but may I know how do I go about solving this? I think the problem lies at *pa[i].
Thank you!
Comment: Rephrase your question and is this a homework?
Answer: The statement
std::cin >> *pa[i];

dereferences an uninitialized pointer.
You don't need int* pointers for this case at all. Just change your array and function signature to
 int expenses[Seasons];

 void fill(int*  pa, const int x)

and use
 std::cin >> pa[i]; // Note no dereferencing

Array and pointers input


C++ Boost Graph - Why do I have an additional vertex?

Question: I have a graph whose vertex and edge are of custom type. In my example below, I created the graph with 4 vertices and 4 edges. When I iterate through the vertices to print it however, the system outputs a total of 5 vertices. I am unsure what I did wrong and I hope someone would be able to enlighten me on this.
struct Vertex { int id; double data; };
struct Edge { float distance; };

int main(int, char** argv)
{

typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, Vertex, Edge> Graph;

//instantiate a graph
Graph g;

//add vertices
boost::add_vertex(Vertex{ 1, 1.1 }, g);
boost::add_vertex(Vertex{ 2, 2.2 }, g);
boost::add_vertex(Vertex{ 3, 3.3 }, g);
boost::add_vertex(Vertex{ 4, 4.4 }, g);

boost::add_edge(1, 2, g);
boost::add_edge(1, 4, g);
boost::add_edge(2, 4, g);
boost::add_edge(1, 3, g);

// Iterate through the vertices and print them out
typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter;
std::pair<vertex_iter, vertex_iter> vp;
for (vp = boost::vertices(g); vp.first != vp.second; vp.first++)
    std::cout << g[*(vp.first)].id << " " << g[*(vp.first)].data << std::endl;

// Iterate through the edges and print them out
auto es = boost::edges(g);
for (auto eit = es.first; eit != es.second; ++eit) {
    std::cout << boost::source(*eit, g) << ' ' << boost::target(*eit, g) << std::endl;
}

the output are as follows
1 1.1
2 2.2
3 3.3
4 4.4
0 0
1 2
1 4
1 3
2 4

Answer: From the docs:

If the VertexList of the graph is vecS, then the graph has a builtin vertex indices accessed via the property map for the vertex_index_t property. The indices fall in the range [0, num_vertices(g)) and are contiguous.

The description of add_vertex doesn't say it explicitly, but I believe that the above necessitates that adding vertex with descriptor u into a graph must create vertices 0 through u if any of them don't already exist. Fundamentally, it just resizes the vertex vector to the size u + 1, so that u becomes a valid index.


Need help in understanding Scenario and writing SQL

Question: Thank you very much. I need to add a particular functionality to  all records and the record counts. i have pasted it here-

The requirement for this scenario as given to me is just below and its in BOLD and Italics.
I am somewhat confused with the scenario on how to write the SQL query that gives us "%"
(percentage)-

Take the latest scripts for all clients and add percentages to all record counts per the instructions at the top of these scripts (when the % is at least 1%).
Be sure to use the total record count at the time of each test to get your %'s.  We need these %'s for all time periods that are latest.
I have to ensure that we have these %'s so we can see meaningful trends in latest SQL scripts.  Just looking at records counts in these scripts is not nearly as useful"
My Understanding- What i get is I need to add % for record counts ,but its confusing that
(when the % is at least 1%).  So,if any field is BLANK/NULL or empty =-how would i handle it?
Need your help in writing the SQL query to add % by taking the condition of BLANK/NULL or empty
Code Sample-
Give % of total records if greater than 0%, and put the date next to the count for each query
Presently, SQL query to get total count
SELECT COUNT(1)
FROM Table A;

I am new to SQL.So,please correct me if i understood it wrongly.
When  Count(1) is used,it filters all NULL values
Also,i have seen
SELECT COUNT(*)
FROM Table A;

COUNT(*) gives total record count including null values.
Now,next SQL queries are executed for each field-
--Count members
SELECT COUNT(DISTINCT B_id)
FROM enrollment;

Hence,now i have given to write an SQL query to calculate %  and to include the "% " for each record count.
I suppose it will total count of the Table divide by each column count.
Hi,
Thank you very much for formatting my query.I am gradually trying to learn formatting.
I have not received any suggestions/answers for my query and i have been waiting for your inputs on how to get SQL queries correctly.
I am sorry for making it bold,i just wanted to highlight.
Requesting again for helping
**strong text**
Thanks Hamlin.
" We require that all values from record counts should have to display the percentage value also.
Let me explain with above example -
 1) Initially lets take a table A and a partcular colum called "B_id"  .
 So lets get the record count without NULLs for which I used COUNT(1). There are values which are NULL for B_id.
So,for this field,Total = 100
2)Next,we get the total record count of the Table(So,here we get everything)= 150
Now,if we see the above requirement-
"So,I hope i explained better now. Finally,I need percentages of  all record counts for each Column like B_id,SSN,etc
**Also,must take care of a scenario when it comes 0.76% ->Then I need to round off it to 1%
So,SQL query should calculate %
(when the % is at least 1%).**
So i need a
Comment: I understand, you need to modify an already existing script. Why don't you post or at least outline it here?
Comment: Hi,   I have code sample as an example.
Comment: **Hi,   I have given above code sample as an example. First Query gives me record of a particular field by removing all Blanks. The,I do a query on the entire table which gives total row count irrespective of NULLs.So,please help me with a query which gives % of values present **
Comment: @Rohit, I have tried, but can't make sense of the question. It would help me if you can try to present the question in a more understandable form. Pretend I'm a programmer that you are assigning a task to, and you only have one chance to give me all of the information.
Comment: Thanks Hamlin. " We require that all values from record counts should have to display the percentage value also.
Answer: I see why people are not responding. The question is unclear, and based on what I got out of reading it two or three times, the requirement is not all the clear either. At any rate, I can try to help with a few issues:
a) There is most likely no difference between count(*) and count(1) in your example, unless you are using a non-standard database. That is:
select count(1) from tableA

and
select count(*) from tableA

return the exact same answer. Both ignore non-existent records. Try it and you will see.
b) To get percentages, you are correct that you have to run two queries. Here is a possible method. First, get the total number, with something like this:
select count(*) from TableA

Then, get the count per item, and divide that by the total.
select item, count(*) from TableA group by item

Combine those into a larger select statement, maybe like this:
select x.item, round (x.nbr / (select count(*) from TableA), 2) * 100 as Pct
from (
  select item, count(*) as nbr
  from TableA
  group by item
  ) x

c) Which SQL are you using? Syntax varies enough to make it worth your time to tell us.
d) Your concern for nulls is unnecessary. Generally, if a record does not exist, SQL statements will ignore it. I could be missing your point, but I don't think that will be one of your top concerns. On the other hand, null values are special in SQL, as they are not zero and nulls don't equal anything. Null does not even equal null. If there is a problem with null values in the code above, you might have to do this:
select x.item, round (x.nbr / (select count(*) from TableA), 2) * 100 as Pct
from (
  select item, count(*) as nbr
  from TableA
  where item is not null
  group by item
  ) x

Hope this helps. It might not be the answer you are looking for, but I think it might get you started on the way to formulating the question better.


How to get count in views when group by some field?

Question: I have view which display results based on taxonomy field grouping:

And results look like below :

I am trying to display count of each group in brackets next to Topic field, Is that possible to achieve with this kind of view. Please suggest.
Thanks!
Answer: You can try using this module
Term Node Count
Comment: I want to list nodes as well but do not want to show only count. count is possible by doing aggregation. But I am just displaying list of nodes  which are grouped by term and for each group want to display count at top of grouped title. any other ideas ?


How can I upgrade to core 9?

Question: I have Drupal 8.8.* and I would like to migrate to Drupal 9 using Drush 8. I know, we can use composer however I just wanted to confirm, whether we can do by using Drush command?
I tried using Drush but it's showing no updates available.
$ drush pm-update drupal-9.0.0
Update information last refreshed: Thu, 06/11/2020 - 11:42
 Name    Installed Version  Proposed version  Message
 Drupal  8.9.0              8.9.0             Specified version not found

No code updates available.

Comment: You can't. Drupal 9 requires Drush 10. And Drush 10 won't let you update manually, if I remember it right.
Comment: Does this answer your question? [How can I manually upgrade my Drupal 8 site to Drupal 9?](https://drupal.stackexchange.com/questions/294372/how-can-i-manually-upgrade-my-drupal-8-site-to-drupal-9)
Answer: No, you can't. drush pm-update has been deprecated for a while. The command is still available in the Drush 8.x branch but in later revisions it only exists as a signpost to inform the user how to move to Composer:

The pm-updatecode command was removed. Please see composer update --dry-run and composer update.

Noting that Drush 8 isn't supporting revisions past 8.3.x or 9.x, you should look into upgrading Drush and moving to a Composer-driven upgrade process.
Answer: While this not neither bulletproof, here is what I did now to move from Drupal 8 to 9 using composer:

make sure you are on the latest drupal 8 version (let's call this d8)
verify you meet the d9 server requirements: php min 7.3, mysql min 5.7.8
do yourself a favor and make a database backup (I did not out of lazyness)
create a new project standard drupal 9 somewhere: composer create-project drupal/recommended-project d9 (let'S call it d9)
use composer require drupal/module-name-xy in the new d9 folder for every contrib module the d8 site is using - chances are pretty high, that they are all compatible with 9 already - if not composer will tell you and ideally also some options to fix it
optional: if you are not using drush jet: composer require drush/drush
add core_version_requirement: ^8 || ^9 to your custom my-module.info and my-theme.info files
override the d8 composer.json with the d9 one
run composer update in the d9 folder - now the main update is happening
some files that have been changed by this automatically might need a rollback depending on your local deveopment settings: web/sites/development.services.yml and web/.htaccess in particular
update the DB (I'm using drush): drush --yes updb
start drupal and check the php error logs - you might encounter a few coding issues in your custom modules and thems, but they should be relatively straight foreward to identify and fix.
in the end have a short look to /admin/reports/status

Fingers crossed and best of luck!
(feel free to edit and extend this answer to make the best possible upgrade guide out of it)

How can I upgrade to core 9?


My dict appears to overwrite and not update with new rows?

Question: Given the following code:
https://bpaste.net/show/dd44a1fa01dc
from ciscoconfparse import CiscoConfParse
from pprint import pprint
parse = CiscoConfParse("testconfig.txt", syntax="junos")

interfaces = {}
intfs = parse.find_objects_w_parents(r'^interface', r'^\s+ge-')
for intfobj in intfs:
    intf_name = intfobj.text.strip()
    interfaces.update({'name': intf_name})
    descr = intfobj.re_match_iter_typed(r'description\s+"(\S.+?)"$', group=1)
    interfaces.update({'description': descr})
    mode = intfobj.re_match_iter_typed(r'port-mode\s+(\S+)\s*$', group=1,
        all_children=True)
    interfaces.update({'mode': mode})

print (interfaces)

Using the following test data:
https://bpaste.net/show/df422a96aaae
interfaces {
    ge-2/0/0 {
        description "site1;;hostname1;ge-16/0/9;;;TRUST;";
        unit 0 {
            family ethernet-switching {
                port-mode trunk;
            }
        }
    }
    ge-2/0/2 {
        description "site2;;hostname2;ge-16/0/8;;;TRUST;";
        unit 0 {
            family ethernet-switching {
                port-mode trunk;
            }
        }
    }

    vstp {
        bpdu-block-on-edge;
        vlan VLAN_0005 {
            interface ge-2/0/0 {
                edge;
            }
        }
        vlan VLAN_0015 {
            interface ge-2/0/0 {
                edge;
            }
            interface ge-2/0/2 {
                edge;
            }
        }
    }
}

I'm trying to understand why my interfaces = {} just contains one row:
{'name': 'ge-2/0/2', 'description': 'site2;;hostname2;ge-16/0/8;;;TRUST;', 'mode': 'trunk'}

I would expect it to contain both interfaces from the test data:
{'name': 'ge-2/0/0', 'description': 'site1;;hostname1;ge-16/0/9;;;TRUST;', 'mode': 'trunk'}
{'name': 'ge-2/0/2', 'description': 'site2;;hostname2;ge-16/0/8;;;TRUST;', 'mode': 'trunk'}

Comment: `interfaces` is a dict. It can't contain multiple "rows". You need a list of dicts or similar.
Comment: `dict`s are mappings, not sequences. Each key is associated (or mapped) to a single value. That "single" value can be a `list` or other nested container, however.
Comment: Any chance you have an example?  I'm without a doubt getting confused about things.  Interfaces is the dict, within the dict each ge-x/x/x should be a new key with values of desciption and port-mode
Answer: You are creating a dict and updating its values. So you end up with a dict with last values.
You could rather use a list of dicts, as such :
from ciscoconfparse import CiscoConfParse
from pprint import pprint
parse = CiscoConfParse("testconfig.txt", syntax="junos")

interfaces = []
intfs = parse.find_objects_w_parents(r'^interface', r'^\s+ge-')
for intfobj in intfs:
    interface = {}
    interface['name'] = intfobj.text.strip()
    interface['description'] = intfobj.re_match_iter_typed(r'description\s+"(\S.+?)"$', group=1)
    interface['mode'] = intfobj.re_match_iter_typed(r'port-mode\s+(\S+)\s*$', group=1,
        all_children=True)
    interfaces.append(interface)

print (interfaces)

Answer: Could try something like this
allInterfaces = {}
interfaces = {}
intfs = parse.find_objects_w_parents(r'^interface', r'^\s+ge-')
for intfobj in intfs:
    intf_name = intfobj.text.strip()
    interfaces.update({'name': intf_name})
    descr = intfobj.re_match_iter_typed(r'description\s+"(\S.+?)"$', group=1)
    interfaces.update({'description': descr})
    mode = intfobj.re_match_iter_typed(r'port-mode\s+(\S+)\s*$', group=1,
        all_children=True)
    interfaces.update({'mode': mode})
    allInterfaces = allInterfaces + [interfaces,]

print (allInterfaces)
Comment: Ooops... not fast enough :-)