text:
Q: Symfony Form Type with multiple input fields With Symfony 2.1, how can I create a form type with multiple input fields in it?
So in the form builder I want to add a custom form type :
$builder->add('test','my_fieldtype')

Then if I do this in the template :
{{ form_row(form.test) }}

I want it to display a row that has a label and 2 or 3 input fields. Something like the date type I suppose.

A: You will need to create a custom field type. The best way to achieve it is to look at the code of the DateTimeType.
Remember to create as well the appropriate Twig form template.


text:
Q: What is the right way to insert an equation within a pseudo code I start writing my note in Latex and I am trying to write a pseudo code based on this equation:

Here is my code I have tried so far.
\begin{addmargin}[10mm]{0mm}
     \textbf{Repeat until convergence:} \ \{
     \[
         \theta_j := \theta_j + \alpha \sum_{i=1}^m(y^{(i)}-h_\theta(x^{(i)})) \ x_j^{(i)} \quad (\text{for every} \ j).
     \]
     \}
  \end{addmargin}

I still think it is a bit messy. Do you have an easier way to write this?

A: This question should probably be moved to tex.stackexchange.

There exists several different neat Latex packages specifically with the purpose of writing pseudocode. One of the more simple ways to do it is by using the Algorithmicx package (package documentation here), specifically the algpseudocode part of it.
Here is an MWE for your pseudocode using Algoritmicx:
\documentclass{article}

\usepackage{amsmath}
\usepackage{algpseudocode}
\renewcommand{\algorithmicforall}{\textbf{for each}}

\begin{document}
\noindent Let $\mathcal{J} := \{1, ..., n\}$.

\begin{algorithmic}
    \While {Some convergence criteria is not fulfilled ...}
        \ForAll {$j \in \mathcal{J}$}
            \State $\theta_j \gets \theta_j + \alpha \sum_{i=1}^m(y^{(i)}-h_\theta(x^{(i)})) \ x_j^{(i)}$
        \EndFor
        \State {... update some convergence measure} \Comment{Describe convergence measure}
    \EndWhile
\end{algorithmic}

\end{document}

Note that, at the fourth non-empty line, I've overloaded the text of \ForAll command from algorithmicx (\algorithmicforall), to become "for ... each" rather than "for ... all".
Note also that, generally, only comments may contain text in pseudocode, so the sentences "Some convergence criteria is not fulfilled ..." and "... update some convergence measure" above should be replaced with however your define convergence of algorithm/equation.

A: Here is what you want, from the packages algorithm and algorithmic
\begin{algorithm}
\caption{Gradient Descent}\label{alg-gd}
\begin{algorithmic}[1]
\STATE Initialize \( \theta_{0} = k\in \R^d \)
\STATE Initialize \( t \leftarrow 0 \)
\REPEAT
\STATE \( \forall j \in \{1,..., d\}, \theta_{j,t+1} \leftarrow \theta_{j,t} - \alpha \frac{\p }{\p \theta_{j} } L(\theta )\bigg|_{\theta = \theta_{t} }  \)
\STATE \( t \leftarrow t + 1 \)
\UNTIL{convergence}

which gives,

Note: if you are using it in beamer, put \begin{algorithm}[H] in the line above instead of just \begin{algorithm}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deployment of a web application using FSharp.Data to Azure Websites This is a similar question to How do I deploy a web application using F# to Azure Web Site.  My C#/F# MVC project uses the FSharp.Data NuGet package, and the deployment process fails with the message
Could not locate the assembly "FSharp.Data, Version=1.1.4.0, Culture=neutral, PublicKeyToken=null".
The only effective workaround I can see is to replace all of the NuGet references (FSharp.Data, FSharp.Data.DesignTime, FSharp.Data.Experimental, FSharp.Data.Experimental.DesignTime) with explicit references to the DLLs, and Copy Local set to true.  I am loath to throw the NuGet baby out with the bathwater in this way.  Is there a cleverer way?  Alternatively, is there an open issue to which I can add my vote?

A: You can add a <dependentAssembly> element to your web.config to make sure the FSharp.Data assembly is included when your project is deployed to Azure. I've used this technique before when deploying mixed F#/C# ASP.NET MVC projects to Azure; it's been a while, but I don't think I had to change the Copy Local setting on the referenced assemblies (which I added via NuGet).
Anyway, the entry you need to add should look something like this:
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="FSharp.Data" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Based on Rob's comment that he's still getting the same error message, here're the next steps I would take to diagnose the issue.

*

*Build the Azure deployment package (you don't need to deploy it). When it's finished building, find the deployment package file (*.cspkg); this is actually just a zip file, so extract the contents into a folder, e.g., with 7-zip. In the extracted folder, there should be one file with the *.cssx extension which is much larger than the others; it's also a zip file, so extract it into another folder, then browse into that folder with Windows Explorer. From there, go into the sitesroot folder, then the 0 folder. You should now be looking at the root of your website (i.e., the files/folders that'll be copied to C:\inetpub\wwwroot on the web server). Check the bin folder -- do you see the FSharp.Data assembly there? If not, this is a build/packaging problem, not a server problem; if you do see the FSharp.Data assembly, proceed to the next step.

