Service located on network

Question: I've got a WCF web service that handles a portion of business logic and data access. This service is hosted on a server on our network at our office. Our website, hosted elsewhere, uses this service and believes it to be located at http://thatservice.somedomain.com.
I've also got a Winforms app used (only) on machines on our network that wishes to consume the  same service. What I'd like to do is have the local machines attempt to consume the service at http://thatservice.somedomain.com without having a dependency on our internet connection.
I believe I could do this by editing everyone's hosts file to point http://thatservice.somedomain.com to the server's internal static IP address, but I don't think that's the way to go. Is this something I can do in our internal DNS server? Is there some better way to handle this altogether?
Comment: @razlebe - I did think of that, however I half expected the contributors here to come back with "No, no, no. You should do it this way..." from a software architecture point of view.
Answer: Despite this not being the place for it, the solution I ended up implementing is:
I created a Zone in my network's DNS for somedomain.com and pointed thatservice.somedomain.com to the internal IP of the service, but had to also duplicate all of the DNS records that exist on somedomain.com publicly.

Service located on network


Solving the logarithmic inequality by using manipulation

Question: I am trying to solve this problem but stuck
$$\log_x\frac{4x+5}{6-5x}<-1$$
Comment: Where are you stuck?
Answer: Can you take the log in a negative base?
While we are on the subject of undefined solutions, can we take the log of a negative number.  Can, $\frac {4x+5}{6−5x} < 0$
And what would be the implications of $x = 1$?  That would also be undefined
The domain of $\log_x \frac {4x+5}{6−5x}$ is $x\in(0,1)\cup(1,\frac 65)$
$\log_x \frac {4x+5}{6−5x}<(−1)$
Take the inverse log of both sides.
What is going to happen to that inequality?  Does it stay the same, or does if flip?
If $x>1, x^a < x^b$ when $a<b$  when $x>1, x^a>x^b$ when $a<b$.  We must consider the two cases separately.
case $x>1:$
$\frac {4x+5}{6−5x}<x^{−1}\\
\frac {4x+5}{6−5x}<\frac {1}{x}\\
4x^2+5x < 6−5x\\
(4x - 2)(x+3)<0\\
x\in(-3,\frac12)$
But that contradicts that $x>1$
Note: when cross multiplying watch for the possibilities of flipping the inequalities when $x<0.$  Not the case here, so not a risk.
Case $0<x<1:$
$\frac {4x+5}{6−5x}>x^{−1}\\
\frac {4x+5}{6−5x}>\frac {1}{x}\\
4x^2+5x > 6−5x\\
(4x - 2)(x+3)>0\\
x>\frac 12$
$x\in (\frac12,1)$
Comment: When $0<x<1$, the function $\log_x(\cdot)$ is not increasing!!
Answer: Hint:
Note that $$\log_x\frac{4x+5}{6-5x}$$ is a real number iff $0<x<\frac{6}{5}$.
We know that $y=\log_a x$ is a monotoning increasing function for $a>1$ and motonotic decreasing if $0<a<1$.
So, from the definition: $\log_x A=-1 \iff x^{-1}=A $, we have two cases for the given inequality:
$$
\begin {cases}
1<x<\frac{6}{5}\\
\frac{4x+5}{6-5x}<x^{-1}
\end{cases}
$$
$$
\begin {cases}
0<x<1\\
\frac{4x+5}{6-5x}>x^{-1}
\end{cases}
$$
Answer: We have that for $x>0$, $x\not=1$, and $A>0$,
$$\log_x(A)=\frac{\ln (A)}{\ln(x)}$$
where $\ln$ is the natural logarithm.
In our case, for $x>0$, $x\not=1$,
$$A=\frac{4x+5}{6-5x}>0\Leftrightarrow  x\in (0,1)\cup (1,6/5).$$
Now we have two cases.
1) If $1<x<6/5$, then $\ln(x)>0$ and the inequality is equivalent to
$$\ln \frac{4x+5}{6-5x}<-\ln(x)=\ln(1/x)
\Leftrightarrow \frac{4x+5}{6-5x}<\frac{1}{x}
\Leftrightarrow 4x^2+5x < 6−5x \Leftrightarrow  4x^2+10x < 6
$$
which is impossible for $x>1$.
2) If $0<x<1$, then $\ln(x)<0$ and the inequality is equivalent to
$$\ln\frac{4x+5}{6-5x}>-\ln(x)=\ln(1/x)
\Leftrightarrow \frac{4x+5}{6-5x}>\frac{1}{x}\Leftrightarrow  4x^2+10x >6\Leftrightarrow x\in (1/2,1).$$
We conclude that the inequality is satisfied iff $x\in (1/2,1)$.
Answer: Let $f(x):=\frac{4x+5}{6-5x}.$
Firstly, let us work on domain restrictions:

1) $f(x)$ must be $>0$, (because the domain of any logarithm function is $(0,\infty)$; thus $-5/4<x<6/5.$
2) $x>0$ (because any basis of logarithms is positive).

Therefore, values of $x$ are restricted to open interval $I:=(0,6/5)$.
Taking the definition of a logarithm in base $b$:
$$\tag{1}\dfrac{\ln(f(x))}{\ln(x)}<-1 \Leftrightarrow \begin{cases}(a) &if& 0<x<1&\ln(f(x))>-\ln(x)\Leftrightarrow f(x)>\frac{1}{x}\\(b) &if& 1<x<6/5&\ln(f(x))<-\ln(x)\Leftrightarrow f(x)<\frac{1}{x}\end{cases}$$
(we have used the increasing property of function $\ln$).
Can you conclude from there?
Comment: I had made a mistake that is now corrected.


Move Cursor to Beginning of Prepopulated Textview On Load in Objective-C

Question: Upon a View Controller loading from code where a UITextView is prepopulated with some text, I would like the cursor to be at the beginning of the text not at the end.
The following code however is having no effect. The cursor still appears at the end of the prepopulated text.
What can I do to get the cursor over to the beginning of the text?
   self.myTextView.text = @"Text that should go after cursor";
    [self.myTextView becomeFirstResponder];
    UITextPosition* start = self.myTextView.beginningOfDocument;
    UITextRange *newRange = [self.myTextView textRangeFromPosition:start toPosition:start];
NSLog("newRange is%@",newRange);
    [self.myTextView setSelectedTextRange:newRange];

Note, newRange logs as <_UITextKitTextRange: 0x17463f0c0> (0, 0)F so I think the next line is not actually changing the rang.  But I don't know of another way to do this.
Answer: I found that your print was wrong, missing an @
NSLog(@"newRange is%@",newRange);

Then I found that your code is effective, the cursor can be positioned to the front
I tested iOS 9.1、 iOS 10.1、 iOS 11.1、 iOS 12.4 with the simulator, all of which are effective. I don't know what your environment is like.
One more thing to note is that before executing that piece of code, make sure that myTextView has been created successfully. I used storyboard to create myTextView when I tested, and added your code in viewDidLoad.
Comment: I also put the last line inside of a dispatch_async(dispatch_get_main_queue(), ^{
            [self.myTextView setSelectedTextRange:newRange];
        });


Homotopy pushouts and induced maps

