Embedding assembly in C with compiler finding registers for you

Question: When embedding assembly code into a C/C++ program, you can avoid clobbering registers by saving them with a push instruction (or specify clobber list of compiler supports it).
If you are including assembly inline and want to avoid the overhead of pushing and popping clobbered registers, is there a way of letting gcc choose registers for you (e.g. ones it knows have no useful info in them).
Comment: Why are you assuming this is homework?  I never had homework ask me details about using gcc.. This is very much an issue that is faced once you actually try to achieve something in the real world.
Comment: please add the 'homework' tag, also please note that this is not meant to be a homework-only site, so you'll have to provide what you've got so far, for other people to chime in and provide the rest.
Comment: Not sure what you mean. This is a theoretical question so there is no 'code' so far.
Comment: ok, my bad sounded pretty much like HW - so I'm very sorry, but gcc is regularly used for CS classes, so that type of question wouldn't really surprise me at all.
Comment: You should add the gcc flag, since the answer for gcc (or any other compiler for which there is an answer) is *very* compiler specific.  The C and C++ standards are very demure on "asm".
Answer: Yes.  You can specify that you want a particular variable (input or output) to be stored in a register, but you don't have to specify a register.  See this document for a detailed explanation.  Essentially, the inline assembly looks like this:
asm("your assembly instructions"
      : output1("=a"),  // I want output1 in the eax register
        output2("=r"),  // output2 can be in any general-purpose register
        output3("=q"),  // output3 can be in eax, ebx, ecx, or edx
        output4("=A")   // output4 can be in eax or edx
      : /* inputs */
      : /* clobbered registers */
   );

Comment: Thanks! I actually skimmed that file before posting but missed it. Now having taken a long time just to read those small sections I can see why! It's not pretty, but it works. Thanks again.
Answer: Compiler intrinsics are a very useful way to mix assembly and C/C++ code. They're declarations that look like functions, but actually compile directly to individual native instructions (via a special case inside the compiler). This gives you much of the control of working in assembly, but leaves the register coloring and scheduling up to the compiler.
An advantage is that then you can pass an ordinary C variable into an intrinsic, and let the compiler take care of loading it onto the register and scheduling other ops around it. For example,
struct TwoVectors
{
   __m128 a; __m128b;
}

// adds two vectors A += B using the native SSE opcode
inline void SimdADD( TwoVectors *v )
{
   v->a = _mm_add_ps( v->a , v->b ); // compiles directly to ADDSS opcode
}

Answer: OK, so I can't leave a comment above, but I'm pretty sure that the correct syntax (different from that shown above) is:
asm ( "your assembly instructions"
    : "=a"(output1),
      "=r"(output2),
      "=q"(output3),
      "=A"(output4)
    : /* inputs */
    : /* clobbered registers */
);

Although you can leave the allocation of input and output registers to the compiler, there's no obvious way of leaving the allocation of scratch/temp registers (i.e. used for intermediate values but not an input or output) to the compiler. Historically, I just listed them explicitly in the clobber list (e.g. "%xmm1", "%rcx"), but I now think it might be better to list them as outputs in order to allow the compiler to choose them. I don't know of any source that addresses this issue definitively.


Finding source of over release

Question: I'm consistently seeing the same message sent in as a crash report from users of an app. It's clear that an object is being over-released but I'm unable to replicate it and I'm looking for tips on tracing the source of it.
The relevant section from the crash report shows this:
<code>Application Specific Information:
objc_msgSend() selector name: release

Thread 0 Crashed:  Dispatch queue: com.apple.main-thread
0   libobjc.A.dylib                     0x90892edb objc_msgSend + 27
1   com.apple.CoreFoundation            0x95ec5a40 __CFBasicHashStandardCallback + 384
2   com.apple.CoreFoundation            0x95ec564e __CFBasicHashDrain + 478
3   com.apple.CoreFoundation            0x95ead6f1 _CFRelease + 353
4   com.apple.CoreFoundation            0x95eda0ed _CFAutoreleasePoolPop + 253
5   com.apple.Foundation                0x97ecedd6 NSPopAutoreleasePool + 76
6   com.apple.Foundation                0x97ececfe -[NSAutoreleasePool drain] + 130
7   com.apple.AppKit                    0x9211255f -[NSApplication run] + 1013
8   com.apple.AppKit                    0x9210a535 NSApplicationMain + 574
9   TheApp                          0x000020a6 start + 54
</code>
I've used zombies and leaks, but haven't seen anything there.
I've gone through the code and can't see it.
What's the next step?
Are there any hints I can discern from this information as to the source of it?
Does the fact that this nearly exact same crash report is coming in repeatedly mean that it's the same object that's being over released, or because this is referring to the autorelease pool mean it could be any object?
Does the reference to _CFRelease mean it's a Core Foundation object that's being over released?
Answer:
I've used zombies and leaks, but haven't seen anything there.

That's strange.

What's the next step?

The next step for an over-release crash is generally to run the app using Instruments' Zombies template. The second release message will raise a flag in Instruments' timeline graph, with a button you can click to find out more information.
Also try building your app with the static analyzer in Xcode 3.2 or later.

Does the fact that this nearly exact same crash report is coming in repeatedly mean that it's the same object that's being over released, or because this is referring to the autorelease pool mean it could be any object?

It could be any object, but is almost certainly the same object every time, unless you are doing memory management wrong all over your code base.

Does the reference to _CFRelease mean it's a Core Foundation object that's being over released?

No.

Finding source of over release


Simultaneous actions with conditional legality for reinforcement learning agent

Question: I'm training a reinforcement model playing a game with self-learning. For each state, the agent can select one or several simultaneous actions from a list of possible actions. One possible action is a binary choice that can make other actions irrelevant (not illegal, just irrelevant). Some actions do however become "illegal" for certain states. And some combinations of actions are illegal.
My plan is to produce a fixed-length vector of binary values indicating the agent's choice of actions given a state. I have two questions:
Question 1: In the tutorials I've done the algorithm typically selects ONE action from a list of possible actions using something like $\text{argmax}_{a \in
> \mathcal{A}} \hat q(s,a)$. I want to instead predict an action vector, not just an action index. What is the best way to do this? The number of possible action vectors is huge, so I'm worried the task becomes very hard...
My second question is how to handle the legality of various combinations. Assuming there is a good way to predict a vector of actions per Question 1 (i.e. the agents act method outputs a vector [0,0,0,1,1,0,1] where each value indicates if action with index n is taken or not) I need to decide how to handle illegal combinations of actions.
The response to this question "How to handle a changing action space in Reinforcement Learning" claims that

You don't need to do anything special to handle [illegal actions]. The only thing
you need to change is to not take any illegal actions.
The typical Q-learning greedy policy is $\pi(s) = \text{argmax}_{a \in
> \mathcal{A}} \hat q(s,a)$ and the epsilon-greedy rollout policy is
very similar. Simply replace the action space $\mathcal{A}$ with just
the legal actions $\mathcal{A}_\text{legal}(s)$.

Question 2:  Am I correct to just run the prediction step as if all actions can be selected together, and then remove all vectors of illegal actions from the predictions before selecting which one to take? What if the network only produces illegal vectors? It feels like this might get very sparse...
Answer:
The number of possible action vectors is huge, so I'm worried the task becomes very hard.

If each component of the action vector is "independent", then you could just parameterize a bunch of univariate distributions for each component, and sample them independently.
Of course, this only works when the components are really independent -- for example, if your game is actually the "product" of two MDPs, where you're trying to train your agent to multi-task by playing two games simultaneously, then game 1 action components and game 2 action components are independent. On the other hand, if the game is a flight simulator, and one action component is yaw and another is roll, and another is pitch, these are quite dependent on each other.*
In the case where components of an action vector are dependent, you can model the distribution auto-regressively: $\pi(x,y,z;s) = \pi(z|x,y;s)\pi(y|x;s)\pi(x;s)$, using a neural network to parameterize each factor. This is fairly easy to sample from, and lets you model complicated joint distributions.

What if the network only produces illegal vectors?

This shouldn't be possible, since at least one action must be legal in every non-terminal state of an MDP. In particular, for a factored distribution like  $\pi(z|x,y;s)\pi(y|x;s)\pi(x;s)$, you would

first sample from $\pi(x;s)$, masking out all $x$ which are illegal.
This guarantees that $\pi(y|x;z)$ contains some $y$ for which the combination $(x,y)$ is legal. Mask out the other y's which are illegal and sample.
Repeat in the same manner for $z$.

*Most situations probably fall somewhere in between these two examples in terms of action independence, and you just have to use judgement to trade-off between more expressive policies, and easier to work with policies.
Comment: thank you! I will study your answer.


How to do a CNAME record lookup in swift

Question: I found some example code online that I'm trying to use to do a CNAME record lookup (notice that I pass a callback block that I want to be run):
DNSServiceQueryRecord(serviceRef, 0, 0, domainName, UInt16(kDNSServiceType_CNAME), UInt16(kDNSServiceClass_IN), callback, &mutableCompletionHandler);
DNSServiceProcessResult(serviceRef.pointee)

The problem is that this code is getting blocked at DNSServiceProcessResult(serviceRef.pointee) and the callback is never called. According to Apple's documentation for DNSServiceProcessResult, I need to

Use DNSServiceRefSockFD in conjunction with a run loop or select() to determine the presence of a response from the server before calling this function to process the reply without blocking.

So I looked at DNSServiceRefSockFD and found that I could create a dnssd_sock_t with DNSServiceRefSockFD(serviceRef.pointee). But now that I have the socket, I'm not sure how to "use it in conjunction with a run loop" as an event source for the run loop (according to the DNSServiceRefSockFD documentation).
I'm just not understanding how this works. I don't understand how to use the dnsssd_sock_t as an event source to a run loop so that I can call DNSServiceProcessResult at the right time without blocking so that my callback will actually run.
If it's better to use the socket as a kqueue event source or in a select() loop (as the documentation mentions), I'm fine with that, but I don't know how to do that either.
CoreFoundation can be quite cryptic, so any help is much appreciated!
And if there's a better way to do a CNAME record lookup then, by all means, please share!
Answer: See my (ethan-gerardot) comments on https://gist.github.com/fikeminkel/a9c4bc4d0348527e8df3690e242038d3
The first paragraph answers how to get the callback to be called without blocking.


Como chamar método de classe em outro app?

Question: Quero criar um arquivo chamado config.py e colocar algumas configurações dentro de um dicionário para sempre que precisar invocar esses parâmetros.
Mas como eu chamo esse parâmetro no Python?
Por exemplo, vou criar a classe Config.
class Config:

@classmethod
def getConfig(self):
    parameters = {
        'url_m'                 : 'domain',
        'url_ws_m'              : 'domain.api',
        'url_get_token'         : 'domain.token',
        'url_external_access'   : 'external',
        'name_ws_m'             : 'service'
    }

    return parameters

No outro app fiz assim:
from pp.core.Config import *
.
.
.
a = Config().getConfig()['url_m']

