Exchange 2010 don't see its PDC (same machine)

Question: I have two 2008 R2 servers which should replicate AD. One si production server, second backup. On primary server is also Exchange 2010. There were plans about a year ago to install exchange to backup server to to replicate and serve as backup in case primary server is unavailable. My former colleague completed first two steps (or may be just one) in Exchange install as presented by exchange installer (I think it has to do something with AD integration and redistributables installation). Today I accidentally broke backup server (probably bad drivers) and from the moment backup server went down, Exchange on primary server is not working. Exchange Active directory topology complains that it cannot find any suitable DCs, Active directory complains that it doesn't feel like servicing clients and application because it may be in wrong state, because of nonfuctional replication. Primary server is FSMO for all roles. By looking into historic logs I found that Eschange doesn't see domain controller it resides on since I fiddled with DNS servers and routing on our network. I remeber I changed network masks and some firewall setings, as a result primary DNS on primary server was backup server and secondary was itself. Any ideas how to fix it, so Exchange see its own machine as PDC?
Some logs:

Process MSEXCHANGEADTOPOLOGYSERVICE.EXE (PID=1884). Exchange Active
  Directory Provider has discovered the following servers with the
  following characteristics:
(Server name | Roles | Enabled | Reachability | Synchronized | GC
  capable | PDC | SACL right | Critical Data | Netlogon | OS Version)
  In-site:
  primary   CDG 1 0 0 1 0 0 0 0 0
  backup    CDG 1 0 0 1 0 0 0 0 0

Process MSEXCHANGEADTOPOLOGYSERVICE.EXE (PID=1884). All Domain
  Controller Servers in use are not responding:  primary secondary
The Microsoft Exchange Replication service attempted to start the
  Active Manager RPC server but failed because an error occurred when
  attempting to read the Exchange Servers universal security group SID
  from Active Directory. Error:  The Microsoft Exchange Active Directory
  Topology service on server localhost did not return any suitable
  domain controllers.

Process STORE.EXE (PID=1960). Topology discovery failed, error
  0x80040a02 (DSC_E_NO_SUITABLE_CDC). Look up the Lightweight Directory
  Access Protocol (LDAP) error code specified in the event description.
  To do this, use Microsoft Knowledge Base article 218185, "Microsoft
  LDAP Error Codes." Use the information in that article to learn more
  about the cause and resolution to this error. Use the Ping or PathPing
  command-line tools to test network connectivity to local domain
  controllers.

When I look into logs older than backup server shut-down I see this:

Process MAD.EXE (PID=9556). Exchange Active Directory Provider has
  discovered the following servers with the following characteristics:
  (Server name | Roles | Enabled | Reachability | Synchronized | GC
  capable | PDC | SACL right | Critical Data | Netlogon | OS Version)
  In-site:
primary  CDG 1 0 0 1 0 0 0 0 0
secondary    CDG 1 7 7 1 0 1 1 7 1
  Out-of-site:

UPDATE:
Ok, After starting backup(secondary) server I got: primary CDG 1 0 0 1 0 0 1 0 0 secondary CDG 1 7 0 1 0 1 0 0. After fixing netlogon service not starting on backup server (and thus nonfunctional replication) because of some remnants of rename a long time ago I am back at operational: primary CDG 1 0 0 1 0 0 0 0 0 secondary CDG 1 7 7 1 0 1 1 7 1 What puzzles me, is, why it still can't see its own machine. Any suggesstions?
Comment: Ok, After starting backup(secondary) server I got: primary CDG 1 0 0 1 0 0 1 0 0 secondary CDG 1 7 0 1 0 1 0 0. After fixing netlogon service not starting on backup server because of some remnants of rename a long time ago I am back at operational: primary CDG 1 0 0 1 0 0 0 0 0 secondary CDG 1 7 7 1 0 1 1 7 1 What puzzles me, is, why it still can't see its own machine. Any suggesstions?
Answer: There is no such thing as a Primary Domain Controller or a Backup Domain Controller unless you are using Windows NT4. That's your first problem.
Your replication problem can be caused by your "secondary" DC using itself as the primary DNS resolver. Don't do that. A DC should never have itself listed first in the DNS resolver list. It can cause a replication island like the one you're seeing.
Fix replication and stop treating your second DC like it's a backup. They're both live, both respond to authentication requests, and are peers. Once you do this, your problems will likely resolve themselves.
Comment: I had DNS servers set up like this all the time (primary - replication partner, secondary - itself). As for primary and backup DCs, that is just naming convention and reflects intended use (backup DC is off-site). At the time of your answer, replication was functional, as it was functional before secondary DC shutdown, however exchange had problems finding AD on its own machine. None the less it's solved now.
Answer: Everthing fixed now. Problem was disabled IPv6 on primary server. Automatic IPv6 address is enough to make it work. Exchange and AD on same machine probably communicate with each other only by using IPv6 and cannot use IPv4. Servers see themselves because if they are on other machines, they can use IPv4 to communicate. I tried demultihoming primary server but without any change. I tried changing NIC properties on backup server and after disabling IPv6, AD on secondary server had problems seeing primary server as online (but replicated non the less). Thus I enabled IPv6 on both and everything is working now.


How to put strap on acoustic electric?

Question: How does one put a strap on an acoustic electric guitar?  Is there a special strap to buy just for acoustic electrics?
The reason I ask is that the lower strap button also serves as the jack for the guitar cable.  It has a wide diameter, and I find it to be too wide for my guitar strap.  Just getting it on there is an intense struggle.  And then, once on, it doesn't want to stay, because to me, it seems like the strap was not designed for a button this wide.  And so I bought little rubber disk-shaped strap locks, and those won't even go on at all because this jack/button is too wide and the rubber won't stretch that far, not to mention that the design of this jack/button does not provide enough room for both the strap AND the strap lock.
Based on all the troubles I have had, I have lately begun assuming that this guitar is designed for some other special strap.
I'm not sure if my model matters but if so it is a Martin 000cxe.
Thanks for any assistance!
Answer: Some minor surgery with an exacto knife, utility knife or a pair of very sharp scissors should do the trick. See my illustration below. First elongate the slot a bit (blue line). If the diameter of the post is bigger than the hole and it still doesn't sit right then cut the circle out a little more (red line) One might do the trick but both will definitely work. Be very careful not to cut yourself and not to cut too much off the strap.
Comment: Lately I've been buying belts - 3" wide - from charity shops, etc. At £1 a piece, they're good value, and with a craft knife and a bit of care, they make great guitar straps. Most non-adjustable in the end, but since it's me wearing them, who cares? This solution seems so obvious! Only downside is, can't use straploks with those buttons/sockets.+1.
Comment: I'd suggest getting a suitable sized leather punch (available from the usual online suppliers) - that's what I use to adjust holes in straps to accomodate strap locks. Much easier to get it right and tidy than using a knife. See (e.g.) https://www.amazon.co.uk/Pieces-Hollow-Leather-Punch-Heavy/dp/B07L1G5J8V
Comment: @MarkBluemel Yes a hole punch will give you a cleaner hole for sure if you have or want to buy a set. Without having one large enough for a strap  I've done ok with a little care and patience. It doesn't look super pretty but it's covered by the wide part of the strap button.
Comment: @Tim That's a great idea if they're long enough, especially since a decent leather strap costs $30-$100. I have bought large sheets of leather and made my own straps. I can customize the width and length I want. The hard part is getting nice clean straight cuts the length of the strap.
Comment: 5'4" and wearing guitar/bass high means most will fit! Only problem is if the leather's too thick, it won't take Dunlop straploks easily - or at all. But now, I can have a dedicated strap (whatever colour) for each, rater than having to remember to swap one strap over for gigs. Carrying gaffer tape has got me out of that trouble before. Doubled, it's plenty strong enough, if a tad uncomfortable. A good sharp craft knife, or scalpel, along a metal straightedge the whole length ought to do the cutting well.
Answer: John's idea is the best, but, if you need to use a locking end, you'll have to drill another hole somewhere near the original strap button, for the locking button. Or, better, maybe, depending on skill level, put the locking button where the jack socket is, and replace that in another position with another jack socket in a convenient place, further round the curve of the body.

How to put strap on acoustic electric?


How can i list Cassandra cql result? Do i have to parse JSON?

Question: How can i parse my json style result from Cassandra?
I'm using the cassandra-cql gem for rails and i want to parse the query result to list all messages. My query looks like:
def self.get_messages uid
  @@db.execute("SELECT * FROM messages WHERE uid=?", uid)
end

how can i list all messages? My current view is:
<% json_dec = ActiveSupport::JSON.decode(u.row.to_json) %>
<% json_dec.each do |f| %>
  <%= f[1] %>

<%end%>

and it returns:
1
[{"name"=>"uid", "value"=>"1", "timestamp"=>-1}, {"name"=>"1326751801", "value"=>"test content", "timestamp"=>1326751801970000}, {"name"=>"1326754147", "value"=>"some content to test", "timestamp"=>1326754147612000}]

Is there any better way for the query? how do others solve this problem?
Answer: Encoding to json and the decoding again doesn't make much sense. Instead you can call #to_hash on the row object which will give you a hash of column_name => value. Then you could iterate over that:
<% row.to_hash.each do |key, value| %>

key: <%= key %>, value: <%= value %>

<%end%>

It also looks like you need to change your implementation of get_message to call fetch:
def self.get_messages uid
  @@db.execute("SELECT * FROM messages WHERE uid=?", uid).fetch
end


Como exibir um item de um enum em minha table usando AngularJs?

Question: Eu tenho uma tabela em que faço um ng-repeat, até aqui normal.

                            {{::item.Description}}
                            {{::item.Order}}
                            {{::item.Type}}

Só que o campo Type da minha tabela que é um campo INT, eu teria que ao invés de exibir esse valor inteiro, exibir um item da minha tabela enum.
No meu controller eu já estou trazendo os enuns...
        AuditingItemType.query().$promise.then(function (itemtypes) {
        $scope.itemtypes = itemtypes;
    })

Json que recebo da tabela enum
[{"$id":"1","Id":0,"Name":"TEXT"},{"$id":"2","Id":1,"Name":"QUANTITY"},{"$id":"3","Id":2,"Name":"MULTIPLE"}]