Question: Suppose we are in a proper closed model category and consider a commutative square
$$
\begin{array}{rcl}
A&\to& B\\
\downarrow&&\downarrow\\
C&\to&D
\end{array}
$$
in its homotopy category. This square is canonically isomorphic in the homotopy category to a square in which all morphisms are morphisms of the model category (we assume here to have (fixed) functorial factorizations such that all this can be done nicely). Hence, w.l.o.g. the square above is a commutative square in the model category.
If we (functorially) factorize the morphism $A\to B$ into a cofibration followed by a trivial fibration like $A\to B'\to B$, we can form the categorical pushout $P$ of
$$
\begin{array}{rcl}
A&\to& B'\\
\downarrow&&\\
C&
\end{array}
$$
There is an induced map $i:P\to D$ in the homotopy category and one can define the initial square to be a homotpy pushout square if the map $i$ is an isomorphism in the homotopy category.
If one considers now such a homotopy pushout square
$$
\begin{array}{rcl}
A&\to& B\\
\downarrow&&\downarrow\\
C&\to&D
\end{array}
$$
in the homotopy category with morphisms $B\to E$ and $C\to E$ such that everything commutes, there should be a (unique?) morphism $e:D\to E$ in the homotopy category obtained by the construction above.
My question is: Why isn't this construction the colimit in the homotopy category? I have heard that homotopy colimits are not categorical colimits in the homotopy category. Does it fail with the uniqueness of the morphism $e$? The existence of $e$ should be sure. Does one have at least the existence of an induced morphism (in the homotopy category!) for general homotopy (co)limits?
Answer: It's not true that the homotopy colimit is the colimit in the homotopy category. In fact, colimits (other than disjoint unions, say) tend not to exist there.
Here's a bit of intuition for homotopy colimits. (A nice reference is Dan Dugger's primer on the subject.) Suppose you have a diagram of, say spaces or simplicial sets, as in
$$\begin{array}{rcl}
A&\to& B\\
\downarrow&&\downarrow\\
C&\to&
\end{array}$$
To form the push-out in an ordinary sense, you would take the disjoint union $B \sqcup C$, and then quotient by the relation that for each $a \in A$, the image of $a$ in $B$ is identified with that in $C$. This, however, is not homotopy invariant, because the operation of quotienting in this way is not well-behaved homotopically. A better variant (from this point of view, at least) is not to quotient by this relation, but to glue in paths for it. That is, if $i: A \to B, j: A \to C$, then to form the homotopy push-out of this diagram, you should draw in paths from $i(a)$ to $j(a)$ for each $a \in A$.
This is one explicit construction of the homotopy push-out which works for spaces that are nice (say, CW complexes) or for arbitrary simplicial sets (for the more general theory, you should look up the Bousfield-Kan formula). You can check that in this case the operation just described is homotopically well-behaved, and that it is weakly equivalent to the usual colimit for projectively cofibrant diagrams.
So, let's take this as our explicit construction of the homotopy push-out of spaces or simplicial sets. Now, we want to describe maps from the homotopy push-out, which I'll call $D$, into an arbitrary space $X$. By definition, this is given by maps $B \to X$, $C \to X$, and a homotopy $A \times I \to D$ of the restriction $A \to B \to X$ with $A \to C \to X$. This follows from the other construction as $D$ by gluing in lots of paths.
Note that the homotopy itself is part of the data; it's not enough to just give two maps that happen to be homotopic. We can think of this as  a space of maps, and its connected components are the morphisms $[D, X]$ in the homotopy category.
Now, if the space of maps $D \to X$ were  just the space of maps $B \to X, C \to X$ whose restriction to $A$ were homotopic, then you're right: $D$ would be the push-out in the homotopy category. But the problem is that the homotopy has to be included in the data. Here's an explicit example to illustrate this. Let $B = C = \ast$. Then the homotopy push-out is given by drawing paths $\ast \to \ast$ for each $a \in A$; this, in other words, is the suspension of $A$ (whether it's reduced or unreduced depends on whether you work in the pointed or unpointed category). What the above says is that to give a map $\Sigma A \to D$ is to give two points of $D$, and a homotopy between the two constant maps $A \to D$ given by these points; this is reasonable. More to the point, in this case the homotopy push-out is definitely not the push-out in the homotopy category, because $\ast$ is final in the homotopy category and that push-out would be $\ast$.
Finally, note  that even homotopy inverse limits are not inverse limits in the homotopy category (e.g. because of the Milnor exact sequences with $\lim^1$ terms).
Answer: I think you don't even have the existence of $e$.
The problem is:

What are the morphisms in the homotopy category, and
When two morphisms are equal in the homotopy category.

As for the first question, in general the answer is that a morphism from $A$ to $B$ in the homotopy category is a sequence of maps of the original category
$$
A= A_0 \stackrel{\sim }{\longleftarrow} A_1 \longrightarrow A_2 \stackrel{\sim}{\longleftarrow} \dots \stackrel{\sim}{\longleftarrow} A_n \longrightarrow B
$$
where the ones going to the left are weak equivalences.
In general, it's difficult to tell when two such sequences are equal. The best think you can have is that your class of weak equivalences admits a (right, left) calculus of fractions. Then, arrows in the homotopy category are sequences of length $2$
$$
A \stackrel{\sim}{\longleftarrow } A_1 \longrightarrow B
$$
and equality between two such sequences means that some diagram made up from four triangles is commutative. In general, equality involves bigger commutative diagrams in the original category. For more information, see Dwyer, Hirschhorn, Kan, Smith, "Homotopy limit functors on model categories and homotopical categories", AMS Math. Surveys and Monographs, 113.
So, try now to say what's the meaning for two such arrows (sequences) starting from your $B$ and $C$ and ending in $E$ to form a commutative diagram in the homotopy category. Then, try to imagine how this could imply the existence of some $e: D \longrightarrow E$.
EDIT. Maybe I can add another point of view. If $\cal{C}$ is a model category, then its (Quillen) homotopy category (obtained inverting its weak equivalences) $\mathrm{Ho} \cal{C}$ is equivalent to the (classical) homotopy category $\pi_{cf}(\cal {C})$; i.e., the category whose objects are the fibrant-cofibrant ones and maps are homotopy classes of maps of $\cal{C}$.
So, this $\pi_{cf}(\cal {C})$ allows you a more specific representations of maps of the (equivalent, Quillen) homotopy category: here, they are "real" (homotopy classes of) maps of $\cal{C}$, not unmanageable sequences.
Even in this equivalent homotopy category, the problem remains: when you have two (classes) of maps $B \longrightarrow E$ and $C \longrightarrow E$, making your diagram commutative in $\pi_{cf}(\cal {C})$... "Commutative" in $\pi_{cf}(\cal {C})$ means  commutative up to homotopy in $\cal{C}$. And it doesn't matter if your objects are fibrant-cofibrant and your morphisms cofibrations: from the universal property of the push-out in $\cal{C}$ you cannot deduce the existence of $e: D \longrightarrow E$ if you have commutativity up to homotopy in the diagram involving $B \longrightarrow E$ and $C \longrightarrow E$.
Comment: Ncatlab (http://ncatlab.org/nlab/show/homotopy+pullback) says that these notations of "global" and "local" homotopy pushouts coincide, but I don't see why.
Comment: I'm sorry. I'm not familiar with those "homotopy push-out".

Homotopy pushouts and induced maps


How to rotate ios simulator to landscape from the command line

Question: I am testing a flutter app on an iOS device in a CI/CD system from the commandline, so I am using xcrun simctl commands to controll the simulator.
For tablets, I want to test the app also when the device is in landscape mode. But I cannot find anything on how to rotate an ios simulator from the command line to lanscape.
Can I rotate the ios simulator to landscape using xcrun simctl or some other command line tool?
Comment: Did you find a solution to this problem?
Answer: osascript -e 'tell application "Simulator" to activate' -e 'tell application "System Events" to click menu item "Rotate Right" of menu 1 of menu bar item "Device" of menu bar 1 of application process "Simulator"'


Difference between Foreground service vs Activity in android

Question: I am trying to create one hobby app on Android rooted device. In this app there is no need for user interaction as well and app need to run continuously . I am trying to use some sensors (accelerometer/gps) and camera also.
I have 2 approaches for this implementation as mentioned below-
1- Single Activity with Kiosk mode
2- Foreground Activity starting from application class
So I am looking for pros and cons for both the approaches in terms for battery , some background tasks etc.
Does doze mode/screen sleep impact activity and foreground service differently?

Edit-1
I am using custom ROM for my embedded project . I need to keep it for single application and user interaction is not there. I was thinking for better approach for my project in that case.
Answer: If I understand your question correctly, you're asking about creating an app that runs some sort of task without an active user. In this case, you're looking into deferred and exact tasks.
You can use WorkManager to schedule tasks to be executed at the exact time.
As for the services, there is a distinction between foreground and background ones. Please note that Android opposes certain background execution restrictions when you're targeting SDK versions 26 and above. With foreground services, you're required to display a status bar notification.
The documentation clearly states that the use of WorkManager is preferred over starting a foreground service. I would advise you to read this Medium article for more information.
Comment: I am using custom rom for my embedded project . I need to keep it for single application and user interaction is not there. I was thinking for better approach for my project in that case.


Cutting a square and gluing it back together

Question: I have a $1 \times 1$ square and I cut the triangle that has vertices at the center and bottom right and left corners of the square. Then I glue this triangle to the right edge of the square as shown in the picture:
The task is to cut the second shape in two such that after rotating and maybe flipping those two shapes, we get the unit square back. The cut can be any curve that separates the shape into two pieces. For example, the cut shown by the color green trivially gives a square after we rotate the triangle back into the place where we cut it from.  The question is whether there are other cuts, and if they exist whether they are finite or infinite.
By arguing that a distance larger than $\sqrt2$ cannot exist, I managed to reduce the possible curves to the ones starting at the Yellow line and ending at the Red zigzag as shown in the image above. But I couldn't go further. Also, a continuation of this problem would be to show the existence or finiteness of solutions given any regular polygon.
Comment: I also (from again using the same reasoning) know that the curve cannot start from $\frac{1}{2}(3 - \sqrt{7})$ units from the left of the yellow line; and some amount of units from the left of the red zigzag
Comment: Difficult question to answer... maybe functionals can be used to determine some sort of a minimalizing condition
Comment: your first step is essentially one used in a hinged dissection https://en.wikipedia.org/wiki/Hinged_dissection
Comment: Well, this does not assist the problem by any means.
Answer: We can show that any working straight or zigzag (alternating concave-convex angle) cut divides the piece into two pieces A and B, where A has an convex angle a and B has an convex angle b such that $a+b=180^{\circ}$.
Let's start by forgetting about the square specifically. Instead, we wonder whether this shape can be divided into two pieces that can be formed to make any quadrilateral in any way but the trivial case. We notice that for almost all convex $a$-gon A and convex $b$-gon B where A has no angle $a$ and B has no angle $b$ such that $a+b=180^{\circ}$, when glued together we get a polygon with at least $(a+b)-2$ vertices. For example, here's two 5-gons joined together into an 8-gon.

However, we're assuming that when joining two convex vertices, we always form another vertex. This, however, is not always true, as if we join two pieces A and B, where A has an convex angle a and B has an convex angle b such that $a+b=180^{\circ}$, the angles a and b may combine to "cancel out", so to speak, meaning that both vertices "disappear" from our count. Let us assume that this condition does not happen for the rest of our analysis.

We need to place a similar lower bound on the number of vertices in the gluing of concave polygons. For the sake of terminology, let us define an $(a,b)$-gon as a simple polygon with $(a+b)$ vertices, $a$ of which are convex and $b$ of which are concave. It is evident that in an extremely optimal (and potentially impossible setting), when we join an $(a,b)$-gon and a $(c,d)$-gon, we might be able to get every concave angle in one polygon to "cancel out" a convex angle in the other. Thus, we would obtain a polygon with at least $(a-d)+(c-b)-2$ vertices, subtracting the $2$ again as before. You can of course rearrange this formula, but I think this representation is most intuitive. For example, to make a 4-gon from the blue $(5,2)$-gon below, you need to glue on the red $(6,3)$-gon.

This formula allows us to show that dividing our shape with zigzag rather than straight lines has no effect on the number of vertices in the polygons we can ultimately create. Adding zigzags in a straight line increases the number of convex vertices in one polygon, but simultaneously increases the number of concave vertices in the other polygon by the same amount. These cancel, so even in our hyperoptimal (and again, probably generally impossible) case, the minimum vertices of the glued polygon remains the same. Here's an example: no matter how many zigzags we add to this dividing line, the resulting blue and red pieces can't be joined together to make anything with less than 6 vertices.

Now, we can analyze our particular shape using casework, building off of OP's result that the line must start at the top yellow line (but not at the top left corner, because then we'd have lines longer than $\sqrt{2}$) and come down to the red line (but not the bottom left corner for the same reason). Because we don't care about distance, only the vertex counts of the resulting polygons, many points are interchangeable. Precisely, we only have seven classes of points - left half of yellow line, right half of yellow line, top right corner, left half of red line, midpoint of red line, right half of red line, bottom right corner. Note: Zigzag cuts alternate between concave and convex, causing this cancellation. If one drew a cut with, say, three concave angles (from the perspective of the left piece), these would not apply. It may be possible to reduce these further, but this is good enough for the casework. Remember that zigzags don't affect the final vertex count, so we can add them to our lines if needed.

We see in the cases above that the only line that produces polygons that may form a quadrilateral is in the trivial case, from the top right corner to the bottom right corner. Thus, assuming our initial condition regarding angle sums, no non-trivial solution exists. As OP has mentioned in the comments below, though, it is possible to find a non-trivial solution, but as shown, there must be two angles (one in each piece) that sum to 180 degrees.
Note: It may be possible to generalize from our piecewise-linear cuts to smooth curves by taking limits. However, this may break our method of counting, so I won't extend to that here.
Comment: A very nice attempt, which shows a good approach to solving the problem, but I am afraid that it is wrong as the types of PL curves that you have considered(not even the cuts with the amount of turns less than 3) do not include all the possible PL-curve "types". There is a non-trivial solution to this problem.
Comment: Furthermore, the main problem with your argument lies in the fact that when a convex vertex is attached to a concave vertex; the resulting shape can give rise to 3 collinear points which contradicts your basic addition/subtraction formulas. This is what happens in the non-trivial case.

This argument can be used to prove that if a solution exists; then a collinearity of vertices is a must as otherwise it would contradict your point.
Comment: @SStormM What do you mean by 3 collinear points? Do you mean that the polygon contains 3 vertices, not necessarily adjacent, that are collinear? And if so, how does this contradict the formulas? (I'm not denying that they're wrong, I'm just curious what exactly breaks) And what do you mean by PL-curves?
Comment: For example, if both polygons are of the form $(5,1)$ ; then by your formula, there should be $6$ vertices of the glued shape. But you are assuming that an edge necessarily forms between any two vertices after gluing. In fact there can be no edge between two vertices; and the two vertices (1 after gluing) may even lie in the middle of a line (it is collinear with 2 other vertices); therefore it may not be a vertex after gluing.
Comment: PL = piecewise-linear
Comment: Can you fix your answer please?
Comment: I've edited it to clarify the collinear condition (and defined it using angle sums). However, I understand that I still have some error about PL-curves, but as I haven't been able to figure out what the other kind(s) of curve is, I'm not sure how to address it (besides a note I left in the post).
Comment: I looked at the possible cuts one last time and I made a mistake. Your calculations include all cuts up to 2 turns.
Comment: Ah, I got it. I added the note to explain that this only works for straight cuts or cuts that alternate between concave and convex angles.
Comment: Yes I saw it thank you very much :)


How do I view cached PMTU under Linux (and all other OSs)

Question: When I ping a remote site with the DF bit set and a packet size that is too big for my router the first ICMP "fragmentation required" message is sent from the router. After that the message comes from my localhost.
Netstat -rC (on Linux) allows me to view the routing table cache, but
1) Seems to show MTUs under a column called MSS (which I would expect to be the lower TCP MSS of the link)
2) Always shows the value as 1500
My localhost must be caching the PMTU somewhere so it can generate the fragmentation required message. But how do I see that?
Here is an example on my machine (-n on netstat inhibits reverse DNS lookups):
[root@vbcentos ~]# ping -c 4 -M do -s 1431 184.108.40.206
PING 22.214.171.124 (220.127.116.11) 1431(1459) bytes of data.
From 18.104.22.168 icmp_seq=1 Frag needed and DF set (mtu = 1458)
From 184.108.40.206 icmp_seq=2 Frag needed and DF set (mtu = 1458)
From 188.8.131.52 icmp_seq=2 Frag needed and DF set (mtu = 1458)
From 188.8.131.52 icmp_seq=2 Frag needed and DF set (mtu = 1458)