Assim funcionou.
Mas existe um método mais elegante de importar a classe com o método ou esse é o jeito mais correto mesmo?
Comment: Onde tem esse config.py?
Comment: Eu criei numa pasta.
Comment: Criou onde? Na raiz? dentro da `main app`? dentro de outra app? Talvez ajudasse se colocasse a estrutura como está agora
Comment: Criei dentro da pasta core dentro da pasta principal do projeto.
Comment: Seria legal se você usasse o configparser: https://docs.python.org/3/library/configparser.html
Answer: Dá pra ficar mais simples e elegante sim. Use o módulo apenas e crie uma função que dê acesso a um dicionário interno do módulo. Ex:
Arquivo "Config.py"

_parameters = {
    'url_m'                 : 'domain',
    'url_ws_m'              : 'domain.api',
    'url_get_token'         : 'domain.token',
    'url_external_access'   : 'external',
    'name_ws_m'             : 'service'
}

def get(key):
    return _parameters[key]

E para usar, chame assim:
import pp.core.Config as Config

a = Config.get('url_m')

A classe, no teu caso, está apenas colocando uma camada de complexidade que vc não precisa.
Comment: Sim. A função get não é realmente necessária. Eu poderia dar um `from Config import parameters` (nesse caso eu faria sem underscore) e simplesmente usar `parameters['myKey']`. Porém eu quis fazer um exemplo mais próximo de os parâmetros serem read only. É uma questão de preferência pessoal. O proprio settings.py do django usa essa semantica de dicionário em que os parâmetros podem ser alterados em runtime. O jeito que eu pus é só uma maneira de fazer. Não a única.
Comment: Na verdade, esse seu método get também é uma "camada que não é precisa": o dicionário definido no módulo pode ser usado diretamente.
Comment: Como faria isso @jsbueno?
Comment: Fica elegante mesmo Eric. Eu conheço esses recursos, mas não lembro de usar.
Comment: Por que sua variável começa com underscore? Eu venho do PHP, então estou acostumado com camelCase...
Comment: "Como faria isso @jsbueno?" - simplesmente importe diretamente a variável no módulo em que for usar as configurações, em vez de importar a função `get` e use-a. O "_" no prefixo também não é necessário.
Comment: O underscore é uma convenção do python para dizer que aquela variável não deve ser usada globalmente. Se vc realmente quiser usar nada te impede. Mas a convenção fica aí como lembrete.
Answer: Você não precisa criar uma class pra isso. Você pode criar um arquivo config.py com um dicicionario e depois importar esse dicionário onde deseja usar.
No arquivo config.py
parameters = {
    'url_m'                 : 'domain',
    'url_ws_m'              : 'domain.api',
    'url_get_token'         : 'domain.token',
    'url_external_access'   : 'external',
    'name_ws_m'             : 'service'
}

E no foo.py
from config import parameters

a = parameters['url_m']


Bootstrap show whitespace in rows/columns

Question: I have a situation in my web page where items in a row/columns setup (based on bootstrap) shows white space where it shouldn't. Please refer to this image:

It's a container div, with a row div and then a whole bunch of columns (to be exact: col-lg-4).
The vertical white space between 'Millenium Gold' and 'Midnight Oil' should not be there.
I don't think it's that important, but I build the page using React (i.e., Javascript).
I hope anyone can shed some light on this.
Thanks!
[Update]
Here's the console output for this page:

And this is my additional CSS:

html {
    height: 100%;
}

body {
    margin: 0;
    padding: 0;
    font: 140% sans-serif;
}

input {
    font-size: 110%;
    outline: 0;
}

.jumbotron {
    color: #eee;
    background-color: #333;
}

.navbar-menu {
    padding-top: 5px;
    padding-bottom: 5px;
    margin-bottom: 0;
}

.search-bar-wrapper {
    width: 100%;
}

.blend-item {
    padding-top: 15px;
    padding-bottom: 15px;
}

.blend-item-name {
}

.blend-item-descr {
    color: rgba(0, 0, 0, 0.7);
    padding-top: 10px;
}

.blend-item-roast {
    padding-top: 15px;
    padding-bottom: 5px;
    color: rgba(0, 0, 0, 0.6);
}

.result-item {
    padding-bottom: 30px;
}

.result-item h5 {
    color: rgba(0, 0, 0, 0.6);
}

.result-item-content h2 {
    margin-top: -6px;
}

.result-item h2 small {
    color: rgba(0, 0, 0, 0.7);
}

.result-item-content {
    background-color: #FFFAF0;
    outline: 1px solid rosybrown;
    padding: 15px 15px 15px 30px;
}

.result-item-content hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid rosybrown;
    margin-bottom: 12px;
    padding: 0;
}

.result-item-content ul.list-inline li {
    color: rgba(6, 10, 26, 0.7);
}

@media screen and (min-width: 640px) {
    .search-bar-wrapper {
        min-width: 480px;
        width: 40%;
    }
}

.search-bar-field {
    position: relative;
}

.search-bar-input {
    -webkit-appearance: none;
    border: 1px solid #ddd;
    border-radius: 2px;
    box-sizing: border-box;
    margin: 0;
    padding: 10px 40px 10px 10px;
    width: 100%;
}

.has-suggestions .search-bar-input {
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
}

.icon {
    background-position: center center;
    background-repeat: no-repeat;
    border: 0;
    cursor: pointer;
    font-size: 0;
    height: 100%;
    outline: 0;
    padding: 0;
    position: absolute;
    right: 0;
    top: 0;
    width: 25px;
}

.search-bar-clear {
    background-image: url(../public/img/cancel.svg);
    background-size: 25%;
    right: 40px;
    width: 40px;
}

.search-bar-submit {
    background-color: #e5e5e5;
    background-image: url(../public/img/search.svg);
    background-size: 35%;
    border: 1px solid #ddd;
    border-top-right-radius: 2px;
    border-bottom-right-radius: 2px;
    padding: 0 20px;
    opacity: .8;
    width: 40px;
}

.search-bar-submit:hover {
    opacity: 1;
}

.is-focused .search-bar-input,
.is-focused .search-bar-submit {
    border-color: #ccc;
}

.search-bar-suggestions {
    border: 1px solid #ccc;
    border-bottom-left-radius: 2px;
    border-bottom-right-radius: 2px;
    box-sizing: border-box;
    font-size: 100%;
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
    top: -1px;
}

.search-bar-suggestions li {
    cursor: default;
    letter-spacing: 0.03em;
    padding: 12px 7px 12px 10px;
    -webkit-tap-highlight-color: transparent;
}

.search-bar-suggestions li:last-child {
    border: none;
}

.search-bar-suggestions .highlighted {
    background: #f5f5f5;
}

.search-header {
    width: 100%;
}

.logo-home {
    margin-left: 72px;
}

.logo {
    float: left;
}
.logo ::after {
    clear: both;
}

.search-box {
    margin-top: 60px;
}

.results-header {
    font-family: "serif";
    margin-bottom: 20px;
}
.results-header h3 {
    font-size: 18px;
}

.results-body {
}

.results-box {
    float: left;
    margin-top: 60px;
}
.results-box ::after {
    clear: both;
}

.cafe-box {
    float: left;
    margin-top: 20px;
}

.cafe-info-beans {
    margin-top: 50px;
}

.bean-box {
    float: left;
    margin-top: 20px;
}

.bean-image {
    margin-top: 10px;
    margin-bottom: 20px;
}

.imaginary-container {
    margin-top: 20%;
}

.leftimage {
    float:left;
}

.righttext {
    margin-left: 60px;
    float: none;
}

.righttext h2 {
    margin-top: 15px;
}

.hcenter {
    text-align: center;
}

.vcenter {
    min-height: 60%;  /* Fallback for vh unit */
    min-height: 60vh; /* You might also want to use
                        'height' property instead.

                        Note that for percentage values of
                        'height' or 'min-height' properties,
                        the 'height' of the parent element
                        should be specified explicitly.

                        In this case the parent of '.vertical-center'
                        is the  element */

    /* Make it a flex container */
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    /* Align the bootstrap's container vertically */
    -webkit-box-align : center;
    -webkit-align-items : center;
    -moz-box-align : center;
    -ms-flex-align : center;
    align-items : center;

    /* In legacy web browsers such as Firefox 9
       we need to specify the width of the flex container */
    width: 100%;

    /* Also 'margin: 0 auto' doesn't have any effect on flex items in such web browsers
       hence the bootstrap's container won't be aligned to the center anymore.

       Therefore, we should use the following declarations to get it centered again */
    -webkit-box-pack : center;
    -moz-box-pack : center;
    -ms-flex-pack : center;
    -webkit-justify-content : center;
    justify-content : center;
}
Comment: Could we see the bootstrap file?
Comment: I'm using the bootstrap-3.3.7 npm module. You want me to post the entire CSS file, or is that not what you're asking?
Comment: Nevermind lol I thought you had edited it, but I realize those bootstrap files can be pretty large
Comment: It's not related to React, even though sometimes it can be. This particular problem is purely in CSS.
Answer: It's inevitable effect of float: left CSS property value that is engraved into every col-• classname of Bootstrap 3. See this Codepen, or just try this code:

and
.big-and-tall {
  width: calc(100% - 20px);
  height: 500px;
  margin: 10px;
  background-color: green;
}

.big-and-short {
  width: calc(100% - 20px);
  height: 200px;
  margin: 10px;
  background-color: red;
}

.big-and-kinda-tall {
  width: calc(100% - 20px);
  height: 300px;
  margin: 10px;
  background-color: brown;
}

The problem is that "big-and-kinda-tall" element would like to fit somewhere under the "big-and-tall" but preceding element restricts topmost boundary of the former with its bottom line.
You could either put every triplet of cols into a separate row, or you could use Bootstrap 4 that relies on Flexbox rules: see how it would look like in another Codepen.
Comment: Your Codepen illustrates the problem very nicely. Here's a thought: what if I make each of the items the same height, enough so that the information always fits without enlarging the box?
Comment: Although my previous comment relies on the assumption that the information will never lead to a bigger enclosing box.
Comment: If all the cols are of equal height, they will form rows of three perfectly. You can play around with different hypotheses in Codepen and see how `float` makes the elements behave relative to each other. That's actually a lot of fun. :)
Answer: Your columns are different heights and all inside a single row so you'll need to clear the float of the designated nth columns breakpoint and correct media query as well.
@media (min-width: 1200px) {
  .blend-item:nth-child(3n+1) {
    clear: left;
  }
}

Working Example:

@media (min-width: 1200px) {
  .blend-item:nth-child(3n+1) {
    clear: left;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

ONE

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Lorem Ipsum has been the industry's

TWO

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Lorem Ipsum has been the industry's

THREE

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

Lorem Ipsum has been the industry's

FOUR

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Lorem Ipsum has been the industry's

FIVE

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

Lorem Ipsum has been the industry's

SIX

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

Lorem Ipsum has been the industry's

SEVEN

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

Lorem Ipsum has been the industry's


Kotlin | Problem using if as expression along with also scope function

Question: I had the following code on my project:
val typeface = if (isBold && isItalic) {
   Typeface.BOLD_ITALIC
} else if (isBold) {
   Typeface.BOLD
} else if (isItalic) {
   Typeface.ITALIC
} else {
   Typeface.NORMAL
}

updateTypeface(typeface)

Then, I decided to change my code to this:
if (isBold && isItalic) {
   Typeface.BOLD_ITALIC
} else if (isBold) {
   Typeface.BOLD
} else if (isItalic) {
   Typeface.ITALIC
} else {
   Typeface.NORMAL
}.also { typeface ->
   updateTypeface(typeface)
}

But when the value of isBold is true and isItalic is false, updateTypeface(typeface) is not being called, although the breakpoint is stoping in the Typeface.BOLD line.
Am I missing something, or there's a bug here?
Current kotlin plugin version: 223-1.9.0-release-358-AS8836.35.2231.10811636
Analyzer Version: 1.9.0-release-358
Android Studio: Giraffe | 2022.3.1 Patch 2
Runtime version: 17.0.6+0-b2043.56-10027231 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
Answer: Try to use a when construct like this:
val typeface = when {
    isBold && isItalic -> Typeface.BOLD_ITALIC
    isBold -> Typeface.BOLD
    isItalic -> Typeface.ITALIC
    else -> Typeface.NORMAL
}.also { updateTypeface(it) }

Answer: The .also { } block is only applied to the last if else statement.
If you take this example:
fun test(value: Int) {
    if (value == 0) "Cond: 0"
    else if(value == 1)"Cond: 1"
    else if(value == 2) "Cond: 2"
    else if(value == 3) "Cond: 3"
    else { "Cond: 4" }.also { println(it) }
}
repeat(5) { test(it) }

It will print out:
Cond: 3
Cond: 4

You can test it here
To counter the issue, you can wrap all if else statements in parenthesis.
(
if (value == 0) "Cond: 0"
else if(value == 1)"Cond: 1"
else if(value == 2) "Cond: 2"
else if(value == 3) "Cond: 3"
else "Cond: 4"
).also { println(it) }

Or use a when statement without arguments.

when can also be used as a replacement for an if-else if chain. If no
argument is supplied, the branch conditions are simply boolean expressions, and a branch is executed when its condition is true

In your case it looks like this:
when {
    isBold && isItalic -> Typeface.BOLD_ITALIC
    isBold -> Typeface.BOLD
    isItalic -> Typeface.ITALIC
    else -> Typeface.NORMAL
}.also { updateTypeface(it) }


Calling a React function PropType from outside the class definition

Question: I have the following React Component..
import React, { Component,PropTypes } from 'react';
import RequestListItem from '../RequestListItem';
import { ScrollView,Text,View } from 'react-native';

class  RequestList extends Component {

  render(){
    return (
      <ScrollView
        onScroll={() => { console.log('onScroll!'); }}
        automaticallyAdjustContentInsets={false}
        scrollEventThrottle={200}>
        {this.props.requests.map(mapRequests)}
      </ScrollView>
    );
  }
}

RequestList.propTypes = {
  requests: PropTypes.array.isRequired,
  onRequestItemClick: PropTypes.func.isRequired
};

var mapRequests = (request, i) => {
  <RequestListItem
      id={request.id}
      title={request.title}
      onRequestItemClick={this.props.onRequestItemClick.bind(this)}
  />
};

export default RequestList;

The problem I am having is concerning the mapRequest function. I need to be able to invoke the onRequestItemClick that is passed in as a property to this component,but since this is defined outside of the class definition, it doesn't appear I have access to the properties. How do I accomplish what the code above is trying to do?
Answer: You can pass the callback to the mapRequests method, instead of trying to pull it directly from the props:
class RequestList extends Component {
  constructor(props) {
      super(props);

      this.props.onRequestItemClick = this.props.onRequestItemClick.bind(this) // I'm not sure why your binding to this something you got from the props, so consider removing this line
  }

  render(){
    return (
      <ScrollView
        onScroll={() => { console.log('onScroll!'); }}
        automaticallyAdjustContentInsets={false}
        scrollEventThrottle={200}>
        {this.props.requests.map((request) => mapRequests(request, this.props.onRequestItemClick))} // the arrow function calls mapRequest, and passes the request and the callback
      </ScrollView>
    );
  }
}

var mapRequests = (request, onRequestItemClick) => {
  <RequestListItem
      id={request.id}
      title={request.title}
      onRequestItemClick={onRequestItemClick}
  />
};

However, if you already use an anonymous function, you don't need mapRequests function anyway:
class RequestList extends Component {
  constructor(props) {
      super(props);

      this.props.onRequestItemClick = this.props.onRequestItemClick.bind(this) // I'm not sure why your binding to this something you got from the props, so consider removing this line
  }

  render(){
    return (
      <ScrollView
        onScroll={() => { console.log('onScroll!'); }}
        automaticallyAdjustContentInsets={false}
        scrollEventThrottle={200}>
        {this.props.requests.map((request) => (
            <RequestListItem
                id={request.id}
                title={request.title}
                onRequestItemClick={this.props.onRequestItemClick}
            />
        )}
      </ScrollView>
    );
  }
}

Comment: Thanks! I originally tried this and was having issues, but I went back and tried it again and it worked!


How do you quickly form this C7 shape on guitar?

Question: There is a somewhat difficult chord near the beginning of Isaac Albeniz's Asturias:
<code>%8/1.10/3.8/1.9/2.8/1.12/4[C7]
</code>
The chord is difficult to form in time with the tempo.
Here is what I am already doing:

Low-action guitar.
Strings held at fingertips, close to the frets.
Nails are trim.
Side of index finger used for the barre.
Thumb is held relaxed but firm at the middle of the back of the neck.

After a considerable amount of practice I still can't cleanly form this chord as written.
I really can't foresee my current form improving much with additional practice so I guess I am doing something wrong.
Are there any tricks to playing this chord?
Comment: `I can barely form this chord in 30 seconds` and `I really can't foresee my current form improving much with additional practice` seem like completely incompatible statements.  If this chord is new to you, you will undoubtedly improve tremendously with (much) practice.  That said there may indeed be some tricks to it, though I'm not familiar with this chord myself.
Comment: It is a tricky chord, but it should take you less than a second if you practice it.
Comment: Anyone else who can't see the tab?
Comment: I can't see the tab, either. I've tried it in Safari and in Chrome, no luck with either one.
Comment: yeah for some reason it goes away, i'll just make it fullwidth
Comment: What is the "4|1|2|1|3|1" mean on your tab?
Comment: That is the left-hand fingering 4->pinky    3->ring   2->middle    1->index
Answer: I want to remind you that Isaac Albéniz was a pianist, and "Asturias" was written for solo piano. Albeniz never published any music for guitar. There are now many different transcriptions of Albeniz' pieces for solo guitar, duet guitar, trio guitar, you name it, made by any number of transcribers.
So I say to you: If it's too hard for you to play that chord rapidly, then change the fingering of the chord to something you like better. Sr. Albéniz has been dead for 103 years, so he will not mind.
Comment: Albeniz' beloved guitar pieces were all written and arranged for piano, and Bach's famous lute pieces were written on harpsichord or *Lautenwerck*. Many transcribers have been working up their own different versions for years, and many solo guitarists make their own transcriptions. So if you are not literally-minded, you are free to make your own modifications to these classics--unless you're in a classical guitar competition at a conservatory where they are judging you on reading the exact notes on the page!
Comment: This is a good answer to *why* it is difficult on guitar (which is an important one), but there are other answers here which should also get credit, as they give options and advice to how to play it in a manageable way. The final accepted answer should be the one that gives the best "transcription" advice for this.
Comment: This makes a lot more sense... I was a little worried I was a terrible guitar player with my answer.
Answer: The stretch from 8 to 12, while barring all strings is indeed tricky.
Depending on the song and the emphasis on certain notes in this chord, I would not play the complete chord. I would focus on playing the notes which are most emphasized.
I'd try:
<code>%8/T.X/X.8/1.9/2.8/1.12/4[C7]

$8.X.10.9.8.12
</code>
This will strain your fingers less, and keep the high E note that I'm guessing is emphasized in this chord voicing. If its not emphasized, I'd say get rid of it; you don't need a whole lot of 3rd in a chord to make it sound major/minor. The important thing is you really should have that Bb (D string 8th fret) in the chord to get the C7 sound.
Comment: How does that strain your fingers less? In a good classical position (as you have with a proper barre) it's relatively easy to stretch the fingers so far; but distorting the hand to get the thumb around the neck makes it close to impossible at least for me.
Comment: For electric guitar players, I guess this is easier and more intuitive. This is a very "Hendrix" way to play a root-E major chord.
Answer: You can learn to do this (but the other options are good, too).
Start with the 6th string using the "face" of your index finger, no the "tip".
You sort of roll into the barre, stretching your pinky as soon as the lowest note is anchored. Lay the ring finger, then the middle, then the pinky. Only then do you finish the barre, completing the stretch.
It is very hard. I still can't do it super fast. But it is possible.
It's the same shape as the B7 in that Romance Anonimo that's in all the books. You're only adding the ring finger.
-7-----8-----7-----|-11----8-----7------
---7-----7-----7---|---7-----7-----7----
-----8-----8-----8-|-----8-----8-----8--
-------------------|--------------------
-------------------|--------------------
-7-----------------|-7------------------
Answer: Google has been my friend to at least establish that I'm not the only one with this problem :)
It isn't so much making the chord, but doing so without compromising either the high E or the Bb. Even professionals tend to either duck the high E in order to get a nice full C7 (including John Williams, yes check it out!), or stretch to the high E and partially obstruct the Bb with the ring finger (most others). Rare is the performance in which there is a beautifully crisp C7 plus a ringing high E, at speed. The best on YouTube, imho, is Anabel Montesinos (www.youtube.com/watch?v=f8J5VxpvCQc). So it can be done, damn it.
I would agree with two earlier points: 1) there are multiple guitar transcriptions and fingerings of this piano piece, so no 'right way', and 2) unless you are in competition, nobody is going to notice an omitted high E or an accidentally damped Bb if the piece is flowing in other respects.
Personally I'm sticking with the std C7 and leaving the high E battle till I've got the rest of the piece well under control.


CollectionView SelectionChange event not working properly in Android (.Net MAUI)

Question: I'm trying to create custom tabs control in .Net MAUI, for that, I had first tried it with ScrollView and BindableStackLayout control but in that, I'm facing a problem.
Reported here Custom tabs with ScrollView bug
So, as an alternative approach or work-around, I have tried to develop the same Tabs control using CollectionView.
This alternative approach is working fine in iOS but not working properly in Android.
There is one problem that is common in both Android and iOS. I have taken BoxView control as an Indicator for the selected tab. That I'm going to show only for the Selected tab but this just shows in the first tab, when I click on other tabs the tabs get changed but it does not get hidden from the first tab and get visible in the other selected tab.
I have used the visual state manager with white color for the selected state because it gives looks like an indicator which I',m trying to create using BoxView. But this also shows Selected item for Android only when that view gets loads for iOS I have to select the tab first then only it shows the selected color there.
Here is what I have done:
MainPage.xaml
<ContentPage.Content>

    <Grid RowDefinitions="50, *" RowSpacing="0">

        <CollectionView x:Name="TabsView"
                        Grid.Row="0"
                        ItemsSource="{Binding Tabs,Mode=TwoWay}"
                        ItemsUpdatingScrollMode="KeepItemsInView"
                        ItemSizingStrategy="MeasureAllItems"
                        SelectedItem="{Binding SelectedTab}"
                        SelectionChangedCommand="{Binding Path=BindingContext.TabChangedCommand,Source={x:Reference TabsView}}"
                        SelectionChangedCommandParameter="{Binding SelectedTab}"
                        SelectionMode="Single">

            <CollectionView.ItemsLayout>
                <LinearItemsLayout Orientation="Horizontal"/>
            </CollectionView.ItemsLayout>

            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid RowSpacing="0" RowDefinitions="*, 3">

                        <BoxView Grid.Row="1" Color="{Binding BoxColor}"
                                    IsVisible="{Binding IsSelected}"/>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup Name="CommonStates">
                                <VisualState Name="Normal"/>
                                <VisualState Name="Selected">
                                    <VisualState.Setters>
                                        <Setter Property="BackgroundColor" Value="White" />
                                    </VisualState.Setters>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                    </Grid>
                </DataTemplate>

            </CollectionView.ItemTemplate>
        </CollectionView>

        <tabs:ParentRecordTabView Grid.Row="1"
                                    IsVisible="{Binding IsParentRecordTabVisible}"
                                    VerticalOptions="FillAndExpand"/>

        <tabs:AdditionalInfoTabView Grid.Row="1"
                                    IsVisible="{Binding IsAdditionalInfoTabVisible}"
                                    VerticalOptions="FillAndExpand" />

    </Grid>

</ContentPage.Content>

MainPageViewModel.cs
public class MainPageViewModel : BaseViewModel
{
    public MainPageViewModel()
    {
        GetTabs();
    }

    private bool _isParentRecordTabVisible = true;
    private bool _isAdditionalInfoTabVisible;

    private ObservableCollection<TabViewModel> _tabs { get; set; }
    private TabViewModel _selectedTab { get; set; }

    public bool IsParentRecordTabVisible
    {
        get => _isParentRecordTabVisible;
        set { _isParentRecordTabVisible = value; OnPropertyChanged(nameof(IsParentRecordTabVisible)); }
    }

    public bool IsAdditionalInfoTabVisible
    {
        get => _isAdditionalInfoTabVisible;
        set { _isAdditionalInfoTabVisible = value; OnPropertyChanged(nameof(IsAdditionalInfoTabVisible)); }
    }

    public ObservableCollection<TabViewModel> Tabs
    {
        get => _tabs;
        set { _tabs = value; OnPropertyChanged(nameof(Tabs)); }
    }

    public TabViewModel SelectedTab
    {
        get => _selectedTab;
        set
        {
            _selectedTab = value;
            OnPropertyChanged(nameof(SelectedTab));
        }
    }

    public ICommand TabChangedCommand { get { return new Command<TabViewModel>(ChangeTabClick); } }

    private void GetTabs()
    {
        Tabs = new ObservableCollection<TabViewModel>();
        Tabs.Add(new TabViewModel { TabId = 1, IsSelected = true, TabTitle = "Parent record" });
        Tabs.Add(new TabViewModel { TabId = 2, TabTitle = "Additional Info" });
        Tabs.Add(new TabViewModel { TabId = 3, TabTitle = "Contacts" });
        Tabs.Add(new TabViewModel { TabId = 4, TabTitle = "Previous inspections" });
        Tabs.Add(new TabViewModel { TabId = 5, TabTitle = "Attachments" });

        SelectedTab = Tabs.FirstOrDefault();
    }

    public void ChangeTabClick(TabViewModel tab)
    {
        Tabs.All((arg) =>
        {
            if (arg.TabId == tab.TabId)
            {
                arg.IsSelected = true;
            }
            else
            {
                arg.IsSelected = false;
            }
            return true;
        });
        SelectedTab = Tabs.Where(t => t.IsSelected == true).FirstOrDefault();

        switch (SelectedTab.TabId)
        {
            case 1:
                IsParentRecordTabVisible = true;
                IsAdditionalInfoTabVisible = false;
                break;
            case 2:
                IsParentRecordTabVisible = false;
                IsAdditionalInfoTabVisible = true;
                break;
        }
    }
}

TabViewModel.cs
public class TabViewModel : BaseViewModel
{
    private bool _IsSelected;
    public bool IsSelected
    {
        get { return _IsSelected; }
        set
        {
            _IsSelected = value;
            OnPropertyChanged(nameof(IsSelected));
        }
    }

    private int _TabId;
    public int TabId
    {
        get { return _TabId; }
        set
        {
            _TabId = value;
            OnPropertyChanged(nameof(TabId));
        }
    }

    private string _TabTitle;
    public string TabTitle
    {
        get { return _TabTitle; }
        set
        {
            _TabTitle = value;
            OnPropertyChanged(nameof(TabTitle));
        }
    }
}

Note: This same approach again works fine in Xamarin.Forms (Visual Studio 2019), this just not working in MAUI, so does anyone notice something like this?
How to Reproduce error: check github
Answer:
Remove the BoxView default style in your project. Resource> Styles> Styles.xml


Why does my linux box fail to send SYN/ACK until after eight SYNs have arrived?

Question: Two people are using different PCs behind the same NAT box. They are regularly accessing the same website, hosted elsewhere. Intermittently, one of them sees the website take several minutes to load. The other can still access the website at normal speed. This lasts until the PC is rebooted, then the speed returns to normal. This slowness can affect either of the two devices but (so far) never both of them together.
Running tcpdump on the web server confirms that for some reason linux is not sending SYN/ACK packets in response to the SYNs until exactly seven SYNs later.
The eighth SYN packet does not include a TCP Timestamp. Other connections from behind the same NAT box (from the other PC) are responded to immediately and the TCP Timestamp is present but far in advance of the timestamps on the problem PC. I'm guessing this is relevant.
Is this PAWS at work? If so, is there a workaround? If not, what might it be?
Here are examples. First, a slow connection.
14:08:07.030430 IP 220.127.116.11.56423 > DSQ4003-45.tagadab.com.www: Flags [S], seq 1211796088, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755098862 ecr 0,sackOK,eol], length 0
14:08:07.940504 IP 22.214.171.124.56423 > DSQ4003-45.tagadab.com.www: Flags [S], seq 1211796088, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755098871 ecr 0,sackOK,eol], length 0
14:08:08.939792 IP 126.96.36.199.56423 > DSQ4003-45.tagadab.com.www: Flags [S], seq 1211796088, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755098881 ecr 0,sackOK,eol], length 0
14:08:09.940510 IP 126.96.36.199.56423 > DSQ4003-45.tagadab.com.www: Flags [S], seq 1211796088, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755098891 ecr 0,sackOK,eol], length 0
14:08:10.942483 IP 188.8.131.52.56423 > DSQ4003-45.tagadab.com.www: Flags [S], seq 1211796088, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755098901 ecr 0,sackOK,eol], length 0
14:08:11.942386 IP 18.104.22.168.56423 > DSQ4003-45.tagadab.com.www: Flags [S], seq 1211796088, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755098911 ecr 0,sackOK,eol], length 0
14:08:13.942542 IP 188.8.131.52.56423 > DSQ4003-45.tagadab.com.www: Flags [S], seq 1211796088, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755098931 ecr 0,sackOK,eol], length 0
14:08:17.954887 IP 18.104.22.168.56423 > DSQ4003-45.tagadab.com.www: Flags [S], seq 1211796088, win 65535, options [mss 1460,sackOK,eol], length 0
14:08:17.954902 IP DSQ4003-45.tagadab.com.www > 126.96.36.199.56423: Flags [S.], seq 1999044177, ack 1211796089, win 5840, options [mss 1460,nop,nop,sackOK], length 0