como eu posso exibir ele em minha tabela dinamicamente?
Comment: Não...
    public enum AuditingItemType
    {
        TEXT,
        QUANTITY,
        MULTIPLE
    }
Comment: Jhonas, seu enum já possui a annotation description?
Comment: Está utilizando WebAPI 2.0?
Comment: Estou usando sim.
Answer: Uma possibilidade é criar um ng-repeat interno, e filtrar o conteúdo - só exibir a descrição quando o valor de Id for igual ao Type do elemento referenciado pelo laço principal.
Exemplo a seguir:

function SampleController($scope) {

  $scope.itemsconfiguration = [
    {"Description": "Secretaria", "Order": 2, "Type":2, "Active": 0},
    {"Description": "Patrimonio", "Order": 3, "Type":3, "Active": 1},
    {"Description": "Tesouraria", "Order": 2, "Type":2, "Active": 1}
  ];

  $scope.itemtypes = [
    {"$id":"1","Id":0,"Name":"TEXT"},
    {"$id":"2","Id":1,"Name":"QUANTITY"},
    {"$id":"3","Id":2,"Name":"MULTIPLE"},
    {"$id":"3","Id":3,"Name":"OTHER"}
  ];

}

        Descrição
        Ordem
        Tipo
        Ativo

          {{item.Description}}
          {{item.Order}}

              {{type.Name}}

          X


Check if the mouse and spacebar are pressed at the same time in QML

Question: I'd like to check whether or not the mouse and the spacebar keys are being pressed at the same time using QML
I can check if the mouse and other modifier keys are being pressed. For instance:
MouseArea {
  onPressed: {
    if(mouse.modifiers & QT.ControlModifier) {
      // do something
    }
  }
}

However, the only way I know how to check for keys is inside of the Keys.onPressed handlers. Is there a way to communicate between the MouseArea onPressed and Keys.onPressed in unison?
Comment: What does _the same time_ mean? There will always be a small gap in time. So you can start a timer when one of them was pressed and check the time difference when the second one will do.
Comment: @folibis Same time meaning detect if the two keys are held down concurrently. The part that's tripping me up is where to place the Keys.onPressed handler. Since I (assume) I can't nest it inside of the mouse area block. I need to be able to pass some information between the MouseArea onPressed and the Keys.onPressed.
Answer: Here is example code of the same issue:
MyItem.qml
import QtQuick 2.12

Rectangle {
    id: element
    width: 100
    height: 100
    color: "orange"
    signal mySignal()
    property int myState: MyItem.Bits.None
    enum Bits {
        None = 0,
        MouseOn = 1,
        KeyOn = 2,
        AllOn = 3
    }

    function checkBits()
    {
        if(element.myState === MyItem.Bits.AllOn)
        {
            element.mySignal();
            element.myState = MyItem.Bits.None;
        }
    }

    MouseArea {
        anchors.fill: parent
        onPressed: {
            element.myState |= MyItem.Bits.MouseOn;
            element.checkBits();
        }
        onReleased: {
            element.myState &= ~MyItem.Bits.MouseOn;
            element.checkBits();
        }
    }
    Keys.onSpacePressed: {
        element.myState |= MyItem.Bits.KeyOn;
        element.checkBits();
    }
    Keys.onReleased: {
        if(element.myState & MyItem.Bits.KeyOn)
        {
            element.myState &= ~MyItem.Bits.KeyOn;
            element.checkBits();
        }
    }
}

main.qml
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 600
    height: 400

    MyItem {
        anchors.centerIn: parent
        focus: true
        onMySignal: {
            console.log("My Signal")
        }
    }
}

MySignal will be fired on simultaneously Mouse and Space clicking.
Note, enum requires Qt 5.10 or higher


Sidekiq won't shut down after Ctrl+C

Question: I'm using Sidekiq for background operations of my Rails 4.1 app.
When I type Ctrl+C to shutdown Sidekiq, Sidekiq catches the signal but seems to freeze after this last log line:
<code>^C2014-09-18T16:17:19.194Z 20686 TID-ovwtinh0g INFO: Shutting down
2014-09-18T16:17:21.041Z 20686 TID-ovwtixflc INFO: Shutting down 5 quiet workers
</code>
Thus, I need another terminal window where I need to type:
<code>bundle exec sidekiqctl stop pidfile
</code>
This is really inconvenient (and takes about 8 seconds) and I can't find why Sidekiq won't stop properly with Ctrl+C.
My conf is:

Rails 4.1.5
Sidekiq 3.2.4
Postgresql DB
Comment: Instead of opening another terminal window you can also press `ctrl-z` to move sidekiq to the background. Then you can stop sidekiq with `sidekiqctl`.
Answer: I came across this same issue.  Sidekiq 3.2.4 relies on the Celluloid gem at version 0.16.0, which partially breaks Sidekiq. See here: https://github.com/celluloid/celluloid/issues/457
Update Sidekiq to 3.2.5 which locks Celluloid at version 0.15.2.
Comment: Still applicable. Thanks!
Answer: It's possible you have another thread in your Sidekiq process which is not stopping, maybe because you are rescuing Exception.
Comment: I don't think this is my issue cause workers won't shut down nicely even when they all had no jobs to process in their whole lifetime.

Sidekiq won't shut down after Ctrl+C


nginx passenger - restart app periodically or when it reaches too high memory

Question: I have a memory leak on one of my apps being served with nginx + passenger and a min/max_instances 2 setting. Memory keeps growing up as time passes by, and this can be a problem on a machine with limited memory (eg Amazon Web Services) that can end up crashing badly.
Is there a way / trick to restart some passenger processes of the same app, either periodically or when memory reaches a certain threshold ?
Suppose I have an application group A that can start up to 2 processes A1 and A2. I'd like to restart A1 and A2 one at a time to ensure service continuity (this is not a zero-downtime deployment since it relies on the same unmodified app, but some way to purge the memory leak and restart a fresh process until I figure out the problem).
Eg suppose I have the following state:
Requests in queue: 0
  * PID: 11124   Sessions: 0       Processed: 14638   Uptime: 1d 12h 31m 29s
    CPU: 0%      Memory  : 341M    Last used: 24s
  * PID: 11131   Sessions: 0       Processed: 9323    Uptime: 1d 12h 31m 29s
    CPU: 0%      Memory  : 389M    Last used: 24s

Process n°2 starts taking up a lot of memory (~400) so I'd like to restart it (and only this process) which should bring it back to 100MB ish, and I'd do the same with Process n°1 later
The memory leak takes some time to build and it would be best if I could restart only when detecting too high memory usage, but if I can schedule a process restart every night or so this could also work totally fine (eg restart process n°1 at 3am, then process n°2 at 4am)
Is there any signal I can send to this passenger group that would let me restart processes one by one ?
Answer: If this is your production application, I'd suggest you go with passenger enterprise. There is a nice feature you can add to the nginx config:
passenger_memory_limit 1024;
Passenger will reload the process when the memory hits 1024 or whatever number you want to specify. You can also take advantage of multi-threading since passenger standalone is single threaded.
Answer: This is may be a little bit to late for the OP, but we have the following cron-script running on our AWS hosts every minute:
#!/bin/bash
let "TARGET = 400 * 1024" # = 400 MB
ps aux --sort -rss | grep "Passenger RackApp" | while read -r LINE; do
        read PID MEMORY <<< $(echo $LINE | awk '{ print $2; print $6 }')
        if [ $MEMORY -gt $TARGET ]
        then
                `kill -15 $PID`
        fi
done
exit 0

Depending on the configuration, passenger will immediately re-spawn the stopped process.


How to set fixed column widths in PrimeNG table? (Autolayout property is now deprecated)

Question: I used to be able to add style="width: 25%" to the th elements in the template of the primeng table. However, it appears that this no longer works and their documentation states that autolayout is now deprecated and the table's layout is always auto. This is making my table look absolutely awful and unaligned. Is there any way around this? I've tried adding style classes to the th elements manually but this hasn't worked. https://i.stack.imgur.com/sAnjl.png
Answer: I on my case I can still assign a specific width to 'th' elements and it works (primeng v15.2.0).
What happens to me is that for columns where I don't specify the width, prime calculate it and uses it based on the content of cells. It sounds great, but I have a paginator and every time I go to a different page it move columns from the original position.
Anyways, I just noticed they remove a css rule they had before:
<code>.p-datatable table{
    table-layout: fixed;
}
</code>
I put it back on my own styles and it fixed my problem.


Intuition behind designing DNN models

Question: For a long time, I have been looking for a reference that could give me an intuition for designing DNN models, however, I have met with little success. I have a set of training data, I know how input and output layers should look like, but what should I add in the middle?
Yes, everyone knows that RNNs are proper choice for time series, whereas Convolutions do a better job at vision. For NLP (or perhaps everything else) the go to is transformers. Add normalization for faster learning, to deal with overfit add dropout, etc, but these ideas are too broad and general. Although designing DNN models may not be very different from antique alchemy at the moment, I refuse to believe that researchers randomly put layers on top of each other until they get a good result, to publish it later on.
I am not looking for a set of rules that dictate how a DNN model should be designed, it doesn't exist yet, rather, I would like to get an intuition, a feeling that tells me for example, to add a pooling max layer, instead of a pooling average layer, after a convolution layer. Grid search and any other similar method is not really feasible. Sure it can be used for hyper parameters to some extent, but nothing beyond that really.
As a physicist, I have not gone through proper academic training for deep learning, so maybe that's why I am lacking this type of feeling, nevertheless, I appreciate any book, article, tutorial, etc, that can give me such intuition.
Comment: @Firebug Care to post that as an answer?
Comment: "I refuse to believe that researchers randomly put layers on top of each other until they get a good result, to publish it later on." I'm sorry for breaking the news for you, but it works absolutely like that. Obviously, researchers have operationalized such choices, but the design of deep neural networks is most often based on applying heuristics, starting from previous successful network architectures, and is quite handwavy. AutoML takes this to the extreme, performing meta-learning (i.e., optimizing the architecture to the task at hand).
Comment: @Dave I would call it more anecdotal than 'fact-based', including my own experience. I might delete it if a better-sourced answer appears.
Answer: I'm sorry for breaking the news for you, but it works absolutely like that (this is mostly anecdotal based off my experience and what I see in the field, so I'm willing to delete this answer if someone brings up something else).
Obviously, researchers have operationalized such choices, but the design of deep neural networks is most often based on applying heuristics, starting from previous successful network architectures, and is quite handwavy.
AutoML takes this to the extreme, performing meta-learning (i.e., optimizing the architecture to the task at hand).
It's also possible to 'elicit' some choices based on group equivariances (i.e., convolutions give you translation equivariance).
This is an active area of research, although it does not answer the question of how many layers and how many units per layer are necessary.
Neural network architecture design is the topic of many books in the literature as well, you might want to check them.