--- 220.127.116.11 ping statistics ---
1 packets transmitted, 0 received, +4 errors, 100% packet loss, time 1002ms

[root@vbcentos ~]# netstat -rCn
Kernel IP routing cache
Source          Destination     Gateway         Flags   MSS Window  irtt Iface
18.104.22.168   188.8.131.52   188.8.131.52   il        0 0          0 lo
220.127.116.11   22.214.171.124   188.8.131.52          1500 0          0 eth0
22.214.171.124   184.108.40.206   126.96.36.199   l     16436 0          0 lo
220.127.116.11   220.127.116.11 188.8.131.52 ibl       0 0          0 lo
184.108.40.206   126.96.36.199   188.8.131.52          1500 0          0 eth0
220.127.116.11   188.8.131.52   22.214.171.124   il        0 0          0 lo
18.104.22.168   18.104.22.168   184.108.40.206   l         0 0          0 lo
[root@vbcentos ~]#

EDIT:
As per suggestion:
ip route get to 22.214.171.124

gives
22.214.171.124 via 188.8.131.52 dev eth1  src 188.8.131.52
    cache  mtu 1500 advmss 1460 hoplimit 64

Which also seems wrong as the MSS is just 40 less than the mtu, which is the interface
mtu rather than the PMTU
Comment: On Fedora 22, `netstat -rCn` returns nothing, but `watch ip route get to $HOST` shows what's up, including the cache TTL. `ip route show cached` shows probably also output something but does not.
Comment: I've tried on both Debian 9 and on Fedora 34  `ip route get to IP` and it does not show the mtu
Comment: @sebelk From `man ip-route`: Starting with Linux kernel version 3.6, there is no routing cache for IPv4 anymore.
Answer: Maybe
ip route get to 22.214.171.124

Comment: Edited question to add this.
Answer: Under Windows, use the netsh command to view the "destination cache" which holds this information. For example (assuming IPv4):
netsh interface ipv4 show destinationcache

Answer: MSS should be 40 bytes less than your MTU (it doesn't include IPv4 (20 bytes) and tcp (20) byte headers). So that is correct.
ICMP fragmentation needed message is sent by the router, not your server.
Comment: MSS should be 40 bytes less than the *PATH* MTU, which is 1458 (assuming PMTUD is working, which appears to be the case.)  And yes, of course, the ICMP fragmentation is sent from the router, which is what the OP says.
Answer: The route get doesn't work for me either. But what worked was route show cache
For IPv6 ip -6 route show cache shows everything that is currently cached. And the ip -6 route get 2001:470:1:18::3:1280 shows the PMTU for the specified target.
To test this use the curl command from this test page: https://test-ipv6.com/faq_pmtud.html
Related ip route documentation: http://linux-ip.net/html/tools-ip-route.html#tools-ip-route-show-cache
If you want an alternative to PMTU on IPv4 look at this cloudflare article: https://blog.cloudflare.com/path-mtu-discovery-in-practice/
which mentions "Enable smart MTU black hole detection" which can be enabled (temporarily) by: echo 1 > /proc/sys/net/ipv4/tcp_mtu_probing; echo 1024 > /proc/sys/net/ipv4/tcp_base_mss


Setting up tours

Question: I think I have two pretty straight questions about the tours and tours ui module but I can't seem to find the answers. Sorry for putting them in one post it seems more logic this way.

How can I create a custom tours button to call the tour on the current page. The default button is shown in my admin menu but I want it to show to people who don't have access to the admin menu as well.
I know I can do this with a simple link but this makes the page reload and this doesn't happen with the default button. So there must be another way.
I have to insert a route for the page where the tour should be shown. The route I can find for my content type page is entity.node.canonical but I think this is the route to all node pages. Is there a way to make it specific for one content type page?
Answer: Question 1
If you look in tour module, there are a js/tour.js file with the logic. You could use it to figure out how it works.
Drupal.behaviors.tour = {
attach: function attach(context) {
  $('body').once('tour').each(function () {
    var model = new Drupal.tour.models.StateModel();
    new Drupal.tour.views.ToggleTourView({
      el: $(context).find('#toolbar-tab-tour'),
      model: model
    });

    model.on('change:isActive', function (model, isActive) {
      $(document).trigger(isActive ? 'drupalTourStarted' : 'drupalTourStopped');
    }).set('tour', $(context).find('ol#tour'));

    if (/tour=?/i.test(queryString)) {
      model.set('isActive', true);
    }
  });
 }
};

When you talk about default button, i think you are refering to '#toolbar-tab-tour' button, so you could write a js file following this example.
Question 2
You are right. Tipically,you could work with this route using paramenters to build URL. For example:
$url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 1], $options)

But you can't add these params in module Tour UI. I think the easiest approach is build a simple module and create your own route to map a node. It should be fast.
Here the link for more infomation to build a module
Comment: Thanks a lot. Creating a button was as simple as creating a div with the #toolbar-tab-tour id. When the use doesn't have acces to the admin toolbar this custom div will work as the default button replacement.

Setting up tours


which SD for Cohens D in psychotherapy pre-post study?