Here's another slow connection:
14:11:07.663535 IP 188.8.131.52.56486 > DSQ4003-45.tagadab.com.www: Flags [S], seq 3598517192, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755100668 ecr 0,sackOK,eol], length 0
14:11:08.634437 IP 188.8.131.52.56486 > DSQ4003-45.tagadab.com.www: Flags [S], seq 3598517192, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755100677 ecr 0,sackOK,eol], length 0
14:11:09.635522 IP 184.108.40.206.56486 > DSQ4003-45.tagadab.com.www: Flags [S], seq 3598517192, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755100687 ecr 0,sackOK,eol], length 0
14:11:10.635860 IP 184.108.40.206.56486 > DSQ4003-45.tagadab.com.www: Flags [S], seq 3598517192, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755100697 ecr 0,sackOK,eol], length 0
14:11:11.637469 IP 220.127.116.11.56486 > DSQ4003-45.tagadab.com.www: Flags [S], seq 3598517192, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755100707 ecr 0,sackOK,eol], length 0
14:11:12.637582 IP 126.96.36.199.56486 > DSQ4003-45.tagadab.com.www: Flags [S], seq 3598517192, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755100717 ecr 0,sackOK,eol], length 0
14:11:14.637423 IP 22.214.171.124.56486 > DSQ4003-45.tagadab.com.www: Flags [S], seq 3598517192, win 65535, options [mss 1460,nop,wscale 3,nop,nop,TS val 755100737 ecr 0,sackOK,eol], length 0
14:11:18.639374 IP 22.214.171.124.56486 > DSQ4003-45.tagadab.com.www: Flags [S], seq 3598517192, win 65535, options [mss 1460,sackOK,eol], length 0
14:11:18.639386 IP DSQ4003-45.tagadab.com.www > 18.104.22.168.56486: Flags [S.], seq 559871738, ack 3598517193, win 5840, options [mss 1460,nop,nop,sackOK], length 0

Here's a normal connection from the same NAT box, different host,  (note larger timestamp value despite being before both the other examples):
14:07:26.288656 IP 18.104.22.168.65146 > DSQ4003-45.tagadab.com.www: Flags [S], seq 4164516354, win 65535, options [mss 1460,nop,wscale 1,nop,nop,TS val 908816007 ecr 0,sackOK,eol], length 0
14:07:26.288669 IP DSQ4003-45.tagadab.com.www > 184.108.40.206.65146: Flags [S.], seq 1207614459, ack 4164516355, win 5792, options [mss 1460,sackOK,TS val 14867019 ecr 908816007,nop,wscale 9], length 0

Comment: @bmk A comment from the OP was lost (it was on another version of the post); I'm reposting it manually: "Er... they're behind the same NAT box so they present the same IP to the world. But obviously behind the NAT device they have different RFC 1918 addresses."
Comment: Do both hosts have the same IP address?
Answer: Try to disable window scaling as advised here: Why would a server not send a SYN/ACK packet in response to a SYN packet
sysctl net.ipv4.tcp_window_scaling


Avoiding package reinstalls when developing binary module