Geometric deep learning can be a good gateway, providing an unification of most current neural network layers.
On this topic, you can find this book Geometric Deep Learning: Grids, Groups, Graphs, Geodesics, and Gauges  and the accompanying portal https://geometricdeeplearning.com/, which contains a lot of material.
Comment: That's unfortunate. Can you please give me some references (or keywords) for finding papers regarding group equivalences? It does sound what I am looking for. Also suggesting some books helps.
Comment: @Paradoxy You can search for geometric deep learning, regarding the equivariances. Also, there is this book [Geometric Deep Learning: Grids, Groups, Graphs, Geodesics, and Gauges](https://arxiv.org/abs/2104.13478) and this portal [https://geometricdeeplearning.com/](https://geometricdeeplearning.com/) with a lot of material.

Intuition behind designing DNN models


hard-sequence problem and limits

Question: Let be $x_n$ a sequence such that $$2\le x_1\le 4$$ and  $$x_{n+1}=\frac{1}{x_n}+\frac{4}{2n+1}$$
Find the value of $$\lim _{n\to \infty }\left(n\left(x_n-1\right)\right)$$
I would like somebody to provide a complete proof showing that the sequence $x_n$ is decreasing and convergent to 1 since the book where this come from states that and overlooked the proof. I would also like to know what I have done wrong there.
I did the following using Stolz Cesaro lemma. Obvious the sequence $\frac{1}{\left(x_n-1\right)}$ is increasing to infinity.
$$\lim _{n\to \infty }\left(n\left(x_n-1\right)\right)=\lim _{n\to \infty }\left(\frac{n}{\frac{1}{\left(x_n-1\right)}}\right)=\lim _{n\to \infty }\left(\frac{n+1-n}{\frac{1}{\left(x_{n+1}-1\right)}-\frac{1}{\left(x_n-1\right)}}\right)=\lim _{n\to \infty }\left(\frac{1}{\frac{1}{\left(x_{n+1}-1\right)}-\frac{1}{\left(x_n-1\right)}}\right)=\lim _{n\to \infty }\left(\frac{\left(x_{n+1}-1\right)\left(x_n-1\right)}{x_n-x_{n+1}}\right)=\lim _{n\to \infty }\left(\frac{\left(\frac{1}{x_n}+\frac{4}{2n+1}-1\right)\left(x_n-1\right)}{x_n-\frac{1}{x_n}+\frac{4}{2n+1}}\right)=\lim _{n\to \infty }\left(\frac{\left(\frac{1}{x_n}-1\right)\left(x_n-1\right)}{x_n-\frac{1}{x_n}}\right)=\lim _{n\to \infty }\left(\frac{\left(1-x_n\right)\left(x_n-1\right)}{x_n^2-1}\right)=\lim _{n\to \infty }\left(\frac{\left(1-x_n\right)}{x_n+1}\right)=\lim _{x\to 1}\left(\left(\frac{\left(1-x\right)}{x+1}\right)\right)=0$$
The book states that the correct answer is 1. What I have done wrong and what is the correct solution?
Comment: I see that the 6th equality doesn't work (you ignored the terms containing $n$ but these terms can interact with $\frac{1}{x_n}-1$ or $x_n - \frac{1}{x_n}$)
Comment: thank you NN2 for the explanation
Answer: This is probably not the expected answer, but it is a solution, and it might be of some interest: the recurrence is equivalent to $$x_{n+1}\,x_n=1+\frac{4\,x_n}{2n+1}.$$ With $x_n=y_n/y_{n-1}$, this becomes
$$y_{n+1}=y_{n-1}+\frac4{2n+1}\,y_n.$$ Now $y_n=2n+1$ is a particular solution of this linear recurrence, so let $y_n=(2n+1)\,z_n$. This gives
$$(2n+3)\,z_{n+1}=4\,z_n+(2n-1)\,z_{n-1},$$ and after some elementary algebra,
$$(2n+3)(2n+1)(z_{n+1}-z_n)=-(2n+1)(2n-1)(z_n-z_{n-1}).$$ This means
$$(-1)^{n-1}(2n+1)(2n-1)(z_n-z_{n-1})$$ is constant, and thus
$$(-1)^{n-1}(2n+1)(2n-1)(z_n-z_{n-1})=3\,(z_1-z_0).$$ Obviously, we can assume $y_0=z_0=1$, implying $y_1=3\,z_1=x_1$ and $3\,(z_1-z_0)=x_1-3$. This gives
$$z_n=1+(x_1-3)\,\sum^n_{k=1}\frac{(-1)^{k-1}}{(2k-1)(2k+1)}.$$ It's clear that $z_n$ converges to some non-zero value $z_\infty$ for all $x_1$ except when
$$z_\infty=1+(x_1-3)\,\sum^\infty_{k=1}\frac{(-1)^{k-1}}{(2k-1)(2k+1)}=0,$$ i.e.
$$x_1=3-\frac4{\pi-2}$$ (since the sum of the infinite series is $\frac{\pi}4-\frac12$). From $z_n=z_\infty+O(n^{-2})$ immediately follows
$$\frac{z_n}{z_{n-1}}=1+O(n^{-2})$$ and $$n\,(x_n-1)=n\,\left(\frac{2n+1}{2n-1}\,\frac{z_n}{z_{n-1}}-1\right)=\frac{2n}{2n-1}+O(n^{-1}).$$

hard-sequence problem and limits


Array of objects - modyfing object's fields C#

Question: I've got such a problem. I'm a beginner in C#.
I have an object array (various classes) and in one place of application I want to modify fields like an age or name. Construction
static Object[] prac = new Object[10];
public static void Main(string[] args)
{
    prac[0].age = 21;
}

shouts an error

'object' does not contain a definition for 'age' and no extension method 'age' accepting a first argument of type 'object' could be found

I thought that will be similiar to a Java code, but it isn't. What am I doing wrong?
Regards.
Comment: Trying not to sound condescending, but I think you need to go take a tutorial in c#
Comment: I don't think this code works in Java also, probably you mean javascript ( which is dynamic language) you need to cast from Object to the class you need...
Comment: Ow, I made a mistake. It's a `Person[] prac = new Person[10]`.
Answer: You need to cast your member to the class type that contains the age. I'll just assume that your class name is Person and that is has a age member :
static Object[] prac = new Object[10];
public static void Main(string[] args)
{
    ((Person)prac[0]).age = 21;
}

Important to note are the brackets : (Person)prac[0] is the cast part, you cast the Object prac[0] to a Person object. The outer brackets ((Person)prac[0]) are there so that the code is taken as a Person object, instead of a regular Object.
Comment: Yeah, that's it! My array type should be `Person` at all... Thanks.
Answer: First you need to cast the object to the type you're intending to work with.
If you work with type object, it has only a limited amount of properties and methods. To use property age, you first need to cast it to the corresponding type that has that property. For instance something like this:
static Object[] prac = new Object[10];
public static void Main(string[] args)
{
    SpecificType myObject = prac[0] as SpecificType; // returns null if not successful
    if (myObject != null)
        myObject.age = 21;
}

HOWEVER, I'm not convinced you're doing the right thing here. I'd personally avoid type object unless absolutely there would be no other way of doing it (and that is very rare in my code). C# is a strongly-type language and by using object you're prone to errors all over the place.
Answer: Object doesn't have property age.
All Object's properties and methods are stated here.
Answer: It's an array of objects and as the error message suggests, 'object' does not contain a definition for 'age'
You need to declare your array with the type that has age field or property.And the you can modify it whatever you want. For example:
class Person
{
    public string Name { get; set; }
}

Answer: You have to use an array of your class instead of Object which is the base type of all classes.
static MyClass[] prac = new MyClass[10];

or you have to cast it:
MyClass mc = (MyClass) prac[0];
mc.age = 21;

Answer: Object is the base class for all classes in .Net.
Just cast the required value to the required typed class. Or Create a list with the right type instead of object.


How many terms are created when multiplying two polynomials of different length

Question: I'm about to finish up a problem which asks me to figure out how many terms are present when multiplying two polynomials raised to different powers. However, there's one caveat: one of the polynomials contains one less terms in its simplified form than the other. I've figured out how many terms are in the respective expansions of each polynomial, but I don't know how to figure out how many terms will be produced by multiplying the two polynomials. Does anyone know how I can figure this out? Apologies if this is not specific, I can provide more details if need be.
I feel it's best I supply some extra information. Using arbitrary numbers, the question is essentially how many terms are in the expansion of $ \ (a+b+c)^{10}·(a+b+c+d)^2 \ . $ By the multinomial theorem, there are 66 terms in $ \ (a+b+c)^{10} \ $ and 10 terms in $ \ (a+b+c+d)^2 \ . $ I just can't figure out how many terms there are in $ \ (a+b+c)^{10}·(a+b+c+d)^2) \ . $
Comment: Substitute $u=a+b+c$. It makes the expression much cleaner.
Comment: @Trebor:  that hides much of what OP is looking for.
Comment: @RossMillikan Well, what prevents you from substituting back once you dealt with $d$ properly?
Answer: The degree of the product is the sum of the degrees of the polynomials you multiply.  The minimum degree of a term is $0$, achieved whenever both polynomials have a constant term.  You then have to worry about whether any terms in between are missing, but have not supplied enough information to determine that.
Added:  now that you have explained that your polynomials have multiple variables, you need to assess all the mixed terms that can come up.  On the other hand, because all the terms are positive, you will never have one missing because the coefficients sum to $0$.  You need to count all the terms of the form $a^eb^fc^gd^h$ with $e+f+g+h \le 12,$ and $e,f,g \le 10, h \le 2$
Answer: Hint: how many terms without a $d$, how many with $d$ and how many with $d^2$?


Mock a JSON request parameter using Quarkus and RestAssured