Question: I'm reading a study where two groups receive two different psychotherapeutical treatments. The authors calculated Cohens D:
'In addition, we report estimates for Cohen's d effect sizes as the adjusted mean difference of the outcome (between the groups) divided by the sample SD of the outcome at baseline.'
Why did they use the baseline SD and not the post-SD or the pooles baseline-post SD?
There were no baseline differences between the group.
Here is the link to the study: https://www.thelancet.com/journals/lanpsy/article/PIIS2215-0366(21)00158-9/fulltext
I really aprecciate any kind of help.
Comment: See, for example [this paper](https://psycnet.apa.org/doi/10.1037/1082-989X.7.1.105) and the references therein.
Comment: Greetings! It may help answerers if you provide a link to the study you refer to.
Comment: Thank you for the tip. I've added the link to my question.
Answer: This is standard practice.
You want to know the effect of treatment, scaled by it's standard deviation before you do any treatment - because that's the estimate of the treatment effect.
The treatment might have an effect on the standard deviation of the data, in which case the interpretation would be weird.
Cohen's D is just there to help with the interpretation of the size of the treatment effect.


Russell Paradox and set theories

Question: The Russell paradox arise in the Cantor set theory, but it can be avoided in the $ZF$ and in $NGB$ axiomatic set theory. Are there other axiomatic set theories in which this paradox can be avoided? Thanks.
Comment: Aaargh. The Russel paradox does not arise in the set theory of Cantor. It was a paradox for the set theory of Frege. And no theory that we would call a set theory today allows for the paradox.
Comment: Every set theory built on standard logic tries to avoid the known difficulties. Whether it succeeds is another matter. The only exceptions are set theories based on paraconsistent logics, which limit the damage done by $A\land \lnot A$ in other ways.
Comment: Quine's [New Foundations](https://secure.wikimedia.org/wikipedia/en/wiki/New_Foundations) avoids the paradox by forbidding comprehension over the poisonous predicates.
Comment: Most (if not all) modern set theories avoid Russell's paradox by limiting set construction principles.  In particular, the [_Comprehension Scheme_](http://en.wikipedia.org/wiki/Axiom_schema_of_specification) is restricted so that a definable class is a set only if it is a subclass of a set.
Comment: Much like when defining a function you first check whether or not it is well defined, there is a list of usual paradoxes which one checks when defining axioms of set theory. Russell's one is probably the first.
Comment: @Mathemagician1234: I'm not certain if the CS restriction is _more_ important in either NBG or MK set theory than in ZFC.  In either case, it serves the same purpose.  A ZFC-like theory with an unrestricted CS would give a _set_ of all sets, since there is nothing else for this definable object to be.  NBG has the the Axiom of Limitation of Size which itself implies that $V$ is a proper class.
Comment: Possibly also useful: [Elementary Set Theory With a Universal Set](http://math.boisestate.edu/~holmes/holmes/head.pdf).
Comment: @Arthur I prefer NBG set theory models over ZF models because I want to be able to give a common foundation to both category theory and set theory and NBG does that. (So does Quine's NF,but NF has major issues that make it very problematic as a foundation for mathematics.) But in the case of any set theory that allows proper classes, the CS restriction is even MORE important since the set of all sets-if it exists-is a proper class.
Answer: As it is mentioned in comments above, the so called Russell paradox is a consequence of non-restricted Comprehension Schema according to which for any formula $\varphi(x)$, where $x$ is free, $\{x\mid\varphi(x)\}$ is a set. This paradox is actually a result of a logical truth ($R$ is a binary predicate):
$$
\neg\exists x\forall y(yRx\iff \neg yRy)\,.
$$
In light of this, assuming non-restricted comprehension in a language in which you have at least one binary predicate you always get inconsistent theory. Thus if you want to build a set theory based on classical logic you must restrict the schema one way or another.
EDIT: This address Asaf question below (I should have written it before it was asked). As I wrote above, if you build a system of set theory you must restrict the Comprehension Schema. All such restrictions I am aware of allow you to avoid falling into inconsistency due to Russell paradox.
Comment: I'm not sure I understand how this is an answer to this question really...
Comment: @Asaf: I edited my answer a bit. Hope you can read my intentions now.

Russell Paradox and set theories


Simple preprocessing large columns set

Question: I have a huge dataset about the effect of the drug on cancerous cell lines with a 17k column.
I need to prepare a simple regression, but I don't know, how to pick the most important columns.
I prepare a simple preprocessing:
<code>variances <- apply(X=data.train, MARGIN=2, FUN=var)

sorted <- sort(variances, decreasing=TRUE, index.return=TRUE)$ix[1:500]

# use that to subset the original data
dat.highvariance <- data.train[, sorted]
</code>
It is the correct way?
Answer:
how to pick the most important columns

It is depending on how do we define important. What you are doing is picking the columns that have more variance (information), which is a good way to start.
However, be aware of that columns with large variance may have nothing to do with the regression target.
See this post for details.
How to decide between PCA and logistic regression?

Simple preprocessing large columns set


Counterpoint with more than 4 parts

Question: In Rachmaninoff Prelude in B Minor Op. 32 No. 10 I've noticed that not all voices are 4 parts. In fact I've noticed that in 19th century and 20th century music there's more than 4 parts in a harmony. I've seen 5, 6, and even 7 parts or more. This confuses me a lot because I'm currently studying harmony and voice leading and everything is literally 4 parts.
I've also noticed that music isn't always a 4 part harmony, Rachmaninoff and other 19th/20th century composers write in more than 4 parts. The music will alternate to 5 parts then back to 4, etc.
How does one analyze music with more than 4 parts? Are there any books that focus on more than 4 parts? Do I need to focus on SATB to see how voices resolve?
Answer: Counterpoint can be written for basically any number of independent parts greater than 1.  (And even for a solo instrument, there's something called compound melody that can simulate counterpoint as if in multiple voices.)
Counterpoint in more than four parts isn't only in the 19th and 20th centuries, either.  Bach, for example, wrote several motets and other pieces that involve up to eight parts.  Often with 8-voice counterpoint, the voices are divided into two 4-voice "choirs" that function somewhat separately.  But there are extended sections of true 8-voice counterpoint in those pieces.  More commonly, baroque composers occasionally added a fifth or sixth voice at times, likely imitating the common late renaissance mass texture which frequently had five voices in counterpoint.
(For an extreme example, see things like Spem in alium, a renaissance motet by Tallis that involves 40 independent voices in "counterpoint."  I put that in quotation marks partly because a texture that enormous poses huge challenges for voice-leading, so the motet mostly has very slowly moving harmonies and a lot of voices just arpeggiating notes within a harmony.)

This confuses me a lot because I'm currently studying harmony and
  voice leading and everything is literally 4 parts.

Some textbooks use the standard SATB 4-voice framework as a pedagogical tool to introduce students to the beginning notions of counterpoint.  That doesn't mean 4-part counterpoint is the only possibility or even the most common one.  Four voices is chosen partly in introductory courses because it allows for the use of full chords (including full seventh chords), and also brings up issues like proper doubling in triads, etc.  The texture is thick enough to teach students to learn to scan for things like parallels, etc.
Two-part and three-part counterpoint are possible and particularly common in some genres in the baroque period, but they sometimes aren't studied in depth in intro courses.  Part of the reason is because music theory pedagogy today is very chord-focused, whereas counterpoint with fewer voices requires a somewhat different treatment of harmonic concerns.  And music with 5 or more voices doesn't raise a lot of additional "rules" to deal with, but it can be harder to write for beginners simply because more voices are present and thus there are more opportunities for errors in voice-leading.

How does one analyze music with more than 4 parts?

I'm not certain what you mean exactly by "analyze" in this context.  You approach music with more than 4 parts in the same way as 4-part music, for the most part.  If there's something specific that you think might work differently, let me know in a comment, and I can expand on this.

Are there any books that focus on more than 4 parts?

Possibly, though I can't think of one off the top of my head.  You may want to have a look at books devoted specifically to counterpoint, rather than a "harmony and voice-leading" intro textbook.  Generally, books on counterpoint tend to devote a later chapter or two to textures involving 5, 6, 8, or more voices.

Do I need to focus on SATB to see how voices resolve?

No, I don't know that it's particularly helpful to attempt to reduce a thicker texture to four parts in most cases.  If the music is truly contrapuntal, a fifth or sixth voice will have its own line and its own status, which should be analyzed as its own thing.  (One exception are the "double-choir" 8-voice pieces like I mentioned above.  SATB analysis might be helpful there in understanding the individual choirs.)
Note that I'm discussing true counterpoint here.  If you're referring also to harmonic textures that just have an extra chord note or two doubled, that's often not additional "counterpoint."  That's just doubling notes in a chord to create a thicker sound.
All of that said, whether the texture is more chordal or contrapuntal, the motion of individual voice lines should still obey the voice-leading and counterpoint principles you are likely learning for SATB texture.  For example, if you look at a place where Bach has 8 voices going on at the same time, he usually will still only has one voice with a leading tone or with some other moving dissonance (like a seventh).  So, rules you may have learned like "don't double the leading tone" or "don't double the seventh," still usually apply with more voices.  You still need to avoid parallel fifths between all parts, as well as parallel octaves.  (Sort of an exception to the latter is when you deliberately double a part in a different octave.  For example, an orchestral piece might have the cellos playing the same notes as the double basses an octave higher.  Those are not "two different parts" moving in "parallel octaves" but is rather thought of as one counterpoint part that is merely "doubled at the octave.")
The hardest thing about writing or analyzing music in more than four parts is considering the effects of doubling, as well as following all the "rules," just now with ever increasing possibilities of interaction between voices.  For 2-voice counterpoint, there is only one pair of voices to check for parallel fifths.  For 3 voices, there are three pairs.  For 4 voices, there are six pairs (SA, ST, SB, AT, AB, TB).  For 5 voices, there are 10 pairs, and for 6 voices, there are 15 pairs.  Every harmonic shift requires more thought and attention to detail because of these factors, if one is following strict counterpoint.
But again, if you are also referring to segments of music where an additional note or two is doubled in a chord to give a 5-part or 6-part sonority, the composer may not even be worried so much about the formal rules of "counterpoint" in that case.  Some "added voices" may just function like the "doubling at the octave" idea I mentioned above, filling in some chords to create a richer sound.
Comment: What I meant about analyzing is that the chords in the Rachmaninoff Prelude that I mentioned have over 4 voices. I was just wondering how to identify nonchord tones like a neighbour or passing tone, etc. when there's over 4 parts.
Comment: For example: https://imgur.com/vHuyOb1 Rachmaninoff uses 5 and 6 parts.
Comment: @IhshVuhl: In the image you referenced, it just has the "octave doubling" idea I mentioned.  That's really better thought of as an example of 3-voice counterpoint.  Notice that the top voice is the same as the top voice in the left hand, and the 2nd-highest voice is the same notes as the middle voice in the left hand.  When the exact same notes occur an octave (or two octaves or whatever) apart, the tend to be heard as the "same part," rather than a separate independent "part" in counterpoint.

Counterpoint with more than 4 parts


How to apply different frames on image border in flutter

Question: I search a lot how to apply frame on images but found no answer. I read stack function in which we can put an image inside other but its not good trick. I think there must be library for frame and by using that frame can automatically apply on border of image. Please guide me how can I use different design of frame outside image like some filters application.

I want to give options of frame to user like below and when user click on any frame that will apply on image
Answer: There are many approaches for that issue. I've used several in the past. It strongly differs in the way you want to make use of the image. Do you need to paint something on the image or just display it?
In my opinion multiple frames on an image can be achieved best with CustomPainter. Check out the documentation for more. The following Painter should do the trick.
class TestPainter extends CustomPainter {
  final ui.Image image;

  TestPainter({required this.image});

  @override
  void paint(Canvas canvas, Size size) {
    //draw the image
    canvas.drawImage(image, const Offset(0, 0), Paint());

    double rectWidth = image.width.toDouble();
    double rectHeight = image.height.toDouble();
    final imageCenter = Offset(image.width / 2, image.height / 2);

    //first frame
    var border1 = Rect.fromCenter(
     center: imageCenter,
     width: rectWidth + 1,
     height: rectHeight + 1);

    var painting = Paint();
    painting.color = Colors.red;
    painting.strokeWidth = 2;
    painting.style = PaintingStyle.stroke;

    canvas.drawRect(border1, painting);

    //second frame
    var border2 = Rect.fromCenter(
     center: imageCenter,
     width: rectWidth + 3,
     height: rectHeight + 3);

    var painting2 = Paint();
    painting2.color = Colors.green;
    painting2.strokeWidth = 2;
    painting2.style = PaintingStyle.stroke;

    canvas.drawRect(
     border2,
     painting2,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

Please be cautious. The Image in that example needs to be an Image of the dart:ui library (Documentation). There are various way to convert. Depends on your project.
Comment: Thanks for reply sir, I edit question. I want to give different option like given picture and when user click some frame it will apply on border of image
Comment: please tell me how to pass image to ui.image as I take image from gallery so how can I call testpainter by passing gallery image which is a file
Answer: You can load ui.Image from Image.asset with the following
Future<ui.Image> load(String asset) async {
  ByteData data = await rootBundle.load(asset);
  ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
  ui.FrameInfo fi = await codec.getNextFrame();
  return fi.image;
}


Problema em realizar um Groupby de uma Dataframe - Pandas

Question: Estou tentando realizar um groupy em um Dataframe que consta casos de covid-19 por estado no brazil. Porém quando passo a função ele me retorna o seguinte erro na figura abaixo. Há casos de estados que se repetem, por isso gostaria de juntar, para ter uma melhor visualização dos dados...
Answer: Remova o argumento axis=1 do seu código.
Exemplo:
import pandas as pd

>>> df = pd.DataFrame({
...     'cases': [2, 3, 4, 2, 4],
...     'state': ['MG', 'MG', 'SC','RS', 'SC']
...     })

>>> df.groupby('state')
<pandas.core.groupby.generic.DataFrameGroupBy ...

>>> df.groupby('state').count()
       cases
state
MG         2
RS         1
SC         2

Comment: Bom dia companheiro, deu certo o código acima. Ontem tentei desta mesma forma e infelizmente não estava indo de maneira alguma, até mesmo removendo o axis=1. Porém quando eu realizo essa operação, ao invés dele pegar os dados dos estados que se repetem no dataframe e somar, ele simplesmente me retorna dados inconsistentes, por exemplo, em pernambuco, não ouve nenhuma morte e ele me retorna que 24 pessoas morreram...
Comment: Nesse código que você postou, ele apenas conta as vezes que o nome do estado se repete, e não somar os casos de ocorrência nos estados. Não era para ficar MG = 5, RS = 4, SC = 8 ?
Comment: Não sabia o seu intuito com o código, estava apenas mostrando que meu exemplo forma um objeto `DataFrameGroupBy`, como era esperado. Para somar ocorrências ao invés de contá-las, utilize o método `.sum()` ao invés de `.count()`. Mais informações sobre como trabalhar com objetos `DataFrameGroupBy` [neste guia](https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html).
Comment: Funcionou substituindo *count()* por *sum()*. Desde já, obrigado. Irei dar uma olhada neste guia que você repassou!


Can I have identical config on all Keepalived nodes?

Question: While trying to configure an experimental Kubernetes cluster (in a few VMs on my laptop) as "high available" I found the advise to do this using the combination of keepalived and haproxy ( https://github.com/kubernetes/kubeadm/blob/master/docs/ha-considerations.md#options-for-software-load-balancing ).
Looking at the configuration settings I read

${STATE} is MASTER for one and BACKUP for all other hosts, hence the
virtual IP will initially be assigned to the MASTER.

${PRIORITY} should be higher on the master than on the backups.
Hence 101 and 100 respectively will suffice.

and these settings surprise me.
Seemingly I have to choose which of those systems is to be the initial master and I have to "hard" configure this in the nodes themselves.
To me this "high available" setup deviates from the "pet"/"cattle" analogy I find in Kubernetes.
Other systems like for example HBase have a similar setup (one active and multiple standby leaders) and all are configured "identically" (election is done via ZooKeeper).
Is there a way that I can configure Keepalived (for use in Kubernetes) in such a way that all nodes have the same config and it still works correctly?
Answer: Kubernetes itself supplies "cattle" services to applications. Although a lot of the "master" kubernetes services are based on the same infrastructure, at some point you need to bootstrap a service with something lower level to get it all started up.
keepalived as configured in the linked kubernetes docco provides a single VRRP virtual IP address as the highly available endpoint shared between the masters.
The nodes all configure the same VRRP IP address (or name) and keepalived moves that address around the masters. The "election" is completed in the keepalived healthcheck and failover logic.
An alternative to this method is to move the load balancing decision out to an external device or the clients. You can run a reverse proxy on each node (like haproxy) that can weight the kube-api servers and complete the healthchecks.
Comment: No, not using keepalived. It's not based on a highly distributed consensus algorithm. I guess because it's not regularly used in systems that would have a quorum of members to decide (like hbase, etcd etc) and needs to work when only a single node is available.
Comment: I read your answer as a repeat of what the Kubernetes documentation states about keepalived: You have a single MASTER and a bunch of BACKUP nodes. In HBase the active system is elected without the need pre-configure the "initial" master. I would like the same with keepalived. Simply create multiple instances with identical config and let these instances figure it out. How do I do that? Is that possible?
Answer: I realize this is a stale thread but thought I would chime in anyway as I have ran KeepaliveD with identical config on all nodes.
On Debian we have all nodes initially set to BACKUP and have some sort of healthcheck that will increase priority (e.g. how long KeepaliveD has been running or a health check for the local service that you want HA for...)
VRRP v2, which is what KeepaliveD (at least the versions I have worked with) is running on Debian, has a tie-breaker feature, where if the priority is the same on several nodes, then the "highest IP" wins.
This can cause an initial delay if all nodes start up at the same time but this has been acceptable where we use this.
Hope that helps.


Where to change the output of the Symfony2 ConsoleOutput?

Question: I am printing some lines on via the ConsoleOuput. I like to use the Table Helper, yet it uses StdOut by default and this seems to be hardcoded, as in the \Symfony/Component/Console/Output/ConsoleOutput.php, it says:
 * This class is a convenient wrapper around `StreamOutput`.
 *
 *     $output = new ConsoleOutput();
 *
 * This is equivalent to:
 *
 *     $output = new StreamOutput(fopen('php://stdout', 'w'));

Within the project we have Log4Php, and are storing it to a file by changing the default output from stdout to a customized output.
Is there a way to change the output of the ConsoleOutput to something else than sdtout?
Because as of now, I can see the output in the command line in StdOut, yet when the php4log output is redirected to a file, the ConsoleOutput will still be in StdOut.
How can I merge those output together?
Answer: Use BufferedOutput() instead of the ConsoleOutput(). It will store the message and you then can use the messages whereever you want them to.
Use the $output->fetch() method to get the message as a string. The string contain of all write operations you did on the OutputInterface before and the method call will also empty the buffer.
If you need to use it in a different logger, in your case a log4php instance, it would look something like:
$this->getLog4PhpLogger()
    ->info(
        $this->output->fetch()
    );


Implementação de Carrinho de Compras em ASP.NET MVC

Question: Estou tentando montar um "simples" sistema de venda, porém, não possuo conhecimento nenhum em e-commerce. O que eu desejo é o seguinte:
O usuário escolhe os produtos que ele deseja, monta um carrinho, e finaliza o pedido. Aí começa a minha dúvida: o carrinho está meio pronto, eu consigo adicionar os itens e a quantidade desejada, mas não sei como fazer o cálculo para exibir o valor total.
Segue minha Action:
public ActionResult AdicionarCarrinho(int id)
        {
            List<ItemDesign> carrinho = Session["Carrinho"] != null ? (List<ItemDesign>)Session["Carrinho"] : new List<ItemDesign>();

            Design d = db.Design.Find(id);

            if (d != null)
            {
                ItemDesign i = new ItemDesign();
                i.Design = d;
                i.Qtd = 1;
                i.IdDesign = d.IdDesign;

                if (carrinho.Where(x => x.IdDesign == d.IdDesign).FirstOrDefault() != null)
                {
                    carrinho.Where(x => x.IdDesign == d.IdDesign).FirstOrDefault().Qtd += 1;
                }

                else
                {
                    carrinho.Add(i);

                }
                Session["Carrinho"] = carrinho;

            }

            return RedirectToAction("Carrinho");

        }

public ActionResult Carrinho()
    {
        List<ItemDesign> carrinho = Session["Carrinho"] != null ? (List<ItemDesign>)Session["Carrinho"] : new List<ItemDesign>();

        return View(carrinho);
    }

Minha primeira dúvida é: Como posso fazer para fazer o cálculo de valor total de acordo com os ítens do carrinho?
Segunda dúvida: O que fazer após finalizar o carrinho? O que eu estava tentando fazer era mais ou menos o seguinte:
O usuario finaliza o pedido, e abre uma tela de pagamento (apenas boleto). Ele digitaria os dados dele (nome e cpf, sei lá) e o sistema geraria um "pseudo-boleto" com os dados do comprador e os itens que ele pediu. Não precisa ser um boleto de verdade, pois não pretendo implementar isso realmente.
Seguem minhas tabelas:
Design:
IdDesign
Servico
Preco

ItemDesign:
Id
IdDesign
IdPedido

Pedido:
IdPedido
DtPedido
StatusPedido
IdUsuario
DtPagamento
ValorTotal

Aceito sugestão de qualquer tutorial/livro sobre E-commerce.
Edit:
View do Carrinho
@model List<AllFiction.Models.ItemDesign>

@{
    ViewBag.Title = "Carrinho";
}

Carrinho

    @foreach (var item in Model)

    {

        @item.IdDesign - @item.Design.Servico

        <input type="text" value="@item.Qtd" readonly="readonly"/>
        <input type="submit" value="alterar" />
        @Html.ActionLink("Remover", "Remover", "Shop", new {id=item.IdDesign}, null)

    }
@Html.ActionLink("Retornar", "Servicos", "Shop")

Comment: Você quer fazer esse cálculo em *View* ou em *Controller*?
Comment: Acho que no controller. Eu pretendo salvar esse valor depois no banco de dados, ou não há diferença?
Comment: Neste caso, é melhor no *Controller* mesmo.
Answer: Estou supondo que seus Models sejam assim:
public class Design
{
    [Key]
    public int DesignId { get; set; }
    public String Servico { get; set; }
    public Decimal Preco { get; set; }

    public virtual ICollection<ItemDesign> ItensDesign { get; set; }
}

public class ItemDesign
{
    [Key]
    public int ItemDesignId { get; set; }
    public int DesignId { get; set; }
    public int PedidoId { get; set; }

    public virtual Design Design { get; set; }
    public virtual Pedido Pedido { get; set; }
}

public class Pedido
{
    [Key]
    public int PedidoId { get; set; }
    public int UsuarioId { get; set; }
    public DateTime DtPedido { get; set; }
    public StatusPedido StatusPedido { get; set; } // StatusPedido seria um Enum

    public DateTime DtPagamento { get; set; }
    public Decimal ValorTotal { get; set; }

    public virtual Usuario Usuario { get; set; }
    public virtual ICollection<ItemDesign> ItensDesign { get; set; }
}

Não tem muito segredo. Você fez tudo certo até agora. Só vou mudar algumas coisas pra facilitar o cálculo:
    public ActionResult AdicionarCarrinho(int id)
    {
        // Ao invés de colocar uma lista de ítens de Design, vamos colocar
        // Um objeto da entidade Pedido, que já possui List<ItemDesign>.
        // List<ItemDesign> carrinho = Session["Carrinho"] != null ? (List<ItemDesign>)Session["Carrinho"] : new List<ItemDesign>();
        Pedido carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();

        var design = db.Design.Find(id);

        if (design != null)
        {
            var itemDesign = new ItemDesign();
            itemDesign.Design = design;
            itemDesign.Qtd = 1;
            // Esta linha não precisa. O EF é espertinho e preenche pra você.
            // itemDesign.IdDesign = design.IdDesign;

            if (carrinho.ItensDesign.FirstOrDefault(x => x.IdDesign == design.IdDesign) != null)
            {
                carrinho.ItensDesign.FirstOrDefault(x => x.IdDesign == design.IdDesign).Qtd += 1;
            }

            else
            {
                carrinho.ItensDesign.Add(itemDesign);
            }

            // Aqui podemos fazer o cálculo do valor

            carrinho.ValorTotal = carrinho.ItensDesign.Select(i => i.Design).Sum(d => d.Preco);

            Session["Carrinho"] = carrinho;
        }

        return RedirectToAction("Carrinho");
    }

    public ActionResult Carrinho()
    {
        Pedido carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();

        return View(carrinho);
    }

A View ficaria assim:
@model Pedido

@{
    ViewBag.Title = "Carrinho";
}

Carrinho

    @foreach (var item in Model.ItensDesign)
    {

            @item.IdDesign - @item.Design.Servico

            <input type="text" value="@item.Qtd" readonly="readonly"/>
            <input type="submit" value="alterar" />
            @Html.ActionLink("Remover", "Remover", "Shop", new {id=item.IdDesign}, null)

    }

@Html.ActionLink("Retornar", "Servicos", "Shop")

Comment: @RyanSantos Editei a resposta.
Comment: Estou agora com probleminha para montar a view do carrinho. Como eu estava utilizando o model ItemDesign, eu tinha uma lista com o nome do produto e a quantidade. Vou editar para você ver...
Comment: É possível acessar os mesmo atributos da minha antiga view, utilizando a model pedido?
Comment: Pô, ta virando rotina já! Mais uma vez, obrigado.
Comment: Só me tira uma dúvida. O que você indicaria para resolver a questão do pagamento? Digo, acredito que eu não possa sair por ai gerando boletos bancários a vontade(ou posso!?). Eu só preciso simular um e-commerce mesmo. Qualquer coisa eu abro outra pergunta explicando melhor.
Comment: Use um Gateway, [tipo o PagSeguro](https://pagseguro.uol.com.br/).


Crop com html/css/js

Question: Estou tentando usar um plugin que achei neste vídeo, porém estou enfrentando o seguinte problema: gostaria de fazer upload de uma imagem e fazer um crop em 1747px de largura. Porém para dispositivos com largura menor que isto acaba explodindo como na imagem abaixo:

Alguém sabe como resolver isto? Código abaixo.

#uploadimageModal .modal-dialog {
    max-width: 1920px !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.css" rel="stylesheet"/>

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

Image Crop & Upload using JQuery with PHP Ajax

Select Profile Image

       <input type="file" name="upload_image" id="upload_image" accept="image/*" />

Upload & Crop Image

          <button type="button" class="close" data-dismiss="modal">×</button>

        <button class="btn btn-success crop_image">Crop & Upload Image</button>

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Comment: Já tentou colocar a imagem com width em %, tipo max-width: 100% para ver como fica?
Comment: A imagem em si não é o problema, adicionado o 100% ela se adapta ao container, o problema é que tem uma div pai, onde é o tamanho definido no js como viewport e outra div que é definida como boundary, acredito ser nessas divs que deve ser feito algo para a imagem se adaptar.
Answer: Cara eu fiz um ajuste no código, primeiro coloquei no JS a largura $image_crop no viewport e boundary em 100%.
Depois determinei pro modal uma largura máxima com max-width, mas para menos que isso eu tb declarei o width em 100%, isso via deixar a janela responsiva para telas pequenas.
O resultado foi esse:

Segue o código da imagem acima:

<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.css" rel="stylesheet" />

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

Image Crop & Upload using JQuery with PHP Ajax

Select Profile Image

                <input type="file" name="upload_image" id="upload_image" accept="image/*" />

Upload & Crop Image

                    <button type="button" class="close" data-dismiss="modal">×</button>

                            <button class="btn btn-success crop_image">Crop & Upload Image</button>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Comment: hugo, desculpe a demora para lhe responder, mas estive corrido! Então realmente o modal ficará responsivo, mas isso acaba influenciando no crop da imagem, onde ele ficará do tamanho que a janela estivar e não do tamanho definido no viewport o que não pode acontecer, pois como comentei o crop deve ser feito em 1747px independente do tamanho da janela. O que tem que acontecer é que a imagem deve se adequar como normalmente é feio com uma imagem com width 100% dentro de um container, porém quando acontecer o crop deve ser feito pelo tamanho definido no viewport.

Crop com html/css/js


How to send HTML email

Question: I am creating a simple module which will be sending HTML emails to users for deals in our website.
I have searched a lot, but I can't find a solution proper solution for Drupal. Now I can send mails but plain text.
What is a step-by-step procedure to send HTML emails in Drupal 7?
function example_form_submit( $form,&$form_state) {
    $friend_email=$form_state['values']['friend_email'];
    $mailto =$friend_email;  //gift to a friend
    $mailfrom ='email@example.com';
    $subject = "another message for  HTML email from example.com";
    $body="
Hello EMAIL, i here i want to be bolded
";
    if (drupal_mail('example', 'send_gift', $mailto, language_default(),$params,$mailfrom,TRUE)) {
        drupal_set_message(t('Your gift was sent successfully!!!'));
    }
    else {
        drupal_set_message(t('Error occured while sending your mail!!!'));
    }

/****hook_mail*/
function example_mail($key,&$message,$params) {
    $language = $message['language'];
    switch ($key) {
        case 'send_gift':
            $message['subject']=t($params['subject'], $var, $language->language);
            $message['body'][]=$params['body'];
            $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
        break;
    }
}

Comment: You are not passing Full HTML page
Answer: Like geoff mentioned one option would be to use the Mime Mail module, but you can also enable your custom module to send HTML e-mails with some extra code. In short you'd need to alter the mail_system variable and write your own implementation of MailSystemInterface. An example of that is the following code.
Inside 'mymodule.install':
function mymodule_enable() {
  $current = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  $addition = array('mymodule' => 'MymoduleMailSystem');
  variable_set('mail_system', array_merge($current, $addition));
}

function mymodule_disable() {
  $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  unset($mail_system['mymodule']);
  variable_set('mail_system', $mail_system);
}

Inside 'mymodule.module':
class MymoduleMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

You'd have to replace mymodule instances with your actual module's name then disable and re-enable your module to get the variable changed after which things should be working. For a complete example you can check out my answer here. Additionally this page on drupal.org is from where I originally got all the information from.
Comment: i followed your instructions + the complete example you gave now everything is working... Thank you very much.
Answer: Mime Mail module is almost certainly what you are looking for.

This is a Mime Mail component module (for use by other modules).

It permits users to receive HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment.
Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format
If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative.
Allows you to theme messages with a specific mailkey.
Converts CSS styles into inline style attributes.
Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.
Comment: i have downloaded the mimemail module+mail system... will you be kind to please explain to call the mimemail function to my module as the code above.
Answer: None of the above answers worked for me, so here is my take on the original question.
First of all, install and enable the Mime Mail module. You can read the README.txt for complete instructions on how to use it. I'll give you the short version.
You need to enable Mime Mail for your module. You can do this using hook_enable or hook_update_N in example.install:
function example_enable() {
  mailsystem_set(array(
    'example_send_gift' => 'MimeMailSystem',
  ));
}

When you go to admin/config/system/mailsystem you will see that a new entry has been added for your module:

Example module (send_gift key) class
MimeMailSystem

Now you don't need to specificy any text/html headers anymore, Mime Mail takes care of this. So you don't need this:
$message['headers']['Content-Type'] = ...

If you want, you can add $message['plaintext'] to your mail for a non-HTML alternative, but this is not required.
That's it!
Answer: You might also want to look at the Swift Mailer module. It lets you send HTML e-mails with both inline and regular attachments (such as images or files). Furthermore, it is also capable of automatically generating plain text versions based on the HTML e-mail.
You can have a look at it http://www.drupal.org/project/swiftmailer
For the record: I'm the author and maintainer of the module.
Answer: You are not sending proper HTML , you are only including H1 tags and B tags, you probably need to include Full HTML tags as well starting from
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Comment: thx for ur comment,i used @Dooshta example,also added the proper html as u suggested.. everything is working.
Comment: I'm sure there is no harm in using a doctype & fully validating HTML, but it is not required to send an HTML email through drupal. I just removed the doctype & html tag and the email rendered well in Gmail & Outlook. *However*, it is very important to have Dooshta's fix in place: before I implemented those changes I was not able to generate any html at all.

How to send HTML email


Exception in thread "main" java.util.NoSuchElementException caused by a Scanner

Question: I m new, please have patience with me :)
I m not figure out why this method it s not working properly. It is creating me the account but, when the account was successfully created, it s not running well on the same method mainMenu(). I used a recursive call of the same method....
In the debug seems that it s not something well with my scanner from the second call of the method.
I m a Student
   public void mainMenu() {
    System.out.println("Select your option: ");
    System.out.println("1. Open a new account");
    System.out.println("2. Display all accounts");
    System.out.println("If you want to logout press 9");
    Scanner sc = new Scanner(System.in);
    int option = 0;
    do {
        try {
            option = sc.nextInt();
            System.out.println();
            switch (option) {
                case 1:
                    accountUtil.openNewAccount(userConsoleUtil.getUser().getUserName());
                    mainMenu();
                    break;
                case 9:
                    userConsoleUtil.logout();
                    displayLoginMenu();
                    break;
                default:
                    System.out.println("Invalid option! Try again");
            }
        } catch (InputMismatchException e) {
            System.out.println("Invalid option! Try again");
        }
        sc.nextLine();
    } while (option != 9);
    sc.close();
}

if the object account was created, it should return to beginning of the method, allowing to create a new account or exit with logout
Comment: I'll go ahead and assume you close your Scanner in the `openNewAccount` method or in `userConsoleUtil` as well, so please read the linked question.
Comment: it s true...on all the methods I close the scanner at the end of the method. But at the begging of this method I opened a new Scanner. On debug I see another number for that  scanner. It s not a new one?
Comment: Like I said, read the linked post, it answers your question.
Comment: works with Scanner on Main. One more question...if on a method I will open a new Scanner and will not close it at the end of the method ( I don t want to put the parameter scanner to that method, because with parameter will not work again), sc.close from Main class will close that scanner too?
Answer: It feels like you mistakenly wrote sc.nextLine() which takes an input from the user.
After the the end of catch block the line sc.nextLine() might give you unexpected output
Comment: It doesn't matter if you assign it to a variable or not.
Answer: Given your current code and the comments, it looks like you're creating scanners in your other methods and closing them. Don't do that. When you close the scanner, you also close System.in, leading to a NoSuchElementException.

Read this


How to create an iOS signing key?

Question: I am using PhoneGap Build to build my app. I am not sure how do i create a iOS Signing key since i am using a windows machine.
I was able to create a key for Android using following command .
$ keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

However i am not sure how do i create one for iOS ? Can someone link me with a tutorial on how to create a key on windows machine ?
You must provide a signing key, first. Find out how to fix this.

Comment: Have you signed up for an [Apple Developer](https://developer.apple.com/) account? You can read how to sign for iOS in the [documentation](http://docs.build.phonegap.com/en_US/3.3.0/signing_signing-ios.md.html#iOS%20Signing).
Comment: @AndrewLively Yes indeed!
Answer: Yes, you can, this blog post offers all necessary steps. Here is a summery:

Get the OpenSSL

Generate a private Key openssl genrsa -des3 -out ios.key 2048

Generate a Certificate Signing Request or CSR file
openssl req -new -key ios.key -out ios.csr -subj "/emailAddress=MY-EMAIL-ADDRESS, CN=COMPANY-NAME, C=COUNTRY-CODE"

On Apple Developer iOS Provisioning Portal, generate an iOS Development Certificate, using the ios.csr file you've just generated.

Convert Certification into a PEM file: openssl x509 -in ios_development.cer -inform DER -out ios_development.pem -outform PEM

Generate P12 file: openssl pkcs12 -export -inkey ios.key -in ios_development.pem -out ios_development.p12

The last file you need to generate is the provisioning profile, using the Apple Provisioning Portal.

I strongly suggest you to follow the steps on the original post.
Answer: you can't create a signing key through a window system you must to create an apple account with any MAC book and than you can create the certificate for developer and distribution
developer certificate is used for device testing
else
distribution is used for any testing and publish an app on IOS

How to create an iOS signing key?


Get username of user who initiated SSH connection?

Question: How do I find out the username of the user who initiated an ssh connection?
Let's say I ssh from userA@machine1 to userB@machine2. Now that I'm on machine2, how do I find out the username of userA? I have access (but not always root access) to both machines. Ideally this would not require any special setup on machine1, but if that's not possible then I'm open to any solution.
Answer: Assuming Linux on both sides:

Run netstat -nt on machine2 and look for the connection from machine1.  It will look something like this:
tcp 0 48 10.243.18.22:22 10.48.209.120:54875 ESTABLISHED

The first ip:port is the address and port on the local machine (i.e., machine2), and the second is the address and port on the remote machine (in this example, machine1).
Log into machine1.  Run (as root) netstat -tpn | grep 54875 (where 54875 is the port you found in the previous step).  This will show you the PID of the originating ssh process, from which you can trivially determine the user using the ps command.

You can avoid a lot of this work if you're running an ident daemon on the originating system, but (a) not many people do that, because it exposes information about your users, and (b) it's nice to know how to do it.
Answer: Do you need to know or want to know? I mean that in a technical sense, because without root access on the remote machine ("machine1" in your setup), there's no way to know authoritatively. However, you may be able to make reasonable guesses. That helps if it's informational, but is no good for security.
The ident daemon was the old-fashioned way of running that, but since in the current world there's no sense in just handing out user information for free to untrusted sites, modern identd implementations usually give an encrypted result. This can be decrypted using a secret kept on the system itself. But even more often now, people just don't run an ident daemon at all.
If you have root on machine1, you can run identd with encryption and use the secret on machine2 to find your answer. Or you can do the netstat stuff larsks suggests. But if you don't have root, you can look at processes not-as-root and make educated guesses based on timing.
Alternately, you can approach the question from a different angle. If identity assurance is your concern, some type of time- or counter-based cryptographic OTP solution might make it so you can be reasonably sure the remote users connecting are the ones they're supposed to be, no matter what they connect to.
Comment: Or maybe a ticket-based auth system such as Kerberos.
Answer: This is handled by an ident daemon running on the auth port (authd, oidentd, pidentd, etc.).
Answer: Couldn't you simply run ps -aux on the machine2?
I SSH into Machine2 from Machine1 and here is the output.  I even did a su to root and I can see the original UID I connected with.
root     31519  0.1  0.1   6512  1940 ?        Ss   10:56   0:00 sshd: eric [priv]
eric     31521  0.0  0.1   6512  1224 ?        S    10:56   0:00 sshd: eric@pts/0
Comment: This will give you the name of the user you ssh'ed into on machine 2, not the name of the user you're coming from.


Drupal 7 views join two profile2 profiles together

Question: I would like to join two profile2 profiles so they appear as one row in the view module and not two rows like the example below. Can this be done?

Fields

User: Name
Content: image_profile_image

Relationships

User: Profile
User: Content authored
Answer: Have you tried Display Suit.
Also panels is a good solution for this.
Oskar
Comment: Hi Oskar I updated my question. Does that help better to explain what i require. As you can see the image shows two images both with name but only one profile2 profile is displayed.
Comment: In this case maybe use a views, with /%uid, and choose what elements must bee show with the views fields tpls. It's harder but it works also.


Manually Send Ajax request to a PHP file

Question: It seems that the Drupal Ajax  API are comming a little un handy for my current project so i was trying to do the ajax request the good old way with actual Javascript.
I have this code
<code>valdBut.click(function(event){
    event.preventDefault();

            jQuery.ajax({
            type: "POST",
            dataType: 'json',
            data: grabValue(),
            url: urkl,
            success: function () {

                alert(back)

            }
        });
    alert(grabValue())

})
</code>
What i am wondering is how should i link that URL value to my module page, so that my user_login hook receive the data sent via Ajax ?
Thanks for any help,
Manu
Answer: For most functionality that you require with drupal, there is typically a module that already does what you are after or close to it.
I would recommend either:

using the module http://drupal.org/project/ajax_register
or looking at the code for the above module and make one that suits your exact needs

Hope this helps
Comment: Thanks for you answer, unfortunately it's not really help full in my case.
Comment: Then may I suggest you clarify your question? I read it like you are after a solution to allow users to login via AJAX on your site, is this not the case?
Comment: Yes it is but i am using Drupal 7 and the module you suggested is Drupal 6 only. It s ok i got it figured out. See answer below.
Answer: This tutorial (tough Drupal 6) helped me a lot http://viziontech.co.il/tutorial1?1309179897 .
The big piece that i was missing is that i needed a Hook_menu that countain my php script that will handle the ajax request, then in the ajax path i add the newly created link (from the Hook_menu).
Also the JS needed to be added to that specific module with a drupal_add_js for the ajax call back to be received. It took me a while to figure out but if i add the script via Theme.info file it behaves very oddly..


Replace summary/description with another field in Views RSS output

Question: I have a view for an RSS feed which uses the node output (only option it seems when RSS style is selected) so I cant choose custom fields. But, as the body field is 'text and summary' the RSS view uses that summary for the 'description' field but I'd like to use another field for that element in the feed.
Does that make sense?
An option is to just create another field-based view and my own templates to create an RSS output, but it just seems like such a trivial change to require so much work.
Would love to hear some thoughts.
Thanks in advance.
Comment: The edit you added could be an answer; I would put it in an answer.
Comment: You can add fields through the settings, but last time I looked at it you couldn't change some of the predefined settings for example author or publish date.
Answer: I worked it out. On the 'Manage Display' tab for a content type, there is a 'Custom Display Settings' section at the bottom. Opening that and selecting RSS gives you an RSS Display Fields area where you can change the fields to be used. Looks like it might just work for me.
Comment: I have searched deep and found servals solutions for D7 with template files,but this is obviously a better solution !
Answer: Before rolling your own templates, you may be able to do what you want using the Views RSS module. This allows you to map fields to RSS elements, rather than being forced to use the node display.
Comment: Argh, looks great but no D7 release. :)
Comment: D'oh! That's too bad. Hopefully soon.
Comment: There is a RC now.


Estimating quantities of a posterior distribution.

Question: Consider the following model:
$$ \alpha \sim N(0,1)$$
$$ \beta \sim N(0,1)$$
$$ d_i \mid \alpha, \beta \sim \mathrm{Bernoulli}(\Phi(\alpha + \beta x_i))$$
$d_i$ is $1$ if person $i$ has some property, and $0$ if they do not. $i = 1, \dots, N$.
I have found the posterior for $\alpha$ and $\beta$ conditional on all the $d_i$. I am now asked how I may estimate $\mathbb{P}(\beta > 0 \mid d_1, \dots, d_N)$.
$p(\alpha, \beta \mid d_1, \dots, d_N) \propto \exp{(- \frac{\alpha^2 + \beta^2}{2})}\Pi_{i = 1}^N (\Phi(\alpha + \beta x_i))^{d_i} (1 - \Phi(\alpha + \beta x_i))^{1 - d_i} $
I am familiar with the Gibbs Sampler or Metropolis Hastings Monte Carlo methods. I'm not sure how to go about it in this case however.
Much thanks.
Comment: So what is the posterior for $\alpha$ and $\beta$ conditional on all the $d_i$?
Comment: Are you given the value of $d_i$ for every $i\in\{1,\ldots,N\}$ or only for one of them? ${}\qquad{}$
Comment: We're given the value for every $d_i$. Sorry for the confusion. I have edited what I found to be the posterior into the question.
Answer: You could run your MCMC, and after the burn-in period look at the points in the chain where $d_1,...,d_N$ takes some fixed vector of values, say $\mathbf d$. Then calculate the proportion of $\beta$'s which is greater than zero in this set of points, and you have an estimate for $\mathbb P[\beta > 0 | (d_1,...,d_N)=\mathbf d]$.
On a side note, I assume you meant you have the posterior for $\alpha$ conditional on the $d_i$ as well as $\beta$ (similarly for the posterior of $\beta$), in which case you can use the Gibbs sampler (otherwise you would need a more general MH algorithm).
Edit: From your given posterior, it seems that you could consider $(\alpha,\beta)$ to be a single parameter vector. So the Gibbs sampler should cycle through $N+1$ steps: Sample $(\alpha,\beta)$ from this posterior (which I hope it is assumed that you are sample from without problem), then sample the $N$ values of $d_i$ given $(\alpha,\beta)$.
Comment: So if I am understanding correctly, you suggest I obtain posteriors of the form $p(\alpha \mid \beta, d_1, \dots, d_N)$ and $p(\beta \mid \alpha, d_1, \dots, d_N)$, then run the Gibbs Sampler, then use the proportion of beta values greater than 0.
Comment: Almost: you need to restrict yourself to consider the proportion within the samples where $d_1,...,d_N$ takes your values of interest (remember that you are answering the question, "Given values of $d_1,...,d_N$, what proportion of the $\beta$'s are greater than zero?").

Basically it would look like this: say your chain obtained via Gibbs sampling is $X_1,X_2,...$, then (burn-in period aside) you will be looking only at some of these points, e.g. $X_3,X_{10},X_{14},...$ etc. because only points in the chain where the $d_i$'s take certain values will be relevant.
Comment: A remark: Your chain could potentially take very long, because there are $2^N$ values that $d_1,...,d_N$ could possibly take, e.g. if each of these were equally likely, on average you would need a chain of length $k \cdot 2^N$ to obtain a MC estimate of size $k$.


Count values from all table view cells swift

Question: I'm making a simple cafe menu like tableView where you can add food and it will count total price. To count total price, all values(sumLabel) in cells must be summed. My problem is when i'm trying to count it, it counts only sum in particular cell, but when i click "+" in another cell it starting from 0 .
Steps I made:

Create empty array(var totalArr: [Int] = []) in MainViewContoller
Create instance of MainVC in CustomCafeTableViewCell
In func changeSum() append price to totalArr  and the problem occured here . screenshot included.

TableViewController here

    protocol CustomCellDelegate {
    func decreaseNumber(cell: CustomCafeTableViewCell, number: Int)
    func decreaseTotal(cell: CustomCafeTableViewCell, number: Int)
   }

class MainViewController: UITableViewController {

    let minValue = 0
    var totalArr: [Int] = []

    let sumCount: UILabel = {
        let foodCount = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 50))
        foodCount.textColor = .black
        foodCount.textAlignment = .center
        foodCount.translatesAutoresizingMaskIntoConstraints = false
        return foodCount
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        let customView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 50))
        customView.backgroundColor = UIColor.systemBackground
        sumCount.text = "Sum: \(totalArr.reduce(0, +))"
        customView.addSubview(sumCount)
        tableView.register(CustomCafeTableViewCell.self, forCellReuseIdentifier: CustomCafeTableViewCell.identifier)
        tableView.tableFooterView = customView
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return "Salads"
        } else if section == 1 {
            return "Drinks"
        } else {
            return "Desserts"
        }
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CustomCafeTableViewCell.identifier, for: indexPath)
        cell.selectionStyle = .none

        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2 {
            return 50
        }
        return 0
    }
}

TableViewCell here
class CustomCafeTableViewCell: UITableViewCell {

var vc = MainViewController()

var foodPrice = 10
var totalSum = 0

static let identifier = "cell"
private var delegate: CustomCellDelegate?
let minValue = 0

@objc func decreaseFunc() {
    changeQuantity(by: -1)
    changeSum(by: -foodPrice)
}
@objc func increaseFunc() {
    changeQuantity(by: 1)
    changeSum(by: foodPrice)
}

func changeQuantity(by amount: Int) {
    var quality = Int(foodCount.text!)!
    quality += amount
    if quality < minValue {
        quality = 0
        foodCount.text = "0"
    } else {
        foodCount.text = "\(quality)"

    }
    delegate?.decreaseNumber(cell: self, number: quality)
}

func changeSum(by amount: Int) {
    var sum = Int(sumLabel.text!)!
    sum += amount
    if sum < minValue {
        sum = 0
        sumLabel.text = "0"
    } else {
        sumLabel.text = "\(sum)"
        vc.totalArr.append(amount)
        print("sum to show \(vc.totalArr.reduce(0, +))")
    }
    delegate?.decreaseTotal(cell: self, number: sum)
}

private let foodLabel: UILabel = {
    let label = UILabel()
    label.textColor = .black
    label.text = "food"
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

private let priceLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

private let increaseButton: UIButton = {
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    button.setImage(UIImage(systemName: "plus.rectangle"), for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()

private let decreaseButton: UIButton = {
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    button.setImage(UIImage(systemName: "minus.rectangle"), for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()

private let foodCount: UILabel = {
    let foodCount = UILabel()
    foodCount.text = "0"
    foodCount.translatesAutoresizingMaskIntoConstraints = false
    return foodCount
}()

 let sumLabel: UILabel = {
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "0"
    return label
}()

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    contentView.addSubview(foodLabel)
    contentView.addSubview(priceLabel)
    contentView.addSubview(increaseButton)
    contentView.addSubview(foodCount)
    contentView.addSubview(decreaseButton)
    contentView.addSubview(sumLabel)

    priceLabel.text = "\(foodPrice) $"
    increaseButton.addTarget(self, action: #selector(increaseFunc), for: .touchUpInside)
    decreaseButton.addTarget(self, action: #selector(decreaseFunc), for: .touchUpInside)

    foodLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5).isActive = true
    priceLabel.leadingAnchor.constraint(equalTo: foodLabel.leadingAnchor, constant: 75).isActive = true
    decreaseButton.leadingAnchor.constraint(equalTo: priceLabel.leadingAnchor, constant: 170).isActive = true
    foodCount.leadingAnchor.constraint(equalTo: decreaseButton.leadingAnchor, constant: 35).isActive = true
    increaseButton.leadingAnchor.constraint(equalTo: foodCount.leadingAnchor, constant: 20).isActive = true
    sumLabel.leadingAnchor.constraint(equalTo: increaseButton.leadingAnchor, constant: 35).isActive = true

}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Sum: 0 placed in UIView and added with tableView.tableFooterView
I don't understand why totalArr not saving values when selecting another cell
My goal - count sumLabel.text values in all cells and show in Sum:
Comment: Each call of `MainViewController()` creates a new, different instance. This is certainly not what you want. You have to connect the UI elements in the cell to a data model and do all the math in the main controller. Or – as you have a fixed number of cells – consider to use static cells.
Answer: Each time a new cell is created it initialises its own MainViewController with a new totalArr which is why your sum is now zero.
A quick fix is to pass a reference of the MainViewController to the cell. Like so:
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CustomCafeTableViewCell.identifier, for: indexPath)
        cell.selectionStyle = .none
        cell.vc = self
        return cell
    }

Now you probably don't want to do that as @vadian mentioned. Instead math should be done in the MainViewController or even better some other model type.
Now if you do choose to pass a reference like a described make sure to use weak var vc: MainViewController! otherwise you will end up with a retain cycle with the cell holding a reference to the VC and the VC having a reference to the table view, which holds the cells. Adding weak var creates a weak reference and ensures that automatic reference counting does not increment the count in this case.


XmlDocumentFragment equivalent in LINQ to XML?

Question: I am unable to find something like XDocumentFragment. Is there an equivalent of XmlDocumentFragment in LINQ to XML?
I know that I can keep nodes in a collection. But how to conveniently serialize a bunch of various nodes to string, like this:
new XDocumentFragment(myNodes).ToString()

Comment: Could you give an example of what you're trying to achieve? Pretend that `XDocumentFragment` *did* exist, and show us how you'd use it.
Answer: You can simply concatenate string representation of nodes:
var xml = String.Concat(myNodes);


The frequency of loading Secret Manager in Cloud Run

Question: I am considering migrating my current web services to Cloud Run.
In Cloud Run's "Variables and Secrets", if we use Secret Manager to mount environment variables and credential files, how often will Secret Manager be read by which of the following?

Whenever a web service is accessed.
Every time an instance is created
Whenever a revision is deployed
other (I would appreciate it if you could tell me)

Currently, the web service is accessed by about 300 people per minute, and I expect that if 1 or 2 is selected, the number of accesses to the Secret Manager will increase and the billing amount will increase.
If you have any best practices, I would appreciate it if you could share them with me.
Thank you in advance for your help.
Answer: The answer depends on the code in your container. Typically each container would access Secret Manager on container start and hold those variables in the global namespace.
Using global variables
How many containers depend on how many simultaneous requests can be handled by each container.
How often a container is started and stopped depends on how frequently requests arrive. When a container is not processing requests it is eligible to be stopped. For your use case (300 requests per minute), consider the Always On option so that a minimum number of containers are always running.
Comment: Thank you for the clear answer and the primary documentation.
I will calculate the number of containers needed and use the Always On option so that the containers are always running.


Derivative of a function $y(x)= \sum\limits_{n=1}^\infty nx^{-n}$

Question:
Can anyone show and explain how to obtain the derivative of the following function,
  $$y(x)= \sum_{n=1}^\infty nx^{-n}$$

which is, for $n=3$, equivalent with,
$$y(x)=x^{-1}+2x^{-2}+3x^{-3}$$
now, what is the derivative of $x$ with respect to $y$, i.e. $\dfrac{dx}{dy}$ for $n=\infty$?
Can this kind of problem be solved analytically?
Comment: Your question is not properly formulated. I see what you mean, but you cannot fix $n$: it runs over all the natural numbers. Your sentences "for $n=3$" and "for $n=\infty$" make no sense. The variable is $x$, not $n$.
Answer: Hint. Your function is defined for $|x|>1$ (the series is convergent for such $x$) and, see for example Solve $\sum nx^n$,
$$y(x)= \sum_{n=1}^\infty nx^{-n}=\frac{1/x}{(1-1/x)^2}=\frac{x}{(1-x)^2}.$$
Therefore $yx^2-(2y+1)x+y=0$.
Can you take it from here?
Answer: For $|x|>1$ , let us put
$$y (x)=z (\frac 1x) $$ with
$$z (x)=\sum_{n=1}^{+\infty}nx^n $$
$$=x+2x^2+3x^3+...$$
$$=x (1+2x+3x^3+...)=x\frac {d (x+x^2+x^3+...)}{dx} $$
$$=x\frac {d\frac {x}{1-x}}{dx} =\frac {x}{(1-x)^2} $$
but
$$y'(x)=\frac {-1}{x^2}z'(\frac 1x) $$
with $$z'(x)=\frac {1+x}{(1-x)^3} $$
we find that
$$y'(x)=z' (x) $$
Answer: Let's see:
$$
\sum\limits_{n=1}^{\infty} n x^{-n} = x \sum\limits_{n=1}^{\infty} n x^{n-1} = x \sum\limits_{n=1}^{\infty} \frac{d}{d x}x^{n} = x \frac{d}{dx}\sum\limits_{n=1}^{\infty} x^{n} = x \frac{d}{dx}\left( \frac{1}{1-x} - 1 \right) = \frac{x}{(1-x)^2}
$$
where the second to last equality is from the geometric series formula (assuming $|x| < 1$).
Answer: From this Solve $\sum nx^n$ See that for $|x|<1$ we have,
 $$y\left(\frac{1}{x}\right) = \sum_{n=1}^{\infty} nx^n = \frac{x}{(1-x)^2}$$
Hence $$y\left(x\right) = \frac{x}{(1-x)^2},~~~~~|x|>1$$
can you conclude?
Answer: Maybe your question is about the derivation of $y_N(x)=\sum_{n=1}^N n\cdot x^{-n}$?
then you can say that, fixed N, $y'_N(x)=-\sum_{n=1}^N n^2\cdot x^{-n-1}$, naturally valid in the domain of the function $y_N$. The problem is when you want to calculate the derivation of $\sum_{n=1}^\infty n \cdot x^{-n}$.
Then you have to use some Criterions of convergence of series in order to derivate term by term.