Question: I'm working on a Python module that contains compiled code. Compiling and installing the module works when using pip install . from the directory containing pyproject.toml and setup.py (I'm not actually sure which combination of these files I need, but it works when both are present at least).
The issue I'm having is that every time I run pip install ., pip will reinstall cmake and friends:
From the output: Successfully installed cmake-3.28.3 distro-1.9.0 ninja-18.104.22.168 packaging-23.2 scikit-build-0.17.6 setuptools-69.1.1 wheel-0.42.0
This has the effect that every time I'm iterating on changes in the source code, I have to sit through this reinstall which takes several seconds each time.
Is there not a way to install just my module and none of the dependencies? I've tried pip install --no-deps . and pip install --no-dependencies . to no avail.
Contents of pyproject.toml:
[build-system]
requires = [
    'setuptools>=42',
    'scikit-build>=0.13',
    'cmake>=3.20',
    'ninja'
]
build-backend = 'setuptools.build_meta'

setup.py just has the name of the package, license, etc.
Answer: When pip sees an pyproject.toml file, it automatically enables the "build isolation" feature[^1].
This means that pip will create a "disposable virtual environment" just for building your project and delete this environment once the build is done[^2].
That is why the build dependencies are always re-installed.
To avoid this, you can perform the installation using following steps:

Manually install the build dependencies in the same environment where you want your package to be installed (it is a good idea to use virtual environments here).

In your example, this means running:
pip install ninja cmake>=3.20 scikit-build>=0.13
pip install -U setuptools wheel  # It is good to use the latest version...

Explicitly disable build isolation when installing your project:
pip install --no-build-isolation .

Note that when using --no-build-isolation pip will not install any build dependency automatically. That is why we need step 1.
This is also why you need to install wheel (setuptools automatically adds wheel to whatever you specify in build-system.requires).

[^1]: Eventually, future versions of pip will enable "build isolation" by default, even if you don't have a pyproject.toml.
[^2]: The reasoning behind this behaviour is, broadly speaking, to avoid dependency hell and version collisions.
Comment: This works, thank you! And sorry for the late reply.


Directory for PHP 5 FPM socket files is deleted after reboot on Ubuntu Server

Question: I've created a directory to store socket files for PHP 5 FPM: sudo mkdir /var/run/php-fpm. It is owned by root:root as well as core PHP FPM process.
When PHP FPM is starting, it creates socket files for each pool inside of this directory and nginx uses them to communicate.
However, when I reboot my machine (sudo reboot) this directory is gone after reboot and PHP FPM can't start, cause it can't create socket files inside of a missing directory.
What can be the problem? How do I debug it?
I'm using latest Ubuntu Server 14.04.
Answer: Current version of Ubuntu is using so-called up-start configs to run services. More info about this can be found here.
All up-start scripts are located in the /etc/init directory. Do not confuse it with old init scripts in /etc/init.d directory.
As @Rhim stated in his answer, /var/run is a temporary mounted filesystem, that is re-created after each reboot, so changes are not persisted in it. So in order to have a custom directory for socket files you will have to create it every time. The best place to add such functionality is an upstart config for PHP FPM located in: /etc/init/php5-fpm.conf.
Here's the modified version of this config:
# php5-fpm - The PHP FastCGI Process Manager

description "The PHP FastCGI Process Manager"
author "Ondřej Surý <firstname.lastname@example.com>"

start on runlevel [2345]
stop on runlevel [016]

# Precise upstart does not support reload signal, and thus rejects the
# job. We'd rather start the daemon, instead of forcing users to
# reboot https://bugs.launchpad.net/ubuntu/+source/php5/+bug/1272788
#
# reload signal USR2

pre-start script
    mkdir -p /var/run/php-fpm
    /usr/lib/php5/php5-fpm-checkconf
end script

respawn
exec /usr/sbin/php5-fpm --nodaemonize --fpm-config /etc/php5/fpm/php-fpm.conf

pre-start stanza was already used to check PHP FPM configuration file so I've converted it to a script section and added my own command for creating the direcotry for socket files before calling the checkconf.
With this script it should work fine. In order to control state of the service use the service command like this: service php5-fpm start, service php5-fpm restart etc.
I hope it will help someone. Cheers!
Comment: isn't `/etc/init/php5-fpm.conf` file overwrited after php-fpm package is updated?
Comment: A valid concern. However, I'm not sure about this. I'm running this setup for at least half a year with automatic updates. No problems so far, no conflicts. etc.
Answer: I think that in Ubuntu also!
cat /etc/redhat-release
Fedora release 20 (Heisenbug)

df -h /run
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           3.9G  904K  3.9G   1% /run

ls -la /var | grep run
lrwxrwxrwx.   1 root root      6 Dec 28  2013 run -> ../run

This directory is mounted as tmpfs.

Add to a startup script, create a directory or change the directory for pid files.
 But I am surprised that it is not created automatically after reboot.
Comment: I'm sorry for the delay. Here's the requested piece of script: https://gist.github.com/slavafomin/cef2d5b0f6c6b5a011b2
Comment: PHP FPM is storing it's socket-files in the `/var/run` directory by default. I just wanted to group them together so I've created a sub-directory: `/var/run/php-fpm`. However it's deleted after each reboot.  How do I alter my starup-script to make sure it's working? I've tried to add `mkdir -p /var/run/php-fpm` in the begining of file, but it's not working for some reason.
Comment: Thanks! I've finally figured this out. Thanks for the pointer about `tempfs`.
Comment: Oh, I see. Is it OK to alter the `/etc/init.d/php5-fpm` script or is it better to create my own startup script then?
Comment: Show section start() in file `etc/init.d/php5-fpm`
Comment: I think you need to add `dir=$(dirname ${pidfile})
        [ -d $dir ] || mkdir $dir`
in the beginning of the function start().

Variable `pidfile` must be defined `/var/run/php-fpm/php-fpm.pid`


Python loop delay without time.sleep()

Question: In an MMO game client, I need to create a loop that will loop 30 times in 30 seconds (1 time every second).
To my greatest disappointment, I discovered that I can not use time.sleep() inside the loop because that causes the game to freeze during the loop.
The loop itself is pretty simple and the only difficulty is how to delay it.
limit = 31
while limit > 0 :
  print "%s seconds remaining" % (limit)
  limit = limit -1

The python libs exist in the client as .pyc files in a separate folder and I'm hoping that I can avoid messing with them.
Do you think that there is any way to accomplish this delay or is it a dead end?
Comment: It's difficult to offer a solution when the only thing we know about your game is "it loops"...
Comment: multithreading is your friend.
Answer: Your game has a main loop. (Yes, it does.)
Each time through the loop when you go to check state, move the players, redraw the screen, etc., you check the time left on your timer. If at least 1 second has elapsed, you print out your "seconds remaining" quip. If At least 30 seconds has elapsed, you trigger whatever your action is.
Comment: That's it, I found the main loop and everything was easy afterwards. The existence of this loop was all I needed to know, thak you very much.
Comment: Will the work be heavy if the while loop checked many many times if statement in the main loop? although the if statement is true only once in a second
Answer: You can't do it without blocking or threading unless you are willing to lose precision...
I'd suggest sometime like this, but threading is the correct way to do this...
import time

counter = 31
start = time.time()
while True:
    ### Do other stuff, it won't be blocked
    time.sleep(0.1)
    print "looping..."

    ### When 1 sec or more has elapsed...
    if time.time() - start > 1:
        start = time.time()
        counter = counter - 1

        ### This will be updated once per second
        print "%s seconds remaining" % counter

        ### Countdown finished, ending loop
        if counter <= 0:
            break

or even...
import time

max = 31
start = time.time()
while True:
    ### Do other stuff, it won't be blocked
    time.sleep(0.1)
    print "looping..."

    ### This will be updated every loop
    remaining = max + start - time.time()
    print "%s seconds remaining" % int(remaining)

    ### Countdown finished, ending loop
    if remaining <= 0:
        break

Comment: Keep in mind, it is just an example and i put that `time.sleep(0.1)` to make "tick" 10 times per second to avoid filling your screen with hundred "looping..." lines, they are working examples, copy+paste and try them.
Comment: A better approach is to remove the `break` statement and just use `while counter > 0`.

Python loop delay without time.sleep()


Utilizar o dropbox como repositório de projetos NetBeans 8 no Windows

Question: Estou utilizando o  NetBeans 8 em meus projetos e gostaria muito de utilizar o dropbox como versionador. Eu configuro o repositório no Dropbox mas com o diretório do projeto em outro caminho. Pode ser que eu esteja confundindo as coisas, mas o que é enviado para a pasta do dropbox é somente o diretório .git.
No entanto, o projeto não é enviado para o dropbox, o que fica é somente o .git o que impossibilita que uma pessoa que possua acesso a pasta do meu dropbox inicie o projeto, atualize e etc.
Procurei por tutoriais e informações, mas tudo por linha de comando, tem realmente que ser assim por linha de comando?
Desculpe não ter nada de código para enviar.
Comment: Tanto faz, mas em algum momento vc precisa fazer um push pra atualizar o remoto, no seu caso na pasta do dropbox. Ah, e considere nao usar o dropbox para isso, veja o bitbucket que oferece repositorios privados gratuitos.
Comment: Não conhecia o bitbucket, minha primeira ideia era usar o dropbox por ser free. A sua dica ai valeu o ano, rsrs.
Comment: Sim, somente o git basta. Voce deve estar cometendo algum erro no seu processo. Vc precisa de um .git local, na mesma pasta do seu projeto, e vc pode ter um remoto, que vc atualiza ele via push
Comment: Não entendi. O .git é enviado ou não para o dropbox? Vc precisa somente dele para poder trabalhar em equipe no msm projeto. Ah, e usar o dropbox para isso pode ser uma ideia terrível, pois ao sincronizar ele não garante a atomicidade da operação, o que pode estragar completamente o seu repositório.
Comment: Me tira uma duvida, o que vai para o repositório de versões é somente o .git? o problema é que quando eu tento clonar não da certo, os arquivos do projeto não estão lá.
Comment: O .git no local do projeto existe sim, eu somente utilizei os recursos do NetBeans, não tentei via linha de comando, seria melhor tentar por linha de comando?
Answer: Uma das principais vantagens do Git é o fato dele ser uma ferramenta de versionamento distribuída. Isto é, cada desenvolvedor pode contribuir com código para outros repositórios e ao mesmo tempo pode manter um repositório público em que outros podem basear seu trabalho e que eles podem contribuir. [1]
A ideia de utilizar o Dropbox como centralizador do repositório, permitindo que outras pessoas com acesso a este possam também trabalhar no projeto não é ruim, mas o resultado pode não ser o que você espera. Pode ocorrer o risco de dois developers estarem utilizando ao mesmo tempo, e um commit anule o outro.
Trabalhar com o Git utilizando um repositório remoto (desconsiderando Dropbox, OneDrive, etc) é o ideal nesses casos. Conforme citado pelo Math, o Bitbucket é uma opção para repositórios privados gratuitos. O Github também é uma alternativa, sendo este privado apenas em caso de assinatura de um plano.


Outras maneiras de fazer matriz

Question: Consegui desenvolver até aqui, não se deve imprimir espaços após o último elemento de cada linha o que faz com que o exercício dê errado, alguém conhece outro método ?
minha_matriz= [[1,2,3],[4,5,6],[7,8,9]]

def imprime_matriz(minha_matriz):
      for i in range(len(minha_matriz)):
             print(end="\n")
             for j in range(len(minha_matriz[i])):
                            print(minha_matriz[i][j], end =' ')