Question: Using Quarkus, I have the following API.
@RequestScoped
@Path("/api/v1")
public class MyApi {

    @POST
    @Consumes(APPLICATION_JSON)
    public Response create(Entity entityToCreate) {
        if (entityToCreate.isValid()) {
            // create the entity in my app...
            return Response.ok().build();
        } else {
            return Response.status(BAD_REQUEST).build();
        }
    }
}

My Entity class looks like this
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Entity {

    private final String property1;
    private final String property2;
    // ...

    @JsonCreator
    public Entity(@JsonProperty("property1") String property1,
                  @JsonProperty("property2") String property2,
                  // ...
    ){
        this.property1 = property1;
        this.property2 = property2;
        // ...
    }

    // getters for every property...

    public boolean isValid() {
        // check if the entity is valid, then return true or false
    }
}

What I want to achieve, in my unit tests, is the following:
import static io.restassured.RestAssured.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@QuarkusTest
public class MyApiTest {

    private final Entity entityMock = mock(Entity.class);

    @Test
    public void shouldCreateEntityWhenValid(){
        when(entityMock.isValid()).thenReturn(true);

        given()
            .contentType(ContentType.JSON)
            .body(entityMock)
        .when()
            .post("/api/v1")
        .then()
            .statusCode(200);
    }

    @Test
    public void shouldNotCreateEntityWhenInvalid(){
        when(entityMock.isValid()).thenReturn(false);

        given()
            .contentType(ContentType.JSON)
            .body(entityMock)
        .when()
            .post("/api/v1")
        .then()
            .statusCode(400);
    }
}

Currently, I'm stuck with the following error, because Jackson tries to deserialize the mock.
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.mockito.internal.invocation.mockref.MockWeakReference and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: blah blah blah... )

Answer: Just create a real instance of your entity and let the validation happen.
Rest Assured is going to post an actual HTTP request in the test, so it serializes your mock as JSON. When the implementation handles the HTTP request, the request body is then deserialized into an entity. This entity is instantiated internally, so it's not the same instance as created in the test.
Comment: If you really want to separate the validation concern I'd suggest throwing a ConstraintViolationException or using the Java validators. That way you only need one exception handler and can forget about handling the validation status manually in each controller method.
Comment: I don't want to instantiate a real entity. The conditions leading to a valid or invalid object is not the concern of `MyApi` class, or its test class. I don't want to have to choose a specific valid or invalid configuration of the entity.
Comment: The deserialization is done by the framework so you don't really have an option. If you want to separate the validation concern you cannot test it with an integration test like this.
Comment: You can still test the validation separately by writing a unit test for the entity. But the handling of the validation in the controller requires something to actually trigger the validation.
Comment: I tested the validation separately. In the controller, I may end up mixing RestAssured tests and more simple JUnit tests in which I will call the controller method myself...
Answer: I ended up mixing several test techniques, to validate both the JSON mapping and the method behaviour.
import static io.restassured.RestAssured.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@QuarkusTest
public class MyApiTest {

    private final Entity entityMock = mock(Entity.class);
    private final Entity validEntity = // [...] instantiate a valid entity here

    private MyApi api;

    @BeforeEach
    void beforeEach() {
        myApi = new MyApi();
    }

    // this test validates both the JSON parsing and the valid entity case
    @Test
    public void shouldCreateEntityWhenValid(){
        given()
            .contentType(ContentType.JSON)
            .body(validEntity)
        .when()
            .post("/api/v1")
        .then()
            .statusCode(200);
    }

    // this test validates the invalid entity case
    @Test
    public void shouldNotCreateEntityWhenInvalid(){
        when(entityMock.isValid()).thenReturn(false);

        Response response = myApi.create(entityMock);

        assertThat(response.getStatus()).isEqualTo(400);
    }
}

Comment: The first test doesn't do what you think it does. Read my explanation again.
Comment: Thanks for your vigilance. It was a wrong copy/paste. I instantiate a real valid entity in the first test case.


Why isn't my javascript returning the correct answer to Project Euler's Number One?

Question: I'm attempting to solve Project Euls Problem Number One using Javascript.
I know this isn't the most eloquent solution however I do not understand why it does not work. I am taking the multiples of three, five under 1000 then storing them in two seperate arrays. I'm then adding the arrays together, outputting the answer using console.log() and the answer I'm getting is 266333 instead of the correct answer 233168. Does anyone know why?
/* Declaring Global Variables */
var n;
var sumOfThree = 0;
var sumOfFive = 0;

/* Declaring Arrays */
multiplesOfThree = [];
multiplesOfFive = [];

/* Finding how many numbers < 1000 divide evenly by three and five then adding them to my arrays*/

console.log("Let's calculate how many numbers divide evenly by three and five in the number one thousand.");
console.log("Calculating...");

for(n = 0; n < 1000; n ++) {
    if(n % 3 === 0) {
    multiplesOfThree.push(n);
    }
}

for(n = 0; n < 1000; n ++) {
    if(n % 5 === 0) {
        multiplesOfFive.push(n);
    }
}

/* Letting the User know how many multiples of three exist */

console.log()
console.log("There are " + multiplesOfThree.length + " multiples of three in the number one thousand.");

/* Letting the user know how many multiples of five exist */

console.log()
console.log("There are " + multiplesOfFive.length + " multiples of five in the number one thousand.");
console.log()

/*Letting the User know the sum of the number of multiples*/

console.log("Let's get the sum of the number of multiples.");
console.log("Calculating...");
console.log(multiplesOfThree.length + multiplesOfFive.length);
console.log()

/* Letting the user know the sum of all the three multiples*/
console.log("Let's get the sum of all the three multiples")
console.log("Calculating... ");
for (i=0; i < multiplesOfThree.length; i++) {

    sumOfThree += multiplesOfThree[i];

}
console.log(sumOfThree);
console.log()

/* Letting the User know the sum of all the five multiples */

console.log("Let's get the sum of five multiples")
console.log("Calculating... ");
for (i=0; i < multiplesOfFive.length; i++) {

    sumOfFive += multiplesOfFive[i];

}
console.log(sumOfFive);
console.log()

/* Letting the user know the added sum of all the three, five multiples */

console.log("Let's add these two sums together")
console.log("Calculating... ");
var sumOfBoth = sumOfFive + sumOfThree;
console.log(sumOfBoth);

Comment: Have you considered what you are doing with values that are multiples of both 3 *and* 5?  (Hint: your sum is too big)
Comment: `3*(333*334)/2+5*(199*200)/2-15*(66*67)/2`
Comment: Thanks for all of the help everyone! I ended up adding a For loop that checks my multiplesOfFive array for multiples of three and removes them so I now get the correct answer. :)
Answer: Yes, because you are adding the numbers which are multiples of both 3 AND 5 twice.
Answer: The sum of the numbers from 1 to N is N*(N+1)/2.
To compute the sum you're trying to compute, we need to think about the parts. The sum of the numbers from 1 to 999 that are divisible by 3 is going to be the sum of the numbers from 1 to 333, times 3. Similarly, the sum of the numbers from 1 to 999 that are divisible by 5 will be the sum of the numbers from 1 to 199, times 5. Finally, we have to take into account that both of those sums will include numbers that are divisible by both 3 and 5, so we need to subtract out the sum of the numbers from 1 to 66, times 15.
Thus, the overall sum is:
3*(333*334)/2 + 5*(199*200)/2 - 15*(66*67)/2

The fact that the sum of the numbers from 1 to N is N*(N+1)/2 is I think generally attributed to Gauss, though it's not a very complicated relation so it may be much older. You can demonstrate that it's true by considering the values 1 through N written out, and the values N down to 1 written out immediately below. The sum of each top-and-bottom pair from both rows of values is clearly N+1; the first pair is N and 1, the second is N-1 and 2, the third is N-2 and 3, and so on. There are N of those pairs, so the result is clear: N instances of N+1, and since the list is doubled we need to divide by 2 to get the final sum. Note that dividing by 2 cannot introduce a fraction, since either N or N+1 must be an even number.


UserControl changing Visibility for Rectangles with ComboBox

Question: I have a ComboBox in UserControl with 4 choices that change the visibility of 4 Rectangles which are in the MainWindow.
I managed to make it work while the Combobox is in the MainWindow, but when i move it to the UserControl it doesn´t work anymore
I tried to put in UserControl
MainWindow mw = new MainWindow();
and put in front
mw.blau_rec.Visibility = Visibility.Visible; -> Here i do get StackOverFlow error
This is the XAML for the Rectangles in the MainWindow:
    <Rectangle x:Name="blau_rec" Visibility="Hidden">
        <Rectangle.Fill>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                <GradientStop Offset="0.2" Color="Aqua"/>
                <GradientStop Offset="1" Color="Blue"/>
            </LinearGradientBrush>
        </Rectangle.Fill>
    </Rectangle>

    <Rectangle x:Name="orange_rec" Visibility="Hidden">
        <Rectangle.Fill>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                <GradientStop Offset="0.2" Color="Orange"/>
                <GradientStop Offset="1" Color="OrangeRed"/>
            </LinearGradientBrush>
        </Rectangle.Fill>
    </Rectangle>

    <Rectangle x:Name="grey_rec" Visibility="Hidden">
        <Rectangle.Fill>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                <GradientStop Offset="0.2" Color="#8E8E8E"/>
                <GradientStop Offset="1" Color="#585858"/>
            </LinearGradientBrush>
        </Rectangle.Fill>
    </Rectangle>

    <Rectangle x:Name="light_rec" Visibility="Hidden">
        <Rectangle.Fill>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                <GradientStop Offset="0.2" Color="#D5D5D5"/>
                <GradientStop Offset="1" Color="#BEBEBE"/>
            </LinearGradientBrush>
        </Rectangle.Fill>
    </Rectangle>

