What is the expectation of the order of automorphism group in Erdos-Renyi random graphs?

Question: Suppose $\Gamma(V, E) \sim G(n, p)$ is an Erdos-Reyi random graph with $n$ vertices and edge probability $p$. What is the expected size of the automorphism group of $\Gamma$?
What have I tried:
Suppose, $I_{Aut(\Gamma)}$ is the indicator function of $Aut(\Gamma)$ in $Sym(V)$. Then $|Aut(\Gamma)| = \sum_{\sigma \in Sym(V)} I_{Aut(\Gamma)}(\sigma)$. Thus $$E(|Aut(\Gamma)|) = E(\sum_{\sigma \in Sym(V)} I_{Aut(\Gamma)}(\sigma)) = \sum_{\sigma \in Sym(V)} E(I_{Aut(\Gamma)}(\sigma)) = \sum_{\sigma \in Sym(V)} P(\sigma \in Aut(\Gamma))$$ However, I do not know how to proceed further.
Here is also the analysis of the situation for small $n$:
If $n = 1$, then $E(|Aut(\Gamma)|) = 1$ because $|Aut(\Gamma)| = 1$ almost surely.
If $n = 2$, then $E(|Aut(\Gamma)|) = 2$ because $|Aut(\Gamma)| = 2$ almost surely.
If $n = 3$, then $|Aut(\Gamma)| = 6$ with probability $p^3 + (1 - p)^3$ and $|Aut(\Gamma)| = 2$ with probability with probability $1 - (p^3 + (1 - p)^3)$. Thus $E(|Aut(\Gamma)|) = 2 + 4(p^3 + (1 - p)^3)$.
Also note, that because the automorphism group of a graph is always isomorphic to the automorphism group of its complement graph, that value is invariant under the map $p \mapsto (1-p)$
Comment: Did you try Google? I quickly found a few papers from the 80s which suggested that random graphs have trivial automorphism groups. ("Suggested" as they either had assumptions or proved that $|\operatorname{Aut}(\Gamma)|$ is very small.) I guess a more dedicated Google will uncover the result you are looking for.
Answer: It is a theorem that the proportion of isomorphism classes of graphs on $n$ vertices with with a non-identity automorphism goes to zero as $n$ increases.
It's quite standard; one proof can be found in "Algebraic Graph Theory"
by me and Royle.


Unable to send token from AngularJS to Laravel API

Question: This is how I am handling the process of sendig the csrf_token().
In the  section I added the token as a constant.

In the productService when I send post data, I include the following:
headers: {'Content-Type': 'multipart/x-www-form-urlencoded', 'X-XSRF-TOKEN': CSRF_TOKEN}

Then I receive from Laravel the error:
DecryptException: invalid data

If I remove X-XSRF-TOKEN from headers: above, then I receive the TokenMismatchException.
As suggested from another post, I encrypted the csrf_token(), since Laravel is expecting the token to be encrypted, but even then I still receive DecryptException: invalid data.
Comment: Use your browser's *Network* console to confirm the value sent in the request. I'd also use `json_encode()` to print the token in case it contains any unsafe characters (like single-quote), ie `.constant('CSRF_TOKEN', )`
Comment: @Phil Yes it is. I appreciate the tip of the Network console, I was always using the raw console only.
Answer: Changing X-XSRF-TOKEN to X-CSRF-TOKEN solved the problem.
When testing, I had to destroy the cookie and restart the browser for the token to kick in.
Comment: I am not using exactly the same method of constant but I use the same function and store the token in the meta tag. `` But I get `token mismatch` if I use `CSRF` and `cannot decrypt` error if using `XSRF`! I am using laravel 5.And I face this on server on local angular default generates a token with each request
Comment: I have added a question here,if you could help http://stackoverflow.com/questions/29863483/unable-to-decryt-csrf-xsrf-token-in-laravel-sent-through-angular
Answer: change XSRF to CSRF and restart your browser.


How to export default 2 constructors?

Question: I try to run the React JS file where you can see below
const PostArticles = ({classes, ...props})

const Categories = ({classes, ...props})

export default connect(mapStateToProps, mapActionToProps)(withStyles(styles)(PostArticles));

export default connect(mapStateToPropsCat, mapActionToPropsCat)(withStyles(styles)(Categories));

I want to export these 2 constructors to be print data from mongodb by using react js but I get this error
SyntaxError: C:\Users\hatzi\Desktop\restapi-client\src\components\PostArticles.js: Only one default export allowed per module. (197:0)
Can you help me please?
Comment: Please cut it down to a [mre], then.
Comment: [Please don't post images of code and errors](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557)
Comment: I know but the code was very big to copy paste it
Comment: Better? I need this help
Answer: So the error clearly states that you cannot have more than one default export.
Instead, you can use a named export.
For example:
const PostArticles = ({classes, ...props})

const Categories = ({classes, ...props})

export const PostArticlesConnected = connect(mapStateToProps, mapActionToProps)(withStyles(styles)(PostArticles));

export const CategoriesConnected = connect(mapStateToPropsCat, mapActionToPropsCat)(withStyles(styles)(Categories));

Please also look at the documentation.
If you indeed want to use default exports - you should split those 2 connected components into different modules.
Comment: I tried it and then I get this:

./src/App.js
Attempted import error: './components/PostArticles' does not contain a default export (imported as 'PostArticles').
Comment: @AlexandrosChatziandreou so as soon as you use named export - you should use named import as well (like `import {PostArticlesConnected} from './components/PostArticles'`)

How to export default 2 constructors?


Tela de pesquisa de documentos com paginação e filtro de pesquisa com asp.net

Question: Tenho o layout de uma tela de pesquisa, ela tem que mostrar documentos de meu banco de dados sqlserver. Para facilitar a pesquisa coloquei filtro e como são muito documentos seria interessante fazer paginação. Ainda estou aprendendo; portanto, se alguém tiver um bom tutorial ou postar algum código a respeito para eu estudar, agradeceria muito. Só sei fazer a pesquisa de maneira básica, como buscar determinados campos do banco de dados. Se alguem puder ajudar, agradeço desde já.
Comment: Acho melhor fazer a paginação no servidor de banco de dados. Pesquise na web por _sql server paging_
Answer: Vou postar a forma que utilizo para as minhas pesquisas em ASP.NET MVC com EntityFramework.
Defino uma ViewModel com os campos de parâmetros e uma lista com os resultados da pesquisa, é nessa classe que ficará também as informações de paginação.
public class BancosViewModel : PagedListViewModel<Banco>
{
    public BancosViewModel()
    {
        Pagina = 1;
        TamanhoPagina = 50;
    }

    [Display(Name = "Página")]
    public int Pagina { get; set; }

    [Display(Name = "Itens por página")]
    public int TamanhoPagina { get; set; }

    [JsonIgnore]
    public IPagedList<Banco> Resultados { get; set; }

    //TODO: adicionar filtros de pesquisa
    public string Descricao { get; set; }
}

A pesquisa é feita na Action do meu Controller
public async Task<ActionResult> Indice(BancosViewModel viewModel)
{
    var query = _db.Bancos.AsQueryable();

    //TODO: parâmetros de pesquisa
    if (!String.IsNullOrWhiteSpace(viewModel.Descricao))
    {
        var descricaos = viewModel.Descricao?.Split(' ');
        query = query.Where(a => descricaos.All(descricao => a.Descricao.Contains(descricao)));
    }

    viewModel.Resultados = await query.OrderBy(a => a.Descricao).ToPagedListAsync(viewModel.Pagina, viewModel.TamanhoPagina);

    return View("Indice", viewModel);
}

O método ToPagedListAsync faz parte do pacote PagedList.EntityFramework
A View que demonstra os resultados da pesquisa é a seguinte
@using Syns.Web.Areas.Cadastros.ViewModels
@model BancosViewModel
@{
    ViewBag.Title = "Bancos";
}

        Pesquisa - @ViewBag.Title

                @using (Html.BeginForm("Indice", "Bancos"))
                {

                            @Html.LabelFor(model => model.Descricao, htmlAttributes: new { @class = "control-label" })
                            @Html.EditorFor(model => model.Descricao, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Descricao, "", new { @class = "text-danger" })

                                <button type="submit" class="btn btn-default" id="submit" name="submit">Pesquisar</button>

                }

                                    Número

                                    Descrição

                            @foreach (var item in Model.Resultados)
                            {

                                        @item.Numero

                                        @item.Descricao

                            }

@Html.PagedListPager(Model.Resultados, page => Url.Action("Pesquisa",
    new BancosViewModel()
    {
        Pagina = page,
        Descricao = Model.Descricao
    }), PagedListRenderOptions.Classic)

A paginação fica a cargo do Helper @Html.PagedListPager.


Get value when pressing a button

Question: How to post a value from div when click on button.
I have tried to leave the action blank so it will refresh the site when pressing the button. But the value does not come to? I only want TransID to post when pressing the button.
<form action=" ">

TransID

Medlemsnummer

Beskrivelse

Indløs

                <?php
                foreach($Test as $key){
                ?>

#<?= $key['TransID']; ?>

<?= $key['member_id']; ?>

<?= $key['title']; ?>

            <?php
            $indløst = isset($key['indløst'])?($key['indløst']) :"";
            ?>
            <?php
            if($indløst)
            {
            ?>

<?= date('d-m-y H:i:s', $indløst) ?>

            <?php
            }
            else
            {
            ?>
            <input class="span2" type="submit" value="Ja ">
            <?php }
            ?>

        <?php
        }
        ?>

    </form>

Comment: This is not the right way.Just use ajax
Comment: use header tag to refresh the page after processing request.
Comment: you at least need a request method, either POST or GET, also normal request methods are catching the name attributes
Comment: Zaz, instead please tell us what you *want* to accomplish? Do you want to submit data using POST to another PHP script? Or do you want to avoid refreshing page and just have the form be processed on client side (with JavaScript)?
Comment: I want to submit data using POST to another PHP script?
Answer: You could use a hidden input to store the variable:
<input type="hidden" name="TransID" value="<?= $key['TransID']; ?>" />

Your form will send it by GET method as you are not specifying the method to be sent.
If you want to send it by POST, change your form to:
<form action=" " method="post">

Answer: Do something like this..
<a rel="tooltip" class="btn btn-mini" href="javascript:void(0)" onClick="somefunction('<?=$key['TransID']?>');" id="somefunction" data-original-title="somefunction">Some text

Or
<a rel="tooltip" class="btn btn-mini"  href="somefile.php?id=<?=$key['TransID']?>"  >Some text

Comment: When i am using the second one, it cant find the row

Get value when pressing a button


Probability of drawing green ball before seeing any red one

Question: Suppose we have $4$ red $7$ green and $4$ yellow balls. Draw repeatedly at random and with replacement. What is the probability of drawing a green ball before seeing any red ball?
I did it as follows:
Let $A_n$ be the event that you draw at least one green ball and no red balls for $n-1$ draws, before finally seeing a red ball on draw $n$. Then to calculate $P(A_n)$ it is equal to $1 - $ the probability that you see no green balls and no red balls, times $(\frac 4 {15})$ the probability of seeing a red ball.
I calculated the probability that you see no green balls and no red balls as $\frac {4} {15}$ - that is the probability of drawing only yellow balls.
Hence, the probability $A_n$ is given as $(\frac {11} {15})^{n-1} \cdot \frac 4 {15}$.
Then we sum from $n = 1$ to $\infty$ and find that the solution is $\frac 4 {15} \cdot \frac {15} 4$...which is $1$, clearly wrong. Which part in the solution went wrong?
Comment: The yellow draws don't mean anything, all that matters is which of the $11$ relevant balls you draw first.  Given that, the only relevant fact is: when you draw from the $11$ meaningful balls for the first time, do you get a green one or a red one?
Comment: The yellow balls don't matter.  You have $4$ red and $7$ green.  What is the probability that the first draw is green?
Comment: I think the probability of drawing only yellow balls should also depend on $n$, right?
Comment: @lulu that would be 7/11 - but intuitively I don't really understand why (1) we can ignore the yellow balls and (2) why the probability that first draw is green = we see green draw before any red.
Answer: Your probability for $A_n$ is wrong. $$\left(\dfrac{11}{15}\right)^{n-1}$$ could be the probability that you receive no red balls, but it is not the probability that you also receive at least one green ball.
Let $B_n$ be the event that you draw no red balls in the first $n-1$ draws.
Let $C_n$ be the event that you draw at least one green ball in the first $n-1$ draws.
These are not independent events. So, $$P(B_n\cap C_n) \neq P(B_n)P(C_n)$$
This probability would be difficult to calculate. It is certainly possible, but not really necessary. An easier way to calculate your original probability:
You draw a green ball on the first draw. Or you draw a yellow ball followed by a green. Or you draw a yellow, then a yellow, followed by a green. Etc.
Let $P$ be the probability you are looking for.
$$P = \dfrac{7}{15}\sum_{n=0}^\infty \left(\dfrac{4}{15}\right)^n = \dfrac{7}{11}$$
It does not matter what comes after you draw the first green. You know that you drew it before you ever draw a red. By the law of large numbers, if you kept drawing, you would eventually draw a red.
Comment: Once you reach the first green, you are guaranteed to have reached a green before a red. If you reach a second green, great. But, once you reach that first green before a red, you have a 100% chance of reaching a green before red.
Comment: Thanks for your answer ! Why don't we have to consider the events like drawing 2 greens and one yellow then a green then a red for example? Why is considering the events of solely one green going to account for all possibilities?
Answer: Yellow balls are irrelevant, they can all be removed. Now the question is what is the probability of a green ball before a red ball with $4$ red and $7$ green. This is the same as the probability of the first ball being green. This is simply $\frac{7}{11}$


Is Drupal Cache Warmer for real?

Question: I am using  Varnish + Default Page cache with a expiring time (1 day) in a site.
When I am browsing the site, everything seems loading fine; once I come back to the site after a day or so, the the pages start loading slow and they become okay after a while.
It seems like the cache is being cleared after a while and generated again once someone visit the site again. I do not want that user to suffer.
I read about Drupal Cache Warmer; is there something which can keep the cache alive and no user suffers?
Comment: Also, keep in mind that Drupal caches the pages for anonymous users; authenticated users would probably not see much improvement.
Comment: Welcome to Drupal Answers! You should report exactly what you mean by _Drupal Cache Warmer_, in your question.
Answer: Well, there's the Cache Warmer module you can set up if you have drush access on your server.
You can also use a 3rd party service like Pingdom to do that as well.
Comment: okay great i will try these.
Comment: Do you have any idea what Drupal is doing if the site gets visited after many hours first time. (i meant page loads very slow. is it running cron or caching pages ?). Is there a way to stop this behavior .
Answer: See following for good description of Drupal caching and how cache is flushed on cron run.
http://tomroelandts.com/articles/how-to-ensure-that-visitors-always-see-cached-pages-in-drupal-7
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

Is Drupal Cache Warmer for real?


winforms DataGridViewComboBoxColumn, ComboBox not clickable when DataPropertyName is set

Question: I have DataGridView with DataGridViewComboBoxColumn with datasource binding, when I bind DataPropertyName of DataGridView, ComboBox becomes not clickable.
dgFMS.ReadOnly = false;

Correct DataPropertyName is bind with each row but I can not choose from drop-down
BindingSource _bsCats2 = new BindingSource();
DataGridViewComboBoxColumn catCol = new DataGridViewComboBoxColumn();
_bsCats2.DataSource = CategoryManager.Categories.Select(x => new {
    Key = x.ParentWithName.ToLowerInvariant(),
    Value = x.Id })
    .ToList();
catCol.DataSource = _bsCats2;
catCol.DataPropertyName = "catID";
catCol.DisplayMember = "Key";
catCol.ValueMember = "Value";
catCol.Width = 250;
catCol.ReadOnly = false;
dgFMS.Columns.Add(catCol);
dgFMS.ReadOnly = false;

I am also implementing dgFMS_EditingControlShowing as well
private void dgFMS_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox cb = e.Control as ComboBox;
    if (cb != null)
    {
        cb.DropDownStyle = ComboBoxStyle.DropDown;
        cb.SelectedValueChanged -= new EventHandler(CmbCat_SelectedIndexChanged);
        cb.SelectedValueChanged += new EventHandler(CmbCat_SelectedIndexChanged);
    }
}