Answer: Sim. Por exemplo, esta forma:
def imprime_matriz(minha_matriz):
      for linha in minha_matriz:
        print(' '.join(str(i) for i in linha))

minha_matriz= [[1,2,3],[4,5,6],[7,8,9]]
imprime_matriz(minha_matriz)

Você pode ver executando no Ideone.
O que ocorre é que no seu código você imprime número por número e indica à função print para "trocar" o caractere de nova linha (o famoso '\n') por um espaço em branco (' '). Ela faz isso para todos os elementos, incluindo o último. Você poderia fazer uma verificação (um if) para saber quando é o último e só nesse caso usar end='', mas o jeito mais "pythônico" é usar o join. Ele vai juntar os itens de uma lista (a linha dentro do for) separando-os com a string data, sem colocar nada no começo ou no final do resultado. :)
Comment: Muito obrigado por sua resposta, me deu um chão ... VLW
Comment: Por nada. :) Se a resposta foi útil, por favor considere [marcá-la como aceita](http://pt.stackoverflow.com/help/someone-answers).
Comment: poderia me ajudar com este exercício ?
http://pt.stackoverflow.com/questions/186090/operador-de-subtra%C3%A7%C3%A3o-n%C3%A3o-reconhecido-no-python

Outras maneiras de fazer matriz


How to average out values of Textview inside a listView

Question: I 'm devoloping an app with a listview , every row is populated with various objects including a Textview  with int value,  how can I average out the valus contained in the textview in my listview ? thanks
Comment: what do you mean by "how can I average out the value of every textview"?
Comment: for example I have two rows, in the first one I have value 4, in the second I have value 2, how can I obtain the average 3? ps. I edit the title, thanks
Comment: you have to check the data source via which you are adding values to textviews? Avg out from that data source.
Comment: thanks , but I don't understand completely,  you mean I have to average out the Database data?
Comment: Exactly, If you are not changing the data on run time, you can take values and avg them out.
Comment: unfortunately I'm changing data on run time, thanks for answer anyway
Answer: you should implement a method of counting the average values in your adapter
public class Adapter extends BaseAdapter{

        ......

        public int getAverageValue(){
            int result = 0;
            if(getCount() > 0) {
                for (int i = 0; i < getCount(); i++) {
                    AdapterDataItem item = getItem(i);
                    result += item.getYourInt();
                }
                result = result/getCount();
            }
            return result;
        }
    }

this is not the end result you will need to adjust for themselves
Comment: Thank you,  I use your code with little adjustments,  it works
Answer: Assuming the calculation of that average will be performed on some view click which is not a part of ListView.
In ListView's Adapter you must be passing the ArrayList of some Java Model class. That class will have one variable which will represent the value entered by user. You have to store the value on focus change listener.
After user click the Calculate Average button. You simply iterate through the ArrayList and apply the formula of average i.e. Sum of All Values/ Number of Values


How can I handle files in a cloud when when the site is configured as multi-site?

Question: I want to run Drupal from a cloud and I am trying to figure out the design of the file system for multi-site setup.
In the cloud, there are multiple servers hidden under the load balancer which serve content from a single database (a service that handles replication on its own) and using central storage for user or Drupal data.
I solved the problem for user data, mostly images attached to nodes or uploaded via fields, but I'm stuck on how to handle files like compiled Twig templates, configuration files, services file, and  similar files.
Once a new server instance is created, it will fetch the code from a Git repository. The user data is handled via a stream wrapper (and CDN); no action is needed.
How should I handle the system files?
The more static files like the settings.php and services.yml files could be potentially stored in some "remote" storage and fetched from there, or they could be dynamically generated based on data stored in a special database.
What about the other files (template and configuration files, for example)?
Would something like a fast cache be a good design?
A Redis database could hold the current files; each instance could either fetch them manually or serve them directly. Once an instance flushes the cache, this would be immediately "synchronized" to all the instances, in second scenario. For first scenario, there could be  timestamp value for latest change that each instance would check on each page load to re-fetch the files when necessary.
Answer: This is why platform as a service solutions like platform.sh, getpantheon and others are so popular. They provide solutions to problems like this.
If you don't want to use them, then you can still learn from them. In this case, the answer is environment variables. You commit a settings.php file that reads the configuration from environment variables, e.g. which database server/solr/redis/... to connect to, configuration overrides and so on.
platform.sh also automatically generates a settings.local.php that some configuration built in, but they move more and more towards just documenting how to do it yourself as that's more flexible. See their example setups and specifically, settings.php of the 8.x-composer approach.
How to actually get those environment in place yourself is a non-drupal related question that you'll have better chances for good answers elsewhere. It also depends a lot on how you actually instrument those cloud servers.
So far, I've haven't had the need for customized services.yml files, all I do sometimes (beside having a services.local.yml, just like settings.local.php), is to dynamically load additional files, e.g. with the redis configuration. If you need that, you can either generate those files or you can implement a site specific service provider that generates the service/parameter definitions dynamically.
For twig, while they are generated PHP files, unless you do something really weird, they are based only on the static .html.twig files that you are deploying. So, you do not need to share them between your servers, you just need a deployment step that deletes the files on all servers when you deploy new code. Or, you could write a script that pre-generates them, then you less of a performance hit when re-deploying. Haven't seen a script yet for Drupal that does that, there might already be a question about that here.
The container is in cache, by default in the database, with a bit of configuration you can also have it in Redis or Memcache, see https://github.com/md-systems/redis/issues/12.
I'm not aware of any other files that need to be maintained like this. (other than public or other stream wrappers, which you apparently have already solved).


Oracle SQL - Summing a time series partition based on month

Question: I am working with a data set that looks like this:
MTD       | ID | Active
-----------------------
01-APR-16 | A  | y
01-MAY-16 | A  | y
01-JUN-16 | A  | n
01-JUL-16 | A  | y
01-AUG-16 | A  | n
01-APR-16 | B  | n
01-MAY-16 | B  | y
01-JUN-16 | B  | y
01-JUL-16 | B  | y
01-AUG-16 | B  | y

I would like to add a count column to the data set that counts the number of times an ID has been active ('y') AFTER the current MTD. The desired output is:
MTD       | ID | Active | COUNT
-------------------------------
01-APR-16 | A  | y      | 2
01-MAY-16 | A  | y      | 1
01-JUN-16 | A  | n      | 1
01-JUL-16 | A  | y      | 0
01-AUG-16 | A  | n      | 0
01-APR-16 | B  | n      | 4
01-MAY-16 | B  | y      | 3
01-JUN-16 | B  | y      | 2
01-JUL-16 | B  | y      | 1
01-AUG-16 | B  | y      | 0

The query I am thinking of is:
SELECT
 MTD,

 ID,

 ACTIVE,

 SUM(CASE WHEN MTD > (current records MTD)
          AND ACTIVE = 'y' THEN 1 ELSE 0 END)
          OVER (PARTITION BY ID)
   as COUNT

I'm not sure how to compare each record's MTD to the current record's MTD in the window sum. How can I amend the first line of the case statement?
Thank you,
Ryan Barker
Comment: perhaps just `order by MTD desc` within the over after the ID?
Answer: Use count() over() with a range specification so you look at the rows following the current row (for each id) for an active flag y and only count them. This assumes mtd is a date column for the ordering to work.
SELECT
 MTD,
 ID,
 ACTIVE,
 COUNT(case when active='y' then 1 end) OVER(partition by ID order by mtd range between 1 following and unbounded following)
FROM your_table

Sample Demo
Comment: I did not realize the following keyword existed. That is super useful. Thank you!
Answer: To me, it looks like you want to sum the number of rows with a "y" in reverse.  Something like this:
select t.*,
       greatest(sum(case when active = 'y' then 1 else 0 end) over (partition by id order by mtd desc) - 1,
                0)
from t;

Your idea is quite close.  You just need an order by in the partitioning clause.
Comment: I'd like to sum all "y"'s after the current month. This is close, but not quite there. If I have n, y, n, y, y as my ACTIVE column, your query returns the counts 2, 2, 1, 1, 0. The counts I am looking for is 3, 2, 2, 1, 0.
Comment: @RyanBarker . . . I don't see how to resolve the counts in your comment with the counts in the question.  Your use of MTD doesn't really help.  I'm not sure what this means in this context.
Comment: Hi Gordon, sorry I should have been clearer. MTD = Month to date. It is the value representing when the record occurred. I am looking to count the number of times active = 'y' after the record occurred. See vkp's solution: By saying range between 1 following and unbounded following and ordering by MTD in the partition, you are only considering from 1 MTD later than the current record to the end of the data set only when you do the count. Does that make sense?


Como obter a última localização do dispositivo

Question: Gostaria de saber se existe alguma forma de obter a ultima localização do GPS, antes de eu rodar a opção para executar o obtenção da posição atual.
public class Localization{

 private GetGPSResponse delegate = null;

 public void setDelegate(GetGPSResponse delegate){
    this.delegate = delegate;
 }

 //Método que faz a leitura de fato dos valores recebidos do GPS
 public void startGPS(Object local, final Context context){
    final LocationManager lManager = (LocationManager) local ;
    LocationListener lListener = new LocationListener() {
        public void onLocationChanged(Location locat) {
            if( locat != null ) {
                delegate.getGPSResponse(locat);
                lManager.removeUpdates(this);
            }
        }
        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
        @Override
        public void onProviderEnabled(String arg0) {}
        @Override
        public void onProviderDisabled(String arg0) {}
    };
    lManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, lListener, null);
 }

 interface GetGPSResponse{
    void getGPSResponse(Location location);
 }
}

Comment: Você poderia salvar a variável `Location locat` para uma variável na classe. Tipo: `public class Localization{ private Localtion lastLocat`.
Answer: O objeto LocationManager possui o método getLastKnownLocation que você pode utilizar para este caso, e se houver sucesso, é possível também obter qual foi a data desta última localização, assim você garante que não foi obtido uma localização muito antiga. É o que costumo fazer.
Mais ou menos assim:
boolean isSignificantlyNewer = false;

Location lastKnownLocation = lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (lastKnownLocation != null) {
    Date currentDate = new Date();
    long timeDelta = currentDate.getTime() - lastKnownLocation.getTime();
    isSignificantlyNewer = timeDelta < 120000;
}

if (isSignificantlyNewer) {
    // A última localização foi obtida a menos de 2 minutos
} else {
    // Não possui última localização ou ela tem mais de 2 minutos
    lManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, lListener, null);
}


How do I check if a module is being used by another?

Question: I'm using a multi-site setup with Drupal 7.14 core, and I want to disable some modules within my sites/all/modules shared folder. One of them in particular is the File_Entity module.
Is there a way (drush, programmatically, bash script, etc) to check if another module (e.g. Views, custom CCK) is using it? drush pml | grep File Entity only let me see what is enabled or disabled, not if it is currently in use, or safe to remove.
Answer: drush pm-info mymodule|grep "Required by"

grep or don't grep is up to you ;)
Beware this does not list fields that require the module. This implies to views that use fields too.
fields: admin/reports/fields

views: admin/reports/fields/views-fields