This is the Code in UserControl.cs
    private void cbx_colorChanger_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var farbe1 = cbx_colorChanger.SelectedItem as ComboBoxItem;
        if (farbe1.Content.ToString() == "Blau")
        {
            blau_rec.Visibility = Visibility.Visible;
        }
        else
        {
            blau_rec.Visibility = Visibility.Hidden;
        }

        var farbe2 = cbx_colorChanger.SelectedItem as ComboBoxItem;
        if (farbe2.Content.ToString() == "Orange")
        {
            orange_rec.Visibility = Visibility.Visible;
        }
        else
        {
            orange_rec.Visibility = Visibility.Hidden;
        }

        var farbe3 = cbx_colorChanger.SelectedItem as ComboBoxItem;
        if (farbe3.Content.ToString() == "Grau")
        {
            grey_rec.Visibility = Visibility.Visible;
        }
        else
        {
            grey_rec.Visibility = Visibility.Hidden;
        }

        var farbe4 = cbx_colorChanger.SelectedItem as ComboBoxItem;
        if (farbe4.Content.ToString() == "Hell")
        {
            light_rec.Visibility = Visibility.Visible;
        }
        else
        {
            light_rec.Visibility = Visibility.Hidden;
        }
    }

and this is the ComboBox in UserControl:
    <ComboBox x:Name="cbx_colorChanger" Width="200" Height="25" SelectionChanged="cbx_colorChanger_SelectionChanged" >
        <ComboBoxItem Name="cbx_blau_rec" Content="Blau"/>
        <ComboBoxItem Name="cbx_orange_rec" Content="Orange"/>
        <ComboBoxItem Name="cbx_grey_rec" Content="Grau"/>
        <ComboBoxItem Name="cbx_light_rec" Content="Hell"/>
    </ComboBox>

Please i need some help getting along with this, thank you!
Comment: A UserControl should never directly access the main (or any other) Window. It should instead expose four bindable properties (i.e. dependency properties), to which the Visibility properties of the Rectangles could be bound. Or better, expose a single property, and bind the Visibilities with a Binding Converter.
Answer: Create a static instance of MainWindow and set it equal to this in the constructor like so:
public static MainWindow thisWindow;

public MainWindow()
    {
        InitializeComponent();

        thisWindow = this;
    }

Now you can access your MainWindow from anywhere:
MainWindow.thisWindow.blau_rec.Visibility = Visibility.Visible;

Comment: Besides that this shows bad practice, it is entirely redundant, because you can already access the MainWindow instance by `(MainWindow)Application.Current.MainWindow`.
Comment: @Clemens thanks for the tip, is there a way to access other Pages than the MainWindow like this?
Comment: Maybe, but a control should never directly access other elements.


Clion c++ executable vs C++ library

Question: I am new to the C++ language. And when I start building a new project, I can see two options. C++ Executable and C++ Library.
I have tried looking for their difference at a lot of places, but could not get anything. Can someone please guide me to a correct answer on this topic?
Thanks
For reference
Answer: If you're building a self standing program, you'll want an executable.
But you might be building a library of functions/classes that provide utility to someone else or another project.  In that case you'll want other programs to be able to link against the library to access those functions/classes, either statically - to compile the library into their project - or dynamically to fetch stuff the library at runtime.
Comment: For more about libraries see also: https://stackoverflow.com/questions/2766233/what-is-the-c-runtime-library, https://stackoverflow.com/questions/140061/when-to-use-dynamic-vs-static-libraries and https://stackoverflow.com/questions/9688200/difference-between-shared-objects-so-static-libraries-a-and-dlls-so?rq=1

Clion c++ executable vs C++ library


PHP - Storing session username or ID preferred?

Question: I'm just wondering, for a PHP session, would it be preferred to store a session variable containing a logged in user's ID or username?
At the moment it stores the username, whereas would ID be safer because to potential "hackers", they may not know which user the ID correlates to?
Comment: Seems like an ID would be the smarter choice, but not because it's safer, but because that is most likely the primary key in the database.
Comment: From a "hacking" point of view, this makes no difference. If a hacker is trying to impersonate another user, he will use the username if your session stores the username and the id if your session uses ids.
Comment: @zuc0001: of course, but you call this class everytime you need user info? Better way is to call it once, save into session and every next time take data from session instead of database :-) You didn't mention that before, I didn't know how you do it in your app.
Comment: @Devon that's also my sort of thinking. I've been using usernames forever, however it recently occurred to me that IDs are easier to work with.
Comment: @zuc0001: you can save both, ID for working with database (select my comments, articles, profile, ...), name for showing info in website (logged as: XY). In sessions often have all (more) info about user, except password, of course.
Comment: @panther, I have a class which grabs all the critical user information on page load. So if I feed it the ID, it will grab the username, email, and all relevant information automatically for use. So I don't think I'd need a session for that :). Thanks for your point of view though!
Comment: @panther Oh! I never thought of doing it that way. That would decrease load on the SQL server dramatically instead of grabbing it each time the page loads! I call the class each time the page LOADS, however it can also be used for grabbing user information for a number of users (input ID into the class).
Answer: PHP sessions work by giving an "opaque" cookie to users - that is, the cookie is just a number, and the actual data is stored on your server. When a user sends you the session cookie, PHP looks up the number in a table to retrieve the data you've stored for that user.
This means that it is impossible, without access to your server, for anyone listening over the network to figure out what the session cookie actually means. They would need the table stored on your server. So it really doesn't matter if you store an ID number or a username in the session: if they have enough access to see what's in the session, then they could probably just look up the username based on the ID number anyway.


PHP - Como receber um fluxo de dados partindo de um post Python?

Question: Eu pretendo carregar uma sessão autenticada de um site usando os cookies enviado por um aplicativo feito em Python nao codificado por mim.
Como mostrado na imagem a abaixo, os dados são enviados via post em um fluxo de bytes. A questao é, como receber e tratar esses dados de forma correta para uso na opção CURLOPT_COOKIE do curl em um script PHP ?

Desta forma funciona corretamente se usar o arquivo cookies.txt localmente.

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => false,
    CURLOPT_COOKIE => 'cookies.txt',
    CURLOPT_COOKIEFILE => 'cookies.txt'
]);

$response = curl_exec($ch);
echo $response;

curl_close($ch);

?>

Mas desta forma recebendo os cookies por meio de um post do Python não carrega a sessão corretamente.

$cookiedata = var_dump($_POST);

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => false,
    CURLOPT_COOKIE => $cookiedata,
    CURLOPT_COOKIEFILE => 'cookies.txt'
]);

$response = curl_exec($ch);
echo $response;

curl_close($ch);

?>

Acho que isso é tudo.
Answer: Primeiro, ler a documentação ajuda muito, ao invés de programar chutando como as coisas funcionam.
Segundo, é tanto erro em seu código, logo de cara já dá pra ver que isso está errado:
CURLOPT_COOKIE => 'cookies.txt',

Porque CURLOPT_COOKIE como é descrito na documentação https://www.php.net/manual/pt_BR/function.curl-setopt.php serve para setar os cookies manualmente com uma string, seria o mesmo setar o header Cookie: foo=bar, então se está usando o cookie.txt e não pretende setar um valor fixo então nem tem sentido usar isso.
Outra coisa, você usou CURLOPT_RETURNTRANSFER => false, e depois $response = curl_exec($ch); não faz sentido algum, na documentação está escrito:

TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

Traduzindo:

TRUE para retornar a transferência como uma "string" do valor de retorno "curl_exec()" em vez de enviar diretamente para o "OUTPUT".

Agora esse foi o mais errado e sem sentido:
 $cookiedata = var_dump($_POST);

A função var_dump SEMPRE retorna NULL e só retorna alguma coisa quando usado o segundo parâmetro como true assim var_dump($array, true), mas só pra constar, mesmo que retornasse valores NÃO TEM SENTIDO usar var_dump para passar os valores de POST para os cookies.
Se quer enviar o post como cookies então tem que "fixar" no próprio CURLOPT_COOKIE, outra coisa o CURLOPT_COOKIEFILE não é pra manter seus "cookies salvos", seria quase equivalente ao CURLOPT_COOKIE, e o que "difere" ele do CURLOPT_COOKIEJAR é que ele o cookie recebe todos cookies e os mantêm para outras requisições futuras, ou seja:

CURLOPT_COOKIEFILE para setar cookies "fixos"
CURLOPT_COOKIEJAR para manter cookies setados nas próximas requisições, é salvo quando usado o curl_close, pois os cookies podem vir da página requisitada

As pessoas costumar misturar ambos arquivos, o que não faz sentido algum.
Agora para resolver o seu problema, vamos simplesmente explicar por partes, primeiro pegue os valores do POST, você pode iterar e gerar uma string assim:
//Um array para receber os POST
$cookies = array();

//Itera o POST
foreach($_POST as $name => $value) {

     //Adiciona item por item no array no formato "foo=bar"
     if (is_string($value)) {
         $cookies[] = urlencode($name) . '=' . urlencode($value);
     }
}

//Junta todos para o formato aceito pelo header Cookie: foo-bar; abc=123
$cookiedata = implode(';', $cookies);

No entanto note que tem uma função mais simples para fazer isto, o http_build_query, poderia até usar isto em uma linha só:
$cookiedata = http_build_query($_POST);

Mas se o payload recebido for algo como:

user[name]=Bob+Smith&user[age]=47&user[sex]=M&user[dob]=5%2F12%2F1956&pastimes[0]=golf&pastimes[1]=opera&pastimes[2]=poker&pastimes[3]=rap&children[bobby][age]=12&children[bobby][sex]=M&children[sally][age]=8&children[sally][sex]=F&flags_0=CEO

Então vai atrapalhar um pouco a estrutura dos cookies, não muito, mas o suficiente para vai gerar cookies que com certeza não seriam o que você deseja, então por isto usei o is_string no foreach, claro que não garante muita coisa, mas é o básico.
Segundo, você deve enviar a variável $cookies no CURLOPT_COOKIE apenas, algo como:
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_COOKIE => $cookiedata
]);

$resposta = curl_exec($ch);

Terceiro, note que usei CURLOPT_RETURNTRANSFER => true, porque isto vai retornar pra variável, mas lembre-se isso será usado se for o que você deseja, se você não quer isto e quer apenas exibir direto então não precisa nem setar, deve ficar apenas isto:
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_COOKIE => $cookiedata
]);

curl_exec($ch);
curl_close($ch);

Agora uma nota adicional, note que todo e qualquer resposta HTTP pode conter um redirecionamento ou mais, logo o ideal seria definir:

CURLOPT_FOLLOWLOCATION para redirecionar automaticamente (internamente)
CURLOPT_MAXREDIRS limita os redirecionamentos, porque a página que esta acessando pode ter algum "bug" que faz redirecionamentos infinitos, um valor talvez ideal aqui seja limitar para 10, mas é apenas sugestão.