Answer: I have found problem with binding data
DataPropertyName = "catID" was read-only property with only getter without setter like this
public int catID
    {
        get
        {
            return CategoryManager.Categories.FirstOrDefault(x => x.Name.Equals(SubCategory, StringComparison.InvariantCultureIgnoreCase)).Id;
        }
    }

By adding setter of the property solved the problem.


Backspin takes tennis ball over the net and back, but hits the player who hit it?

Question: I had a strange situation on court and I don't know who wins this point.

Player 1 hits a ball with a ton of backspin which lands on players 2 side of the net.
The backspin causes the ball to bounce back over the net to player 1's side without player 2 touching it. Normally, this would be player 1's point.
The twist is, player 1 was very close to the net and when it bounced back to his side, the ball hit his body before hitting the ground.

Does the fact that it hit player 1 change who wins the point?
Or is it still player 1's point since player 2 never touched the ball?
Answer: Player 2 wins the point.
In ITF tennis rules:

Rule 24. Player Loses Point
The point is lost if: ...
i) The ball in play touches the player or anything that the player is wearing or carrying, except the racket.

and

Rule 25. A good return
It is a good return if: ...
b) After the ball in play has hit the ground within the correct court and has spun or been blown back over the net, the player reaches over the net and plays the ball into the correct court, provided that the player does not break Rule 24.

So when player 1 hits a ball with backspin and the ball touches players 2 court side and then bounces back over the net to players 1 court side the ball is still in play and player 2 is supposed to play it.
However, if player 1 touches it before player 2 can, he prevents player 2 from playing the point and it does not matter if the player 2 could not reach the ball anymore. The ball was in play and player 1 touches it means that he loses the point.


Redirect HTTP to HTTPS getting Connection Refused

Question: I want to redirect https requests to http on an apache server.
I have updated my .htaccess file as described in this previous question:
Redirect HTTPS to HTTP
However, this doesn't work and gives (in Chrome):
<code>Error 102 (net::ERR_CONNECTION_REFUSED): The server refused the connection.
</code>
I am guessing that the server isn't enabled to handle 443 requests. So my question is - is there a graceful way to handle this?
Answer: If your server is not listening on port 443 there is no way you can have it do anything on requests send to that port. If you want your server to redirect from https to http you will first have to enable https on that server.
Comment: go to `startssl.com` and issue one year free certificate there.
Comment: As I suspected. So I have enabled SSL on apache but now when you go to the https address before it redirects to http you get the untrusted certificate message as it is now using a self signed certificate. Is there a way to redirect without this. I am guessing not.
Comment: So just to close this off I got a free certificate from startssl and then installed following these instructions: http://jasoncodes.com/posts/startssl-free-ssl now redirects fine. Thanks


Como acessar, em PHP, valores passados como parâmetro utilizando jQuery.post()

Question: Como acessar, individualmente, os valores da string cores e do array filmes em uma página PHP?
var filmes = ["Mad Max", "Assassin's Creed"];

var cores = "cor_um=Azul&cor_dois=Preto";

$.post("autosave.php", {'_cores': cores, '_filmes': filmes});

Answer: Utilizando a tag $_POST
$filmes = $_POST['_filmes'];
parse_str($_POST['cores'], $cores);

Para pegar cada valor dos arrays enviados, basta utilizar o foreach
foreach($filmes as $filme) {
    print_r($filme)
}

Recomendo você alterar o formato da sua variável cores para um array em vez de query string
Comment: Jeferson, como pego cada valor individualmente?
Comment: Como você esta passando eles em um array, você precisa percorrer este array usando `foreach`, vou editar com um exemplo
Comment: Se você enviar as cores como array, basta fazer a mesma coisa para a variável `$cores`
Comment: `"cores"` é uma `string` é serializada a partir de um formulário. Isto é só um exemplo MCV.
Comment: Adicione uma opção para vc transformar query string em array
Comment: Jeferson, se puder complementar sua resposta mostrando como faz...


How to prove this operation is unique

Question:
Given a prime number $p$, an operation "$*$" is defined over the $N^{+}$ structure of Abel group and satisfies:

$a*b\le a+b$

All nonzero elements have order $p$

Question: Is this operation unique?