those will list fields only, so if you have special pagers, formatters or something else that come from a module you will still have to search for them.
Comment: Sure, that's what a developer /should/ do, but how many do when writing a custom theme for a single site? Considering how many times I've found SQL queries in template.php functions, that's a relatively minor offence :)
Comment: Yes, there can be dependencies in configuration as well as in code. For example if you create a view using a handler supplied by a module, then uninstall that module the view will break. Can be hard to track all these down.
Comment: As an example of a real stinker, suppose a module includes a template preprocess function that rearranges the content of certain variables. Your theme might depend on this having been done, but try tracking that down without code inspection!
Comment: hopefully those are listed as dependencies in the .info file for the actual module or theme (thats what that notice is for) if not you have a problem - but that mess is caused by bad style then.
Comment: So, how can I achive similar result with Drush 9 ?
Answer: There is no drush pm-info command in Drush 9.3, it was replaced pm:list.
(https://github.com/drush-ops/drush/issues/3487, https://github.com/drush-ops/drush/issues/5557)
But now there is no Required by field in a field list
(see FIELDS section in drush pm:list --help)
Current workaround is just open /admin/modules page and look for Required by,
or use some php code if you have access to the drush.
drush ev '$module = "views"; $modules = _system_rebuild_module_data(); \Drupal::moduleHandler()->buildModuleDependencies($modules); var_dump($modules[$module]->required_by);'

UPD: Drupal 9 version:
# Dependencies of the module
drush ev '$module = "views"; $modules = \Drupal::service("extension.list.module")->getList(); echo implode(array_keys($modules[$module]->requires),", ");'
# Dependencies to the module
drush ev '$module = "views"; $modules = \Drupal::service("extension.list.module")->getList(); echo implode(array_keys($modules[$module]->required_by),", ");'

NOTE: be worried with php code, may cause performance issues.
Comment: This worked well, but I tweaked it a little to clean up the output. Editing above.
Comment: Thank you @froboy! I would add also `."\n"` into echo statements.


Why does this progression alternating between major and minor chords sound right?

Question: I'm an intermediate guitar player and I'm trying to improve my music theory. When I'm sweep picking I play a pattern because it sounds right to me. Now that I'm learning how music theory works, I'm interested in finding out why that pattern sounds right. Here is an example;
Dm - F - Gm - B♭ - Cm - E♭ - Fm - A♭
I think it works for all notes as long as the pattern is the same which is;
Minor - 3 half steps higher Major - 2 half steps higher Minor
The starting point does not matter either. Could start from major etc
I'm sure this is a novice question and I'm missing technical terms but I'm trying to learn by myself.
Answer: The chords you're playing are the paired triads of what are called relative keys, which are keys that have the same key signature.
D minor, for instance, has one flat in the key signature, which is the same as F major. Thus Dm and F are the tonic triads for these two relative keys. The same relationship holds true for Gm and B♭, Cm and E♭, and Fm and A♭.
Simultaneously, you're moving around the circle of fifths: Dm goes down a fifth to Gm, which goes down a fifth to Cm, which goes down a fifth to Fm. Similarly, F goes down a fifth to B♭, B♭ down a fifth to E♭, and E♭ down a fifth to A♭.
In short, you're exploiting two of the most famous facets of tonality: root motion by descending perfect fifth and relative keys. No wonder it sounds so good!
Comment: I would also mention that each set of four chords can all be derived from the same key, so compared to some other circle of 5ths progressions, this progression should feel smoother.  For example, Dm, F, Gm and Bb can all be derived from the Dm scale, or F, Gm, Bb, Cm can all be derived from the Gm scale.  So not only are the different keys closely related but the chords used from each key are included in the surrounding keys.
Comment: In fact, I even have a book of cello exercises that has you learn the scales in the above order!
Answer: The minor to major is relative - Dm has a relative major of F. The major to minor is a I>ii relation - if F is I, then the ii is Gm. This works for the whole pattern and could scroll through all 12, till it gets back to the beginning. The last couple will be Am then C. It's a sort of subtle modulation, but at some point you'll have to move down the neck, possibly a couple of times, depending how well you know the different chord shapes, and their geography. Sounds like fun.
Comment: I am fairly certain that your analysis fully coincides with the application of Heptachord Shift, which only recently came to my knowledge, which suggests continuous modulation (major heptachord -> melodic minor heptachord on the 2nd note of the previous heptachord -> harmonic minor heptachord on the 1st note of the previous heptachord -> major heptachord on the 3rd note of the previous heptachord, etc.). Although the modulation seems "silent" at all shifts, because the changing note, when a heptachord shifts, is always missing from successive chords.


Single path for multiple menus

Question: I need to list nodes both in the main site navigation and within a section side navigation. Is it possible to target a specific menu for the Pathauto module to reference?
This is an example of the two menu structure.
Main Nav:
- Home
-- Page A
--- Page A Child 1
--- Page A Child 2
-- Page B

Page A Side Nav:
- Page A Child 1
- Page A Child 2

This results in Page A Child 1 and  Page A Child 2 having /Page-A-Child-1 and /Page-A-Child-2 as respective paths.
What I want is for both menus to have /Page-A/Page-A-Child-1 and /Page-A/Page-A-Child-2 as paths.
The pattern I'm using is [node:menu-link:parents:join-path]/[node:title].
Comment: You are confusing two different concepts: paths and menu entries. A path can be in any number of menu entries (including none, which is most commonly the case for nodes). When a node is created a menu entry can be added for it, but not by pathauto, which only generates a path. If you want a second menu entry for the same node, then with Drupal out-of-the-box it has to be created manually.
Answer: You can create multiple path aliases for a single node, but you can not re-use existing path alias to point to different node.
If Child 1 and Child 2 in your example point to the same nodes, then I I am not sure if I understood your problem correctly, because you can create multiple menus to point to the same nodes. Let's say you created both child nodes associating them with Main menu checking on the Provide a menu link in node's Menu settings. Then you could just create a new menu on admin/structure/menu and add menu items for the same nodes replicating the same or creating new path aliases.
Another way is to let Pathauto generate whatever path aliases you want for the first menu, then programmatically copy its items and override the second menu items with theme_menu_tree().

Single path for multiple menus


Mailbox, auto responder, forwarder - prevent emails being saved

Question: I've set up an auto responder for an address, and any emails sent to this address are being forwarded to another inbox.
What's the easiest way to keep the autoresponder, forward emails BUT prevent these forwarded emails from being "received" by the original recipient.
i.e. the person doesn't want to have to go through 5 weeks of emails when they return that have already been dealt with.
I have access to exim filters etc - just not sure what I'm looking for.
order of desired outcome is:

Email is sent to Inbox A
Auto Responder kicks in
Email is forwarded to Inbox B
Email is removed from Inbox A

thank you !
Answer: I can't speak for exim forwarding, but for sendmail - and I'm guessing it's pretty similar - the forward file for use with vacation (the standard autoresponder since the year dot) normally looks like
<code>\user,|/usr/bin/vacation user
</code>
The bit before the comma says "send me another copy and don't run it through the forward file", and the bit after the comma says "send this email to vacation".
To avoid keeping a local copy, change that to
<code>|/usr/bin/vacation user
</code>
If that's not going to work for you, can you be more specific about how your autoresponder is currently invoked?


windbg crash dump analysis, high cpu usage -

Question: My application(web api) is suffering with high cpu, while analyzing dump, I see my most of the threads have this !dumpstack -:
  Child-SP         RetAddr          Caller, Callee
00000030497bec00 00007ffbb19e1118 KERNELBASE!WaitForSingleObjectEx+0x94,

    calling ntdll!NtWaitForSingleObject
    00000030497beca0 00007ffba8375dda clr!CLRSemaphore::Wait+0xee, calling kernel32!WaitForSingleObjectEx
    00000030497becd0 00007ffba837345d clr!GCCoop::GCCoop+0xe, calling clr!GetThread
    00000030497bed60 00007ffba8375842 clr!ThreadpoolMgr::WorkerThreadStart+0x482, calling clr!CLRSemaphore::Wait
    00000030497bee00 00007ffba8393e1e clr!Thread::intermediateThreadProc+0x7d
    00000030497bee30 00007ffbb19e1f86 KERNELBASE!ConsoleCallServerGeneric+0xf2, calling KERNELBASE!_security_check_cookie
    00000030497bee50 00007ffbb45011a5 ntdll!RtlpLowFragHeapAllocFromContext+0x355, calling ntdll!memset
    00000030497beed0 00007ffbb450d0c6 ntdll!LdrpGetProcedureAddress+0x66, calling ntdll!RtlImageNtHeaderEx
    00000030497bef50 00007ffbb450c6f5 ntdll!LdrpResolveNonStaticDependency+0x1cd, calling ntdll!LdrpDereferenceNode
    00000030497befd0 00007ffbb4500d07 ntdll!RtlAllocateHeap+0xd7, calling ntdll!RtlpLowFragHeapAllocFromContext
    00000030497bf000 00007ffbb45011a5 ntdll!RtlpLowFragHeapAllocFromContext+0x355, calling ntdll!memset
    00000030497bf020 00007ffbb450f5f3 ntdll!LdrGetProcedureAddressForCaller+0x153, calling ntdll!_security_check_cookie
    00000030497bf030 00007ffb93fc8c84 mfc120u!DllMain+0x210, calling mfc120u!__security_check_cookie
    00000030497bf080 00007ffba8ce2cbb mscoreei!operator delete+0x34, calling kernel32!HeapFreeStub
    00000030497bf0d0 00007ffbb4500d07 ntdll!RtlAllocateHeap+0xd7, calling ntdll!RtlpLowFragHeapAllocFromContext
    00000030497bf140 00007ffbb4500d07 ntdll!RtlAllocateHeap+0xd7, calling ntdll!RtlpLowFragHeapAllocFromContext
    00000030497bf180 00007ffbac0c51bd gzip!DllMainCRTStartup+0x139, calling gzip!DllMain
    00000030497bf1e0 00007ffb979dbc9d clrcompression!calloc_impl+0x5d, calling ntdll!RtlAllocateHeap
    00000030497bf210 00007ffb979d8eff clrcompression!initptd+0xb7, calling clrcompression!unlock
    00000030497bf230 00007ffbb44ebf57 ntdll!RtlDeactivateActivationContextUnsafeFast+0xc7, calling ntdll!_security_check_cookie
    00000030497bf240 00007ffb979d7919 clrcompression!CRT_INIT+0x135, calling kernel32!GetCurrentThreadId
    00000030497bf270 00007ffb979d7a0e clrcompression!__DllMainCRTStartup+0x8a, calling clrcompression!DllMain
    00000030497bf280 0000000056b32052 msvcr100!_initptd+0xaa, calling msvcr100!_unlock
    00000030497bf2a0 00007ffbac051779 IitTlsCleanupHelper!UnregisterTLSCleanupCallback+0x679, calling IitTlsCleanupHelper!UnregisterTLSCleanupCallback+0xf0
    00000030497bf2b0 0000000056b31308 msvcr100!__CRTDLL_INIT+0x16c, calling msvcr100!_CrtEndBoot
    00000030497bf2d0 00007ffbb450bee8 ntdll!LdrpReleaseModuleEnumLock+0x1c, calling ntdll!RtlReleaseSRWLockShared
    00000030497bf2e0 00007ffbb44ec0f4 ntdll!LdrpCallInitRoutine+0x4c
    00000030497bf300 00007ffbb450be9b ntdll!LdrpReleaseLoaderLock+0x27, calling ntdll!LdrpReleaseModuleEnumLock
    00000030497bf340 00007ffbb44ebe53 ntdll!LdrpInitializeThread+0x1f3, calling ntdll!LdrpReleaseLoaderLock
    00000030497bf3b0 00007ffbb44ebd93 ntdll!LdrpInitializeThread+0x133, calling ntdll!RtlActivateActivationContextUnsafeFast
    00000030497bf3b8 00007ffbb44ebdc6 ntdll!LdrpInitializeThread+0x166, calling ntdll!RtlDeactivateActivationContextUnsafeFast
    00000030497bf420 00007ffbb44e8d73 ntdll!_LdrpInitialize+0x93, calling ntdll!NtTestAlert
    00000030497bf490 00007ffbb44e8c98 ntdll!LdrInitializeThunk+0x18, calling ntdll!NtContinue
    00000030497bf900 00007ffba8393e07 clr!Thread::intermediateThreadProc+0x66, calling clr!_chkstk
    00000030497bf940 00007ffbb43613d2 kernel32!BaseThreadInitThunk+0x22
    00000030497bf970 00007ffbb44e54e4 ntdll!RtlUserThreadStart+0x34

My doubt is in these 3 lines -:
ntdll!RtlAllocateHeap+0xd7, calling ntdll!RtlpLowFragHeapAllocFromContext
00000030497bf140 00007ffbb4500d07 ntdll!RtlAllocateHeap+0xd7, calling ntdll!RtlpLowFragHeapAllocFromContext
00000030497bf180 00007ffbac0c51bd gzip!DllMainCRTStartup+0x139, calling gzip!DllMain

Can this thread be cause of high cpu usage ?
Comment: I already have run !runaway command, this is one of the stack traces.. and their are many threads with the same stack trace.. just trying to understand what does this stack trace is trying to tell.. Though I doubt, this thread is culprit for cpu usage ..
Comment: WinDbg is a great tool but imo not the right tool for this job. It can only give you information about one specific point in time. To get a better holistic view of what your application is doing, you should use something like ETW *(or procmon)* and draw conclusions from there. That said, you seem to be compressing something so I would *expect* high CPU.
Comment: True. If you keep digging and searching you'll eventually reach the point where you figure out that WinDbg is not the right tool for this job and you need another one like ETW ;)
Comment: Yes. Does that answer your question? Threads are executed on a CPU, so it's the threads that use CPU time and make high CPU. As opposed to the memory. Memory is not executed on the CPU, so it does not cause high CPU trouble. Maybe you want to rephrase the question to get an answer that fits your needs.
Comment: it is webapi call.. web api do gzip compression (based on configuration).. How can I see what Is that compressing and that is actually real problem ..?
Comment: If it's a file being compressed, you could use procmon to find out wich one. The analysis part is bit easier then WPA *(ETW)* because of the overwhelming information ETW provides. You still need to xcopy procmon.exe to the production system though and be able to run it as administrator.
Comment: also use ETW and select File/DiskIO in WPRUI to see file/disk data.
Comment: As per article - https://msdn.microsoft.com/en-us/library/bb742546.aspx I should not focus on this thread.. because it is waiting and perhaps is in sleep mode -WaitForSingleObjectEx and sleeping does not cause cpu usage..
Comment: @LievenKeersmaekers I gave it up, he doesn't want to understand this. I let him now waste his time with the wrong tools.
Comment: @magicandre1981 - I could understand if OP is working in an environment where it's unlikely to get permission to change anything or where it's an administration nightmare to do so. Eventually though, they are going to have to bite the bullet.
Answer: Windbg is not the right tool for this job. Dumps are only snapshots so you have no idea what happened before. Use ETW and here the CPU Sampling, which sums all calls and shows you in detail the CPU usage.
Install the Windows Performance Toolkit which is part of the Windows 10 SDK (V1607 works on Win8/8.1(Server2012/R2) and Win10 or the V1511 SDK if you use Windows 7/Server2008R2)), run WPRUi.exe and select CPU Usage