Deve ficar:
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_COOKIE => $cookiedata,
    CURLOPT_FOLLOWLOCATION => true, //Ativa o redirecionamento
    CURLOPT_MAXREDIRS => 10  //limita os redirecionamentos para 10
]);

Também seria interessante para a maioria dos casos tratar as respostas HTTP, pro seu caso eu não sei, porque é você quem controla a página em python, mas supondo que uma página emita um código diferente do range 2xx então você deveria tratar isto com curl_getinfo+CURLINFO_HTTP_CODE, exemplo:
$resposta_http = curl_getinfo($request, CURLINFO_HTTP_CODE);

//Qualquer código fora do range 200 e 299 provavelmente é pagina de erro
if ($resposta_http < 200 && $resposta_http > 299) {
    $resposta = false;
}

Se deseja pegar o resultado então use desta forma (provavelmente isto é o que deseja, mas não tenho como saber):
//Um array para receber os POST
$cookies = array();

//Itera o POST
foreach($_POST as $name => $value) {

     //Adiciona item por item no array no formato "foo=bar"
     if (is_string($value)) {
         $cookies[] = $name . '=' . $value;
     }
}

//Junta todos para o formato aceito pelo header Cookie: foo-bar; abc=123
$cookiedata = implode(';', $cookies);

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_COOKIE => $cookiedata,
    CURLOPT_RETURNTRANSFER => true,  //Pega resposta em uma var
    CURLOPT_FOLLOWLOCATION => true, //Ativa o redirecionamento
    CURLOPT_MAXREDIRS => 10  //limita os redirecionamentos para 10
]);

$resposta = curl_exec($ch);

//Verifica se conectou e baixou algo, mesmo que tenha um código HTTP de erro
if ($resposta !== false) {

    //Pega O CÓDIGO da resposta HTTP
    $resposta_http = curl_getinfo($request, CURLINFO_HTTP_CODE);

    //Qualquer código fora do range 200 e 299 provavelmente é pagina de erro
    if ($resposta_http < 200 && $resposta_http > 299) {
        //Seta false para evitar continuar o processo no proximo IF
        $resposta = false;
    }
} else {
    $resposta_http = 0;
}

curl_close($ch);

if ($resposta) {
    echo $resposta; //coloquei um ECHO mas aqui você pode fazer o que quiser com a resposta
} elseif ($resposta_http > 0) {
    echo 'Ocorreu o erro HTTP: ' . $resposta_http;
} else {
    echo 'Não foi possivel se conectar com o servidor';
}


Identifying order of integration

Question: In Eviews ADF unit root test shows that variable is I(2), but unit root with structural breaks shows that variable is I(1). Can I conclude that variable is I(1)?
Answer:
...ADF unit root test shows that variable is I(2)...

This means that the ADF test is unable to reject the unit-root null for the first-differenced series, say $\Delta y_t$, but rejects for the twice-differenced series $\Delta^2 y_t$.

...unit root with structural breaks shows that is I(1)...