I think this is the case. But I can't explain why.
This problem is from Algebraic problem book exercise by (zhi xu yang),It is said the author choose AMM problem 1978
Comment: I think Ross must be deep into the mind reading business.
Comment: If I understand correctly, your "operation" $*$ operates on $\{0,1,2,3\dots N-1\}$ and has the two properties stated.  We are asked to prove that the properties stated are sufficient to make the result of the "operation" be unique, which then allows us to call it an operation. Is that what you mean?
Comment: What is a uniqueness operation?
Comment: mean that this opetarion is only one
Comment: Yes,@RossMillikan,That's my mean.+1
Comment: I also believe we are given that $a*b=b*a$ from the Abel group structure.
Comment: So, if I understand the question correctly, you're asking whether there's a unique group structure on $X = \mathbb{N}^{\geq 0}$ such that (a) $x.y = y.x$ for all $x, y$; (b) $x.y \leq x + y$, where the left side is ordinary addition in $\mathbb{N}^+$; and (c) Every $x\not = 0$ has order exactly $p$? (I'm assuming here that $0\in \mathbb{N}^+$ is the zero element of $X$.)
Comment: @anomaly: I'm not sure we are promised a group structure, but saying order $p$ may promise it.  I took order $p$ to mean if you did $a*a*a*\dots*a$ with $p$ operations you got back to $a$.  I think a group structure makes it work.  If you post that as an answer and nobody comes up with one that doesn't use that, I'll award the bounty.
Comment: @RossMillikan: The group structure is the best reading I can come up with for "defined over the $N^+$ structure of Abel group." (And it's certainly not enough of an answer to merit receiving a bounty.) Honestly, if this question weren't assigned a bounty, I'd flag it as being unclear and vote to close.
Comment: @anomaly: I agree it is unclear.  I believe the Abel group just tells us that $*$ is commutative.  I found my reading interesting, but couldn't finish the proof, which is why I offered a bounty.  china math:  could you clarify-are we given that $*$ is a group operation?  Associativity and inverses would then be given-that would help a lot.
Answer: Here is a start.  It needs completion.  I will assume $p \gt 2$.  Similar arguments will work for $p=2$, but some details need to be cleaned up.
First note $0*0=0$ by property $1$, so $0$ is of order $1$, so all other elements have order $p$.  Then $0*1=1, 1*1=2$ because otherwise $1$ has a lower period.  Now $1*n=n+1$ for $n \lt p-1, 1*(p-1)=0$ to get the period right.  Now we can show $2*2=4$ and so on.  We can continue to fill in the table and will show that $*$ is exactly addition $\pmod p$ for $a,b \lt p$.  If $p=N$, we are done.
If $N \gt p$, we have $p$ in our set.  We can't have $1*p$ be anything less than $p$ except $2$ because we get a lower period for $1$.  In general, we can show that if $a \lt p, a*p \lt p$, then $a*p=a+a$  I haven't seen how to exclude this.  Once we do, we will get that there must be at least $p^2$ elements by following this route.  I believe eventually we will show that there must be $p^n$ elements and $*$ is addition in the field of $p^n$ elements.
Added:  If we are given that $*$ is an Abelian group operation we can get there. $1*p$ cannot be anything less than $p+1$ because we can't have $1*p=1*n$ for distinct $n,p$ in a group.  We continue up the same way finding that $*$ is addition $\pmod p$ up to $2p-1$.  As $p$ must have period $p$, we can show that all the elements up to $p^2-1$ are in the group and $*$ is the claimed addition in the field of $p^2$ elements up this high.  Then if $p^2$ is in the group we must have everything up to $p^3-1$ and so on.

How to prove this operation is unique


Add id to image inside views

Question: I have created a grid in views in which there are stored webshops (it's for a website on which you can find all kind of webshops). It shows a picture, a title and a bodytext for each webshop. And now I would like to edit the images only for that page in a seperate id.
Only I have no idea how i should add an id for the css of the image, how is this possible in drupal, css or php?
Answer: If you add the "NID" field to your view's fields, (as the first entry, for reasons I won't get in to here),  you can then use the "rewrite output" function to attach a unique CSS ID using the NID to your image.
Comment: I get your point, but I can't add it to my  line, only override it with the rewrite output function
Comment: Nevermind, I found the solution you were talking about;) thanks!

Add id to image inside views


How to recursively parse json and find a specific object?

Question: This is my JSON file click me !
Following,C# classes from JSON
public class SiteNode
{
    public string url;
    public string[] param;
    public string serviceid;
    public bool is_enabled;
    public string icon;
    public string nodetype;
    public string api;
    public NodeMeta meta;
    public class NodeMeta
    {
        public bool is_module_legal;
        public string module;
        public string func;
        public MuiText title;
        public MuiText desc;
        public string group;
        public List<string> granted_roles;
    }
    public class MuiText
    {
        public string tw;
        public string gb;
        public string en;
    }
    public List<SiteNode> children;
}

I have already use the JavaScriptSerializer.Deserialize method to convert to List ,But I have no idea to find serviceid==System-016 this object.
Special attention to the object in Json file can be changed location,So I think to use recursive to process this problem.
Please, provide me a solution,Thanks a lot!
Comment: @TấnNguyên I'm not sure that's important. I think you can generalise to "serviceId={searchTerm}"
Comment: just to be clear, you want to find an object where serviceid==System-016 ?
Comment: Please edit a small example of JSON into your question. The information to solve your problem must be part of the question. Can you also show what you have tried so far? Unless you specifically want a JSON-focused solution, the JSON may be irrelevant if you just want a recursive search of the object above.
Comment: "System-016" I couldn't find it in your json
Comment: @John Yes I just want to sure that his question is: finding an object with provided serviceId, or he couldn't get the the specific object in json when serializing.
Comment: @Alvin Wu, did my answer below help?
Answer: You could use a method that iterates through all nodes in the tree, for example:
public static IEnumerable<T> Flatten<T>(T node, Func<T, IEnumerable<T>> childSelector)
{
    yield return node;

    var children = childSelector(node);

    if (children == null)
    {
        yield break;
    }

    foreach (var child in children)
    {
        foreach (var grandChild in Flatten(child, childSelector))
        {
            yield return grandChild;
        }
    }
}

Then use it to flatten out your tree structure before filtering the whole set or finding a specific node, for example:
var rootNode = JavaScriptSerializer.Deserialize<SiteNode>(json);
var filteredNodes = Flatten(rootNode, n => n.children)
    .Where(n => n.serviceid== "System-016");

Answer: If I understand you correctly, you would like to query the object from the list? After you have deseriliazed from Json.
var yourObject = SiteNode.Where(s => s.serviceId == "System-16").firstOrDefault()

Comment: I think you've misunderstood the question. Your answer seems to assume a `List SiteNode` variable, and only searches that object for results, but doesn't search any of the child nodes, or child child nodes, etc.
Comment: You need to check the JSON in more detail.  The applicable entry with the right service ID is further down in the tree.


How do you find Eigenvectors for common root Eigenvalue?

Question: I was tasked with finding the eigenvalues and eigenvectors for the matrix:

$$A=\begin{pmatrix}
-2&2&-3\\
2&1&-6\\
-1&-2&0\\
\end{pmatrix}$$

I had found the eigen values as $\lambda=5,-3,-3$. Now, I proceeded to find eigenvectors. For $\lambda=5$, I got the characteristic equation as:
$$A-5I=\begin{pmatrix}
-7&2&-3\\
2&-4&-6\\
-1&-2&-5\\
\end{pmatrix}$$
I used cross multiplication to get the eigen vector.
However for $\lambda=-3$, I'm facing a problem. The characteristic matrix is:
$$A+3I=\begin{pmatrix}
1&2&-3\\
2&4&-6\\
-1&-2&3\\
\end{pmatrix}$$
Here, all the equations are proportional to each other, and cross multiplication only gave me a trivial eigenvectors. How can I solve it in this case?
Answer: If we look at the matrix $A+3I$, we can see that the second and third row are multiples of the first row.
An eigenvector corresponds to eigenvalue $-3$ satisfies $$(A+3I)v=0$$
You just have to solve for all the solution to
$$v_1+2v_2-3v_3=0$$
Let $v_2=s$ and $v_3=t$, $v_1=-2s+3v_3$.
$$\begin{bmatrix} v_1 \\ v_2 \\ v_3\end{bmatrix}= s\begin{bmatrix} -2 \\ 1 \\ 0\end{bmatrix}+ t\begin{bmatrix} 3 \\ 0 \\ 1\end{bmatrix}$$
Comment: The first row of the vector read $v_1 = -2s+3t$, the second line reads $v_2 = s$, the third line is $v_3=t$. I just write them in vector form.
Comment: In other words, $\begin{bmatrix}v_1\\v_2\\v_3\end{bmatrix} = \begin{bmatrix}-2v_2+3v_3\\v_2\\v_3\end{bmatrix} = \begin{bmatrix}-2v_2\\v_2\\0\end{bmatrix} + \begin{bmatrix}3v_3\\0\\v_3\end{bmatrix} = v_2 \begin{bmatrix}-2\\1\\0\end{bmatrix} + v_3 \begin{bmatrix}3\\0\\1\end{bmatrix}$.
Comment: Sure, in fact there are infinitely many eigenvectors but we have found them all. To let $v_1=0$, let $s=1.5$ and $t=1$. The set of all the eigenvectors correponding to eigenvalue $-3$ are the solution set to the linear system $(A+3I)v=0$.
Comment: I don't understand how you got the result from "Let $v_2=s$ and $v_3=t$, $v_1=-2s+3t$". Can you elaborate there?
Comment: @MishaLavrov Thanks
Comment: @SiongThyeGoh Can you have a third eigenvector for eigenvalue -3 with $v_1=0$?


Creating a file using Perl on Windows in a directory the length of whose name exceeds 220 characters

Question: I'm experiencing a problem where I cannot create a file under a directory the length of whose name exceeds 220 characters.
The following is a test script that reproduces the observed behavior, at least on my machine:
use warnings;
use strict;

use Win32::LongPath;

print system ('rmdir /s /q test');
mkdirL('test');

for my $i (200 .. 255) {

  my $dir_name = 'test/' . sprintf("%04d", $i) . ('a' x ($i-4));
  mkdirL($dir_name);

  openL(\my $fh, '>', "$dir_name/" . ('_' x 200) . '.txt') or die "$^E";
  print $fh 'Hello!';
# closeL $fh;
}

This script will create a _________.....___.txt file under 0220aaaa...aaa/ but not under 0221aaaa...aaa/.
Is there a reason for this problem and how can I change the script so that the *.txt file is created in all directories?
Update:
The script, when run, doesn't die or produce any error messages.
Update 2:
This question does not already have an answer in Why does the 260 character path length limit exist in Windows? As the other question, and its answers, clearly show, this path length limit is a Windows issue, not an NTFS issue. NTFS allows paths with a length of up to 32K characters.
In fact, my test script is able to create directories up to 255 characters (as expected from the NTFS specification), it just seems impossible to store files within a directory when the directory name is longer than 220 characters.
Comment: Know issue on Windows:
http://stackoverflow.com/questions/1880321/why-does-the-260-character-path-length-limit-exist-in-windows
Comment: Do you get any error messages?
Comment: @Sobrique, this *max path length* is a Windows issue, not an NTFS issue. `Win32::LongPath` is specifically designed to get around the Windows issue and use the full potential of NTFS. Besides, the script will create the directories until their length is 255 characters, it just seems impossible to create a file within the directories.
Comment: Try using backslashes rather than forward slashes; Windows long path support doesn't allow forward slashes.  (Of course, Win32::LongPath might be doing the conversion for you.)
Answer: TL;DR
The root of your problem is the method by which you are trying to verify that the files have been created. For more information, read the detailed explanation below.
Here are the facts:

perl does not give any errors when using mkdirL or openL calls.
perl can open files created, and read the contents, using openL.

Therefore the problem is due to the fact that whatever tool you are using, is either using ANSI versions of Windows API calls, or specifying relative paths, or a combination of both, and therefore their paths are restricted to 260 characters.
To test this, I ran the script under D:\t. Lo and behold, GVim failed to open a file when $i = 250:

D:\t is four characters, \test is another five. Therefore, 250 + 9 = 259, which hits 260 the moment you add another \.
Using shortpathL
Try this:
#!/usr/bin/env perl

use strict;
use warnings;

use Win32::LongPath;

`cmd /c rd /s /q test`;

mkdirL('test') or die "$^E";

my $dir_length = 255;
my $dir_name = 'test/'
             . sprintf("%04d", $dir_length)
             . ('a' x ($dir_length - 4))
;

mkdirL($dir_name) or die "$^E";

my $file_name = "$dir_name/" . ('z' x 200) . '.txt';

printf "% 3d\n", length $file_name;

openL(\my $fh, '>', $file_name) or die "$^E";

print $fh "Hello!\n" or die "$^E";

close $fh or die "$^E";

system 'notepad.exe', shortpathL($file_name);

You will get:

Therefore, give the short path to any external programs which you cannot rely on to use the Unicode interface.
Long winded explanation
Now that I have had a chance to actually try this on a 64-bit Windows 8.1 system, I cannot replicate the problem.
Here is the code I used:
#!/usr/bin/env perl

use strict;
use warnings;

use Win32::LongPath;

`cmd /c rd /s /q test`;

mkdirL('test')
    or die "$^E";

for my $i (200 .. 255) {
    my $dir_name = 'test/' . sprintf("%04d", $i) . ('a' x ($i-4));
    mkdirL($dir_name) or die "$^E";

    my $file_name = "$dir_name/" . ('_' x 200) . '.txt';

    printf "% 3d\n", length $file_name;

    openL(\my $fh, '>', $file_name)
        or die "$^E";

    print $fh 'Hello!' or die "$^E";

    close $fh or die "$^E";
}

Here is the output:
C:\…\Temp> perl tt.pl
 410
 411
 412
 413
 414
 415
…
 460
 461
 462
 463
 464
 465
I am also attaching a couple of screenshots:

Now, I can report that Explorer has trouble navigating into any directory after C:\...\Temp\test\0220aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
and GVim cannot open files in subsequent directories. That is, system 'c:/.../gvim.exe', $file_name; issued from within the script results in

Presumably GVim runs into the following from Naming Files, Paths, and Namespaces

Because you cannot use the "\\?\" prefix with a relative path, relative paths are always limited to a total of MAX_PATH characters.

By coincidence, the length of the path of my %TEMP% directory happens to be 33 characters. Add to that 5 (length of \test), and we have 38. Add that to 221, and we get 259. Now, the moment you add a directory separator to that string, you hit 260.
Which brings me to, what is the length of the full path of the working directory under which you are creating test?
In better news, perl is able to read back everything written:
#!/usr/bin/env perl

use strict;
use warnings;

use Win32::LongPath;

`cmd /c rd /s /q test`;

mkdirL('test')
    or die "$^E";

for my $i (220 .. 255) {
    my $dir_name = 'test/' . sprintf("%04d", $i) . ('a' x ($i-4));
    mkdirL($dir_name) or die "$^E";

    my $file_name = "$dir_name/" . ('_' x 200) . '.txt';

    printf "% 3d\n", length $file_name;

    openL(\my $fh, '>', $file_name)
        or die "$^E";

    print $fh 'Hello!' or die "$^E";

    close $fh or die "$^E";

    openL(\my $in, '<', $file_name)
        or die "$^E";

    print <$in>, "\n" or die "$^E";

    close $in or die "$^E";
}

outputs:
…
 459
Hello!
 460
Hello!
 461
Hello!
 462
Hello!
 463
Hello!
 464
Hello!
 465
Hello!
Because Win32::LongPath internally normalizes paths so they follow the "To specify an extended-length path, use the "\\?\" prefix" recommendation, and then uses the Unicode version of API calls, e.g. CreateFileW, openL does not run into such issues.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming Files, Paths, and Namespaces.

How are you verifying if the files have been correctly created?
Also, see "Why is Perl system call failing to invoke internal Windows command?" for the explanation of qx{cmd /c rd /s /q test}
Comment: This is exactly it: I/Perl created the files, but tried to look at them using *file explorer* (which, as you pointed out, and I should have known) a pointless, futile excersice.


Count data with mixed effects

Question: EDIT: Thanks for the help so far. I have updated the question based on further work.
I am interested in finding any difference in response of counts of two competing species to dryness and elevation. Both are caught in the same type of trap, but trap placement (bushes vs buildings) probably biases toward one species or the other, so each trap placement is rated according to indoors/outdoors on a scale of 1-3. A trap does not move once it is placed. Traps are nested in sites, dryness is measured at each site/visit combination, and elevation is of course constant at each site.
My data includes the number of each species caught in 4-12 traps, at 8-12 sites during 6-8 visits to each site. The visits and sites are far enough spaced that I assume they are independent. Most data are zeros, especially for Sp_A which is rare. Below is the structure of the data.
R> str(mydata)
'data.frame':   300 obs. of  8 variables:
     $ count    : num  0 5 1 0 1 1 0 0 0 0 ...
     $ species  : Factor w/ 2 levels "a","b": 1 1 1 1 1 1 1 1 1 1 ...
     $ elevation: int  1 1 1 1 1 1 1 1 1 1 ...
     $ dryness  : num  0.179 0.179 0.179 0.179 0.179 ...
     $ site     : Factor w/ 5 levels "a","b","c","d",..: 1 1 1 1 1 1 1 1 1 1 ...
     $ trap     : Factor w/ 50 levels "MT10a","MT10b",..: 6 11 16 21 26 31 36 41 46 1 ...
     $ visit    : Factor w/ 3 levels "1","2","3": 1 1 1 1 1 1 1 1 1 1 ...
     $ in_out   : num  1 1 1 1 1 1 1 1 1 1 ...

As an initial attempt, I had no trouble using R function lmer to model Sp_A presence/absence with Sp_B as a covariate: (SpA>0) ~ Sp_B + elevation + (1|site/trap) + (1|visit)
However on suggestion from R-sig-mixed-models list, and also "ils" from this site, I have reshaped the data as seen above, and tried to model count with species as a factor in the model. I have used two different packages (lme4 and glmmADMB). The functions handle the data ok in simple models, until I add the factor "species." Below are the R code and error messages. These same errors also happen when I use simpler dummy data. Any ideas on syntax or other packages?
require(lme4)
glmera1 <- glmer(count~elevation*species*in_out
                 + (1|visit) + (1|site/trap),
                 data=mydata, family="poisson")
Error in asMethod(object) : matrix is not symmetric [1,2]
In addition: Warning messages:
1: In mer_finalize(ans) :
  Cholmod warning 'not positive definite' at file:../Cholesky/t_cholmod_rowfac.c, line 432
2: In mer_finalize(ans) :
  Cholmod warning 'not positive definite' at file:../Cholesky/t_cholmod_rowfac.c, line 432
3: In mer_finalize(ans) : singular convergence (7)

require(glmmADMB)
admba1 <- glmm.admb(count~elevation*species*in_out, random=~visit,
                    group="site", data=mydata, family="nbinom")
Error in glmm.admb(count ~ elevation * species * in_out, random = ~visit,  :
  The function maximizer failed
In addition: Warning message:
running command './nbmm -maxfn 500 ' had status 1

Comment: @J. Winchester I'm afraid your question still appears to focus on AIC, and responses to the related question on AIC apply as well here. However, I feel you are also wondering whether your `lmer` syntax allows you to test the hypothesis formulated in your first paragraph. If this is the case, you can simply *edit the title and your question* and focus on this issue, rather than AIC. You might also consider adding the output of `summary(lmera.1)`. Finally, the outcome you consider is a ratio of counts (% `Sp_A`): Is it usual in your field to treat this as a continuous response variable?
Comment: @J. Winchester: It might be a crazy idea, but why not treat `abundace` as the dependent variable and add `species_identity` as a factor into the model? Then, when you have estimated the magnitude of `species_identity` you will be able to compare the abundance of both species in relative terms. This way you won't need the model comparison stage and things will be much more simple. I also don't see the purpose of `visit_day` as an estimable parameter; the species abundance will clearly depend on it as an exposure parameter, but then how one will interpret the `dryness * visit_day` interaction?
Comment: @ils Thank you, I have tried that and updated the question. I wonder what is the difference between your suggestion, and using `lmer(cbind(sp_a, sp_b)~elevation*dryness ... )` which is a format used at the bottom of the lmer help page.
Comment: @J. Winchester: What is `in_out` in the new data frame? I feel that the variables are somewhat blindly "thrown" into the model, so you need to clarify the question and add the terms into the model according to the aim of the analysis. I am not sure about the differences in using `lmer` as noted in the help file and as suggested, though.
Comment: @J. Winchester: I also don't see the `dryness` variable included in the model.
Comment: I'm not aware of any question that covers "exactly the same ground." While these criteria are sometimes negative, my question is, have I done something wrong?
Comment: @chl. Thank you. I have rewritten the question and title; regarding your last sentence, I cannot say that it is usual, but I do not have a better idea.
Answer: Check out this question: Negative values for AICc (corrected Akaike Information Criterion)
The same explanation holds for BIC.
Answer: Try the following packages on cran: Rcapture and mra. The easiest method to use in R for a log linear model, open closed or robust, M0, Mh, Mt, or Mth is well detailed here: http://www.jstor.org/pss/3695557 and that is what Rcapture is based on. You forgot to specify in your lmer call that it should be a count response (family = poisson) and your Y should be the abundance associated with a particular capture history. Extracting the estimated abundances, survival probilities, etc, is well detailed in the jstor link.
However, the premier tool people use for this is MARK (http://www.phidot.org/software/mark/docs/book/), and there is a bridge package not on cran called RMark (http://www.phidot.org/software/mark/rmark/RMarkWorkshopNotes.pdf). RMark is the premier tool for this sort of thing and the one which certainly has the largest community. It has its own support forum at phidot.org.
Also, google around for Dr. Schofield's BUGS code for this problem; it is online somewhere, I think in the dissertation.
Btw, if you are interested in a job in population ecology and R programming, we're hiring: https://performancemanager4.successfactors.com/career?company=comScore&career_job_req_id=721&career_ns=job_listing&navBarLevel=JOB_SEARCH

Count data with mixed effects


drupal 8.2 to 8.5 update error

Question: I am getting the following error.

Recoverable fatal error: Argument 3 passed to
  Drupal\page_manager\Routing\VariantRouteFilter::__construct() must be
  an instance of Symfony\Component\HttpFoundation\RequestStack, none
  given, called in
  /home/ranjith/public_html/core/lib/Drupal/Component/DependencyInjection/Container.php
  on line 266 and defined in
  Drupal\page_manager\Routing\VariantRouteFilter->__construct() (line 64
  of
  sites/all/modules/contrib/page_manager/src/Routing/VariantRouteFilter.php).

What does it mean? How can I fix that error?
Comment: Hey, welcome to Drupal Answers. We'd love to help you. To **improve your chances** of getting an answer, please follow these rules: [How do I ask a good question?](https://drupal.stackexchange.com/help/how-to-ask). Thanks
Comment: The question is actually fairly clear and the answer too: You need to update the page_manager module to the latest version (and other contrib modules possibly too)
Answer: What you're seeing is the result of the Drupal service container failing to create a service because its cached definition doesn't match the class anymore: An extra constructor argument was added (in this change), and Drupal is not passing that argument.
This is a typical error that can happen after updating modules. Make sure to completely empty your cache manually. You might be able to do this using drupal cr all or drush cr or by visiting the admin backend, but not if the service is already loaded during bootstrap. In that case, try to empty the cache_container database table directly.

drupal 8.2 to 8.5 update error


What is the season when the title was decided with the most races remaining?

Question: In 2021, the F1 title was decided on the final race of the season, at Abu Dhabi. In 2022, it's possible for Max Verstappen to win the title at the Singapore GP and still have 5 races left. Would this be the most races left where the title is already decided? Has the title ever been decided earlier than this?
Answer: The record for this was set in 2002, when Michael Schumacher won the championship after 11 races of a 17-race season. There were therefore 6 races that took place after Schumacher had already won the title.


Too many False Positives with Unbalanced Data

Question: I am trying to predict customer churn in a telco company, using R.The dataset is very unbalanced, the target is around 0.6% of the base.

8,746 Customers will Churn
1,396,664 Customers do not churn

I have trained a Random Forest in R.Prior to training, I SMOTE the training data:
train.smote <- SMOTE(Churn~ ., train, perc.over = 100, perc.under=200

This gives me a 1:1 Balance. I then train the forest using:
fit<- randomForest(as.factor(Churn)~.,data=train.smote,importance=TRUE,
ntree=500)

When I run,
pred=predict(fit,newdata=test,type="class")

on my validation Data, I get the following Confusion Matrix:
             Positive    Negative
Positive     1,136,610   234,625
Negative     3,762       5,911

The F Score is 0.83, the Specificity is 0.61.
However, the number of False Positives is too high (234,625).
Please suggest a method to curb these False Positives without compromising on the True Positives.
Answer: Probably this question should be moved over to CrossValidated or DataScience.
Anyway, there are tons of things you can do.
Feature Extraction and Importance, which variables are most correlated with the churn, which are less, remove the latter.
Can you extract new feature from the variables you have? This can be hard and a bit of "try and fail", but it can improve your results.
At last, try Ensemble Models, essentially you build several different models (best if uncorrelated with each other), and combine the results. This will boost the performance. Ensemble Models in R.


Retornando item do objeto de um array

Question: Bom estou precisando percorrer um array e retornar uma propriedade do objeto daquele item em questão.
Meu array tem este formato:

Tentei resolver isto com a seguinte função:
public function returnObjectByDayAndTrip($links, $trip, $dayOperation)
{
    $newArray = array_filter($links, function ($obj) use ($trip, $dayOperation) {
        if ($obj['trip'] == $trip && $obj['dayOperation'] === $dayOperation) {
            return true;
        } else {
            return false;
        }
    });

    if (isset($newArray[0])) {
        return $newArray[0]['url'];
    } else {
        return null;
    }
}

E para chamar ela uso:
$link->week = $this->returnObjectByDayAndTrip($links, $trip, 'week');

Onde $links é meu array da imagem, $trip é o dia que preciso pegar, e 'week' é o dia de operação que preciso pegar.
Meu erro acontece quando por exemplo o item é o [3] do array, quando é o primeiro tudo funciona mais apartir da posição 1 nada funciona mais.
Meu retorno com var_dump é

object(stdClass)#632 (4) { ["week"]=> string(77) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-santa-ruth-em-dias-uteis" ["saturday"]=> NULL ["sunday"]=> NULL ["changeDestiny"]=> NULL }

Preciso retornar a url do objeto baseado nas particularidade passada para função. No meu array necessariamente terá apenas 1 items ou nenhum que satisfaz as informações informadas, ou seja sempre terá um resultado ou nenhum.
O retorno de todas vezes que chamei está assim:
array(1) { [0]=> array(4) { ["_id"]=> object(MongoDB\BSON\ObjectId)#477 (1) { ["oid"]=> string(24) "5b3f74ad6ae83d00223504e8" } ["url"]=> string(77) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-santa-ruth-em-dias-uteis" ["dayOperation"]=> string(4) "week" ["trip"]=> string(5) "tripA" } }

array(1) { [2]=> array(4) { ["_id"]=> object(MongoDB\BSON\ObjectId)#479 (1) { ["oid"]=> string(24) "5b3f74ad6ae83d00223504e6" } ["url"]=> string(73) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-santa-ruth-no-sabado" ["dayOperation"]=> string(8) "saturday" ["trip"]=> string(5) "tripA" } }

array(1) { [4]=> array(4) { ["_id"]=> object(MongoDB\BSON\ObjectId)#481 (1) { ["oid"]=> string(24) "5b3f74ad6ae83d00223504e4" } ["url"]=> string(74) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-santa-ruth-no-domingo" ["dayOperation"]=> string(6) "sunday" ["trip"]=> string(5) "tripA" } }

array(1) { [1]=> array(4) { ["_id"]=> object(MongoDB\BSON\ObjectId)#478 (1) { ["oid"]=> string(24) "5b3f74ad6ae83d00223504e7" } ["url"]=> string(77) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-bela-vista-em-dias-uteis" ["dayOperation"]=> string(4) "week" ["trip"]=> string(5) "tripB" } }

Comment: Não tem duplicação, no momento de criar cuidei para que não houves-se ou seja, tem apenas um combo de cada um week, tripa, tripb, saturday, tripa, tripb, sunday, tripa, tripb
Comment: Não é no `return` o problema? se não tem que retornar o objeto?
Comment: O array_filter não exige true ou false ? Para que retorne aquela posição ? Pergunto porque em javascript funciona desta maneira perfeitamente.
Comment: Atualizei minha resposta @VirgilioNovic você pode ver que ele retorna os objetos mas observe que cada objeto está em uma posição do array, todos eles tem 1 posição mais esta posição esta em diferentes lugares.
Comment: Você precisa trazer os dados de que forma?: isso que eu não entendi?
Comment: @VirgilioNovic no caso preciso trazer apenas url que é um item do objeto.
Comment: Nesse resultado pode ter duplicação? ou só apenas um item?
Answer: Consegui resolver utilizando o current() ele retorna a primeira posição de um array então ficou desta maneira:
public function returnObjectByDayAndTrip($links, $trip, $dayOperation)
{
    $newArray = array_filter($links, function ($obj) use ($trip, $dayOperation) {
        if ($obj['trip'] == $trip && $obj['dayOperation'] === $dayOperation) {
            return true;
        } else {
            return false;
        }
    });

    if (count($newArray) >= 1) {
        return current($newArray)['url'];
    } else {
        return null;
    }
}

Provavelmente existe uma maneira melhor de fazer, e até aceito este novos métodos porém desta forma solucionou meu problema. O ideal neste caso é uma junção com array_map e array_filter para ficar robusto.

Retornando item do objeto de um array


boost::python long/structured docstrings

Question: I have a c++ function wrapped for python exposure. I use boost::python for this purpose. For the same, I wish to have a structured doctoring, which will look very much like
    some text here.....

    Parameters:
    p1 ...
    p2 ...
    p3 ...

    Returns:
    R1 ...

Now, my problem is, when I place the above in the docstring placeholder
     def("wrapFunName", cppFunc, "PLACEHOLDER")

compiler (clang) throws me an error of missing terminating ' " ' character. Does it mean that I can not wrap the long doctoring with booth::python and I have to write it continuously? I thought c++/c would always be free-form languages :(.
Thanks in advance,
Nikhil
Answer: Remember that although you are writing code to be used from Python, you're still writing C++, so you're bound by the rules of C++ syntax. C++ doesn't allow multiline string literals in quite the same way as Python does. In particular, it doesn't allow bare line breaks in strings, so when the compiler reaches the end of the line without finding the end of the string, it rightly complains, as you've observed.
You can use any of several techniques for getting multiline strings in your C++ code. For example, you can insert the line breaks explicitly with \n, or you can escape the line breaks with \ at the end of each line. Those techniques and more are demonstrated in the answers to the linked question.
Here's an example of the first method. Note the \n at the end of each line. C++ automatically joins consecutive quoted string literals into a single value, which is why there are no operators between the lines.
def("wrapFunName", cppFunc,
    "some text here.....\n"
    "\n"
    "Parameters:\n"
    "p1 ...\n"
    "p2 ...\n"
    "p3 ...\n"
    "\n"
    "Returns:\n"
    "R1 ...")

Comment: multiline string literal was the thing I missed :(... thanks!


custom htaccess

Question: we have urls as;
 - mydomain.com/my-keyword/
 - mydomain.com/my-other-keyword/
 - mydomain.com/my-another-keyword/

and also
 - mydomain.com/my-keyword/a-page.html
 - mydomain.com/my-keyword/another-page.html
 - mydomain.com/my-other-keyword/some-page.html
 - mydomain.com/my-other-keyword/any-page.html
 - mydomain.com/my-another-keyword/another-page.html
 - mydomain.com/my-another-keyword/some-page.html

We want to convert (301) all urls created without / for example; mydomain.com/my-another-keyword -> to -> mydomain.com/my-another-keyword/ without harming the rest of the url structure.
Any ideas?
Answer: RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://mydomain.com/$1/ [L,R=301]

if the file exists: dont add slash, if it's not a file: add slash
Comment: this would NOT work, because we dont have a files with those names. Basically our original rewrite can rewrite anything regardless of what address is called as long as keyword exists. It will pull out the details and print them on page.

    mydomain.com/colorado-hotels/ or
    mydomain.com/colorado_hotel/

They both bring out the same data.
So obviously **mydomain.com/colorado_hotel** will also work.
Thanks but, this is why yours is no good.

Any ideas ?
Answer: This should work for you as long as a "directory" in the path does not contain a .
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\..+$
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) http://domain.com/$1/ [R=301,L]

custom htaccess


Converting vector to array. How to deallocate memory?

Question: I am converting a vector of doubles to an array of doubles as seen here:
The difference is, that I want to return the pointer a as a function parameter:
void getArray(double* a)
{
    std::vector<double> v;
    a = &v[0];
}

So my question is, when does the memory of a gets deallocated? Or do I have to call delete[] a by myself, which seems strange since I did't allocate the memory with new. I have read the comments to the above mentioned answer but it still isn't clear to me.
Comment: `a` will point to garbage, once `v` is out of scope, there is nothing to delete
Comment: Also, next to the UB, from c++11 on, the less hackish version is `v.data()` instead of `&v[0]`, see http://stackoverflow.com/a/10740171/104774
Comment: The memory of `a` is deallocated as soon as the function returns, because `a` is a pointer to a vector's element and ´v´ is local to the function.
Comment: "I am converting a vector of doubles to an array of doubles" - Why?
Comment: Anyway, forget about the `getArray` function, just use vectors in your program and use `v.data()` where a vector can't be used (e.g. C interface) making sure that the data used is within the timeline of the vector, which is not the case in your example as already mentioned in the answer of Andrew.
Comment: Possible duplicate of [Pointer to local variable](http://stackoverflow.com/questions/4570366/pointer-to-local-variable)
Comment: As you see there ... is no function call involved.
Comment: @DieterLücking what do you mean? Is not destructor a function?
Comment: @Basilevs I think they mean that no function is explicitly called by the programmer.
Comment: [Return a pointer to array from a function in C++?](http://stackoverflow.com/q/30448688)
Comment: Thanks for all the comments. I need to convert the vector to an array because the function is part of (C interface) DLL that is called by a LabView VI which doesn't know `vectors`.
Comment: @rkgghz: and would passing v.data() be a reasonable solution then?  After all, that's what is it there for.
Comment: @ stefaanv : I don't think so. Instead I will copy each element to a `new` array and pass that pointer. Then the caller has to delte it.
Answer: The memory pointed to by a gets deallocated when the vector v is destructed. In this case, that's at the end of the function getArray.
Comment: @Basilevs A good approach to memory management would be to keep the vector as a vector and have that manage the memory instead of taking upon oneself to manually manage it. It really depends on the end goal. Sample usage for something that shouldn't be done could suggest that that's the right thing to do. A modern C++ programmer should try to avoid raw pointers.
Comment: @Basilevs Depends what OP is trying to do. When *do* you want the memory destructed? Who should be managing this?
Answer: Don't do this:
void getArray(double* a)
{
    std::vector<double> v;
    a = &v[0];
} // The vector is destroyed here, and the memory
  // is deallocated.

In any case, you're not modifying the a pointer outside of your function, so you won't get the desired effect.
Instead, return the vector and use it directly. Or, in general, use vectors throughout your code. If you need to pass them in to a function that expects a pointer to an array, you can pass &v[0] there. Such a function usually expects the size too. For this, pass v.size(). You can do this safely as long as that function doesn't take ownership, or deallocate the memory.
Note, also, that a vector declared as std::vector<double> v; does not have a size, so attempting to access the first element, as in v[0] is also undefined behaviour. At the very least, you need to give the vector a size (pass a size to its constructor) to ensure some memory is allocated. You should always make sure the vector has some allocated memory before indexing into it, including when trying to take the address of the first element.
What you probably want to do is:
std::vector<double> getArray() {
  std::vector<double> v = /* some sane initialisation */;
  return v;
}

// some time later, assuming a function:
//   void do_something(double* a, size_t n);
// ...

std::vector<double> v = getArray();
if (v.size()) {
  do_something(&v[0], v.size());
} else {
  // fail gracefully
}

Answer: This implementation would invoke undefined behavior because v is local:
void getArray(double* a)
{
    std::vector<double> v;
    a = &v[0]; // would be a UB for returning the pointer to internals of a local variable.
}

However, the caller will never see any effect of this, because modifications to a stay local to getArray function.
If you want to make an array out of a vector, allocate a new array, use std::copy to copy the content into it, and return the array to the caller. Make sure the callers call delete[] on the result once they are done with the copyL
double *getArray(const vector<double>& v) {
    double *res = new double[v.size()];
    std::copy(v.begin(), v.end(), res);
    return res;
}

The caller should use it as follows:
vector<double> data;
data.push_back(...);
... // populate the vector
double *tmp = getArray(data);
... // Use the array
delete[] tmp; // Avoid memory leaks

Comment: i dont think there is ub, because as you said, any modifications to a are local to the function.
Comment: @tobi there is UB when accessing `v[0]` of a vector that has not been constructed with a size.
Comment: @Andrew ah right, and I thought he was referring to dereferencing the invalid pointer (actually "...because `v` is local" is misleadling)
Comment: Consider adding a method documentation in form of a comment. IMHO, this is a good practice when returning raw pointers.
Answer:
when does the memory of a gets deallocated?

The a pointer itself is a local variable, so it is deallocated at the end of its scope.
a points to the memory allocated by the vector v. The pointed memory is deallocated in the destructor of v (The memory may also be deallocated if objects are added to or removed from the vector). And because v is a local variable, it is destroyed at the end of scope.

Or do I have to call delete[] a by myself,

No, because the memory is owned by the vector object, but also because

which seems strange since I did't allocate the memory with new.

Exactly. You didn't call new[], so you don't call delete[].

Note that v[0] has undefined behaviour because the vector is empty.


Can sendmail reject mail with nonexistent From-Header?

Question: I have a sendmail/cyrus installation.
Sendmail rejects mails from non existent MAIL FROM:-addresses. This is good. But sendmail does not reject mails from non-existent From:-header-addresses. The mail is then forwarded to cyrus, cyrus makes this check and rejects the mail. Now sendmail tries to (and usually can) send mail back an error mail to the MAIL FROM address.
Is it possible to configure sendmail to not accept non-existent domains in From:-header field?
Other ideas for a solution?
Probably writing a milter could be a solution, but are there simpler solutions?
Thanks
Teddy
Comment: On further reflection I think your problem is that the rejected message isn't sent to envelope sender but to the random crap a spammer put in the message body and headers there...
Comment: The message body can be poked around with by a milter such as MIMEDefang.
Answer: There are two different FROM "headers", one as part of the SMTP envelope, which sendmail can check, and the one in the message body that your mail clients usually display. As far as I know sendmail doesn't care a whit about the second one.
Disable the following feature in your sendmail.mc and regenerate your sendmail.cf:
FEATURE(accept_unresolvable_domains)

and your mailserver will decline messages from non-existent domains.
Test with:
telnet mailhost 25

220 mail.example.nl ESMTP Sendmail 8.14.4/8.14.4; Fri, 23 Sep 2016 22:25:58 +0200
MAIL FROM: email@example.com
553 5.1.8 firstname.lastname@example.com...
          Domain of sender address email@example.com does not exist

Sendmail adds the SMTP envelope sender as the Return-Path header to messages it processes.


Getting values from a query that retrieves two entites in jasper reports

Question: i am using ireport 4.1.1 with hibernate jpa and I have a query that retrieves two entities:
select a,b from TableA a left join a.tableBList b

I am trying to get the value of a and b, in java, it returns an array of objects (Object[]) with two items, but when I try to do this on jasper reports it gives me this error:
Exception in thread "main" net.sf.jasperreports.engine.JRRuntimeException: net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : fieldName

I think that i only need to replace fieldName with the name of the object that will be returned but I don'w know it and I have tried to find it but I have had no success, anyone of you can help me please???
Thanks in advance :)
Comment: Not sure how hibrenate does it, but I would check if each row returned is an Object [], meaning if your query returns 5 rows, then you get back a list of 5 Object arrays. `Object[0]` would have `a` and `Object[1]` would have `b`. So maybe if you do `$F{fieldName}[0]` it would give your `a` and you could access the properties of that object.
Comment: @jschoen yes I have tried that and it should work, the problem is that I have to specify the field name but I can't get that name, for example, if my query returns an entity named 'person' this entity have a property named 'age', so if I want to access that property I declare a field named 'age' and I can get acces to that property with '$F{age}', but in the case that the query returns an array of two objects, I don't know what name give to the field, did I explain me??
Comment: Ahh, that is not the field. Your field is actually an object array. Say you name the object array `row` in your report then it would look something like `$F{row}[0].getAge()`. This may or may not work out the box as you probably need to cast the `$F{row}` to a `Person` class which means you will need to add the class to the class path of iReport to compile. But if you need to cast it should look like `((Person)$F{row}[0]).getAge()`. This is all off the top of my head, so your mileage might vary.
Comment: You could also process the results in java before passing the results to JasperReports. Taking the fields you want and creating a HashMap for each row. With the key being what you what to name the fields in the report. You would then use a JRMapCollectionDataSource as the datasource for the report.
Comment: yep, the problem is the name of the field, I don't know how to get the object array into a field, and processing before sendig to jasper reports is a good option but i'd have to change my report processing standard ... :(
Answer: This error is because your data is not mapping with beans property, or you can that your data pattern is not according to the beans property. I was having the same problem in my java project. And I sorted out that your data should be in a proper 2D array form, then I took sample data from somewhere and did this
String[][] data =
{{ "N263Y", "T-11", " 39 ROSCOE TRNR RACER"},
{ "N4087X", "BA100-163", "BRADLEY AEROBAT"},
{ "N43JE", "HAYABUSA 1", "NAKAJIMA KI-43 IIIA"},
{ "N912S", "9973CC", "PA18-150"}};

        JTable m = new JTable(data,headers);
try {

            JasperReport jasperReport = JasperCompileManager.compileReport(fileName);

            if(jasperReport != null )
               System.out.println("so far so good ");

            // Fill the report using an empty data source

            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JRTableModelDataSource(m.getModel()) );//create());//con.connection);
            try{
            JasperExportManager.exportReportToPdfFile(jasperPrint, outFileName);
            System.out.printf("File exported sucessfully");
            }catch(Exception e){
                e.printStackTrace();
            }
            JasperViewer.viewReport(jasperPrint);

        } catch (JRException e) {
            JOptionPane.showMessageDialog(null, e);
            e.printStackTrace();
            System.exit(1);
        }

Note:
Your field name should start with small letters, moreover field names should be small as of the columns names u r providing within that data.
Hope this will help you.
Comment: is it neccessary that I use an empty datasource? because in my report, I am doing 'nested' querys and an emptydatasource isn't functional to me, I need to do the querys inside the report


Output of entity_metadata_wrapper does not dump to dsm()/dpm()

Question: Given this code in a theme_preprocess_page($vars)..
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
dsm($wrapper);

Why doesn't $wrapper produce a debug dump in dsm() or dsp()? I can get data using print_r. Can someone please explain this?
Answer: Never mind, I found it. Leaving the answer here for anyone who follows
Basically, dpm($wrapper->getPropertyInfo());
https://drupal.stackexchange.com/a/42542


Alternative, more secure user registration process wanted

Question: I don't like that Drupal 7 exposes at the registration page whether the provided e-mail is known by displaying a "The e-mail address firstname.lastname@example.com is already registered. Have you forgotten your password?" message.
I would prefer if it only lets the user know that the process has been initialized, and depending on the status of the e-mail it either sends out a normal registration e-mail or a password reset.
What would be the best way (the closest to Drupal's philosophy) to implement such a feature?
Is this a module?
Could it be accomplished by reconfiguring the fields of the user account?
Comment: Note that, as often, there's a conflict between security and usability. There is also the password recovery tab, as mentioned by @kiamlaluno, which tells you whether the submitted username/e-mail exists or not. What do you want to with that? "Maybe your entered e-mail address exists so maybe we sent a mail to you." ? ;)
Comment: Drupal 6 or Drupal 7 ?
Comment: Drupal 7. I've edited the question, thanks for bringing this to my attention.
Answer: If you want to change the way a user can register on a Drupal site, I would rather implement hook_menu_alter() to alter the menu callback called when a user access user/register.
function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_register_form');
  }
}

If you are going to allow users to enter an email that is already used from another account, then you should alter also the menu callback associated with user/register, as Drupal allows users to reset a password by entering their username or their email address.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_register_form');
  }
  if (isset($items['user/password'])) {
    $items['user/password']['page arguments'] = array('mymodule_user_pass');
  }
}

The functions Drupal uses as form builders for those menus are user_register_form(), and user_pass(). You can use them as guideline for the code you implement.
Keep in mind the following points, though:

The unique email is necessary because Drupal allows users to request a new password by entering the email associated with their account. This is also helpful for who simply forgot their username, as the email sent from Drupal contains a link that redirects them to their account, where they will eventually change their password (or just enter their previous password to keep it).
There isn't any security involved, as that doesn't allow a user to know all the emails used in a Drupal site, nor any email matching a partial email address. The users need to enter a complete email, and at that point there is few they can do; even in the case they try resetting a password, Drupal would sent an email to that email address, to which that user needs to have access. If that user can change the password of that email address, or can obtain it, that is not a Drupal security issue, but eventually with how that email address is handled, or who knows the password used for an email address.
If there is a security issue with allowing to use an email address to reset a password, then there would be a security issue even in the case the user is able to enter a username to request a new password, because somebody could find out a username already in use on a Drupal site.
Allowing to have not unique emails can create problems with modules such as the LoginToboggan module that allows users to log in entering their email address when logging in. There are probably other modules that assume there aren't two user accounts using the same email.
Enforce unique email addresses for users is a Drupal issue report related to what you are trying to achieve. If this patch is going to be applied, it will be possible to allow users not to have unique emails by setting the user_mail_unique Drupal variable.
Comment: I like a lot of what Kiamlaluno has said here, so rather than provide an alternate answer I'll add a +1 for this and suggestion: if you want to hide information about your users then you probably also need to try to identify and prevent the ways to find which usernames are registered http://drupal.org/project/username_enumeration_prevention is a module that tries to do that.
Comment: @greggles, what makes the menu alter method preferable over form altering the submit and/or validation on the user forms?  I may be missing something, but don't a lot of third party module rely on the exiting form names for adding functionality?
Comment: @MPD that's probably a good point that these pages should use the same forms to allow third parties to continue to modify them. Drupal's access/validation system is quite inconsistent, but in the case of user operations I would say that access/validation should be added via related hooks rather than to forms. Hooks should always be called even if login happens via a different form.
Answer: Yes, you can alter the form and replace the validate and submit functions with your own. You want to alter user_register_form(), which uses user_account_form_validate() as the validate and user_register_submit() as the submit callbacks.
You have to copy these two functions and then adjust them as you want. Basically, in the validate function, remove the form_set_error() and add the same check in submit instead, where you use the functionality of user_pass_submit() to send the mail.
Answer: I would look at
    function yourtheme_form_user_register_form_alter(&$form, &$form_state, $form_id)
and the associated functions.


Can joomla be configured to browser through a proxy server?

Question: In wordpress there are some simple variables that can be set to make the configuration of a navigation proxy server trivial.
<code>var $proxy_host = ""; // proxy host to use
var $proxy_port = ""; // proxy port to use
var $proxy_user = ""; // proxy user to use
var $proxy_pass = ""; // proxy password to use
</code>
Are there any equivalents to accomplish the same for joomla?
I've been searching on internet and couldn't find anything.
For the original wordpress source see here
Answer: I am currently using this to set the proxy with my servers, it works on everythin except for joomla, so there's probably something being force in joomla's side.
http://php.net/manual/en/function.stream-context-set-default.php
Answer: I'm updating the question with a definitive answer, as the time passed the proxy feature was integrated into joomla, and it's now present on Joomla 3.3 (you just have to check it in general configuration settings), the ticket with the discussion can be found here
So basically, as of joomla 3.3 proxy is working


Trouble with DNS resolution on and Microk8s cluster

Question: My microk8s cluster is running on a centos8 vm and I have some issues with DNS resolution of my pods. Nameserver are at x.x.x.101 and x.x.x.100 both are ping able from within the pods and I can also ping 18.104.22.168
nslookup from within a pod looks like this:
root@debug-7857894f66-mnklp:/# nslookup kubernetes.default
Server:         10.152.183.10
Address:        10.152.183.10#53

Name:   kubernetes.default.svc.cluster.local
Address: 10.152.183.1

coredns config looks like this:
apiVersion: v1
data:
  Corefile: ".:53 {\n    errors\n    health {\n      lameduck 5s\n    }\n    ready\n
    \   log . {\n      class error\n    }\n    kubernetes cluster.local in-addr.arpa
    ip6.arpa {\n      pods insecure\n      fallthrough in-addr.arpa ip6.arpa\n    }\n
    \   prometheus :9153\n    forward .  x.x.x.101 x.x.x.100 \n    cache 30\n
    \   loop\n    reload\n    loadbalance\n}\n"
kind: ConfigMap
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","data":{"Corefile":".:53 {\n    errors\n    health {\n      lameduck 5s\n    }\n    ready\n    log . {\n      class error\n    }\n    kubernetes cluster.local in-addr.arpa ip6.arpa {\n      pods insecure\n      fallthrough in-addr.arpa ip6.arpa\n    }\n    prometheus :9153\n    forward .  x.x.x.101 x.x.x.100 \n    cache 30\n    loop\n    reload\n    loadbalance\n}\n"},"kind":"ConfigMap","metadata":{"annotations":{},"labels":{"addonmanager.kubernetes.io/mode":"EnsureExists","k8s-app":"kube-dns"},"name":"coredns","namespace":"kube-system"}}
  creationTimestamp: "2021-08-31T08:57:27Z"
  labels:
    addonmanager.kubernetes.io/mode: EnsureExists
    k8s-app: kube-dns
  name: coredns
  namespace: kube-system
  resourceVersion: "2420090"
  selfLink: /api/v1/namespaces/kube-system/configmaps/coredns
  uid: 471b258a-253d-4b51-aaf7-7e934ab300d1

the /etc/resolv.conf in my pods looks like this:
search default.svc.cluster.local svc.cluster.local cluster.local xxx.xxxxx
nameserver 10.152.183.10
options ndots:5

when I look at the logs of my kube-dns with $ microk8s kubectl logs --namespace=kube-system -l k8s-app=kube-dns I get the following response:
[INFO] 10.1.107.105:47549 - 5288 "AAAA IN www.google.com. udp 36 false 512" NOERROR - 0 0.000256103s
[ERROR] plugin/errors: 2 www.google.com. AAAA: read udp 10.1.107.127:51486->x.x.x.101:53: read: no route to host

DNS service is up:
$ microk8s kubectl get svc --namespace=kube-system
NAME                        TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                  AGE
[...]
kube-dns                    ClusterIP   10.152.183.10    <none>        53/UDP,53/TCP,9153/TCP   21d

DNS endpoints are exposed:
$ microk8s kubectl get endpoints kube-dns --namespace=kube-system
NAME       ENDPOINTS                                           AGE
kube-dns   10.1.107.127:53,10.1.107.127:53,10.1.107.127:9153   21d

The virtual machine the cluster is running on is using the same nameserver without a problem. Is this something I need to bother our admins about, or am I missing something that is wrongly configured?
EDIT:
Okay I tried out a bit more and there is some weird behavior that I think has to do with me incorrectly creating the coredns config file. I completely reset the cluster and tried again, still same error when I use 220.127.116.11 or 18.104.22.168 as DNS servers. But, when I run the following command: $ microk8s enable dns:x.x.x.101,x.x.x.100 finally it works. Then I tried to configure for this with $ microk8s kubectl -n kube-system edit configmap/coredns and I add both DNS to the config it stops working, and I again get the error: [ERROR] plugin/errors: 2 www.google.com. AAAA: read udp 10.1.107.127:51486->x.x.x.101:53: read: no route to host so what is wrong with my configuration that is automatically correctly set with $ microk8s enable dns:x.x.x.101,x.x.x.100 ?
2nd Edit
I tried to use dig here even when I specify a DNS server it is not working. Is there any reason ping could go through but DNS is blocked by the system? It only happens on the microk8s cluster, host system runs fin docker runs fine ...
here are the printouts:
this is from within the pod:
root@debug-865cb7fb4-wfhw4:/# dig www.google.com

; <<>> DiG 9.11.5-P4-5.1+deb10u5-Debian <<>> www.google.com
;; global options: +cmd
;; connection timed out; no servers could be reached
root@debug-865cb7fb4-wfhw4:/# dig @x.x.x.101 www.google.com

; <<>> DiG 9.11.5-P4-5.1+deb10u5-Debian <<>> @x.x.x.101 www.google.com
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached
root@debug-865cb7fb4-wfhw4:/# dig @18.104.22.168 www.google.com

; <<>> DiG 9.11.5-P4-5.1+deb10u5-Debian <<>> @220.127.116.11 www.google.com
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached
root@debug-865cb7fb4-wfhw4:/# dig @x.x.x.100 www.google.com

; <<>> DiG 9.11.5-P4-5.1+deb10u5-Debian <<>> @x.x.x.100 www.google.com
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached

and this is from the host system:
$ dig www.google.com

; <<>> DiG 9.11.20-RedHat-9.11.20-5.el8_3.1 <<>> www.google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 25735
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4000
;; QUESTION SECTION:
;www.google.com.                        IN      A

;; ANSWER SECTION:
www.google.com.         113     IN      A       18.104.22.168

;; Query time: 0 msec
;; SERVER: x.x.x.101#53(x.x.x.101)
;; WHEN: Fri Oct 08 15:10:21 CEST 2021
;; MSG SIZE  rcvd: 59

$ dig @126.96.36.199 www.google.com

; <<>> DiG 9.11.20-RedHat-9.11.20-5.el8_3.1 <<>> @184.108.40.206 www.google.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 3924
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;www.google.com.                        IN      A

;; ANSWER SECTION:
www.google.com.         300     IN      A       22.214.171.124

;; Query time: 34 msec
;; SERVER: 18.104.22.168#53(188.8.131.52)
;; WHEN: Fri Oct 08 15:10:49 CEST 2021
;; MSG SIZE  rcvd: 59

$ dig @x.x.x.101 www.google.com

; <<>> DiG 9.11.20-RedHat-9.11.20-5.el8_3.1 <<>> @x.x.x.101 www.google.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 60305
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4000
;; QUESTION SECTION:
;www.google.com.                        IN      A

;; ANSWER SECTION:
www.google.com.         70      IN      A       184.108.40.206

;; Query time: 0 msec
;; SERVER: x.x.x.101#53(x.x.x.101)
;; WHEN: Fri Oct 08 15:11:04 CEST 2021
;; MSG SIZE  rcvd: 59

I have no idea what seems to be going on ....
Comment: Which version of Kubernetes did you use?
Comment: I'm using Kubernetes v1.22
Comment: Please provide your pod yaml file.
Comment: I rebuild the cluster in an infrastructure that is fully under my control, there DNS works.
Comment: It seems to be an issue connected to iptables and the firewall on the host, if I disable both the problem goes away I'll post and answer as soon as I know how to correctly configure these tools.
Answer: I have posted a community wiki answer for better visibility.
As Thagor has mentioned in the comment, problem is resolved and was related to external DNS:

I rebuild the cluster in an infrastructure that is fully under my control, where DNS works.

Try disabling the iptables and the firewall on the host and see if you are able to do via coredns config.
More information about DNS you can find in the official documentation.
Comment: Hello @Thagor. Does this [answer your question](https://stackoverflow.com/help/someone-answers)?
Comment: hey i updated my first post turns out DNS works if i set it with `$ microk8s enable dns:x.x.x.100,x.x.x.101` but as soon as I try to do it via the coredns config it fails, and I have no idea why.


Estou com problemas ao criar um Chatbot em Python

Question: <code>from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('HiAsda')

#Cria um novo treinador para o bot
trainer = ChatterBotCorpusTrainer(chatbot)

#Treina o chatbot baseado no corpus
trainer.train("chatterbot.corpus.portuguese.greetings")
#obtem uma resposta a uma declaração de entrada
chatbot.get_response("Olá, como você está? ")
</code>
Retorna
<code>"C:\Users\Familia Pantoja\chatterbot01\venv\Scripts\python.exe" "C:/Users/Familia Pantoja/chatterbot01/Programa/__init__.py"
Traceback (most recent call last):
  File "C:/Users/Familia Pantoja/chatterbot01/Programa/__init__.py", line 1, in <module>
    from chatterbot import ChatBot
  File "C:\Users\Familia Pantoja\chatterbot01\venv\lib\site-packages\chatterbot\__init__.py", line 4, in <module>
    from .chatterbot import ChatBot
  File "C:\Users\Familia Pantoja\chatterbot01\venv\lib\site-packages\chatterbot\chatterbot.py", line 2, in <module>
    from chatterbot.storage import StorageAdapter
  File "C:\Users\Familia Pantoja\chatterbot01\venv\lib\site-packages\chatterbot\storage\__init__.py", line 1, in <module>
    from chatterbot.storage.storage_adapter import StorageAdapter
  File "C:\Users\Familia Pantoja\chatterbot01\venv\lib\site-packages\chatterbot\storage\storage_adapter.py", line 3, in <module>
    from chatterbot.tagging import PosHypernymTagger
  File "C:\Users\Familia Pantoja\chatterbot01\venv\lib\site-packages\chatterbot\tagging.py", line 4, in <module>
    from chatterbot.tokenizers import get_sentence_tokenizer
  File "C:\Users\Familia Pantoja\chatterbot01\venv\lib\site-packages\chatterbot\tokenizers.py", line 4, in <module>
    from chatterbot.corpus import load_corpus, list_corpus_files
  File "C:\Users\Familia Pantoja\chatterbot01\venv\lib\site-packages\chatterbot\corpus.py", line 5, in <module>
    from chatterbot_corpus.corpus import DATA_DIRECTORY
ModuleNotFoundError: No module named 'chatterbot_corpus'

Process finished with exit code 1
</code>
Podem me orientar? Sou novo em programação e novo em python
Comment: A aplicação depende de um módulo que não está instalado. *ModuleNotFoundError: No module named 'chatterbot_corpus'*. Basta instalá-lo.
Answer: Olá!
Também sou novo com python, estou fazendo um "curso" para criar um chatbot e usa-lo no whatsapp...
...bom, eu também obtive este mesmo erro e procurando por ai afora,
rodei este comando dentra da pasta onde esta instalado o Anaconda3
conda uninstall PyYAML
diversos pacotes foram atualizados e tambem alguns foram removidos.
Terminado o processo, rodei o comando
pip install chatterbot_corpus
Foi instalado, porém esta solicitando novos pacotes no qual estou instalando.
Resumindo, com o comando do "conda uninstall" consegui fazer o downgrade do PyYAML e com isso seguir o "enterro"...
Espero que funcione para você.
Abraços e sucesso no projeto!


Creating and using streams in iOS 5

Question: Bear with me please, I'm a new programmer. (things I say might not make sense)
I'm trying to create an inputStream and outPut stream so that I can write to it using JSON objects elsewhere in the class...
I wanted to know if I'm doing it right. Currently, I'm opening the streams in -(id)init{}
<code> -(id)init{
_isNetworkAvailable = FALSE;
//kCFAllocatorDefault is the same thing as Null
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)requestURL, port, &readStream, &writeStream);

NSInputStream *inputStream = (__bridge NSInputStream *)readStream;
NSOutputStream *outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
//There should really be some checking going on here, but we're going to forget it for now
//Call some checking method
_isNetworkAvailable = TRUE;

return self;
 }
</code>
My question is: is this the right way to handle something like this? Should I declare NSInputStream and NSOutputStream elsewhere?
Why do I have to cast my CFStreams as NSStreams?
Comment: Because `CFStream`s are a C type, and `NSStream`s are an Objective-C type. If you want to use the C API in Core Foundation for `CFStream`s, go ahead. But don't expect to use `NSStream` methods on a `CFStream`.
Comment: @Linuxios they are toll-free bridged. See: http://developer.apple.com/library/ios/#qa/qa1652/_index.html.
Comment: @idz: I know. But to use the tool-free bridging, you still need to cast it using the `(__bridge NSThing)someCFThing` syntax.
Comment: @Linuxios, OK, that just wasn't very clear from your comment (e.g. you did not mention casting and "don't expect to use `NSStream` methods on a `CFStream`" could be taken to imply that it would not work).
Comment: @idz: Thanks for telling me that. I ment you can't use `NSStream` methods *directly* on a `CFStream`. That's all.
Comment: Thanks for the comments, it makes more sense now
Answer: With some testing, this was the proper way of creating streams.
CFStreams are cast to NSStreams because NSStreams are obj-c native and provide more options and flexibility with use. NSStream is actually based on CFStream (which is a wrapper on BSD sockets).
This code should always be run asynchronously, as far as I can tell, or you'll see some hanging during runtime.

Creating and using streams in iOS 5


Requisição ajax não está funcionando

Question: estou tendo problemas para fazer uma requisição via ajax.
A ideia é que ao sair no campo e-mail seja feita uma verificação no banco de dados se há ou não um e-mail igual registrado, porém se eu uso o "dataType: 'json'" ele não funciona. Fuciona apenas com "dataType: 'html'".
Agradeço se alguém souber me dizer o porquê disso.
index.php:
<!DOCTYPE html>

    <title>Consulta de Email</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

   <form id="form1" class="form1" method="post">
        email:

            <input type="text" name="email" id="email"/>

        senha:

            <input type="text" name="senha" id="senha"/>

        <input type="submit" value="Salvar Dados" />

    </form>

email.js:
$(document).ready( function() {
   $('#email').blur(function(){
           $.ajax({
                url : 'consultar_email.php',
                type : 'POST',
                data: 'email=' + $('#email').val(),
                dataType: 'json',
                success: function(data){
                    if(data.cadastrado == true){
                        alert("email já cadastrado");
                    }
                    else{
                        alert("email não cadastrado");
                    }
                }
           });
           return false;
   })
});

consultar_email.php
<?php
include_once("Classes/dadosDoBanco.php");
$cliente = new DadosCliente();

$email = $_POST['email'];

$sql = "SELECT * FROM cliente";
$totalReg = $cliente->totalRegistros($sql);

for($i=0;$i<$totalReg;$i++)
{
    $cliente->verDados($sql, $i);
    $email2 = $cliente->getEmail();

    if($email == $email2)
    {
        $dados['cadastrado'] = true;
    }
    else
    {
        $dados['cadastrado'] = false;
    }
}

echo json_encode($dados);
?>

Comment: Na linha data: 'email=' + $('#email').val(). Altere para data: {'email': $('#email').val()}
Comment: Seu código não aparenta erro. Na sua página **consultar_email.php** deixe apenas `echo json_encode( array('cadastrado' => false) );` para ver se há algum erro escapando no PHP antes de retornar o json.
Comment: @touchmx da forma que estava ele funciona, o que ta dando problema é o dataType: 'json', eu acabei de trocar por dataType: 'html' e funcionou certinho, saberia me dizer o motivo?
Comment: Se você der um `alert(data.cadastrado)` qual é o retorno?
Comment: o problema é que ele não chega a passar pela parte $.ajax, e não chama o outro arquivo.
Comment: não apresenta, eu já testei essa parte sem chama-la através do ajax, e funciona como deveria
Comment: @Vinícius já testou `data: {email: $('#email').val(),` em vez de `data: 'email=' + $('#email').val(),` como foi sugerido aqui?
Comment: @Sergio sim, já testei, porém desta forma não funciona
Answer: O problema não é ao enviar o dado para o server, pois o jQuery envia por padrão os dados com o mimeType application/x-www-form-urlencoded, que é o correto para o método POST.
O dataType é utilizado pelo jQuery para determinar como tratar o resultado do request. No seu caso json deveria funcionar. Como você não postou o erro que está ocorrendo fica difícil de dizer o motivo.
Eu chutaria que o jQuery está identificando de forma errada o tipo do retorno da request quando você coloca json. Tente setar o Content-Type no PHP para application/json, pois o jQuery usa essa informação para descobrir qual o tipo do retorno.
Comment: eu fiz o código igual a [este](http://www.rafaelwendel.com/2012/08/preenchimento-automatico-do-endereco-a-partir-do-cep/) e tive o msm problema, ele nem chega a fazer a requisição ajax
Comment: Mas qual o erro? Não aparece nada no console do Chrome?
Comment: não acusa nenhum erro
Comment: O problema é de javascript então. Se você colocar um alert antes do $.ajax, aparece algo?
Comment: aparece, mas após isso não
Comment: Algum erro está ocorrendo dentro do $.ajax do JQuery. Utilize a opção error para identificar o problema. Sugiro você debugar via Developer Tools do Chrome.
Comment: tentarei, obrigado!
Answer: Cara, o código só funciona quando você seta o dataType como html porque no seu php você esta retornando html ao invés de json, vou explicar...
por mais que no seu php você esteja retornando um:
echo json_encode($dados);

Você não setou um Header, se você abrir o inspector do seu browser e ver o http-response-header da sua requisição, verá que ela esta retornando um content-type: text/html
Para corrigir este problema, antes do seu retorno no php, você deve setar o header como json, assim :
header('Content-type: application/json');
echo json_encode($dados);

Answer: Quanto você define um valor para dataType, o tipo escolhido deve ser usado tanto para valor enviado pelo ajax no campo "data" como para o valor retornado pelo php, que no seu caso e json.
Tenta fazer assim:
$.ajax({
     url : 'consultar_email.php',
     type : 'POST',
     data: {"email":$('#email').val()}, //Alterado como JSON
     dataType: 'json',
     success: function(data){
        if(data.cadastrado == true){
           alert("email já cadastrado");
        }
        else{
           alert("email não cadastrado");
        }
     }
});

Obs.: Não esquece de retornar um JSON do PHP
Answer: Não sei se é o seu caso também mas tive um problema parecido quando alterei a versão do PHP no Wamp para 7.2, normalmente eu uso o PHP5.6 ou PHP 7.1, um dia alterei para o 7.4 para fazer uns teste em um projeto novo e não passava pelo $.ajax de jeito nenhum, quando lembrei que tinha mudado a versão do PHP voltei para o PHP 7.1 e voltou a funcinar normal.
Answer: Vinícius não sei se você resolveu o seu problema depois de muito tempo. Tenta definir as variáveis colocando uma condicional if(isset($_POST)) OU if(isset($_GET) sem informar o name

Requisição ajax não está funcionando


How diagnose why Java app fails to open a socket (after running successfully for a while)

Question: I'm trying to diagnose why a Java-based app runs for a while as a client making SOAP webservice calls, and then starts hitting an exception whereby it cannot open a socket. The OS is Windows 2003 server SP1.
The netstat -an output shows some connections in CLOSE_WAIT or TIME_WAIT, but not enough to suggest that the OS itself is out of sockets.
I suspect that there's an error in the way that the client-side API is being used (Axis2 v1.4), such that it fails to recycle some internal resource. Once we hit the condition of not being able to open a socket, we have to restart the Java app.  (Somewhat strangely, though, we can still make a call out using simple java.net.URL).
I'm wondering if we can use Wireshark/Ethereal or similar to help diagnose the problem from an OS/network standpoint?
In case it is useful, our Java stack trace is:

Caused by: java.net.ConnectException: Connection timed out: connect at
  java.net.PlainSocketImpl.socketConnect(Native Method) at
  java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at
  java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at
  java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at
  java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at
  java.net.Socket.connect(Socket.java:516) at
  java.net.Socket.connect(Socket.java:466) at
  java.net.Socket.(Socket.java:366) at
  java.net.Socket.(Socket.java:239)

Many thanks for any insight.
Dan Haywood
Comment: I can't see the problem. "Connection timed out". The server is not responding in time.
Answer: The first line in the Java stack trace says java.net.ConnectException: Connection timed out. This indicates that the client side successfully created its client socket and attempted to contact the server, however no response came back. Your problem is not in the client. My advice is to investigate whether the remote server is up. Next ensure there is no networking issue preventing the client from contacting the server.
Comment: Thanks for this; that's useful info in its own right.  However, some diagnostic code was added to call the test web service when the prod web service failed, and that also timed out.  It seems odd that it would take down a different server also.  In any event, would Wireshark/ethereal show me outbound packets in this situation.
Comment: Wireshark would help determine what's going on. If you can see outbound packets without response, you know it's something external causing the problem.