and press on Start. Capture 1 minute of the high CPU usage and next click on Save. Open the generated ETL with WPA.exe (Perf analyzer), drag and drop the CPU Usage (Sampled) graph to the analysys pane

and load the Debug Symbols. Now select your process in the graph, zoom in and expand the stack, here you see the weight of the CPU usage of all calls
In this sample most CPU usage from Internet Explorer comes from HTML stuff.
For .NET applications WPA shows you .net related groupings like GC or JIT:

Comment: Issue is in production environment, support wont allow installing tool.
Comment: ETW is the BEST support tool in production, the tool can by xcopied to the server and you use also use the comamndlin version for scripts. . Everyone who says ETW is bad, is an uneducated troll. your support should be fired
Comment: Support most likely doesn't know what ETW is. Explain to them that this is what Microsoft uses to troubleshoot systems, [including production systems](https://blogs.technet.microsoft.com/robertsmith/2012/02/07/analyzing-storage-performance-using-the-windows-performance-analysis-toolkit-wpt/). If you are still not allowed to xcopy the files necessary to start a trace, I would kindly hand over the case to them or ask what their preference is: adding your own heavyweight logging to further analyze the issue or use the lightweight build-in logging that Microsoft provides.
Comment: Note also that Microsoft provides tools builtin to Windows that allows these ETW traces to be captured and analyzed on different machines. For example, [logman](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/logman) should be installed by default. Another useful tool for analysis of the captured ETL file is [PerfView](https://github.com/microsoft/perfview).
Answer: The first WinDBG command you will want to run is: !runaway.This command will show you which thread was using the CPU for the longest time.After receiving input from this command we can think forward on what that is going on...
Comment: @Thomas: !runaway shows which thread was using the CPU for the longest period of time, totaly from the begining of the application. If your executable is exausting the CPU then !runaway should show you the most problematic threads in the beginning of the list, which will help you analyze what intensive tasks you are doing. I used it many times and never did encounter false positives.
Comment: If !runaway gives a high usage, the thread may currently do something totally unrelated to the high CPU cause. !runaway produces many false positives.
Comment: Then you were lucky that you captured the state at the time where the correct stack is currently executed. !runaway may report a thread that was active 3 days ago and does nothing at the moment.
Comment: This is where I am confused... the above thread, whose stack trace I have provided is active as per dump for last 13 hours, looking at the trace it seems like it is doing nothing and waiting for clr to provide some work.. but I as per me, it should not be inactive for such a long time or it is actually stuck somewhere that I don't know ..
Comment: and yes like I mentioned above also .. there are many threads around 70 which are in the same state..
Answer: Set correct symbols path after any analysis.
Set at File->Symbol File Path menu:
YOUR_SYMBOLS_PATH;OTHERS_PATH;SRVC:\symcachehttp://msdl.microsoft.com/download/symbols
Try this commands to view managed stack to:

.cordll -ve -u -l
ld*
!EEStack
Comment: What benefit do you see in !EEStack over !DumpStack? How can performance issues be resolved with it?
Comment: for show some relevant information that could lead to source of the problem. For those who usually investigate crashes this is significant.
Answer: As per article - http://msdn.microsoft.com/en-us/library/bb742546.aspx  I should not focus on this thread.. because it is waiting and perhaps is in sleep mode -WaitForSingleObjectEx and sleeping does not cause cpu usage..
A few more resources if somebody is in same situation -:
https://channel9.msdn.com/Series/-NET-Debugging-Stater-Kit-for-the-Production-Environment
https://msdn.microsoft.com/en-IN/library/ms182372.aspx


Gravar option selecionada em um input text que possui "data-role='tagsinput' "

Question: Resultado esperado:
as opções que o usuário tem é de inserir os números do centro de custo manualmente e de selecionar em um select o ct custo desejado. Cada vez que o usuário selecionar um ct custo este deve aparecer no campo a esquerda como mostrado na imagem, o mesmo deve ocorrer se ele digitar manualmente no campo da esquerda e ao final pressionar a tecla enter ou vírgula.

Como está funcionando agora:
Se inserir os valores manualmente eles aparecem no campo como na imagem mostrada acima de forma instantânea (do jeito que deve ser), porém ao inserir os valores pelo select, os valores não aparecem instantaneamente no campo:

aparecem somente após realizar uma ação submit:

Montagem do input

//estou usando para aparacer as tags azuis no input text

Centro de custo:
<input type="text" name="nCtCusto" id="iCtCusto" data-role="tagsinput" value="<?
  for ($i = 0; $i < count($ctCusto); $i++) {
    echo $ctCusto[$i] . ",";
  }                                                                                ?>">

<select name="nVerCtCusto" id="iVerCtCusto" onchange="adicionar()" style="padding: 0.2em 0.0em 0.3em; width: 200px">
  <? for ($i = 0; $i < $qtCusto; $i++) { ?>
  <option value="<? echo $cdCentroCustoOption[$i] ?>">
  <?
  echo $cdCentroCustoOption[$i];
  echo $dsCentroCustoOption[$i]
  ?>
  /option>
  <? } ?>
</select>

O que eu quero
a cada vez que o usuário selecionar um option, que este apareça na tela na mesma hora
Answer: De acordo com a documentação do tagsinput a melhor forma de adicionar uma nova tag é utilizando a função .tagsinput('add', <value>)
E para utilizar essa função você deve obter o elemento a partir do jQuery utilizando $('#nCtCusto')
Veja o exemplo abaixo

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://email@example.com/dist/css/bootstrap.min.css">

<input type="text" name="nCtCusto" id="iCtCusto" data-role="tagsinput" value="tag1,tag2">


Does increasing partial correlation covariates affect power?

Question: I'm trying to characterise the relationship between variable A and B. I know the relationship is confounded by age, and maybe also variable C.
The partial Spearman correlation coefficient between A and B controlled for age is 0.33, p=0.02. The partial Spearman correlation coefficient between A and B controlled for age + variable C is 0.29, p=0.06.
Can someone please help me interpret this? The p-val has become non-significant p>0.05 but the coefficient doesn't appear to have changed much; have I lost power to detect statistical significance or is there a genuine interaction with variable C being measured here? Any help with understanding/more appropriate tests would be much appreciated. Thank you!
Answer: Confounders can create spurious correlation that is not actually due to a causal effect of A on B. So, in principle, your result that controlling for C makes the correlation disappear is very well possible.
In your case, the p-value is near your level of significance which is not a very clear result. So I would check if there are other methods with which I could improve the results. Here are some possibilities:
First, maybe you can investigate more closely whether C is really a confounder and not actually a mediator. Or you might have missed other confounders you need to control for.
Furthermore, maybe you find non-confounding variables that, when controlled for, decrease noise.
Finally, maybe you can find another way to measure the correlation and compare the results. There are many possible approaches, you could use regression with powerful packages like brms or matching methods (e.g. Matching) or hybrids thereof as implemented in MatchIt.