This means the Perron test (or whatever test you're using) is unable to reject the unit-root null for the series itself $y_t$, but rejects for $\Delta y_t$. (I am assuming that successive differencing is the procedure implemented in EViews. You should check documentation.)

Can I coclude that variable is I(1)?

From purely mechanical considerations, yes.
The Perron test is designed to have power against alternatives which are stationary but has structural break. So these results suggest $\Delta y_t$ is possibly stationary but with structural break, and the ADF test mistakenly took this as unit root.
Without knowing more about your data, that's all one can say.
Ideally, you should be able to explain why $\Delta y_t$ is possibly stationary but with structural break, with more than purely statistical results.
Comment: Thanks for your response. It is exchange rate series. There is a regime shift in monetary policy, therefore it has a structural break.
Comment: @PHPUseless I see. Structural breaks in exchange series are almost always identifiable as due to change in monetary policy.

Identifying order of integration


How to jump to another know page on a button click?

Question: I need to implement a select list (something like auto-complete in JQuery UI) with a Go button on a mini-panel (or block). I can do this in Javascript. When the user selects a value, a corresponding page (for example: article) URL is computed.
Assuming we know the URL of that page, how do I get Drupal to jump to that page when the user clicks on the Go button? I am no expert in PHP, but could implement some if necessary, or is there a better solution?
Answer: If the whole implementation (including the URL computing) is done on the client side with javascript then the easiest solution would be to simply use code like the following:
$('#go_button_id').click(function() {
  location.href = 'url_to_the_computed_page';
});

On the server side you could use Drupal's block hooks and form API to create a block with a simple form and then use $form_state['redirect'] = 'url_to_the_computed_page'; in the form submission handler for the redirect.
Comment: Ok, thanks. I was thinking the same since everything was on the client side.


Finding Radius and period time of a limit cycle using Melnikov Integration

Question: The system of equations I am working on is the following:
$$
\begin{align}
\dot{x}& = y \\
\dot{y}& = -\mu(x^2 + ax^4 - 1)y - x
\end{align}
$$
The question asks first to find the Hamiltonian of the system at $\mu = 0$ which I evaluate to be:
$$
\begin{equation}
H(x,y) = \frac{y^2 - x^2}{2}
\end{equation}
$$
The proceeding parts are the ones I am having trouble with. This is the body of the question:
"Find an explicit expression for the trajectories solving this Hamiltonian
system. Choose suitable initial conditions having in mind
that in the next step you will integrate over a closed orbit."
Is this done by solving the system of equations when $ \mu = 0$? Doing so with initial conditions x(0) = 1 and y(0) = 1 results in:
$$
\begin{align}
x(t)& = cos(t) + sin(t)\\
y(t)& = cos(t) - sin(t)
\end{align}
$$
After plugging this into the Hamiltonian and simplifying I arrive at:
$$
\begin{equation}
H(x,y) = -sin(2t)
\end{equation}
$$
The next part which involves using the Melnikov method is as follows:
"Now consider a small positive $\mu$. To determine the radius R and
period time T to lowest (zeroth) order in $\mu$, evaluate the change
$\Delta H$ in the Hamiltonian H(x; y) as you follow a trajectory governed
by the dynamics in the system of equations. Show that H must vanish
after following a limit-cycle trajectory one lap. Use this fact to find the radius R as a function of a."
When H completes one lap I assume that it goes from 0 to $\pi$ and $H = 0$ at $t = \pi$. I am not sure how to find the radius and the period after this step. For example, I don't know how to handle $\mu$ being non-zero.

Could someone give me some pointers as to how this should be done or if what I have done so far is correct?
Comment: Your Hamiltonian is wrong. It should be $H(x,y)=\frac12(x^2+y^2)$ instead of $H(x,y)=\frac12(x^2-y^2)$ .
Answer: Let $\mu=0$ and then the system becomes a Hamiltonian system
$$ x'=y, y'=-x $$
with $$ H(x,y)=\frac12(x^2+y^2) $$
Clearly this Hamiltonian system has an orbit ${\bf{x}}_\gamma(t)=(\gamma \cos t,y=-\gamma \sin t)$ with period $2\pi$. So the Melnikov function is
\begin{eqnarray}
M(\gamma,a)&=&\int_0^{2\pi}{\bf{f(x_\gamma)}\wedge\bf{g(x_\gamma)}}dt\\
&=&-\int_0^{2\pi}\gamma \sin t(\gamma^2\cos^2t+a\gamma^4\cos^4t-1)\gamma\sin tdt\\
&=&-\frac{\pi}8\gamma(-8+2\gamma^2+a \gamma^4).
\end{eqnarray}
Let
$$ -8+2\gamma^2+a \gamma^4=0 $$
and then
$$ \gamma=γ_\pm=\sqrt{\frac{-1\pm\sqrt{1+8a}}a}=\sqrt{\frac8{1\pm\sqrt{1+8a}}}. $$
This means that if $a>0$, then there is a unique limit cycle with radius $\gamma=\gamma_++O(\mu)$.
If $a\in(-\frac18,0)$, then there are two limit cycles with radius $\gamma=\gamma_{\pm}+O(\mu)$.
If $a<-\frac18$, there is no limit cycle. If $a=0$, there is a unique limit cycle with radius $\gamma=2+O(\mu)$.
Comment: A Hamiltonian system is a system like this: $x'=\frac{\partial H}{\partial y}, y'=-\frac{\partial H}{\partial x}$.


Cannot set up https on microsoft azure VM

Question: For over a week now I am trying to set up https to work with my owncloud hosted on a Microsoft Azure virtual machine (ubuntu server 14.04). I am using apache2. I have gone through every single tutorial i have found on the web and also one person on the owncloud forums was trying to help for a while but the preblem is still unsolved.
I am wondering now is there anything unusual about a linux system that is hosted on microsoft azure? Because this ssl setup as far as ive learned for past couple of days should pretty much work out of the box. I am wondering either this has anything to do with the fast that I have added HTTPS frontend after the VM was created, not in the process of its creation. Anyways I am listening to 443 port and i have ssl enabled, I have created the keys pair and turned on the ssl engine.
Also Debian man pages etc.
Here are my logs and virtual host for ssl:
default-ssl.conf in sites-available:
https://pastebin.com/jvhPpDKa
My rep is to low to post more than 2 links, so here I pase a link to my post from owncloud forums where one can see pastebins with my netstat and acces + errors logs:
https://forum.owncloud.org/viewtopic.php?f=31&t=26375&start=20#p80237
Im really desperate right now, I have no idea why cant I connect to my server using https... I would really aprichiate all help!
Answer: Have you enabled the HTTPS endpoint on your Azure VM? You can check the endpoints when you view the properties of your VM. At the top you will see four items: Dashboard, Monitor, Endpoints and Configure. Click on endpoints and make sure that HTTPS is there. If not, click on the Add at the bottom and add it.
Comment: You can check if you can get anything from apache at the server console. Run the command "`curl https://localhost`" or "`curl https://`" and see if you get anything to download.
Comment: i have tried what u suggested- when curled with localhost it worked, i downloaded the page. However when I curled my public page address (vm.mydomain.com) i got connection timeout.... What does this mean?
Comment: Yes, i did. I think this might be the case- that even though it is enabled, it doesnt work.
Comment: I noticed that in your netstat that apache is listening on 443, but only tcp6. Maybe try to get it to bind to tcp4 and see if that makes a difference? I guess changing the  to  and restart apache might do it, but I haven't tried.
Comment: After changing virtualhost like you specified, the netstat showed that i am still listening on tcp6. Even though I tried but it didnt help :/. netstat: https://pastebin.com/XM7LPzm7
Comment: See if you can find the Listen 443 option in /etc/apache2/ports.conf and change that also to Listen 0.0.0.0:443
Comment: Now i see port 443 in tcp, but https still doesnt work. https://pastebin.com/a6Ps2uTt
Comment: do you have any other ideas?
Answer: The problem has been solved. Appereantly theres a bug in microsoft azure frontends ACLs. I had no reles applied so it means it should allow all trafic on that frontend. Instead it was filterring everything. To fix that i denied a random ip address so a rule to "allow every but this one" would start working. After that i could acces my site with https. Thank you for help.


Can an injectee know its own InjectionPoint?

Question: Is there any way an injectee(EJB, say) know its own injection point?
@Stateless
public class SomeService {

    @PostConstruct
    private void constructed() {
        // do post construction job
        // according to the injectionPoint
    }

    @Context
    private InjectionPoint injectionPoint; // is this possible?
}

Answer: If you are injecting your EJB with CDI (using @Inject) and if it has the default scope (no explicit scope or @Dependent).
You can inject its injection point:
@Stateless
public class SomeService {

    @PostConstruct
    private void constructed() {
        // do post construction job
        // according to the injectionPoint
    }

    @Inject
    private InjectionPoint injectionPoint; // this is possible
}

Comment: @AntoineSabotDurand You got a new question. Thanks.  http://stackoverflow.com/q/32909962/330457


Roman numeral notation for a suspended chord?

Question: On the Wikipedia entry for Roman numeral analysis, it says that major chords use the upper case numerals (e.g. IV for the F major chord in the C major scale) and lowercase letters for minor chords (e.g. vi for the A minor chord in the C major scale), but how about suspended chords? Since the 3rd is missing, the chord is no longer major or minor, so I'm wondering what is the convention used in this case?
Comment: Thanks Casey! Your answer was really informative. For context, I was setting some pop music and came across a suspended chord (that would have resolved to be minor)
Comment: Hey @xdl, I think some of these answers are a little misleading.  If you are asking about traditional Roman numeral analysis, as you would do in a basic harmony or music theory class, take a look at my answer below.  Let me know if you have any questions.
Answer: Typically, in traditional classical music, non-harmonic tones like suspensions are not indicated in the Roman numeral analysis.  You would simply notate the numeral and inversion for the chord to which you are resolving.
Here's an example:

In jazz and pop music, on the other hand, you may find the chord analyzed as IVsus or IVsus4, for instance.  This is because in jazz and pop, notes that were traditionally considered to be non-harmonic in classical music are now considered to be part of the chord, and chord inversion is generally seen as less fundamental to the harmony.
Occassionally, you will see a conflation of figured bass and Roman numeral analysis that looks like this: http://www.sfcmtheory.com/harmony_supplements/chap_21.htm, but it is more typical with classical analysis to indicate non-harmonics independently of the Roman numeral analysis, as shown in the above example.
By the way, the wikipedia entry for Roman Numberal Analysis is somewhat inaccurate.  I wouldn't rely on that as a source.
Comment: Yes, but the question was specifically about how to handle the roman numerals.  Traditional roman numeral analysis does not indicate non-harmonics
Comment: Yes, they are notated in the figured bass, not the roman numeral analysis.
Comment: figured bass can be used as a part of roman numeral analysis to show functions of lines; specifically relating to non-harmonic tones.
Comment: No need to argue—I think you are just misunderstanding the question.  Figured bass and Roman numeral analysis are two different, albeit related, forms of notation.  Roman numeral analysis is traditionally concerned with the function of the harmony; non-harmonics are notated separately. (Source: I've taught classes on harmony and basic music theory.)
Comment: Actually, this is incorrect.  Movement tones are notated using figured bass.
Comment: Spot on! That is EXACTLY how my teacher has us analyze them.
Answer: If I'm not mistaken, the way to symbolize this is: IVsus or IVsus4 (or IVsus4).
(Usually, when you see a IVsus chord, it refers to a sus4 chord, but not everyone writes it this way).
Comment: @DarrenRinger It's not a contradiction. If you had an Asus4 in the key of C major it's not like you need to guess what the 3rd of the chord would have been even though it is suspended. You would still note that it naturally occurs as a minor chord even though it is not functioning in that sense. I.E. you would use vi sus4 instead of VI sus4 because of how chords are built off a root of A in C major.
Comment: Here is a doc showing it in a little more depth: http://www.personal.kent.edu/~sbirch/Theory/21341%20CMT/Assignments/02-Roman_Numeral_Analysis.docx
Comment: "sus4 of A minor" is a contradiction in terms - a chord would be minor, or it would be 'sus4', but not both.  The only real ambiguity I can imagine would be on the seventh, but since in jazz chord notation this is assumed to be flatted (mixolydian) it's not really ambiguous - however, in Jazz notation the roman numerals themselves don't get used.  And, anyway, if the 6 is supposed to be flatted that is usually explicit (same with if the 7 is not), so I'd imagine "iv sus4 b6" or "IV sus4 n7" if it was anything other than "sus4" (major 6, minor 7).
Comment: I'm not sure why this is up-voted - it is incorrect. If the harmony is functional, it is notated with figured bass.  If it is non-functional, it is treated as quintal/quartal harmony and Roman Numeral analysis is no longer appropriate; therefore being notated using a different system.
Comment: Thanks! Although is the reason for using uppercase letters because the fourth chord in C major was originally major? For example, would sus4 of A minor be visus4 or VIsus4?
Answer: In my music theory class in college, a suspended chord was written with its resolution, e.g. I⁴⁻³. We didn't get to the point of unresolved suspended chords, as used in jazz.
Comment: It is not a "minus" sign, it represents an horizontal bar placed below the notes. The bar can last for several notes/quarter notes, see for example the exhibit 4 here :
http://www.sfcmtheory.com/harmony_supplements/chap_21.htm
Comment: @Tim - the movement shows the function of the line. Since the "4" is not a chord tone, people want to see what happens to it / how you get to the chord tone. Also, a "sus2" is really just a "sus4" in inversion, so the analysis would still be the same.  The only difference here being that a suspended 2nd might resolve to unison, in which case the process is the same - only the numbers change.
Comment: Does your example then show that it resolves to a minor, as there is a minus sign?
Comment: By default, it resolves in the tonality.
The "-" sign just shows the resolution from the 4th to the 3rd.
Comment: It seems superfluous - a sus will generally (except in jazz!) resolve to a third.Whether it's a sus 2 or a sus 4.
Comment: @jjmusicnotes - that's what I mean - they'll generally resolve to maj (or min) so why put '-3' .
Comment: @Tim There's no rule that says the suspension has to resolve to a third. I guess you could make the third the default, but you'd still need the horizontal bar to show that the chord resolves in some way. Having a 3 there, however, makes it clearer exactly at what point the chord resolves, rather than depending on the line ending at the exact right point.
Comment: @trikly - generally they do, in my experience, but what else do they resolve to?
Answer: For roman numeral, you have to spell it out completely. like a V64 chord. V52 is your sus2. V54 is your sus 4.


how to crossfade two AudioElements in OSMF?

Question: I'd like to crossfade two AudioElements inside a SerialElement but I don't know where to start. Any clue?
Comment: I removed the Flex tags form this post; since it the Open Source Media Framework is separate from Flex.
Answer: So far I've found that the only way is to put them in a parallel element. Have the 2nd audio element wrapped in a serial element along with a duration element.
Like so:
<code>Parallel Element ->
    Audio Element
    Serial Element ->
         DurationElement
         Audio Element
</code>
You can then set up event listeners using their time and audio traits to perform a fade effect for each element.
Comment: I made something like this with two MediaPlayers and no Parallel elements switching contiuously from one to another and fading. Thanks


redirect html pages to non-secure

Question: on a .NET website, what's the best way of redirecting html pages to http if someone tries to access them by https?
I'm redirecting aspx pages using Global.asax but that doesn't pick up html pages...
Thanks
Answer: IIS can be configured to do the redirects itself, if possible this will be the best approach.
Another approach would be to continue to use your redirect in Global.asax but configure IIS to send more requests, including requests for .html files to the .net run time. You should be able to do this on a website by website basis. You can then create an HttpHandler which will have the code to do the redirecting. This can be configured in the web.config by adding a line like
<httpHandlers>
   <add verb="*" path="*.html" type="You.Namespace.Handlers.RedirectHandler"/>
   <add verb="*" path="*.htm" type="You.Namespace.Handlers.RedirectHandler"/>
   ...
</httpHandlers>

Only use this approach if all of this IIS site (https://example.com) is a redirect.
If you serve real .html pages through .net runtime you will have a performance cost.
Hope that helps.
Comment: I managed to map the html files to the ASP.NET ISAPI extension (Aspnet_isapi.dll) using IIS. This generates an entry under . But how do I link it to the  section ??
Answer: Try using javascript

Comment: it needs to be tested though... will have to do minor modifications i guess
Comment: Thanks but I would rather use something more robust
Comment: You would then need to create a file for every existing .html in the site with this redirect. Also the http redirects can provide much more information to search engins, proxies, caches, browsers e.g. 301, 302, 303, 304, 305, and 307. In this case the best response would be 301 Moved Permanently.

redirect html pages to non-secure


How does Realm for Android actually store data?

Question: I am looking at migrating a native Android project from an SQLite database to an ORM. I have considered what I believe to be the fastest current contenders - DBFlow (based on SQLite) and Realm.
Therefore, out of curiosity, does anyone know what sort of data format Realm is using? Having read their documentation, this is seems to be a pretty closed subject and I could not find anything on the matter.
Comment: https://realm.io/news/jp-simard-realm-core-database-engine/ Here is an simple introduction of Realm's underlying storage engine. It might be helpful a bit.
Answer: From their site - Realm is not an ORM on top of SQLite. Instead it uses its own persistence engine and their source code is open for java.
https://github.com/realm/realm-java
Comment: Your answer does not addresses the OP's question
Comment: Could you clarify a bit more?


How to use Lucid Interpretability tools on a Tensorflow Detection model?

Question: I want to use Lucid to analyze the feature extraction of a detection model I trained using the tensorflow Object Detection API on my own dataset. The model used is one from the Tensorflow Object Detection Zoo, namely faster_rcnn_resnet101.
I followed the Lucid tutorial to import my own model and saved a frozen graph of the model with the node /all_class_predictions_with_background as output_node.
I'm having trouble finding the input node of the graph to make Lucid run on it.
Furthermore I don't really think I have the right approach. Maybe I should first extract all the classification part of the detection model and freeze a new graph with only this part before going to Lucid.
Or maybe I should just import a resnet_101 classification model and copy/paste the correct weights from the detection model on it?
But I don't really know how to do those kind of things.
Can someone help me? I really want to try running Lucid on my detection network.
Answer: Yes, you should export an inference (frozen) graph to work with in Lucid.
I use the following script to export a graph from the training checkpoint files.
Useful information about the nodes in the exported file is logged to the console.
training_model="ssd_mnet_v2_ppn_512x288.config"

model_signature="eb_13_v09_ppmn2_13_256_adam_512x288_tf_1.14_200k"

# the specific checkpoint to export from
checkpoint_path="/TRAIN/models/model/train/model.ckpt-200000"

# directory to export into
output_path="/XYZ/graphs/${model_signature}"

# ensure these graph nodes are exported, and everything in between
additional_output_tensor_names="Preprocessor/sub,concat_1"

#
python export_inference_graph.py \
   --input_type=image_tensor \
   --pipeline_config_path /TRAIN/models/model/$training_model \
   --trained_checkpoint_prefix=$checkpoint_path \
   --output_directory=$output_path \
   --additional_output_tensor_names=$additional_output_tensor_names

I found it convenient to make my own Lucid Model class, after reviewing the examples in the Lucid model zoo.
You have to examine your graph carefully as you need to specify the input node, and provide a list of layers that Lucid can work with.
from lucid.modelzoo.vision_base import Model, _layers_from_list_of_dicts

# the input node "Preprocessor/sub" is appropriate for image injection
class SSD_Mnet2_PPN( Model ):

    def __init__(self, image_shape=None, graph_path=None, labels_path=None ):
        self.model_path = graph_path
        self.labels_path = labels_path

        self.image_shape = image_shape
        self.image_value_range = (-1, 1)
        self.input_name = "Preprocessor/sub"

        super().__init__()

# a hand-crafted list of layers - by inspection of the graph
SSD_Mnet2_PPN.layers = _layers_from_list_of_dicts(SSD_Mnet2_PPN, [
  { 'id':  0, 'tags': ['conv'], 'name': 'FeatureExtractor/MobilenetV2/expanded_conv_2/add', 'depth': 24, 'shape': [ 1, 72, 128, 24 ], 'transform_id': 2 },
  { 'id':  2, 'tags': ['conv'], 'name': 'FeatureExtractor/MobilenetV2/expanded_conv_5/add', 'depth': 32, 'shape': [ 1, 36, 64, 32 ], 'transform_id': 2 },
  { 'id':  5, 'tags': ['conv'], 'name': 'FeatureExtractor/MobilenetV2/expanded_conv_9/add', 'depth': 64, 'shape': [ 1, 18, 32, 64 ], 'transform_id': 2 },
  { 'id':  7, 'tags': ['conv'], 'name': 'FeatureExtractor/MobilenetV2/expanded_conv_12/add', 'depth': 96, 'shape': [ 1, 18, 32, 96 ], 'transform_id': 2 },
  { 'id':  9, 'tags': ['conv'], 'name': 'FeatureExtractor/MobilenetV2/expanded_conv_15/add', 'depth': 160, 'shape': [ 1, 9, 16, 160 ], 'transform_id': 2 },
  { 'id': 11, 'tags': ['concat'], 'name': 'concat_1', 'depth': 13, 'shape': [ 1, 1212, 13 ], 'transform_id': 4 },
])

def model_for_version( version=None, path=None ):

    if "320x180" in version:
        return SSD_Mnet2_PPN( graph_path=path, image_shape=[ 320, 180, 3 ] )

    if "480x270" in version:
        return SSD_Mnet2_PPN( graph_path=path, image_shape=[ 480, 270, 3 ] )

    if "512x288" in version:
        return SSD_Mnet2_PPN( graph_path=path, image_shape=[ 512, 288, 3 ] )

    if "720x405" in version:
        return SSD_Mnet2_PPN( graph_path=path, image_shape=[ 720, 405, 3 ] )

    raise ValueError( "No model for graph_version: {}".format( version ) )

Then you can write code as follows:
from lucid.optvis import render

model = model_for_version(
    version = "eb_13_v09_ppmn2_13_256_adam_512x288_tf_1.14",
    path = "/XYZ/graphs/eb_13_v09_ppmn2_13_256_adam_512x288_tf_1.14_200k/frozen_inference_graph.pb"
)

model.load_graphdef()

_ = render.render_vis( model, "FeatureExtractor/MobilenetV2/expanded_conv_15/add:17", thresholds=( 32, 256, 1024 ) )

Inevitably, one has to experiment quite a bit.


What are the limit points of $A_n=[n,\infty)$ in a metric space? Is $A_n$ closed?

Question: $A_n=[n,\infty)$ in $\mathbb{R}$ with a Euclidean metric.
A set is closed if it contains all its limit points. A limit point is a point whose neighborhood contains a point in the set. I'm not sure what happens when we consider a neighborhood at infinity.
Is $A_n$ the set of limit points of $A_n$? If this is true, $A_n$ is closed.
Comment: Which metric space? $\mathbb{R}$ with the usual metric?
Comment: Yes, $A_n$ is closed.
Answer: Your definition of "limit point" is wrong. The expression "a point whose neighbourbood" makes no sense, since a point generally has more than one neighbourhood. Also, the point contained in the neighbourhood may not be the point itself. Rather, a limit point of a set is a point $x$ each of whose neighbourhoods contains a point in the set other than $x$.
It's also not entirely clear what you mean by "a neighbourhood at infinity". You may be confused by the notation $[n,\infty)$. Here the symbol $\infty$ is a notational device and not an element of $\mathbb R$. Points in $\mathbb R$ have "neighbourhoods at infinity" in the sense that that they have neighbourhoods that extend to infinity, but this is irrelevant here since whether a point is a limit point is decided "at close range": Since every superset of a neighbourhood contains all points of the neighbourhood, the condition that every neighbourhood must contain a point means that every arbitrarily small neighbourhood must contain a point.
In the present case, almost all points $x\in A_n$ are in the interior of $A_n$ and have entire neighbourhoods within $A_n$ (for instance $(\frac{x+n}2,\infty)$), except for $x=n$, but here, too, every neighbourhood contains an open set $(n-\epsilon,n+\epsilon)$, which contains the point $n+\frac\epsilon2\in A_n$.
Comment: @ryagami: The post says "neighbourhood at infinity", not "neighbourhood of infinity"; that was part of the vagueness I was referring to. Also, I didn't say that this expression doesn't make sense, just that it's not entirely clear what's meant. The term "neighbourhood of infinity" is well-defined if infinity is an element of the set; if it isn't, we can guess that the intended meaning is "add infinity to the set, take a neighbourhood of it and remove infinity from it".
Comment: The concept of "neighbourhood of infinity" does make sense if you define it as $(M,\infty)$, for some $M\in\mathbb{R}$


Hyperbolic Coordinate Transformation in n-Sphere

Question: $x= r Cosh\theta$
$y= r Sinh\theta$
In 2D, the radius of hyperbolic circle is given by:
$\sqrt{x^2-y^2}$, which is r.
What about in 3D, 4D and higher dimensions.
In 3D, is the radius
$\sqrt{x^2-y^2-z^2}$?
Does one call them hyperbolic n-Sphere? How is the radius defined in these dimensions. In addition these coordinates doesn't seem equivalent. For Cosh only span positive space, while Sinh span both positive and negative space. How can we resolve this? What another hyperbolic coordinate system is good that resolves this problem? I am mainly interested in changing my coordinates x,y,z, etc. to hyperbolic coordinate system.
Comment: I am not sure what you are asking x and y are coordinates so define a point  but what about r as in normal geometry radius and center are independent
Answer: With $x=r\cosh\theta$ and $y=r\sinh\theta$ you get a hyperbola, or at least one branch of a hyperbola. Usually I'd interpret "hyperbolic circle" as "circle in hyperbolic geometry", and unless you are dealing with some rare instances of the Beltrami-Klein model, the hyperbola you describe is not a circle of hyperbolic geometry.
The three-dimensional generalization of a hyperbola is called a  hyperboloid. For the $x^2-y^2-z^2=r^2$ you mention, you'd get the two-sheeted hyperboloid of revolution. That's the surface you get by rotating your hyperbola around the $x$ axis. You might parametrize one of its sheets (corresponding to one branch of the hyperbola) as
\begin{align*}
x&=r\cosh\theta\\
y&=r\sinh\theta\cos\varphi\\
z&=r\sinh\theta\sin\varphi
\end{align*}
But the one-sheeted hyperboloid $x^2-y^2+z^2=r^2$ is just as valid a generalization. It's what you get if you rotate your hyperbola around the $y$ axis. You might parametrize it as
\begin{align*}
x&=r\cosh\theta\cos\varphi\\
y&=r\sinh\theta\\
z&=r\cosh\theta\sin\varphi
\end{align*}
Comment: I believe the following coordinate transformation also works, equally well for the original case:
\begin{align}
x=rSinh\theta
\\
y=rCosh\theta Cos\phi
\\
z=rCosh\theta Sin\phi
\\
\end{align}
However, the Jacobian is negative, which is -$r^2Cosh\theta$. What does the negative Jacobian mean, does this sort of coordinate transformation change my results?
Comment: @t.jun: What you describe is again the one-sheeted hyperboloid. Comparing your parametrization with mine, you have $x$ and $y$ exchanged. You may see this as an orientation-reversing reflection in the plane $x=y$. Or you could see this as a different parametrization of a rotated version of the hyperboloid. BTW: you may want to look at my Math notation (using right click / Show Math As / TeX Commands) to learn about writing special functions and aligning equations, and/or read https://math.meta.stackexchange.com/q/5020/35416 about this.