*Deploy your project to Azure, then Remote Desktop into one of the instances your project is being hosted on. (There's a special procedure for enabling Remote Desktop on the instances -- if you haven't done this yet, you'll need to do so before continuing.) Once you're logged in, you can open Event Viewer (under Administrative Tools); look at the Application log under Windows Logs -- are there any ASP.NET errors there? If so, click them and look at the error message, it may contain a .NET exception message about not being able to resolve the FSharp.Data assembly. If it does, browse to C:\inetpub\wwwroot\ and make sure FSharp.Data is in the bin folder of the website. If it is, proceed to the next step.

*If the FSharp.Data assembly is being packaged and deployed correctly along with your web project, then there could be some issue arising with it (or one of it's dependencies) being a .NET 4.0 assembly when your project is running on .NET 4.5. While logged in to the Azure instance (via Remote Desktop) you could enable Fusion logging and use the Fusion log viewer to trace how the CLR is attempting to load the assembly. If you do track down the issue, the likely way to fix it will be to add a <bindingRedirect> element within the <dependentAssembly> entry you created in your web.config. Here's how I did it to get the original F# PowerPack (which targeted the .NET 2.0 version of FSharp.Core) working in my F#/C# project on .NET 4.0:
<dependentAssembly>
  <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>


text:
Q: Are Young Marriages in the Magical World The Norm? I've noticed that in the Harry Potter books, many characters are in serious long term relationships in their later years at Hogwarts or while they're recently graduated.  It seems like only a few characters were over 21 and still single or getting married later.  (We see Tonks and Lupin get married when Tonks is about 25, Bill and Fleur marry when Fleur is about 20, just for reference.)
Is marriage while young the norm in the magical world?  Or are there many witches and wizards that wait a few years or more before getting married?

A: It is very common during wartime for the marriage rate to increase. This was certainly true in the United Kingdom and the United States during World War 2. The uncertainty of a future will often cause people to wed young.

[The United Kingdom] from a peak in 1940, when 426,1000 young couples – spurred on by the urgency of World War II – married for the first time... telegraph
Marriage rate rose sharply in the 1940s and reached all-time highs. After World War II, Americans began to marry at a younger age: the average age of a person at their first marriage dropped to 22.5 years for males and 20.1 for females, down from 24.3 for males and 21.5 for females in 1940.[7] Getting married immediately after high school was becoming commonplace and women were increasingly under tremendous pressure to marry by the age of 20. wiki

*

*James and Lily Potter marry just out of Hogwarts during the height of the First Wizarding War

*Lupin and Tonks marry just before the dawn of the Second Wizarding War

*Bill and Fleur married during the Second Wizarding War

In fact, Mrs Weasley backs up this exact reasoning:

Mrs. Weasley - "It's all this uncertainty with You-Know-Who coming back, people think they might be dead tomorrow, so they're rushing all sorts of decisions [Bill & Fleur's engagement] they'd normally take time over. It was the same last time he was powerful, people eloping left, right, and center--"
Ginny "Including you and Dad"
Mrs. Weasley "Yes, well, your father and I were made for each other, what was the point of waiting?"
Harry Potter and The Half Blood Prince ch. 5 pg. 93

We also see people who did not marry young.

*

*Minerva McGonagall didn't marry until she was 47 (Pottermore)

*George Weasley married sometime after the Second Wizarding War

*Percy Weasley married sometime after the Second Wizarding War

*Cho eventually married a Muggle man


text:
Q: Abnormal RAM usage from past several days, a weird problem is worrying me. My fedora takes too much RAM than usual, on idle the usual RAM usage is around 2 GB, but it hikes up to more than 5.2 Gb which mostly results in the crash of my DE. I checked the list of processed running and I dont see the list showing any process taking more than 300 mb of RAM, even if I sum them up, total ram usage of processes dont add up to 5 GB. I cant find relevant answers for a fix on forums. If anyone can suggest a fix, I will appreciate it. Thank you
Distro: Fedora 36
Kernel: 5.18.11-200.fc36.x86_64
DE: GNOME 42.3.1

A: It is tricky to determine how much of RAM each process owns. Numbers you see in the various tools often display how much memory is mapped into the process's address space. But, some memory may be mapped to more than one process — so when you add up their usage that shared part should not be added. Some memory may be shared by many processes. Some memory may be mapped into the process twice.
Therefore, "memory usage" for each process is useful only for considering each process individually, but it should not be added — you never know how much of that memory is shared and what is sharing depth. It is incorrect to sum those values, the result will be overestimage does not correspond to any thing real in the computer. On the other hand, if you are going to sum just memory unique to the processes, you'll fall into great underestimate. So never sum them. Rely on the values for "available" memory that the system reports.
Another widely known misunderstanding is what Linux considers "free" memory is technically not the thing you should be worried about. What you should look at is available memory; technically that's "free plus buffers plus cached". Buffers and cache will be freed immediately upon application request; that's just "the memory was unused so Linux used it to speed up the computer because otherwise the more memory would be just wasted money, but it promises to release it once somebody needs it". See also explanations here: https://www.linuxatemyram.com/ .
Crashes due to insufficient memory are caused by kernel's out of memory killer (OOM-killer). If it is the culprit, it will definitely register its actions in dmesg, along with circumstances. In short, if there is really insufficient memory, it chooses the "worst" fat process and kills it, freeing the memory. Definitely check for that, if you suspect memory overflow. If no OOM killer actions are logged, your crashes are not because of high memory usage.


text:
Q: Draggable legend with multiple axes problem I'm wondering if anyone has a solution for a problem I'm having when using a draggable legend in conjunction with multiple axes.
I'm using gridspec and figure (matplotlib 1.0.1, qt4 backend) to create 2 axes – no pyplot. When the legend is dragged from one axes to the other and released, its draggability ceases to work.
If a portion of the legend is outside the boundaries of the axis, the legend can be picked up by clicking on that portion, but not if the mouse is clicked on any area of the legend inside the axis.
I tried Adam Fraser's original code but the legend would slip under the 2nd axes in my app.
My app is really quite large - too large to show here, so to illustrate the problem, I've modded some code from the Matplotlib Legend Guide (uses pyplot) as follows:
from matplotlib.pyplot import *

subplot(211)
plot([1,2,3], label="test1")
plot([3,2,1], label="test2")
leg=legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)
leg.draggable(state=True, use_blit=True)

subplot(223)
plot([1,2,3], label="test1")
plot([3,2,1], label="test2")
leg=legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
leg.draggable(state=True, use_blit=True)

show()

It produces a plot with a couple of axes and two legends.
Run the code and drag the legends around to see the effect (if you don't have any problems, it must be something I ate and I apologize).
I suspect a solution may be fairly low level, but who knows, maybe it's a simple fix?
Thanks for any help.

A: I reproduced the problem. The part of the legend that enters the alien figure becomes unclickable, as if the figure would be catching the mouse position events and not resending them to other handlers.
The minimal code that reproduces the problem (to experiment with ipython -pylab) is:
In [16]: f211 = plt.subplot(211)
In [17]: f212 = plt.subplot(212)
In [18]: p1 = plot([1,2], label="test1")
In [20]: leg = legend(loc=(0.5,0.5))
In [21]: d = leg.draggable(state=True, use_blit=True)


text:
Q: What Excel formula can I use to combine duplicate entries with both unique data and overlapping data into a single line item? I have a large dataset of shipment tracking numbers and costs associated with transportation, surcharges, and duties & taxes. The majority of the tracking numbers are unique, but a meaningful minority are duplicates. Many of the duplicates introduce new information, i.e. the first entry contains costs associated with transportation and associated surcharges, whereas the second entry contains costs associated with duties & taxes, which are mutually exclusive costs from the transportation and surcharges. There are, however, a smaller minority of duplicate tracking numbers that contain new costs associated with the same surcharges included in the original entry. When a duplicate tracking number introduces new cost categories and amounts, I need to combine the new information on the duplicate tracking number by adding the surcharge category and associated cost to the right of the existing information in a single line item. When a duplicate tracking number has a categorical charge overlap with the original, I need to add the costs associated with the duplicate surcharge across the duplicate tracking numbers into a single cell. In many cases, duplicate tracking introduce both new categories of surcharges and associated costs and overlapping categorical surcharges that need to be summed together across original and duplicate tracking.
I have tried a combination of nested VLOOKUP, INDEX, and ADDRESS functions to no avail.
Example - 3 duplicate entries:

Desired result:


text:
Q: Contracting closed contours that enclose poles If $f(z)$ is analytic in a simply connected domain $D$, its integral over any closed contour is $0$. I don't quite understand how the idea of contracting the contour that encloses a pole follows from that. Specifically, why are we able to say the following integral has the same value over any closed contour that encloses $z_0$, a pole of order $m$,
$$\oint_C \frac{f(z)}{z-z_0}dz$$
where $C$ is the circle of radius $\rho$ centered at $z_0$. In other words, what allows us to be able to contract an arbitrary contour (that encloses $z_0$) to the circle $C$?

A: The easiest way is to draw a picture. I shamelessly use a picture from an entirely different subject from Paul's Online Math Notes

Suppose the pole is in the center, and you were first integrating around the outer circle, and wanted instead to be integrating around the inner circle. If you were to perform the integral around the region indicated by $D_1$ in the picture, you get $0$. So
$$\int_{C_1} + \int_{C_5} + \int_{C_2} + \int_{C_6} = 0.$$
Similarly, from the bottom,
$$\int_{C_4} + \int_{-C_6} + \int_{C_3} + \int_{-C_5} = 0.$$
Adding these together, we see that
$$\int_{C_1} + \int_{C_2} + \int_{C_3} + \int_{C_4} = 0,$$
or equivalently,
$$\int_{C_1} + \int_{C_4} = \int_{-C_2} + \int_{-C_3},$$
which says exactly that integrating around the outer circle gives the same as integrating around the inner circle. Notice the negatives correct the orientation in the picture.
This works essentially as is for general contours as well. I just stole the first picture I could find instead of making my own.


text:
Q: Como filtrar um objeto json com jQuery? Eu tenho o seguinte objeto json:
var json = {
   "tpAmbiente":null,
   "hotelPesquisa":[
      {
         "dtEntrada":"20170510",
         "dtSaida":"20170511",
         "hotel":{
            "id":94,
            "nome":"Itamarati"
         },
         "quarto":[
            {
               "quartoUh":[
                  {
                    "nQUarto": 1,
                     "tarifa":{
                        "vlDiariaTotal":157.21,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
                  {
                    "nQUarto": 2,
                     "tarifa":{
                        "vlDiariaTotal":157.21,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
               ]
            }
         ]
      },
      {
         "dtEntrada":"20170510",
         "dtSaida":"20170511",
         "hotel":{
            "id":95,
            "nome":"copacabana"
         },
         "quarto":[
            {
               "quartoUh":[
                  {
                    "nQUarto": 1,
                     "tarifa":{
                        "vlDiariaTotal":102.1,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
                  {
                    "nQUarto": 2,
                     "tarifa":{
                        "vlDiariaTotal":102.1,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
               ]
            }
         ]
      },
      {
         "dtEntrada":"20170510",
         "dtSaida":"20170511",
         "hotel":{
            "id":96,
            "nome":"Itamarati"
         },
         "quarto":[
            {
               "quartoUh":[
                  {
                    "nQUarto": 1,
                     "tarifa":{
                        "vlDiariaTotal":157.21,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
                  {
                    "nQUarto": 2,
                     "tarifa":{
                        "vlDiariaTotal":157.21,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
               ]
            }
         ]
      },
      {
         "dtEntrada":"20170510",
         "dtSaida":"20170511",
         "hotel":{
            "id":96,
            "nome":"Litoral Hotel"
         },
         "quarto":[
            {
               "quartoUh":[
                  {
                    "nQUarto": 1,
                     "tarifa":{
                        "vlDiariaTotal":1001.00,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
                  {
                    "nQUarto": 2,
                     "tarifa":{
                        "vlDiariaTotal":1001.00,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
               ]
            }
         ]
      }
   ]
};

Como faço para filtrar esse objeto para que so mostre os hoteis onde o preço for maior quem 100 e menor que 900?
O preço fica em:
hotelPesquisa[].quarto[].quartoUh[].tarifa.vlDiariaTotal
Retorno que preciso:

"hotelPesquisa":[
      {
         "dtEntrada":"20170510",
         "dtSaida":"20170511",
         "hotel":{
            "id":94,
            "nome":"Itamarati"
         },
         "quarto":[
            {
               "quartoUh":[
                  {
                    "nQUarto": 1,
                     "tarifa":{
                        "vlDiariaTotal":890.21,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
                  {
                    "nQUarto": 2,
                     "tarifa":{
                        "vlDiariaTotal":890.21,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
               ]
            }
         ]
      },
      {
         "dtEntrada":"20170510",
         "dtSaida":"20170511",
         "hotel":{
            "id":95,
            "nome":"copacabana"
         },
         "quarto":[
            {
               "quartoUh":[
                  {
                    "nQUarto": 1,
                     "tarifa":{
                        "vlDiariaTotal":102.1,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
                  {
                    "nQUarto": 2,
                     "tarifa":{
                        "vlDiariaTotal":102.1,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
               ]
            }
         ]
      },
      {
         "dtEntrada":"20170510",
         "dtSaida":"20170511",
         "hotel":{
            "id":96,
            "nome":"Itamarati"
         },
         "quarto":[
            {
               "quartoUh":[
                  {
                    "nQUarto": 1,
                     "tarifa":{
                        "vlDiariaTotal":890.21,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
                  {
                    "nQUarto": 2,
                     "tarifa":{
                        "vlDiariaTotal":890.21,
                        "desconto":null
                     },
                     "qtDisponivel":null,
                     "desconto":null
                  },
               ]
            }
         ]
      }
   ]

Existe alguma maneira eu posso filtrar o objeto com jQuery e manter todas as propriedades? Obrigado!

A: Analiza onde está a array que queres filtrar e qual o elemento de comparação. A partir daí a lógica é a mesma que esta outra pergunta/resposta tua.
Neste caso precisas de repetir a lógica uma vez que queres filtar em dois niveis:

var pesquisa = {
  min: 100,
  max: 900
};
var hotelPesquisa = [{
    "dtEntrada": "20170510",
    "dtSaida": "20170511",
    "hotel": {
      "id": 94,
      "nome": "Itamarati"
    },
    "quarto": [{
      "quartoUh": [{
          "nQUarto": 1,
          "tarifa": {
            "vlDiariaTotal": 890.21,
            "desconto": null
          },
          "qtDisponivel": null,
          "desconto": null
        },
        {
          "nQUarto": 2,
          "tarifa": {
            "vlDiariaTotal": 890.21,
            "desconto": null
          },
          "qtDisponivel": null,
          "desconto": null
        },
      ]
    }]
  },
  {
    "dtEntrada": "20170510",
    "dtSaida": "20170511",
    "hotel": {
      "id": 95,
      "nome": "copacabana"
    },
    "quarto": [{
      "quartoUh": [{
          "nQUarto": 1,
          "tarifa": {
            "vlDiariaTotal": 0, // este é gratuito!
            "desconto": null
          },
          "qtDisponivel": null,
          "desconto": null
        },
        {
          "nQUarto": 2,
          "tarifa": {
            "vlDiariaTotal": 102.1,
            "desconto": null
          },
          "qtDisponivel": null,
          "desconto": null
        },
      ]
    }]
  },
  {
    "dtEntrada": "20170510",
    "dtSaida": "20170511",
    "hotel": {
      "id": 96,
      "nome": "Itamarati"
    },
    "quarto": [{
      "quartoUh": [{
          "nQUarto": 1,
          "tarifa": {
            "vlDiariaTotal": 890.21,
            "desconto": null
          },
          "qtDisponivel": null,
          "desconto": null
        },
        {
          "nQUarto": 2,
          "tarifa": {
            "vlDiariaTotal": 10000.21, // este é muito caro!
            "desconto": null
          },
          "qtDisponivel": null,
          "desconto": null
        },
      ]
    }]
  }
];

var filtrados = hotelPesquisa.filter(function(hotel) {
  hotel.quarto[0].quartoUh = hotel.quarto[0].quartoUh.filter(function(quarto) {
    return quarto.tarifa.vlDiariaTotal < pesquisa.max && quarto.tarifa.vlDiariaTotal > pesquisa.min;
  });
  return hotel.quarto[0].quartoUh.length > 0;
});

console.log(filtrados);


text:
Q: Query takes extremely too long to execute I'm trying to fetch all the courses that a student has from a MySQL database. This snippet only fetches 1 course, but there are 6 in total (and then it takes 15 seconds). I'm trying to display the course that is already has been set (if any) by using the selected attribute in the option tag. I think this is what causes the query to execute for so long.
Is something wrong with my database design? How do I improve the query?
This is the database's structure. I created an intermediary table user_courses:
users:
user_id
users_courses:
user_id
course_id_1
course_id_2
course_id_3
course_id_4
course_id_5
course_id_6
course_id_7
courses:
course_id
course_name
<?php
    session_start();
    $_SESSION['user_id'] = 1;
    require ('../mysqli_connect.php');

    echo '

<select name="course_id_1">';

    // checking if a user has already chosen a 1st course (out of 6)
    $query = "SELECT c.course_id
              FROM courses AS c
              INNER JOIN users_courses AS u
              ON c.course_id = u.course_id_1
              WHERE u.user_id = {$_SESSION['user_id']}";
    $result = mysqli_query($dbc, $query);

    // if yes, assign the selected course from the database to a variable
    if (mysqli_num_rows($result) == 1) {
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        $selected_course = $row['course_id'];
    }

    // fetch courses, and make 'None' the first option in the drop down menu
    $query = "SELECT course_id, course_name
              FROM courses
              ORDER BY (course_name = 'None') DESC, course_name";
    $result = mysqli_query($dbc, $query);

    // create the drop down menu
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        // select default value
        if ($selected_course == $row['course_id']) {
            $selected =' selected';
        } else {
            $selected='';
        }

        echo '<option value="' . $row['course_id'] . '"' . $selected . '>'
              . htmlspecialchars($row['course_name']) . '</option>';
    }

    echo '</select>
';

    mysqli_free_result($result);
    mysqli_close($dbc);
?>

A: You have a number of problems here.
1) Your explanation of your table structure isn't sufficient to diagnose some common problems like missing indexes, or what you've established as a primary key. Those choices can have dramatic impacts on performance.
2) Your users_courses table is denormalized; a more common way to model many-to-many relationships is to have a table with one foreign key for each of the joined tables. In that case, your table would look like:
USERS_COURSES
-------------
user_id
course_id

And then a user with 7 courses would have 7 records in that table. If it's actually important to your model to know priorities like "first choice", you could extend the join table with an appropriate column.
3) Your PHP code is wide open for SQL injection attacks because you're directly interpolating user input into your query. You need to fix that and adopt a practice of always using bind variables

A: try this ... this creates the indexes, that jeff mentioned
CREATE INDEX _index_course ON courses(course_id);
CREATE INDEX _index_user_course ON users_courses(course_id_1);


text:
Q: mailgun/parse-server(heroku) not working Having two iOS apps (let us name them appA and appB) both using parse-server hosted on heroku and mailgun, I am facing the problem describe hereafter.
Let me first say that the two apps are unrelated except for the fact they both have user accounts and mail mailgun is used on both to send a confirmation mail when a user creates an account.
appA is working fine, meaning confirmation mail is sent when a new account is created.
But appB is no longer working, meaning no confirmation mail is sent when a new account is created.
I have tried to find out what could be the difference between the two, making one work and not the other.
I have also read or listened to a few tutorials on the subject, to remind me how I did this kind of settings (back a few months ago). But I can't get hold of any relevant difference and solve my problem, which is to bring appB back to a working state.
Any hint (on what to do or what to look for) by someone with more experience than me in the field would be very much appreciated.
Thanks in advance!
For reference, here is the parse-server index.js for the app which is not working:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var S3Adapter = require('parse-server').S3Adapter;

var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;

if (!databaseUri) {
  console.log('DATABASE_URI not specified, falling back to localhost.');
}

var api = new ParseServer({
  databaseURI: databaseUri || 'mongodb://heroku_database',
  cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
  appId: process.env.APP_ID || '__appId__',
  masterKey: process.env.MASTER_KEY || '__masterKey__',
  filesAdapter: new S3Adapter(
    "__AAKKIII__",
    "pP7Lm16Tt/nTrKq3242Hv",
    "myapp",
    {directAccess: true}
  ),
  serverURL: process.env.SERVER_URL || 'https://myapp.herokuapp.com/parse',
  liveQuery: {
    classNames: ["User", "myappUnit", "myappFieldOne", "myappFieldTwo"]
  },
  emailAdapter: {
    module: 'parse-server-simple-mailgun-adapter',
    options: {
      fromAddress: 'parse@example.com',
      domain: 'mydomain.net',
      apiKey: 'key-fjdfijofd',
    }
  }
});

var app = express();

app.use('/public', express.static(path.join(__dirname, '/public')));

var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);

app.get('/', function(req, res) {
  res.status(200).send('I dream of being a website.  Please star the parse-server repo on GitHub!');
});

app.get('/test', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/test.html'));
});

var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
    console.log('parse-server-example running on port ' + port + '.');
});

ParseServer.createLiveQueryServer(httpServer);

A: After searching the net, trying different things and taking a closer look, I ended up by finding what was missing.
I put it here in case that may help someone in the future.
The missing lines in the parse-server index.js in my post are those:

*

*verifyUserEmails: true,

*appName: 'Parse App',

The lines above need to be included inside:
var api = new ParseServer({
......
})


text:
Q: Encode unicode characters in URL using PHP? I'm trying to encode a feed's URLs, which unfortunately contain Unicode characters. My feed reader doesn't support this.
My knowledge in php is limited and my basic approach failed when it encountered a French character ç. Clearly listing each character is slow and too much work:
    public function encodeUmlauts($req_url) {
        $req_url = str_replace("ö", urlencode("ö"), $req_url);
        $req_url = str_replace("ü", urlencode("ü"), $req_url);
        $req_url = str_replace("ä", urlencode("ä"), $req_url);
        $req_url = str_replace("Ö", urlencode("Ö"), $req_url);
        $req_url = str_replace("Ü", urlencode("Ü"), $req_url);
        $req_url = str_replace("Ä", urlencode("Ä"), $req_url);
        $req_url = str_replace("ß", urlencode("ß"), $req_url);

        return $req_url;
    }

I assume something can be done with urlencode and/or parse_url, but I don't see an obvious solution.
What I'm looking for is similar to this stackoverflow question, but for PHP.

A: This will urlencode all non-ascii characters in the URL string:
$url = preg_replace_callback('/[^\x20-\x7f]/', function($match) {
    return urlencode($match[0]);
}, $url);


text:
Q: str=str.split('=') AttributeError: 'list' object has no attribute 'split' I have to pass split the data from xpath into two fields
str = response.xpath('.//td//div[@class="cit_maoin"]()')
str=split('=')

print('published)

A: Try this in line 3
str=str[0].split('at')

Your list has only one item, so index will be 0, not one. Index starts from 0 in list.
Hope it helped!

A: str is a keyword in Python.
Let my_str = 'published = 6/11/2019 at 8:02 AM'
my_str = my_str.split('=')[1]

date_str = my_str.split('at')[0]
time_str = my_str.split('at')[1]

print(date_str) #6/11/2019
print(time_str) #8:02 AM

For a list of inputs, use a for loop.

A: try with this
str = ['published = 6/11/2019 at 8:02 AM']
published_date, time = str[0][11:].split('at')[0],str[0][11:].split('at')[1]

check with this Assuming your mystr as given below
my_str = [['\r\n ', '3/28/2019 at 8:52 PM.\r\n This list includes 36
        eligible players.\r\n ', '\r\n \xa0\r\n '],['\r\n ', '3/28/2019 at 8:52 PM.\r\n This list includes 36 eligible players.\r\n']]

date = []
time = []
for x in my_str:
    index_ = x[1].find('PM')
    string_ =  x[1][0:index_ + 2]
    date.append(string_.split('at')[0])
    time.append(string_.split('at')[1])

#op
print(date)
['3/28/2019 ', '3/28/2019 ']

print(time)

[' 8:52 PM', ' 8:52 PM']

A: Try not to use str because it's built in keyword in Python. you didn't specify what your desired output should be like but from the Comments I think you ll need some changes like this to your code:
    data = ["published = 6/11/2019 at 8:02 AM"]
    results = []
    for s in data:
      t = s.split("=")
      z = t[1].split("at")
      tmp = f'published date = {z[0]} published time = {z[1]} '
      results.append(tmp)

   print(results) # ['published date =  6/11/2019  published time =  8:02 AM ']

with this Code you ll get a list of desired outputs. Hope it helps


text:
Q: Display a table based on an array without using table elements but using display properties Hi I have created a table using display properties, now i have an array and i want to iterate through that array and pring the value of column and rows, here is my code : -
html:=

head 1

head 2

cell 1.1

cell 1.2

cell 2.1

cell 2.1

foot 1

foot 2

css:
div {
         padding: 5px;
      }
  #table {
    margin: 0 auto;
    display: table;
    border: 1px solid green;
  }

  .table-row {
    display: table-row;
  }

  .table-cell {
    width: 150px;
    text-align: center;
    display: table-cell;
    border: 1px solid black;
  }

  #thead {
    display: table-header-group;
    color: white;
    background-color: red;
  }

  #tbody {
    display: table-row-group;
    background-color: yellow;
  }

  #tfoot {
    display: table-footer-group;
    color: white;
    background-color: blue;
  }

ts file :=
auditViews : any = [
{
  "id" : "log1",
  "name" : "Audit log 1",
  "description" : "Descrition of audit log 1",
  "status" : "active"
},
{
  "id" : "log2",
  "name" : "Audit log 2",
  "description" : "Descrition of audit log 2",
  "status" : "active"
},
{
  "id" : "log3",
  "name" : "Audit log 3",
  "description" : "Descrition of audit log 3",
  "status" : "active"
}];

This is static, somehow i need the column header be id, name, description and status and below that the values.

A: HTML

{{data?.key}}

{{data?.id}}

{{data?.name}}

{{data?.description}}

{{data?.status}}

foot 1

foot 2

Working Example
PS: If you change the way of format for your JSON you could avoid double loop/iteration which is optimized version to this solution.
Optimized version
HTML

      <ng-container *ngFor='let data of data | keyvalue'>

{{data?.key}}

{{data?.value}}

      </ng-container>

In this version, I have added extra object in the array for the Header section.

A: TS file:
auditViews : any = [
{
  "id" : "log1",
  "name" : "Audit log 1",
  "description" : "Descrition of audit log 1",
  "status" : "active"
},
{
  "id" : "log2",
  "name" : "Audit log 2",
  "description" : "Descrition of audit log 2",
  "status" : "active"
},
{
  "id" : "log3",
  "name" : "Audit log 3",
  "description" : "Descrition of audit log 3",
  "status" : "active"
}];

headings: Array<string> = Object.keys(auditViews[0])
footerElement: Array<string> = [];

HTML file:

    <ng-template *ngFor="let heading of headings">

{{ heading }}

    </ng-template>

      <ng-template *ngFor="let row of auditViews">

         <ng-template *ngFor="let field of row">

{{ field }}

         </ng-template>

      </ng-template>

      <ng-template *ngFor="let footerElement of footer">

{{ footerElement }}

      </ng-template>

Currently, I assigned the footer elements with an empty array if there are elements. you can assign them to "footerElement" array.


text:
Q: how to save featured data into featured table from product table in codeigniter I hope you are doing well. I am new in codeigniter :::
I have two tables in database 1. tbl_product  2. tbl_featured_products. I get data from tbl_product in a form with foreach loop in checkbox system. After that I need to save product data into  tbl_featured_products. I can not save it (multiple data in row ).... please help me out ..
My Question::
1. how can I save data into tbl_featured_products ?
2. how can I show image and others info and save data from view page ?
Controller:::
    $data=array();

    $data['featured_id']=$this->input->post('featured_id',true);
    $data['product_id']=$this->input->post('product_id',true);
    $data['product_name']=$this->input->post('product_name',true);
    $data['product_price']=$this->input->post('product_price',true);
    $data['product_image']=$this->input->post('product_image',true);

    $this->sa_model->save_featured_product_info($data);
}

Model :::::
public function save_featured_product_info($data)
{
    $this->db->insert('tbl_featured_products',$data);
}

view::::

        Product Name:

            <?php foreach($all_product as $values) { ?>
                <input type="checkbox" name="product_name" value="<?php echo $values->product_name;?>"> <?php echo $values->product_name;?>

            <?php } ?>

A: I would try the following:
first load data to your view
Controller:
function dataToView(){
   $data = $this->sa_model->tbl_product_info($data); //gets information from your model db
   $this->load->view('templates/home', $data); //sends data to the view
}

View:

    Product Name:

        <form id="product_form">
        <?php foreach($all_product as $values) { ?>
            <input type="checkbox" name="product_name" value="<?php echo $values->product_name;?>"> <?php echo $values->product_name;?>

        <?php } ?>
            <input type="submit" />
        </form>

Javascript

Controller
<?php
function save(){
    $product = $this->input->post('product_name');//this will get your posted product into the controller
    //...add your own function
    if (works){
        echo true;
    }else{
        echo false;
    }

}
?>


text:
Q: HTML tag finder I am trying to create a method to find and return the first tag in a given HTML string, and returns null if no such tag is found. (A tag would be something like )
I looked through the String class methods but I can't find a method that can suit this purpose. I'm thinking my plan is to scan each word for a "<" then once it is found, scan for a ">", but am unsure of how to do so. Also wondering if I should put a while/for loop in there? Help is appreciated, thank you.
public class HTMLProcessor {

    public static void main(String[] args) {
    System.out.println(findFirstTag("The man jumped."));
    }

    public static String findFirstTag(String text) {
    int firstIndex = text.indexOf("<");
    if (firstIndex >= 0) {
        String newText = text.substring(firstIndex);
        int secondIndex = newText.indexOf(">");

        return text.substring(firstIndex, secondIndex + 1);
    } else {
        return null;
    }

}

A: Use regular expressions.
Pattern p = Pattern.compile("<([A-Z][A-Z0-9]*)\\b[^>]*>(.*?)</\\1>");
Matcher m = p.matcher(yourText);

Will match things like this is bold

A: You can try with indexOf()  and lastIndexOf() methods from String class.
You definitely need a HTML parser, Just pick one. Jsoup is one the best html parser.
Considering you are doing this multiple times and places.
And do not prefer much for regex while dealing with html strings

A: Take a look at java regular expressions here. If you need an introduction to regex look here. This is probably the quickest way to accomplish what you're looking for.


text:
Q: Unitary elements in C*-algebras Let $\mathscr A$ be an unital $C^*$-algebra and let $u \in \mathscr A$ be an unitary element (I.e., $u^*u=uu^*=1$). Is it true that
$$u=e^{ia}$$
for some hermitian element $a\in \mathscr A$?
Im not sure how to construct a counter example. I also think one should use functional calculus(?), but again, not sure how.

A: Here is a counterexample.
Consider $\mathcal A:=\mathcal C(\mathbb T)$, the $C^*$-algebra of all continuous (complex-valued) functions on the unit circle $\mathbb T:=\{ z\in\mathbb C;\; \vert z\vert=1\}$.
The function $u\in\mathcal C(\mathbb T)$ defined by $u(z):=z$ is certainly unitary. However, it is quite well known that one cannot define a continuous logarithm function on $\mathbb T$. So there is no continuous function $w$ on $\mathbb T$ such that $u=e^w$, and hence one cannot write $u=e^{ia}$ for some hermitian $a\in\mathcal A$.


text:
Q: Can't retrieve the 390-characters text record added to 1k Mifare Classic tag I add a text a 390-characters long text record to 1k Mifare Classic card, I can write
it successfully, but records are empty when reading it. I
use NDEF library with PN532 and Ardunio uno.
my code :
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>

PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);

void setup()
{
Serial.begin(115200);
Serial.println("Serial Start");
nfc.begin();
Serial.println("NFC Start");
}

void loop()
{
if (nfc.tagPresent()) {
NfcTag tag = nfc.read();
tag.print();
}
if (nfc.tagPresent()) {
NdefMessage message = NdefMessage();
message.addTextRecord("denemedenemedenemedenemedenemedenemedenemedenemedenemedenemedenemedenemedenemedenemeden");

    bool   success = nfc.write(message);
    if (success)
    {
        Serial.println("Write Success");
    }
    else
    {
        Serial.println("Error");
    }
}
}

I use the example shown here but it doesn't work.

A: You code for adding a text "record" into the tag is correct. The reading from the tag for the message payload however is not. It take a little bit more to get to the "record". The nfc.read() return a tag object which consists of a message object, which could consists of multiple records, and within each record, it has the payload length and payload (which is the text node you added), some parsing is required to get the data you wrote into it.
Please noted that the data are stored with a prefix that indicating the charset used for encoding the record, I add the code to discard the prefix, the record is stored in byte, it need to be cast to char before Serial.print().
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>

PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);

void setup()
{
  Serial.begin(115200);
  Serial.println("Serial Start");
  nfc.begin();
  Serial.println("NFC Start");
}

void loop()
{
  // read from the tag for NDEF message payload
  char tagMsg[100]={'\0'};  // make sure this is longer than your added text
  if (nfc.tagPresent()) {
    NfcTag tag = nfc.read();
    if (tag.hasNdefMessage()) {    // an empty tag won't have any message
       NdefMessage message = tag.getNdefMessage();
       NdefRecord record = message.getRecord(0);  // only get the first records
       int payloadLength = record.getPayloadLength();
       uint8_t payload[payloadLength];
       record.getPayload(payload);
       // drop the first 3 bytes, which specify the language e.g. en=English
       for (uint8_t s = 3, d=0; s < payloadLength; s++, d++) {
         tagMsg[d] = (char)payload[s];
       }
       Serial.println(tagMsg);  //this will be the text msg you added
    }
  }

  // add a text message to the NDEF tag
  if (nfc.tagPresent()) {
    NdefMessage message = NdefMessage();
    message.addTextRecord("denemedenemedenemedenemedenemedenemedenemedenemedenemedenemedenemedenemedenemedenemeden");

    if (nfc.write(message))
    {
        Serial.println("Write Success");
    }
    else
    {
        Serial.println("Error");
    }
  }
}


text:
Q: React Native webview routing I'm building a React-Native app with some native screens, and some screens where I load the website with a WebView. Instead of the classical website navigation, I have a native drawer to switch pages.
My issue is that the website is using react-router, so it handles the URL change smoothly on browsers by loading only the necessary code. Still, when I change the URL in my WebView, it does as if I was refreshing the website, and it reloads everything, leading up to very slow navigation.
The only 'hack' I thought would be exposing a function on the website window variable to trigger a react-router 'go to'.
Any ideas?

A: So, after a few days of struggling, I have settled with the following solution, which I admit is slighlty obscure, but works perfectly (incl. back button, gestures):
In the React Web Application, I keep the ReactRouter history object available through the global Window object.
import { useHistory } from 'react-router'
// ...

declare global {
  interface Window {
    ReactRouterHistory: ReturnType<typeof useHistory>
  }
}

const AppContextProvider = props => {
  const history = useHistory()

  // provide history object globally for use in Mobile Application
  window.ReactRouterHistory = history

  // ...
}

In the React Native Mobile Application, I have custom code injected to the WebView, that makes use of the history object for navigation and the application communicates with this code using messages:
webViewScript.ts
// ...
export default `
  const handleMessage = (event) => {
    var message = JSON.parse(event.data)
    switch (message.type) {
      // ...
      case '${MessageTypes.NAVIGATE}':
        if (message.params.uri && message.params.uri.match('${APP_URL}') && window.ReactRouterHistory) {
          const url = message.params.uri.replace('${APP_URL}', '')
          window.ReactRouterHistory.push(url)
        }
        break
    }
  };

  !(() => {
    function sendMessage(type, params) {
      var message = JSON.stringify({type: type, params: params})
      window.ReactNativeWebView.postMessage(message)
    }

    if (!window.appListenersAdded) {
      window.appListenersAdded = true;

      window.addEventListener('message', handleMessage)

      var originalPushState = window.history.pushState
      window.history.pushState = function () {
        sendMessage('${MessageTypes.PUSH_STATE}', {state: arguments[0], title: arguments[1], url: arguments[2]})
        originalPushState.apply(this, arguments)
      }

    }
  })()
  true
`

intercom.ts (no routing specifics here, just for generic communication)
import WebView, {WebViewMessageEvent} from 'react-native-webview'
import MessageTypes from './messageTypes'

export const sendMessage = (webview: WebView | null, type: MessageTypes, params: Record<string, unknown> = {}) => {
  const src = `
  window.postMessage('${JSON.stringify({type, params})}', '*')
  true // Might fail silently per documentation
  `
  if (webview) webview.injectJavaScript(src)
}

export type Message = {
  type?: MessageTypes,
  params?: Record<string, unknown>
}

export type MessageHandler = (message: Message) => void

export const handleMessage = (handlers: Partial<Record<MessageTypes, MessageHandler>>) => (
  (event: WebViewMessageEvent) => {
    const message = JSON.parse(event.nativeEvent.data) as Message
    const messageType = message.type

    if (!messageType) return
    const handler = handlers[messageType]

    if (handler) handler(message)
  }
)

export {default as script} from './webViewScript'

WebViewScreen.tsx
import {handleMessage, Message, script, sendMessage} from '../intercom'
// ...

const WebViewScreen = ({navigation, navigationStack}: WebViewScreenProps) => {
  const messageHandlers = {
    [MessageTypes.PUSH_STATE]: ({params}: Message) => {
      if (!params) return
      const {url} = params
      const fullUrl = `${APP_URL}${url}`
      navigationStack.push(fullUrl)
    },
    // ...
  }

  const uri = navigationStack.currentPath

  // navigation solution using history object propagated through window object
  useEffect(() => {
    if (uri) {
      sendMessage(webViewRef.current, MessageTypes.NAVIGATE, {uri})
    }
  }, [uri])

  // this is correct! Source is never going to be updated, navigation is done using native history object, see useEffect above
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const source = useMemo(() => ({uri}), [])

  return (
    <View
        // ...
        refreshControl={
          <RefreshControl
              // ...
          />
        }
    >
      <WebView
          source={source}
          injectedJavaScript={script}
          onMessage={handleMessage(messageHandlers)}
          // ...
      />
    </View>
  )

}

A: Have you tried a combination of
UseEffect and route navigation?


text:
Q: String to date in pandas I have a dataset with dates encoded as strings formatted as %B %d, %Y, eg September 10, 2021.
Using:df['sale_date'] = pd.to_datetime(df.sale_date, format = '%B %d, %Y')
produces this error ValueError: time data 'September 10, 2021' does not match format '%B %d, %Y' (match)
Manually checking with strptimedatetime.strptime('September 10, 2021', '%B %d, %Y') produces the correct datetime object.
Is there something I missed in the pd.to_datetime?
Thanks.

A: Upon further investigation, I found out that the error only happens on the first element of the series. It seems that the string has '\ufeff' added to it. So I just did a series.str.replace() and now it is working. Sorry for the bother. Question is how did that BOM end up there?

A: Very likely you have to eliminate some whitespaces first!
If I add whitespaces at the beginning, end or both..
datestring = ' September 10, 2021 '

datetime.datetime.strptime(datestring, '%B %d, %Y')

it will result in the same error message  as you have..
ValueError: time data ' September 10, 2021 ' does not match format '%B %d, %Y'

As a solution for a single value use:
datestring = ' September 10, 2021 '
datestring.strip()

for a column in a dataframe use:
dummy = pd.DataFrame(columns={'Date'}, data = [' September 10, 2021 ', ' September 11, 2021 ', ' September 12, 2021 '])
dummy.Date = dummy.Date.apply(lambda x: x.strip())


text:
Q: "A lot of ideas" is or are? My boyfriend and I are arguing about whether the phrase "a lot of ideas" should be followed with is or are. I say that it should be is because the verb is linking to a lot, not ideas. If it were "lots of ideas" I would say it is definitely are. He thinks, though, that since a lot is synonymous with several it should be are. Which is correct?

A: Lot, when used as a lot or lots, means "a large number or amount." It is used a pronoun in informal contexts and, in the phrases as the one you used as example, is used as plural.

There are a lot of actors in the cast.

It's what happens with other indefinite pronouns, such as both, few, many (which means "a large number of") others, and several.
All those pronouns are regarded as plural. You don't say "few of them is crazy," but "few of them are crazy"; it's not "many of my neighbors has a summer house on Long Island," but "many of my neighbors have a summer house on Long Island."

A: The original meaning of lot as used here is "a number of units of an article, a single article, or a parcel of articles offered as one item" (Merriam-Webster) and is thus clearly singular (e.g., The driver delivered a lot of trees to the parking lot in time for Christmas).
Early on (evidently 16th century), this concrete sense began to be used in a figurative or transferred sense (e.g., 1575: "a lot of wasps" --OED) and in variations such as "a lot," "lots of," "the lot," etc.
With time and frequent use, the phrase "a lot of" has come to be considered plural. Though lot will forever remain grammatically singular, it will also always be considered plural by most readers and writers.
This presents the careful writer with a dilemma: to be grammatically correct or to blend in with the herd? Should one write "In the background of this picture there are a lot of trees" or ". . . there is a lot of trees"?
In defense of plural construction I have actually encountered the arguments: "the grammar of English has changed" and "a lot of" has become a "syntactic unit" (or a "lexical unit"), both of which I find spurious.
No, dilemmas such as this (some of which have already been noted in this thread) abound in English, and, regrettably? there can be no resolution; each writer must decide for him or herself.

A: Logically you are correct; "a lot" is the subject of the sentence. Colloquially, "a lot" can also mean "many", which takes a plural verb.
If you were talking about a lot more directly as a lot, you would use the singular:

This lot of wares is being shipped to (address).
  Up next at the auction is lot 6124.

For cases where I really mean "many" I try to say either "lots of" or "many" instead of "a lot of X are".

A: It seems a bit too simplistic to me to equate 'a lot' with 'many.' It is definitely counter-habitual, like the 'none of them is' vs 'none of them are' question. But 'a lot,' from any which angle is referring to a single object.
It is also not only with 'a lot' that we tend to keep it in plurals. Even when we say "There are a number of problems with your report," we are taking a single object, which is 'A number' and giving it the plural verb form.
Yet we never say "There ARE a bunch of papers in my study." So it seems to me, at the cost of sounding damning, that while we all say it, because it sounds ok to us, we are grammatically incorrect. Many who say 'None of them are' find it very difficult to adjust.

A: See Cambridge Dictionary:
http://dictionary.cambridge.org/us/grammar/british-grammar/quantifiers/much-many-a-lot-of-lots-of-quantifiers
It says: "We use a lot of and lots of in informal styles. Lots of is more informal than a lot of. A lot of and lots of can both be used with plural countable nouns and with singular uncountable nouns for affirmatives, negatives, and questions."
Based on that, I think that the phrase "a lot of ideas" should be followed with "are".


text:
Q: Cannot ping outside network with these IP rules Here is my firewall script for an internal development server.  I want to be able to get out with http/https but I only want the server accessible via ssh/http from within the internal network.
iptables -P INPUT DROP
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -F
iptables -A INPUT -i eth0 -p tcp -s 10.1.1.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp --sport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp -s 10.1.1.0/24 --dport http -j ACCEPT

Seems to work as I expected but for some reason I cannot get seem to access the outside world.  For example:
super@dev0:~$ ping google.com
ping: unknown host google.com

Since I set my default OUTPUT policy to ACCEPT, shouldn't I be able to get out without any limits?  What am I misunderstanding?

A: You're not allowing related packets back in. What you're seeing is not just that ping doesn't work, but that you can't even resolve DNS names. You need to do a state match for ESTABLISHED and RELATED packets:
iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

You might as well just allow ping inbound too:
iptables -I INPUT 2 -p icmp --icmp-type echo-request -j ACCEPT

A: pings use ICMP.
Your rules with states are for TCP.
The ICMP packets goes out of your network, but are blocked with your "INPUT DROP" default policie.


text:
Q: converting const char to string isn't working Trying to convert type const char to type std::string. All the examples I've seen are for const char *. If I change my type to * the dc.at will fail.
The conversion to string is failing. I've been trawling for an hour, it can't be that hard, I'm clearly missing something simple.
std::string dc = "fdsda4w4bfd*4t4vwrsv";
const char dcchar = dc.at(11);
std::string ms_char = dcchar;

std::string ms_char(dchar); also fails


text:
Q: VIM: Replace function call without the arguments how can i search and replace a function call, but without the arguments of the function?
For short, i will search and replace from foobar(arg1, arg2) to foobar: arg1, arg2;
My goal is to keep  the arg1, arg2.
How can i solve this? Is there a best practice?

A: Use following command:
:%s/\v(\w+)\(([^()]*)\)/\1: \2;/g

NOTE This does not work if there nested function call.
See a demo.

A: Here's one approach that works with arbitrarily named arguments:
:%s/\(\<foobar\)(\(.*\))/\1: \2;/g

Basically, it captures (via \(...\)) the function name and the arguments (without the parentheses), and then re-assembles it in a :substitute command. The \< asserts a keyword boundary, so that it doesn't match myfoobar(.
Caveats
Note that regular expressions are limited in their ability to parse programming language constructs; a proper refactoring tool allows more precise and safer modifications.
One problem in your example is how to deal with the arguments; I've chosen a greedy match (.*), but this would improperly handle a construct like foobar(arg1, arg2); baz(arg3, arg4). A non-greedy match (.\{-} in Vim), on the other hand, would fail to capture embedded sub-calls like foobar(hostname(), arg2). Writing a regular expression to handle all cases is close to impossible, so it's your responsibility to use this wisely (maybe by adding the c flag to the :substitute command and acknowledging each replacement manually).

A: Try this:
Insert a line at the top of the file - we'll write a macro here. (That's the letter O, not a zero.)
ggO

Instructions for searching for a string of word-characters followed by an open paren, and leave the cursor at the end of the match
/\w*(/e<Ctrl-V><Ctrl-M>

Then we'd go to the matching parenthesis and replace it with a semicolon
%r;

Jump back to the other parenthesis (ctrl-letter O again, not zero)
<Ctrl-V><Ctrl-O>

Replace this parenthesis with :
s:<Space><Ctrl-V><Esc>

Then execute this macro again (assuming it is in the q register)
@q

Our macro is done, exit insert mode (your line should read: /\w*(/e^M%r;^Os: ^[@q now)
<Esc>

Pull the line into the q register (which also removes it from the current file, returning your file to its previous pristine state)
"qdd

Finally, the Big Moment: execute the recursive macro we've built in the @q register, which will transform the whole file.
@q

BENEFITS: it handles nested functions correctly, since it is not relying on the regular expressions that have trouble capturing parenthesis matching. Instead we rely on the % command to match parentheses.
Demo:
foo(bar, baz)
foo(foo(bar), baz(), foo(foo, foo, foo))
foo(bar(baz()))

turns into
foo: bar, baz;
foo: foo: bar;, baz: ;, foo: foo, foo, foo;;
foo: bar: baz: ;;;

EDIT: typo (\w, not \e in search).

A: You may search for
(foobar)(\()(arg1, arg2)(\))

and replace it with
\1: \3;

(demo @ regex101)
So, in VIM it may be something like
:s/(foobar)(\()(arg1, arg2)(\))/\1: \3;/g


text:
Q: How to control or prevent rendering of HTML page till it download all resource file? How to control rendering of HTML page till it download its all HTML, CSS and JS dependencies?
Adding to the above question, how to validate that all the dependencies have been downloaded successfully ?
FRAMEWORK I AM USING:- jQuery, Twitter Bootstarp
Browser compatibility required:- IE8+, Chrome, Firefox, Safari

A: This might work. Basically, you hide the body by default. When everything loads, you show it:
HTML:
<body class="placeholder">
  ...
</body>

CSS:
.placeholder {
  display: none;
}

JavaScript:
$(document).load(function() {
  $('body').removeClass('placeholder');
});

Just as a question: why would you need to do this?


text:
Q: Kurento recording not recording any data I am working a little bit off of the one2many call tutorial, the one2many call advanced tutorial, and the hello-world recording but I cannot seem to get my recording to work. It creates the file, but it is always 382 bytes with no playable content. There are no errors being thrown and communication between the browser and app server are working without failure as well.
This is what the code that handles the initial recording request looks like:
       //1. Media logic
        BroadcastPipeline broadcastPipeline = new BroadcastPipeline(kurento, "test-broadcast");

        //2. User session
        broadcasterUserSession = new UserSession(session);
        broadcasterUserSession.setWebRtcEndpoint(broadcastPipeline.getWebRtcEndpoint());

        //3. SDP negotiation
        String broadcastSdpOffer = jsonMessage.get("sdpOffer").getAsString();
        String broadcastSdpAnswer = broadcastPipeline.generateSdpAnswerForBroadcaster(broadcastSdpOffer);

        //4. Gather ICE candidates
        broadcastPipeline.getWebRtcEndpoint().addOnIceCandidateListener(
                new EventListener<OnIceCandidateEvent>() {

                    @Override
                    public void onEvent(OnIceCandidateEvent event) {
                        JsonObject response = new JsonObject();
                        response.addProperty("id", "iceCandidate");
                        response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                        try {
                            synchronized (session) {
                                session.sendMessage(new TextMessage(response.toString()));
                            }
                        } catch (IOException e) {
                            log.debug(e.getMessage());
                        }
                    }
                });

        JsonObject startBroadcast = new JsonObject();

        startBroadcast.addProperty("id", "broadcasterResponse");
        startBroadcast.addProperty("response", "accepted");
        startBroadcast.addProperty("sdpAnswer", broadcastSdpAnswer);

        synchronized (broadcasterUserSession){
            session.sendMessage(new TextMessage(startBroadcast.toString()));
        }

        broadcastPipeline.getWebRtcEndpoint().gatherCandidates();

        broadcastPipeline.startRecording();

UserSession is all but the same as hello-world-recording. BroadcastMediaPipeline however looks like this:
public static final String RECORDING_PATH = "file:///tmp/";
public static final String RECORDING_EXT = ".webm";

private final MediaPipeline mediaPipeline;
private final WebRtcEndpoint webRtcEndpoint;
private final RecorderEndpoint recorderEndpoint;

public BroadcastPipeline(KurentoClient kurento, String broadcastTitle){
    log.info("Creating Broadcast pipeline");

    //Create the media pipeline
    mediaPipeline = kurento.createMediaPipeline();

    //Create the broadcaster pipeline
    webRtcEndpoint = new WebRtcEndpoint.Builder(mediaPipeline).build();

    //Create the recording endpoint for the broadcast
    recorderEndpoint = new RecorderEndpoint.Builder(mediaPipeline, RECORDING_PATH + broadcastTitle + RECORDING_EXT).build();

    webRtcEndpoint.connect(recorderEndpoint);
}

public void startRecording(){
    try{
        recorderEndpoint.record();
        log.info("Started recording broadcast");
    }
    catch(Exception e){
        log.error("Something bad happended: + " + e.getMessage());
    }
}
public MediaPipeline getMediaPipeline(){
    return mediaPipeline;
}

public String generateSdpAnswerForBroadcaster(String sdpOffer){
    return webRtcEndpoint.processOffer(sdpOffer);
}

public WebRtcEndpoint getWebRtcEndpoint(){
    return webRtcEndpoint;
}

public WebRtcEndpoint buildViewerEndpoint(){
    return (new WebRtcEndpoint.Builder(mediaPipeline).build());
}

If more information is needed to help resolve this I will provide it.

A: For the recorder file to be generated correctly you need to stop the recording or to release the recorder endpoint. I don't see this happening in your code.
To fix it, when you have finished your recording (e.g. with a finish buttom or something like that), you need to execute one of the following
recorderEndpoint.stop(); //this stops the recording
recorderEndpoint.release(); //this stops recording when releasing the recorder
mediaPipeline.release(); //this relases all the pipeline, including recorder

A: Ensure you setting media profile with RecorderEndpoint like :
recorderCaller
                = new RecorderEndpoint.Builder(pipeline, RECORD_PATH)
                        .stopOnEndOfStream()
                        .withMediaProfile(isAudioOnly ? MediaProfileSpecType.MP4_AUDIO_ONLY : MediaProfileSpecType.MP4)
                        .build();
            hubportCaller.connect(recorderCaller);
            recorderCaller.record();


text:
Q: How to separate the highlights panel fields layout from the popover fields layout in Lightning experience I am setting up my popover views for all objects,
For example, for the Contact object - here is the popover in the Organization object:

And here is the highlight panel of the contact object:

The problem is that both field sets are defined from the primary compact layout that I select from the layout assignment page, but I need a different set for the highlight panel and a different one for the popover:

Does anyone know if this could be done?
Another question is - does anyone know where do I define related lists for the popover - I can see them but cannot find a place to customize:

Thanks
Itai


text:
Q: Trying to sub inside a embed with swears, doesn't work for strings in the last list I'm attempting to make an urban dictionary command, I am substituting swear words with the word '[NSFW]' though it only works when I place the swear in the last part of the list.
My Code:
nsfwdefine = ["swear1", "swear2","swear3"]

// there are headers I just didn't add them because it has my apikey.

async with ClientSession() as session:
    async with session.get(url, headers=headers, params=querystring) as response:
        r = await response.json()
        embed = discord.Embed(title=f"All result for {term}", description=None,color=0xff0000)
        embed.set_author(name=ctx.author.display_name, url="https://ass.com/", icon_url=ctx.author.avatar_url)
        definition = r['list'][0]['definition']
        embed.add_field(name=term, value=definition, inline=False)
        txt = str(definition)
        for y in nsfwdefine:
          x = re.sub(y, '[NSFW]', txt)
        print(x)

embed2=discord.Embed(title=f"All results for {term}", description=x)
embed2.add_field(name="Info",value=":warning: If your message contains the word [NSFW] then you need to rerun the defintion in a NSFW Channel.")

(await ctx.send(embed = embed2))

I'm not entirely sure what's going on, does anyone know the solution to this?

A: I'm not sure why you're using re.sub() though you can achieve this using the string replace() method.
swears = ["swear1", "swear2", "swear3"]
sentence = "hello swear1 this is swear2 a sample swear3 sentence!"

for word in swears:
    sentence = sentence.replace(word, "[NSFW]")

print(sentence)

Output:
hello [NSFW] this is [NSFW] a sample [NSFW] sentance!
Run Code Snippet


text:
Q: wired java func always return null protected String doInBackground(View... params) {
    mView = params[0];
    Account[] accounts = com.xxx.xxx.app.AccountManager
            .get(mView.getContext()).getAccounts();
    if (accounts.length > 0) {
        return HttpUtils.getVPNConf(accounts[0].name);
    } else {
        Log.e(TAG, "get vpnconf failed");
    }
    return null;
}

in Android 4.2 emulator
here is a code snippet, accounts.length == 1 but either DEBUG or nonDEBUG the func always return null
i am a java newbie, can someone explain it for me?

A: There possibly three point(maybe more) that may cause return,

*

*check your accounts[0].name

*check the function of HttpUtils.getVPNConf

*double check the length of the Account[]

also, have you added the permission for getting account information in manifest?
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>

checking carefully should be able to solve your problem.


text:
Q: how to link external libraries and external include directory in configure.ac and makefile.am if I want to create configure.ac and makefile.am from scratch to build my project, the project contains project__include directory, project__lib directory and src directory inside it there are some .c files and .h header files
all what I need is to link the src directory to the project__include and project__lib directory, and link the src with pthread library.
can any one help me?
also, is AC_CHECK_HEADER is used to include header file into the project? or just for checking if it is included already in the project.


text:
Q: How to rewrite this nested call to set using fat arrow es6 syntax? In https://github.com/yeahoffline/redis-mock/blob/master/test/client/redis-mock.keys.test.js:
  beforeEach(function (done) {
    r.set("hello", "test", function () {
      r.set("hallo", "test", function () {
        r.set("hxlo", "test", done);
      });
    });
  });

What is the way to convert this to ES6 fat arrow syntax? I tried looking for an online converter but failed to find one.

A:   beforeEach((done) => {
    r.set("hello", "test", () => {
      r.set("hallo", "test", () => {
        r.set("hxlo", "test", done);
      });
    });
  });

If it was a standalone function you would write
const setHellos = (done) => { .... }


text:
Q: Modify undo/redo behaviour on a textarea using jquery I need to handle the events undo and redo myself when a user selects undo/redo from context menu or presses ctrl z in a textarea.
How can i prevent the default behavior and add custom behavior.

A: You can detect ctrl+z on keyup() with:
var ctrlZ = e.ctrlKey && e.which === 90
if (ctrlZ) { ... }

And context menu on mousedown() with:
var rightClick = e.which === 2
if (rightClick) { ... }


text:
Q: Table scan matching one of a number of fields - OR vs multiple statements I'm facing having to write a number of queries which will involve table scans on some fairly large tables (couple of million records).
(I know this is a terrible idea and I'm pushing for an alternative approach that won't involve this, but right now it's what I'm stuck with. And creating indexes on the relevant fields will probably not be an approved option either.)
For some tables, there are multiple fields which may match the target value.
I would think, but I'd just like confirmation, that a single query with OR would be quicker than multiple queries. That is:
SELECT keyinfo FROM TABLE1 WHERE field1 = target OR field2 = target OR field3 = target;

would be better than
SELECT whatever FROM TABLE1 WHERE field1 = target;
SELECT whatever FROM TABLE1 WHERE field2 = target;
SELECT whatever FROM TABLE1 WHERE field3 = target;

Intuitively this seems correct, since it only has to scan the table once. But it does have to test multiple fields, so not sure how much of the gain you lose on that. A quick test bears this out, but I'm not sure if there's any temporary indexes being built in the background which are affecting the results.
Further info:
I would expect that for most cases no match will be found, but I do need all matches if any exist, so I can't just limit it to FETCH FIRST 1 ROWS ONLY.
Also, it's z/OS DB2.
Given that I'll probably need to run this for multiple targets, I'm probably going to end up pulling all the relevant fields out into a temporary table, as I should be able to build an index on that, and overall that should be much faster. But I'm just curious now about the table scan question.

A: The or is not necessarily better.  Databases can have a hard time using indexes for or conditions on multiple fields.  DB2 might be good enough to optimize for this case.  But, you can compare the performance (and execution plan) to:
SELECT whatever FROM TABLE1 WHERE field1 = target
UNION ALL
SELECT whatever FROM TABLE1 WHERE field2 = target AND field1 <> target
UNION ALL
SELECT whatever FROM TABLE1 WHERE field3 = target AND field1 <> targe AND field2 <> target;

A: The database builds an execution plan based on the query without the values for the parameters. This query is used every time the query is run regardless of what the actual values are supplied.
I think, your best bet would be to look at the execution plan or explain plan of both kind of queries; using OR and using UNION clause.


text:
Q: iterate JSON, swift I am working on swift.
The response that I get from the web server is different when i test it on Postman/ browser and mobile emulator.
Postman/browser response :
items: [
    {
    itemId: 500,
    name: "ABC"
    },
    {
    itemId: 500,
    name: "ABC"
    }
    ]

Response in iOS :
 items: (
    {
    itemId: 500,
    name: "ABC"
    },
    {
    itemId: 500,
    name: "ABC"
    }
    )

I would like to know how to iterate through the array, but since the result is not an array on iOS I am not sure on how should I go about it. Also, I retrieve a result of around 25-30 items in the array. I have a some set of variables too, that are provided in the response after the array.

A: There is no problem with your response in ios when you print an array it will print with () brackets instead of [] brackets and dictionary will be print with {} braces.
As you say let items : [NSDictionary]! your items array contain dictionary then you can iterate it like this
for item in items {
    print(item["itemId"])
    print(item["name"])
}

A: As others have said, your response in iOS is fine.
You can iterate over it simply with:
for item in items {

// do what you want with each item

}

It works fine in a Playground:
let items = [["itemId": 500, "name" : "ABC"], [ "itemId": 500, "name": "ABC"]] as NSArray

for item in items {
    print(item as! NSDictionary) // prints each dictionary as expected
}

A: You have an array of dictionaries. So, you can iterate like-
for itemDict in items {
    let itemId = itemDict["itemId"]
    println("Item ID: \(itemId)")

    let name = itemDict["name"]
    println("Item name: \(name)")
}


text:
Q: Changing the output of APT to contain the repository from where it originates I have a few repositories that are added to the sources other than the original. After updating, doing an apt search gives me a list like this:

snp-sites/disco 2.4.1-1 amd64
    Binary code for the package snp-sites
sparse/disco 0.6.0-3 amd64
    semantic parser of source files
sparse-test-inspect/disco 0.6.0-3 amd64
    semantic parser of source files
stalin/disco 0.11-6build1 amd64
    An extremely aggressive Scheme compiler
tcc/disco 0.9.27-8 amd64
    small ANSI C compiler

Is it possible to get apt to display the repository source as well? As in can the maintainers add a feature to display the repository source


text:
Q: Multi-context requirejs and inheriting dependencies between contexts I am using RequireJs to load AMD-modules on my company's main web site. We are also using requireJS to load modules hosted on separate domains. requireJS supports this using the "context"-field; ie. create a separate sandboxed environment with a separate baseUrl.
The problem at hand is when we want the two separate contexts to share a common object; eg. jquery (to avoid loading it twice) or a pubsub-implementation that trigger events in between widgets.
I've figured a way to inject modules in between contexts, using a define function together with a global requireJS
main.js - hosted on http://example.com/src/main.js
require(['jquery'], functin($){

    // create sandbox/contexted instance of requireJs
    var sandbox = requireJS.config({
        context: "myContext",
        baseUrl : 'http://otherdomain.com/src'
    });

    // load module (with internal dependencies) from other domain
    sandbox.require(['modules/bootstrap.js'], function(bootstrap){
        bootstrap.run();
    });

});

bootstrap.js - eg. hosted on http://widgets.com/src/modules/bootstrap.js
define(function(){

    // define jquery into sandboxed environemnt
    requireJs('jquery', function($) {
        define('jquery', function(){
            return window.jQuery;
       });
    });

    // obtain sandboxed instance from parent
    var sandbox = requireJs.config({
        context: "myContext"
    });

    sandbox(['jquery'], function($){
        console.log($);
    });

});

The problem is that if Im defining jquery (or any other module that returns a function), tje "requreJS"-way (not using globals) it will always throw an error
    // define jquery into sandboxed environemnt
    requireJs('jquery', function($) {
        define('jquery', $);
    });

Is this a bug or a feature ?

A: Ive actually solved this myself. The trick is to wrap the returned function within a new anonymous function.
// inject global module into contexted require
function injectContext(moduleId, module){
    var m = module;
    if(typeof module === 'function') {
        m = function() {
            return module;
        };
    }
    define(moduleId, m);
}


text:
Q: Как правильно разложить функцию в степенной ряд? Хочу написать разложение в степенной ряд функцию ln(x+1) по известной всем формуле (можно посмотреть на сайте http://edu.sernam.ru/book_p_math2.php?id=81). Либо я не понимаю смысл разложения, либо что-то делаю не так, но итоговый ответ не удовлетворяет. Программа, по сути, простая.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;

int main()
{
    setlocale(0, "");

    double x, val, sum = 0;
    int i;
    cin >> x;
    for (i = 1; i <= 100; i++)
    {
        val = (pow(-1, (i + 1))*pow(x, i)) / i;
        cout << " " << val;
        sum += val;
        cout << " " << sum << endl;
    }
    cout << "Логарифм мой: " << sum << endl;
    cout << "Логарифм реальный: " << log(x+1);

    cout << endl;
    system("pause");
    return 0;
}

A: Видимо, вы забываете, что этот ряд сходится только для |x|<1.
У вас считает правильно, но несколько неоптимально, так что я переписал заново.
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    double x;
    cout << "Input x (-1,1): ";
    cin >> x;
    if (fabs(x) >= 1.0)
    {
        cerr << "Wrong value\n";
        return 1;
    }
    double sum = x, term = x;
    double eps = 1e-8;
    for(int k = 2; fabs(term)/sum >= eps ; ++k)
    {
        sum += term *= -x*(k-1)/k;
    }
    cout << "Sum is      " << setprecision(10) << sum << endl;
    cout << "Log(1+x) is " << setprecision(10) << log(1+x) << endl;

}


text:
Q: How to invoke a click button? I need help with invoking method into this class button.
The HTML code on the website for this is shown like this:

    Mot de passe oublié ?
    <button class="btn btn-primary login-btn" type="button" ng-click="login()">Se connecter</button>

I tried the codes below using powershell but it doesnt work for the button
$xe = New-Object -Com "InternetExplorer.Application"
$xe.Visible = $true
$IURL = 'http://example.com/doc/page/login.asp'

$xe.Navigate($IURL)
while ($xe.Busy -eq $true) {
    Start-Sleep -Milliseconds 1000;
}

# It's OK for these ID's
$xe.Document.IHTMLDocument3_getElementByID('username').Value = 'myloginadmin'
$xe.Document.IHTMLDocument3_getElementByID('password').Value = 'mypassword'

# invoke click button ?
$xe.Document.IHTMLDocument3_getElementsByTagName('button').Click()

I have this error message:

Échec lors de l'appel de la méthode, car [System.__ComObject] ne contient pas de méthode
nommée « click ».
Au caractère Ligne:1 : 1
+ $xe.Document.IHTMLDocument3_getElementsByTagName('button').Click()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (click:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Any ideas?

A: Try this
$xe.Document.getElementsByTagName('button').Click()


text:
Q: logrotate : Contents are missing I'm using logrotate to rotate my log file periodically (in my case every 1 hour checking for log file size and rotate if needed using cron). I'm facing a serious issue in it.
The following files should have been created -- user.log.gz.4, user.log.gz.3, user.log.gz.2, user.log.1, user.log.
But sometimes any one of the file goes missing, sometimes file contents are missing at the end of the file, and sometimes the content of the files are repeating. It's strange. Please can someone help me solve the issue.
My logrotate Configuration:
/var/log/project_name/*.log {
  size 512M
  copytruncate
  rotate 30
  compress
  notifempty
  missingok
}

A: This is probably caused by some process writing to the logs while they're being rotated, you need to include a delaycompress declaration in your configuration, this sort of question is better asked in 'SuperUser' or 'ServerFault'


text:
Q: Error while mopub integartion I am integrating MOPUB ADs in application. I am following MOPUB SDK integration steps from https://www.mopub.com/resources/docs/android-sdk-integration/android-getting-started/
After adding mopub-volley-1.1.0.jar, I got following error.
Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'. com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/mopub/volley/AuthFailureError.class
My build.gradle code is
apply plugin: 'com.android.application'
android {
    compileSdkVersion 24
    buildToolsVersion '24.0.1'

    defaultConfig {
        multiDexEnabled true
        applicationId "com.mopubdemo.android"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 27
        versionName '2.05'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/plexus/components.xml'
   }
}

dependencies {
   compile files('libs/universal-image-loader-1.9.3.jar')
   compile files('libs/FlurryAnalytics-6.2.0.jar')
   compile files('libs/acra-4.6.1.jar')

   compile project(':mopub-sdk:mopub-sdk-native-video')
   compile project(':mopub-sdk:mopub-sdk-native-static')
   compile project(':mopub-sdk:mopub-sdk-banner')
   compile project(':mopub-sdk:mopub-sdk-rewardedvideo')
   compile project(':mopub-sdk')
   compile project(':mopub-sdk:mopub-sdk-interstitial')

   androidTestCompile 'junit:junit:4.12'
   compile 'com.android.support:multidex:1.0.1'
   compile 'com.github.johnkil.android-robototextview:robototextview:2.4.2'
   compile 'com.google.code.gson:gson:2.4'
   compile 'com.rengwuxian.materialedittext:library:2.1.4'
   compile 'com.nhaarman.listviewanimations:lib-core:3.1.0@aar'
   compile 'com.nhaarman.listviewanimations:lib-manipulation:3.1.0@aar'
   compile 'com.nhaarman.listviewanimations:lib-core-slh:3.1.0@aar'
   compile 'org.ocpsoft.prettytime:prettytime:4.0.0.Final'
   compile 'com.koushikdutta.ion:ion:2.1.6'
   compile 'pub.devrel:easypermissions:0.1.5'
   compile 'com.android.support:appcompat-v7:24.2.1'
   compile 'com.android.support:cardview-v7:24.1.1'
   compile 'com.android.support:support-v4:24.1.1'
   compile 'com.android.support:recyclerview-v7:24.1.1'
   compile 'com.android.support:support-annotations:24.1.1'
   compile 'com.google.android.gms:play-services:10.2.1'

  compile files('libs/mopub-volley-1.1.0.jar')
}

A: Remove this line and then sync
compile files('libs/mopub-volley-1.1.0.jar')


text:
Q: How can I center my circuit? \documentclass[11pt,letterpaper]{article}

\usepackage[latin1]{inputenc}
\usepackage{graphicx}
\usepackage{geometry}[top=2cm,bottom=2cm,hmargin=2.5cm]
\usepackage[american]{circuitikz}

\begin{document}

\begin{figure}\centering

\begin {circuitikz} [scale = 0.7] [american][H]
\draw

(0,0) node[op amp] (opamp1) {}

(6,-0.7) node[op amp] (opamp2) {}

(opamp1.-) to [short,-] ++ (-2,0)

to [R, l_=$1K$] ++(-5,0) node[left]{$V_1$}

to [V, l_=$3\;V$] ++(0,-3)

to node[ground]{} ++(0,0)

(-6.5,-4) to node[ground]{} ++(0,0)

to [V, v=$6\;V$, invert] ++(0,3)

to [R, l_=$1K$] ++(3,0)

to [short,-*] ++(0,1.7)

to [short,-] ++(0,3)

to [R, l_=$1K$] ++ (3,0)

to[short,-] ++(0,0) coordinate (leftC)

to (leftC -| opamp1.out)

to[short,-*] (opamp1.out)

(opamp1.+) to [short,-] ++ (-1,0)

to node[ground]{} ++(0,-1)

(opamp1.out) [short,-] ++(0,0)

to [R, l_=$1K$] ++ (2,0)

coordinate (leftC)

to (leftC -| opamp2.-)

to[short,-] (opamp2.-)

(opamp2.-) to [short, *-] ++(0,3)

 to [short, -] ++(2,0)

to [R, l_=$2K \Omega$] ++(3,0)

to [short, -] ++(0,-3.7)

coordinate (leftC)

to (leftC -| opamp2.out)

to[short,-] (opamp2.out)

(opamp2.up) to [short, -]  ++(0,5)

to [short, -] ++(8,0)

to [V,l_=$15v$] ++(0,-4)

to [V,l_=$15v$] ++(0,-4)

 to[short,-] ++(0,0) coordinate (leftC)

  to (leftC -| opamp2.down)

  to[short,-] (opamp2.down)

(opamp1.up) to [short, -]  ++(0,4.3)

to [short, -] ++(6,0)

(opamp1.down) to [short, -]  ++(0,-2.15)

to [short, -] ++(6,0)

(opamp2.+) -| ++(0,-0.4) node[ground]{}

(opamp2.out) to [short, -o] ++(3,0) node[right]{$V_o$}

(13.9,0)[short,*-] ++(0,1) to node[ground]{} ++(2,0)

;

\end{circuitikz}

\end{figure}

\end{document}

A: I would redraw your circuit scheme as follows:
\documentclass[11pt]{article}
\usepackage[letterpaper,
            vmargin=2cm, hmargin=2.5cm]{geometry}
\usepackage[american,siunitx]{circuitikz}

%---------------- show page layout. don't use in a real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%---------------------------------------------------------------%

\begin{document}
    \begin{figure}
    \centering
    \ctikzset{bipoles/length=1cm, nodes width=0.08}
\begin{circuitikz}
\node[op amp] (oa1) {};
\draw   (oa1.out)   to [R=1<\kilo\ohm>,*-*] ++ (2,0)
                    node[op amp,anchor=-] (oa2) {}
        (oa1.-)     -- ++ (-1,0)                coordinate (aux1)
                    --  ++ (0,1)                coordinate (aux2)
                    to [R=1<\kilo\ohm>] ++ (2,0)
                    --  (aux2 -| oa1.out) -- (oa1.out)
        (oa1.+)     -- ++ (0,-0.5) node[ground] {}
%
        (aux1)      to [R=1<\kilo\ohm>,*-] ++(-3.5,0) node[left] {$V_1$}
                    to [V_=3<\volt>] ++ (0,-1.5)
                    node[ground] {}
        (aux1)      -- ++ (0,-1)
                    to [R=1<\kilo\ohm>] ++(-2,0) node[left] {$V_1$}
                    to [V_=6<\volt>] ++ (0,-1.5)
                    node[ground] {}
%%
        (oa2.out)   to [short,  -*] ++ (1,0)    coordinate (aux3)
        (oa2.-)     |-  ++ (1,1)                coordinate (aux4)
                    to [R=2<\kilo\ohm>]  (aux4 -| aux3) -- (aux3)
                    to [short, -o] ++ (1,0) node[right] {$V_o$}
        (oa2.+)     -- ++ (0,-0.5) node[ground] {}
%%% suply
        (oa1.up)    |- ($(oa2.up)+(0,2)$)
                    -- ++ (4,0)                 coordinate (aux5)
        (oa2.up)    -- (oa2.up |- aux5)
        (aux5)      to [V_=15<\volt>,-*]    (aux5 |- oa2.out)
        (oa1.down)  |- ($(oa2.down)-(0,2)$)
                    -- ++ (4,0)                 coordinate (aux6)
        (aux5 |- oa2.out)   to [V_=-15<\volt>]    (aux6)
        (aux5 |- oa2.out)   -| ++ (1,-0.5) node[ground] {}
    ;
\end{circuitikz}
    \end{figure}
\end{document}

which after compilation gives:

(red lines mark text width)
In above MWE are in comparison to yours changed:

*

*size of bipoles are reduced

*used is siunitx notation for units

*all circuits elements are positioned relative to neighbors one and slightly reduced

*image scaling is omitted

*also is omitted unknown circuitikz option  H
Edit:
Corrected is scheme. Now is as OP provide it in question.

A: Remove centering and add the following line for \hspace  -- rest no change -- your figure will always extend into margins being large

\begin{figure}
\hspace{-2cm}
........
\end{figure}


text:
Q: Привести число к определенному виду Df
    Телефон
0  749578267921216406327
1  84951491991
2  79037481292
3  74992506983
4  84957975576
5  749567348106039156

Как оставить только первые 11 цифр в строке?

A: df["Телефон"] = df["Телефон"].str[:11]

74956895325
84951491991
79037481292
79269431224

A: Альтернативный вариант:
df["Телефон"] = df["Телефон"].str.slice(0, 11)

результат:
In [219]: df
Out[219]:
       Телефон
0  74957826792
1  84951491991
2  79037481292
3  74992506983
4  84957975576
5  74956734810


text:
Q: delphi opensoure xml writer & reader could you recommend a good XML open source writer and reader,
to generate and read XMLs?

A: NativeXml and OmniXML are open source and popular XML libraries for Delphi. ADOM is another, it is included in some versions of Delphi. For some advanced use cases, libxml with the Delphi wrapper Libxml2 might be interesting.


text:
Q: Android java.lang.VerifyError I am attempting to launch my app on an Android device running 4.4.2.
Yet every-time I attempt to run, the error below appears:
02-24 22:23:30.421 18276-18276/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.android.app, PID: 18276
                                                   java.lang.VerifyError: com/google/android/gms/measurement/internal/zzt
                                                       at com.google.android.gms.measurement.AppMeasurementContentProvider.onCreate(Unknown Source)
                                                       at android.content.ContentProvider.attachInfo(ContentProvider.java:1591)
                                                       at android.content.ContentProvider.attachInfo(ContentProvider.java:1562)
                                                       at android.app.ActivityThread.installProvider(ActivityThread.java:5118)
                                                       at android.app.ActivityThread.installContentProviders(ActivityThread.java:4713)
                                                       at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4596)
                                                       at android.app.ActivityThread.access$1600(ActivityThread.java:169)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:146)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5487)
                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:515)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                       at dalvik.system.NativeStart.main(Native Method)

Clicking through on the ContentProvider link, directs to below, but do not know where to go from here...
   public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
            @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
        if ("*/*".equals(mimeTypeFilter)) {
            // If they can take anything, the untyped open call is good enough.
            return openAssetFile(uri, "r");
        }
        String baseType = getType(uri);
        if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
            // Use old untyped open call if this provider has a type for this
            // URI and it matches the request.
            return openAssetFile(uri, "r");
        }
        throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
    }

I have read it may have something to do with the versioning being out of sync.
The build.gradle file is:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "22.0.1" // 22.0.1

    defaultConfig {
        applicationId "com.example.android.app"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.0'
    compile 'com.google.android.gms:play-services:8.3.0'
    compile 'com.mcxiaoke.volley:library:1.0.+'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.google.code.gson:gson:2.6.1'
    compile 'com.android.support:support-v4:23.1.0'
    compile 'com.android.support:recyclerview-v7:23.1.0'
    compile 'com.firebase:firebase-client-android:2.5.2+'
}

How can I alleviate this issue?


text:
Q: How to decode json array to find the last value of a variable using Perl? I have a Json array of objects that I am trying to decode in perl. The json array looks like this :
[
  {
    "name": "a123",
    "enroll": "12a123",
    "cs": {
      "year1": {
        "status": {
          "oldvalue": "pending",
          "new value": "complete"
        }
      }
    }
  },
  {
    "name": "b123",
    "enroll": "12b123",
    "ecm": {
      "year1": {
        "flag": {
          "oldvalue": "null",
          "new value": "ok"
        }
      }
    }
  },
  {
    "name": "c123",
    "enroll": "12c123",
    "cs": {
      "year1": {
        "status": {
          "oldvalue": "complete",
          "new value": "run new"
        }
      }
    }
  }
]

I want to find the value of the {"status"}->{"new value"} from the last occurrence in the Json file.The output here should be "run new". FYI : not all fields are present in every object. Any help on how to parse this array will be highly appreciated.

A: I'd use a module for this - CPAN has a module called JSON:Parse which looks to do what you want:
use JSON::Parse 'parse_json';
my $json = loadJsonString();   # Load the JSON string from somewhere
my $courses = parse_json($json);
my $lastCourse = $courses->[-1];
my $newValue = $lastCourse->{cs}{year1}{status}{"new value"};