How do I theme the core modal with twig?

Question: Drupal 8 comes with built in modals.
This works:
modal

How can I style that modal using twig, to add new classes to the box? The intention is to take over the bootstrap style language.
Comment: Aren't they jquery UI based?
Comment: @nhck because status messages is a block and the modal isn't one.
Comment: Hmm, I guess (it is part of AJAX API https://www.drupal.org/docs/8/api/ajax-api/ajax-dialog-boxes ) - but on the other hand there is `status-messages.html.twig`
Answer: Modals in Drupal are built with jQuery UI. If you want to add just some class to the modal window, you can make use of the dialogClass option.
Click me

or
\Drupal\Core\Link::createFromRoute(t('Click me'), 'entity.node.canonical', [
  'node' => 11,
], [
  'attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => ['modal'],
    'data-dialog-options' => \Drupal\Component\Serialization\Json::encode([
      'dialogClass' => 'foobar',
    ]),
  ],
]);

but that won't make you a Bootstrap modal. For that you could either dynamically load the node and build the markup completely following the Bootstrap sample with a button targeting a
 with a certain ID (nah, probably not the best idea, performance-wise).
OR you could make use of view modes and the concept of the View Mode Page module.

Create separate pages for different view modes for a given content type.

That is, you create a new view mode for your node type for example mymodal, where you display only the fields you need and where you have full control over the markup using a view-mode-specific template like for example node--article--mymodal.html.twig. Now you can build the markup exactly like Bootstrap needs it. And finally link to this node in that view mode: /node/11/mymodal
or
\Drupal\Core\Link::createFromRoute(t('Click me'), 'view_mode_page.display_entity', [
  'view_mode' => 'mymodal',
  'entity_type' => 'node',
  'entity_id' => 11,
], [
  'attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => ['modal'],
  ],
]);

The only thing that would be missing now is to hide the jQuery UI modal title bar, 'title': FALSE didn't do it. But just CSS would do.
Comment: Thanks for the detailed write-up and research @leymannx . The second option is a really good idea - thanks! I guess one problem will be that there is no fall-back option - in case no ajax is loaded or when you would like to share the link. The first option doesn't really work I think: bootstrap expects more css classes down the tree, so just the dialogClass on top of the tree doesn't really make it. So I suppose after all I'll have to just bend the css so that the jqueryUI classes look bootstrappy - I somehow had hoped that we could extend the bootstrap_barrio theme for everyone.
Comment: @nhck – Yeah me too. I just had the same problem some days ago. Wished the modal would pick up some template. But no. You still could go the full Bootstrap way, by loading the modalable nodes directly into the markup early on.


Does our hearing generate neural signals for harmonics?

Question: First off, the (unrolled) length of our cochlea maps out frequencies such that high frequency sounds cause excitation (neural signals) from the front part of the cochlea, and low frequencies result in neural signals from the end part of the cochlea.  Thus we can associate the neurons at each position along the cochlea with a specific frequency.
The aspect is that I'm unsure of is whether a sinusoidal wave will cause the neural signals from the regions that correspond to the harmonics of the wave's frequency.  I.e. when a person listens to a 440Hz sine wave, the neurons corresponding 880,1320,1760... are activated.  I seem to recall this idea from somewhere, and this claim is made in this video, but it is unsubstantiated.
Basically, I'd like to know how (and by whom) this phenomenon has been studied, in order to better understand the physiological basis for the sensations of harmony.
Comment: A very interesting question.  What do you hope to gain from this?  Is there an application to this knowledge, or more of a curiosity? My thoughts are that we don't really perceive the harmonics of other sounds so much as they influence how we perceive the fundamental, such as tone and being able to identify the instrument.  So even if a sine wave would trigger some sort of harmonic stimulation, the way we perceive it is as a tone without harmonics.  I guess my thought is more based on the psychology/neurology side of things.
Answer: When you use a pure sinusoidal excitation (at reasonably low levels) you will only excite the basilar membrane at a relatively small area and only the neurons associated with that area will be active. At higher levels the middle ear can become non-linear by itself so you will see some harmonics and the according neural activity as well.
Establishing a one to one relationship between specific neurons and pitch perception is overly simplistic. The mechanical properties of the basilar membrane don't allow for as much frequency selectivity than humans actually have. There are a fair bit of other physiological, neurological and cognitive processes involved as well.
If you want to deep dive, I suggest starting with the work of Georg von Bekesy (http://en.wikipedia.org/wiki/Georg_von_B%C3%A9k%C3%A9sy) who pioneered this field of research and actually got a Nobel Price for it. A quick summary of his work can be found here http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3449028/
Answer: Well, the excitation of the receptors happens according to their sinoidal components, and as long as no significant of energy is being dissipated in the hearing organs and attenuation responses (like the coupling in the middle ear) happen on a larger time scale than the vibration itself, the response of the various ear mechanics is essentially linear.  And that means that the sensory receptors for 880Hz... will not get triggered.
With regard to following neural path ways, signals are highly correlated with their harmonics, so the following processing pathways will likely get coexcited.  If you are looking at a partially obstructed circle, your brain will complete the picture of the circle and actual neurons usually related with the obstructed circle path will also fire.
Now some stuff will obviously not fire.  Locating the source of a sinoid signal is actually pretty hard since the wavefronts of the harmonics and the different behavior when turning the head and the auricle are used for location pointers.  But without a good sense of location, neural signals will be inconclusive in some respect.
The respective neurons will be tuned to be "trigger-happy", but there is no concrete signal that would make them fire in an information-carrying pattern in connection with the neurons triggered by the fundamental.
Comment: I think it's worth noting that when the neurons are tuned 'trigger-happy', all it takes is a hint of imagination to actually set some of them off and the mind (or at least part of it) is unaware of the difference.  While not a normal feature of consciousness this type of auditory hallucination is extremely common (studies among college-aged participants reveal around a 50% rate of experiencing some form) and white-noise experiments have been conducted for many, many decades in which imagined perceptions are explored.
Answer: Re. the "by whom this has been studied": As I recall the local deity is Sethares. Do a search on the Alternate Tuning Yahoo Mailing List (https://groups.yahoo.com/neo/groups/tuning/info) for his name, 'cochlea', 'ERB', or a related concept 'harmonic entropy', and you'll find more babbling than you'll ever want to read about it.
Answer: Yes for loud enough sounds.  Fundamentals of Muscial Acoustics (A. Benade 1975) describes this in Chpt. 14.  The bare bones study involves presenting a loud sinusoidal sound to the subject at a given frequency, and then adding in a (sinusoidal) search tone.  When the search tone is close to one of the harmonics of the main tone, beating between the search tone and the induced harmonic are heard by the subject.  More careful experiments by J. Goldstein in the late 60's early 70's allowed for the estimation of the effective amplitude of these components as a function of the strength of the original tone.
This book also cites (as a note) "A good survey of heterodyne phenomena in the ear can be found in four papers by Donald D. Greenwood: "Aural Combination Tones and Auditory Masking" J. Acoust. Soc. Am 50 (1971): 502-43; and three that appear together in J. Acoust. Soc. Am. 52 (1972): 1137-67: "Masking by Narrow Bands of Noise in Proximity to More Intense Pure Tones of Higher Frequency", "Masking by Combination Bands;" and "Combination Bands of Even Order".
Answer: It's as if you saw a treestump that looks like a human. Audio neural response is similar to image neural response. Your brain will definitely see a human where the tree is, and your brain will ALSO experience 880Hz and related subfrequencies of audio where the 440Hz is because they look similar.
Difference between similar shapes and similar sounds, the tree requires your full attention, and the 880Hz subfrequency scan/comparison happens more efficiently, briefly and unconsciously, at the same speed that you can differentiate an oak leaf and a fig leaf, nearly instantly.
Sound will cause a complex pathway of neurons to signal to previously connected neurons which will attribute conscious memories and feelings to the sound. The brain has to compare the tone with other known tones, in a tree of neurons through wich the sound travels...
So the first neurons can identify "static pitch / glissando", and "frequency spectrum of tone" ... measure loudness of "880 / 3rd / 4rth partial" = none. You would think "sounds like a perfect sine wave"
So your neurons project a variety of possible imaginary variations onto the nerve signal that your ears receive, and you imagine for a second that the sound is them, just like you can see a tree that looks like a cat, or a person walking and think "it's a person walking" ...  "oh it's only a tree" your mind actively experiences other sounds and signals and compares them to incoming data...
You imagine other sounds consciously or subconsciously(it's felt as you becoming tuning awareness of something "what's that?"), so effectively, your brain is comparing the sound to all those other frequencies, but it is not activating full stimulus for them, only sensing if that frequency region is responding to the sound.
with a-lot of the human musical response being interpreted by the vocal interpretation structures of humans which are 10-100 times bigger than animal sound-interpretation regions (for voice communication).


Gerar HASH do conteúdo XML em SQL

Question: Existe uma forma de gerar o hash de um XML além da função master.sys.fn_repl_hash_binary?
Atualmente essa é minha implementação, porém, não sei se é o único jeito de se fazer.
--Preparação do ambiente
CREATE TABLE [dbo].[Funcionarios]([FuncionarioId] [int] NOT NULL, [Nome] [varchar](50) NULL)
INSERT INTO [dbo].[Funcionarios] (FuncionarioId, Nome) values(1,'jose')
INSERT INTO [dbo].[Funcionarios] (FuncionarioId, Nome) values(2,'maria')
INSERT INTO [dbo].[Funcionarios] (FuncionarioId, Nome) values(3,'joão')
INSERT INTO [dbo].[Funcionarios] (FuncionarioId, Nome) values(4,'pedro')

DECLARE @XML XML
DECLARE @HASH CHAR(32)

--Esse é um select de exemplo
SELECT @XML = (select * FROM Funcionarios FOR XML PATH('FUNC'))

--Gero o hash com essa função
SET @HASH = CONVERT(VARCHAR(MAX), master.sys.fn_repl_hash_binary(CAST((SELECT @XML).value('.','VARCHAR(max)') AS VARBINARY(MAX))), 2);

--Crio um outro xml incluindo o hash na tag epílogo
WITH
    XMLNAMESPACES('http://www.w3.org/2001/XMLSchema' AS xsd,
                  'http://www.w3.org/2001/XMLSchema-instance' AS xsi)
    SELECT @XML = (SELECT
                        (SELECT @XML
                                , (SELECT @HASH 'xml:hash'
                                   FOR XML PATH ('xml:epilogo'), ELEMENTS, TYPE)
                         FOR XML PATH('xml:teste'),ELEMENTS,TYPE)
                    FOR XML PATH(''), TYPE)

--Resultado final
SELECT @XML 'XML'

Answer: Nesse caso o que você pode fazer é criar um CLR e fazer o hash via CLR que no caso seria em C#.
Veja esse exemplo
Comment: Em `CLR` `c#` eu já fiz. Como solução alternativa, construí em `SQL` para não ter que registrar o `assembly` no servidor do cliente. Como minha aplicação cresceu, formalizei um `CLR`. A pergunta ainda ficará para encontrar outra solução em `SQL`.

Gerar HASH do conteúdo XML em SQL


Show content type form to block

Question: I've created one content type named Newsletter. And I want to display that content type form to block. I've tried with this code but failure. Your suggestions will be appreciated.
$my_module_form = drupal_get_form('blog-node-form');
$my_module_form = drupal_render($my_module_form);

Answer: Using contrib modules will certainly help for this. There are at least two I can think of:

Form Block (https://www.drupal.org/project/formblock)
Advanced From Block (https://www.drupal.org/project/afb)

To answer your question, however, you need to instantiate a new (or existing) node object to set as your form_state (Assuming the machine readable name of your content type is "newsletter").
global $user;
$node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'newsletter', 'language' => LANGUAGE_NONE);
$form_state['build_info']['args'] = array($node);
form_load_include($form_state, 'inc', 'node', 'node.pages');
$form = drupal_build_form('newsletter_node_form', $form_state);

If you want the form to edit an existing node, the you can replace the $node = (object) part with a node_load([nid]) function.
Answer: Try Form Block module. It allows to embed a contact/registration/node form as block.

Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.
Answer: You can also use Advance form block which supports ajax submission and multiple form with same content type.
FORM BLOCK:

Create any number of blocks with a particular node edit form.
Create any number of blocks with a particular node add form of a content type.
Create as many blocks as you like of each kind.
From the content type choose which fields to display on a per block basis.However required fields will be automatically displayed.
All forms will be saved through ajax. So multiple node forms can be independently placed on a single page and worked with simultaneously.

Show content type form to block


Change value in array in order

Question: I need to change maximum values to order. First in order will be maximum value and maximum value - 1. (100, 99, 100) must be equal to 1. It will be [5, 55, 1, 2, 1, 1, 98]. Then I need to change (98) to 2 because now 98 is maximum value in array.
My goal is to have [4, 3, 1, 5, 1, 1, 2]. I tried my first steps and received this
var arr = [5, 55, 100, 2, 99, 100, 98]

func toOrder(_ arr: [Int]) -> [Int] {
  var arr = arr
  var max = arr.max()!
  var order = 1
  for i in arr.indices {
    if arr[i] == max || arr[i] == max - 1 {
       arr[i] = order
    }

  }
 return arr
}
toOrder(arr)

There i'm stuck. I received [5, 55, 1, 2, 1, 1, 98], but how can i continue to iterate through array with saved values?
Comment: I read twice the explanation, and I didn't understood the logic.
Could you explain it with more details. Like showing clearly the input of each step, explaining the logic behind the step, showing the result, and looping if needed with another step or two, and give the final array?
Comment: Sorry for that. My final array must be [4, 3, 1, 5, 1, 1, 2]. Those are maximum values in order, but i received only first 1, 1, 1.
About exercise: System has N tasks, given array of importance to complete those tasks. I should give every task value build on importance.
Comment: Sorry for misunderstanding. I dont understand what should i change?
Answer: First zip the collection elements with their indices and sort by their elements in decreasing order.
Create rank and maxValue vars.
Create an array with exact same number of elements for storing the result.
Iterate the elements and indices.
If the element is less than maxValue minus one increase the rank value, update the maxValue and store the rank at the corresponding position of the original element at the resulting array:
let arr =  [5, 55, 100, 2, 99, 100, 98]

let indexedElements = zip(arr.indices, arr).sorted(by: { $0.1 > $1.1 })
var rank = 1
var maxValue = indexedElements.first?.1 ?? .max
var result = Array(repeating: 0, count: arr.count)
for index in indexedElements.indices {
    let element = indexedElements[index].1
    if element < maxValue - 1 {
        rank += 1
        maxValue = element
    }
    result[indexedElements[index].0] = rank
}
print(result)  // "[4, 3, 1, 5, 1, 1, 2]\n"

Answer: I have no idea what you should call this.
extension Sequence
where Element: AdditiveArithmetic & Comparable & ExpressibleByIntegerLiteral & Hashable {
  var : [Int] {
    var dictionary: [Element: Int] = [:]

    func value(for element: Element) -> Int? {
      dictionary[element] ?? dictionary[element + 1]
    }

    _ = sorted().reversed().reduce(into: 0) { highestValue, element in
      if value(for: element) == nil {
        highestValue += 1
        dictionary[element] = highestValue
      }
    }

    return map(value) as! _
  }
}

Answer: If I understood correctly your logic (because you gave a sample, which answer didn't seem right, I'll talk about later):
I'd go with a recursive method.

Find the max "untreated" value (else, once you have for instance the final output, it will iterate over and over), and stop if not found.
Update the array for values are equal to the max, or equal to the max - 1.
Redo

 func iterates(items: inout [Item], iteration: Int = 0) {
        let maxValue = items.filter { !$0.hasBeenTreated }.max(by: { $0.value < $1.value })
        print("maxValue found: \(maxValue)")
        guard let maxValue = maxValue else { return } //Check if there are still value max non treated, else, it ends here
        let newItems = items.map { anItem -> Item in
            if anItem.hasBeenTreated == false && (anItem.value == maxValue.value || anItem.value == maxValue.value - 1) {
                return Item(value: iteration + 1, hasBeenTreated: true)
            } else {
                return anItem
            }
        }
        print("NewItems: \(newItems)")
        items = newItems
        iterates(items: &items, iteration: iteration + 1)
    }

With the help of:
struct Item: CustomStringConvertible {
    var value: Int
    var hasBeenTreated: Bool

    var description: String {
        return "\(value) (\(hasBeenTreated))"
    }
}

To test it:
var itemsToTest1 = [5, 55, 100, 2, 99, 100, 98].map { Item(value: $0, hasBeenTreated: false) }
iterates(items: &itemsToTest1)
print("Output Items1: \(itemsToTest1)")
print("Output Array1: \(itemsToTest1.map({ $0.value }))")

var itemsToTest2 = [1, 2, 3, 4, 5, 6, 7, 8, 9].map { Item(value: $0, hasBeenTreated: false) }
iterates(items: &itemsToTest2)
print("Output Items2: \(itemsToTest2)")
print("Output Array2: \(itemsToTest2.map({ $0.value }))")

The outputs are just for debugging, but you can see the advancement of the calculations:
maxValue found: Optional(100 (false))
NewItems: [5 (false), 55 (false), 1 (true), 2 (false), 1 (true), 1 (true), 98 (false)]
maxValue found: Optional(98 (false))
NewItems: [5 (false), 55 (false), 1 (true), 2 (false), 1 (true), 1 (true), 2 (true)]
maxValue found: Optional(55 (false))
NewItems: [5 (false), 3 (true), 1 (true), 2 (false), 1 (true), 1 (true), 2 (true)]
maxValue found: Optional(5 (false))
NewItems: [4 (true), 3 (true), 1 (true), 2 (false), 1 (true), 1 (true), 2 (true)]
maxValue found: Optional(2 (false))
NewItems: [4 (true), 3 (true), 1 (true), 5 (true), 1 (true), 1 (true), 2 (true)]
maxValue found: nil
Output Items1: [4 (true), 3 (true), 1 (true), 5 (true), 1 (true), 1 (true), 2 (true)]
Output Array1: [4, 3, 1, 5, 1, 1, 2]
maxValue found: Optional(9 (false))
NewItems: [1 (false), 2 (false), 3 (false), 4 (false), 5 (false), 6 (false), 7 (false), 1 (true), 1 (true)]
maxValue found: Optional(7 (false))
NewItems: [1 (false), 2 (false), 3 (false), 4 (false), 5 (false), 2 (true), 2 (true), 1 (true), 1 (true)]
maxValue found: Optional(5 (false))
NewItems: [1 (false), 2 (false), 3 (false), 3 (true), 3 (true), 2 (true), 2 (true), 1 (true), 1 (true)]
maxValue found: Optional(3 (false))
NewItems: [1 (false), 4 (true), 4 (true), 3 (true), 3 (true), 2 (true), 2 (true), 1 (true), 1 (true)]
maxValue found: Optional(1 (false))
NewItems: [5 (true), 4 (true), 4 (true), 3 (true), 3 (true), 2 (true), 2 (true), 1 (true), 1 (true)]
maxValue found: nil
Output Items2: [5 (true), 4 (true), 4 (true), 3 (true), 3 (true), 2 (true), 2 (true), 1 (true), 1 (true)]
Output Array2: [5, 4, 4, 3, 3, 2, 2, 1, 1]

Now, going with the last example given in a comment (deleted answer):
[1, 2, 3, 4, 5, 6, 7, 8, 9] should produce `[ 5, 5, 4, 4, 3, 3, 2, 2, 1, 1], but I disagree.
Iterations should be:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 1, 1]
[1, 2, 3, 4, 5, 2, 2, 1, 1]
[1, 2, 3, 3, 3, 2, 2, 1, 1]
[1, 4, 4, 3, 3, 2, 2, 1, 1]
[5, 4, 4, 3, 3, 2, 2, 1, 1] (with only one 5 value at start)

Comment: Thank you very much, Its working! I don't know how you understood, you are super human !
Comment: I read too many times. If you had given the trace (the logs, or the last example), with explanation on each step), it would have been faster and easier to understand.

Change value in array in order


Kickstart not working

Question: I'm trying to create a kickstart to automate the installation procedure but when the installation ends and I check to see the result nothing happened. I'm trying to debug it by putting read statements in different places to see if everything runs. It seems the all the variables are there but when the setMask function executes it restarts. Any help would be greatly appreciated.
%pre
#!/bin/sh
curTTY=`tty`
exec < $curTTY > $curTTY 2> $curTTY

echo 'Specify the hostname to assign: '; read hostname
echo -n "Enter ip of ips (separated by spaces): "; read ip
echo -n "Enter ipv6 address: "; read ipv6

#Saving data
echo $hostname > /tmp/hostname
echo $ip > /tmp/ip
echo $ipv6 > /tmp/ipv6

%end

%post --nochroot
#!/bin/sh
curTTY=`tty`
exec < $curTTY > $curTTY 2> $curTTY

#Transfering data to be used in the post phase
ip=$(cat /tmp/ip)
ipv6=$(cat /tmp/ipv6)
hostname=$(cat /tmp/hostname)
numips=$(echo $ip | wc -w)

numberOfIpAddresses () {

if [ numips > 1 ]; then

    ips=$(echo $ip | awk '{$1=""; print}' | cut -c 2-)
    ip=$(echo $ip | awk '{print $1}')

fi

 }

 ipv6GW () {

    echo $ipv6 | awk -F":" '{$(NF--); print}' | while read $output

    do

    do

            gwv6="$gwv6:$output"

    done

    gwv6="$gwv6:1"
}

numberOfIpAddresses
ipv6GW

setGateway () {
case prefix in

22|23|24)
    gateway=$(echo $ip | cut -d. -f1-3)".1"
;;

25)
if [ firstOcted -ne 65 ] || [ thirdOcted -eq 161 ]; then
            gateway=$(echo $ip | cut -d. -f1-3)".129"
elif [ thirdOcted -eq 162 ]; then
            gateway=$(echo $ip | cut -d. -f1-3)".129"
elif [ thirdOcted -eq 162 ]; then
            gateway=$(echo $ip | cut -d. -f1-3)".1"
fi
;;

26)
if [ firstOcted -ne 64 ]; then
            gateway=$(echo $ip | cut -d. -f1-3)".65"
elif [ firstOcted -ne 69 ]; then
            gateway=$(echo $ip | cut -d. -f1-3)".129"
fi
;;
esac
}

setMask () {
#Extracting necesery octeds
firstOcted=$(echo $ip | cut -d. -f1)
thirdOcted=$(echo $ip | cut -d. -f3)

case firstOcted in
8)
    prefix=24
    setGateway
64)
    echo "Aqui en setMask opcion 64"
    read algo
    if [ thirdOcted -ne 7 ] && [ thirdOcted -ne 19 ] && [ thirdOcted -ne 26         ] && [ thirdOcted -ne 30 ] && [ thirdOcted -ne 31 ]; then
            prefix=24
            setGateway
    elif [ thirdOcted -ne 7 ] || [ thirdOcted -ne 19 ]; then
            prefix=25
            setGateway
    elif [ thirdOcted -ne 30 ] || [ thirdOcted -ne 31 ]; then
            prefix=26
            setGateway
    fi
            setGateway
    fi
;;

65)
if [ thirdOcted -ge 164 ] && [ thirdOcted -le 175 ]; then
            prefix=22
            setGateway
elif [ thirdOcted -ge 176 ] && [ thirdOcted -le 185 ]; then
            prefix=23
            setGateway
    elif [ thirdOcted -ge 161 ] && [ thirdOcted -le 162 ]; then
            prefix=25
            setGateway
    elif [ thirdOcted -ge 187 ] && [ thirdOcted -le 190 ]; then
            prefix=24
            setGateway
    fi
;;

69)
    if [ thirdOcted -ge 116 ] && [ thirdOcted -le 123 ]; then
            prefix=22
            setGateway
    elif [ thirdOcted -ge 110 ] && [ thirdOcted -le 115 ]; then
            prefix=24
            setGateway
    elif [ thirdOcted -ge 98 ] && [ thirdOcted -le 109 ]; then
            prefix=24
            setGateway
    fi
;;
*)
    echo "The ip was wrongly typed"        read ip
    echo -n "Type the prefix to use: "
    read prefix
    echo -n "Type the gateway: "
    read gateway
    numberOfIpAddresses
    ipv6GW
;;
esac
}

setMask

counter=0
ls /sys/class/net/ | grep ^e | while read output;
do

    echo    'SUBSYSTEM=="net", ACTION=="add", KERNEL=="'$output'", NAME="eth'$counter'"' \
    >> /etc/udev/rules.d/70-persistent-net.rules;
    ((counter++));

done

if [ -f /etc/debian_version ]; then

else
    echo DEVICE=eth0 >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo BOOTPROTO=none >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo ONBOOT=yes  >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo PREFIX=$prefix >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo IPADDR=$ip >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo GATEWAY=$gateway >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo DNS1=188.8.131.52 >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo DNS2=22.214.171.124 >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo #IPv6 Conf >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo IPV6INIT=yes >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo IPV6ADDR=$ipv6 >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo IPV6_DEFAULTGW=$gwv6 >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo IPV6ADDR=$ipv6 >> /etc/sysconfig/network-scripts/ifcfg-eth0
    echo IPV6_DEFAULTGW=$gwv6 >> /etc/sysconfig/network-scripts/ifcfg-eth0

if [ -n ips ]; then
    counter=0
    for subip in ips; do
            cat ifcfg-eth0 | sed 's/DEVICE=eth0/DEVICE=eth0:$counter/' | sed         's/IPADDR=$ip/IPADDR=$subip/' >> ifcfg-eth0:$counter

    done

%end

Comment: Is it safe to assume that there are some parts that were omitted from this kickstart file for brevity or some other reason?  If that is not a safe assumption I do not see anything other than `%pre` and `%post` sections, which would be its own problem.
Answer: Based on the functions it seems like the --no-chroot option may be causing the issue in this case.  Alternately the path where the root image is located may need to be appended to some of the paths where data is redirected typically something like /mnt/sysimage/root with CentOS.  So it would be possible to set a variable like this and append it where necessary
rootfs=/mnt/sysimage/root
...
echo DEVICE=eth0 >> $rootfs/etc/sysconfig/network-scripts/ifcfg-eth0
...

In addition to removing the --no-chroot option adding a log option might help get more info about the failure.
%post --log=/path/to/post/install/log.log

In addition to logging if chrooted and non-chrooted portions of post are necessary it is possible to have multiple %post sections as outlined from Redhat here.  In cases with complex %post sections splitting the tasks into multiple post scripts with separate logs can be valuable to determine the root cause of an issue with kickstart files.
In addition to splitting %post if you have access to a file server or shared storage of some sort you can write scripts containing the functions used in post, then mount/copy them during the post section and call the relevant functions.  This will give you the opportunity to test some of the scripts without having to rebuild/reinstall with the kickstart file constantly while debugging which can save a lot of time.

Kickstart not working


Problem with differentiation under integral sign

Question: Original problem: I have a problem in which i need to evaluate the integral:
$$
\int_1^\infty \dfrac{\sqrt{r^2-1}e^{-\alpha r}}{r} dr\,
$$
I have tried to evaluate it taking the $\alpha$ derivative, here i give you all the steps i have done:
$$
\int_1^\infty \dfrac{\sqrt{r^2-1}e^{-\alpha r}}{r} dr\,=-\int d\alpha \int_1^\infty\sqrt{r^2-1}e^{-\alpha r}=-\int d\alpha \dfrac{K_1(\alpha)}{\alpha}\\ =-\frac{1}{4} G^{2,1}_{0,1}\left(\frac{\alpha}{2},\frac{1}{2} \middle|
\begin{array}{c}
 1 \\
 -1/2,1/2,0 \\
\end{array}
\right)
$$
The two last steps in the last equation were obtained using Mathematica, and have been checked numerically, however i have calculated numerically the first integral for a few different values for $\alpha$ and it doesn't match the values the MeijerG function gives.
So now i think i have two possibilities:
-There is something wrong in the first step, the differentiation under integral sign doesn't work and i don't know why this could be the case.
-It's a numerical problem. Mathematica could be giving me wrong values of the integral, but i think this can not be because i have been changing the precision and the method for the numerical integral, obtaining the same results.
I want to know what is happening, i have tried similar examples with the same method and i have obtained the good results. Of course, if you have another way of evaluating this integral, don't hesitate, i would like to know it, but also i would like to know what is wrong here.
EDIT:
Comparison between numerical solution vs MeijerG solution (using differentiation under integral sign) as $\alpha$ functions:

EDIT 2:
I have found that the difference between the numeric integral and the analytic solution obtained using differentiation under integral sign is exactly $\pi/2$ for all $\alpha$. Actually I have found that for an integral of the form:
$$
\int_z^\infty \dfrac{(r^2-z)^c e^{-\alpha r}}{r} dr\,
$$
Being z a positive number and $0<c<1$.
The differentiation under integral sign method gives the result up to a function f(z,c).
For example:
-For z=1 and c=1/2, this function is equal to $\pi/2$
-For z=1 and c=1/3 this function is equal to $\pi/\sqrt{3}$
-For c=1/2 this function is exactly $f(z,1/2)=-1+(1+\frac{\pi}{2})z$
With this i can continue with my calculations but,
does anyone know why does this happen?
Do you know a way for obtaining this function f(z,c) analytically?
Comment: Can you post the numerical values?
Comment: I give you a plot of the numerical values. Do you prefer a particular example?
Answer: I have not checked your solution, this is a general answer.
You have your original integral as a function of $\alpha$:
$$
I(\alpha)=\int_1^\infty \dfrac{\sqrt{r^2-1}e^{-\alpha r}}{r} dr\,
$$
You find a derivative of this function:
$$\frac{d I(\alpha)}{d \alpha}=f(\alpha)$$
Now you are solving a first order ordinary differential equation. Notice, that the derivative of a constant is zero, meaning:
$$\frac{d ( I(\alpha)+C_1)}{d \alpha}=f(\alpha)$$
$$I(\alpha)=\int f(\alpha) + C_1=g(\alpha) + C_1$$
This means that you get an arbitrary constant $C_1$ in your solution (which does not depend on $\alpha$), so you need an initial condition for your function to find this constant.
In the case you described the constant apparently $\pi/2$.
An initial condition would be any known value of $I(\alpha)$ for particular $\alpha$, like $I(1)$ or $I(1/2)$.
Then you can find the constant from the equation:
$$I(\alpha)=g(\alpha)+C_1$$


Proving a Geometric Progression Formula, Related to Geometric Distribution

Question: I am trying to prove a geometric progression formula that is related to the formula for the second moment of the geometric distribution. Specifically, I am wondering where I am going wrong, so I can perhaps learn a new technique.
It is known, and I wish to show:
$$
m^{(2)} = \sum_{k=0}^\infty k^2p(1-p)^{k-1} = p\left(\frac{2}{p^3} - \frac{1}{p^2}\right) = \frac{2-p}{p^2}
$$
Now, dividing by $p$ both sides, and assigning $a = 1-p$ yields:
$$
\sum_{k=1}^\infty k^2a^{k-1}=\frac{2}{(1-a)^3}-\frac{1}{(1-a)^2} \qquad \ldots \text{(Eq. 1)}
$$
I want to derive the above formula. I know:
$$
\sum_{k=0}^\infty ka^{k-1}=\frac{1}{(1-a)^2}
$$
Multiplying the left side by $1=\frac aa$, and multiplying both sides by $a$,
$$
\sum_{k=0}^\infty ka^k = \frac{a}{(1-a)^2}
$$
Taking the derivative of both sides with respect to $a$, the result is:
$$
\sum_{k=0}^{\infty}\left[a^k + k^2 a^{k-1}\right] = \frac{(1-a)^2 - 2(1-a)(-1)a}{(1-a^4)} = \frac{1}{(1-a)^2}+\frac{2a}{(1-a)^3}
$$
Moving the known formula $\sum_{k=0}^\infty a^k = \frac{1}{1-a}$ to the right-hand side, the result is:
$$
\sum_{k=0}^\infty k^2 a^{k-1} = \frac{1}{(1-a)^2} + \frac{2a}{(1-a^3)} - \frac{1}{1-a}
$$
Then, this does not appear to be the same as the original formula (Eq. 1). Where did I go wrong?
Thanks for assistance.
Answer: You've actually almost arrived at the correct solution - your mistake is in the differentiation with respect to $a$ - the LHS is $\sum_{k=0}^{\infty}\left[a^k + k^2 a^{k-1}\right]$ instead of $\sum_{k=0}^{\infty}\left[k^2 a^{k-1}\right]$.
You're finished because $\frac{1}{(1-a)^2} + \frac{2a}{(1-a)^3} = \frac{a+1}{(1-a)^3} = \frac{2}{(1-a)^3} - \frac{1}{(1-a)^2}$.
EDIT: Here's some generalization: In general, $\sum_{n \ge 0} \binom{n}{k}x^n = \frac{x^k}{(1-x)^{k+1}}$, which is basically proved by differentiating $\sum_{n\ge 0} x^n=\frac{1}{1-x}$ $k$ times, multiplying by $x^k$ and dividing by $k!$.
From this one can calculate $\sum_{n \ge 0}n^k x^n$ by expressing $n^k$ as a combination of binomial coefficients: $n^k = \sum_{i=0}^{k} \binom{n}{i} a_{i,k}$. If you interpret $n^k$ as the number of functions from a $k$-set to an $n$-set, you realize that $a_{i,k}$ count the number of surjective function from a $k$-set to an $i$-set.
This allows you to compute the $k$'th moment of the geometric distribution quite easily, and it will always be of the form $\frac{f(p)}{p^k}$ where $f$ is a polynomial of degree $k-1$.
EDIT 2: It can be seen that $f(0)=a_{k,k}=k!, f(1)=a_{1,k} = 1$. This allows you to write $f(x)=x+k!(1-x)+(x-1)xg(x), \deg g < k-2$, which gives you the second moment immediately ($k=2$): $f(p)=p+2!(1-p)=2-p$.
In general, $f(p)=\sum_{i=1}^{k} a_{i,k} (1-p)^{i-1}p^{k-i}$. Note that you can express $a_{i,k}$ with Stirling numbers of the second kind: $a_{i,k}=i! \lbrace\textstyle{k\atop i}\rbrace= \sum_{j=0}^{i} (-1)^{i-j}\binom{i}{j}j^k$.
Compare with my edit to this answer.
Comment: Interesting edits. I will keep trying to understand.
Comment: @jrand - I left some details for you to complete, of course. I fixed some typos. I can also elaborate on non-clear conclusion.
Answer: You have $$\sum_{k=0}^{\infty} ka^k = \dfrac{a}{(1-a)^2}$$
Differentiating with respect to $a$ gives us
$$\sum_{k=0}^{\infty} k^2 a^{k-1} = \dfrac{(1-a)^2 - a \times 2 \times (a-1)}{(1-a)^4} = \dfrac{1-a + 2a}{(1-a)^3} = \dfrac{a-1+2}{(1-a)^3}\\ = \dfrac2{(1-a)^3} - \dfrac1{(1-a)^2}$$


SqlConnectionCommand ( CREATE DATABASE)

Question: Does anyone know why the first code works but the second does not?
At the second I get exception (wrong syntax near @databaseName).
First Code
public void CreateDatabase(string databaseName)
{
     string command = "CREATE DATABASE " + databaseName;
     using (SqlConnection sqlConn = new SqlConnection(_sqlConnectionStringBuilder.ToString()))
     {
          sqlConn.Open();
          using (SqlCommand sqlComm = new SqlCommand(command, sqlConn))
          {
               sqlComm.ExecuteNonQuery()
          }
     }
}

Second Code
public void CreateDatabase(string databaseName)
{
     string command = "CREATE DATABASE @databaseName";   \\I tried both
     string command = "CREATE DATABASE '@databaseName'";  \\I tried both
     using (SqlConnection sqlConn = new SqlConnection(_sqlConnectionStringBuilder.ToString()))
     {
          sqlConn.Open();
          using (SqlCommand sqlComm = new SqlCommand(command, sqlConn))
          {
               sqlComm.Parameters.Add(new SqlParameter(@"databaseName", databaseName));
               sqlComm.ExecuteNonQuery()
          }
     }
}

Comment: Because you can't use a parameter for a ddl statement. Why do you need to create a database in your application anyway?
Comment: thank you. because I am currently learning MVVM and would like to write a sample program
Comment: Possible duplicate of [SQL Server: How to use a database name as a parameter in a stored procedure?](https://stackoverflow.com/questions/36400262/sql-server-how-to-use-a-database-name-as-a-parameter-in-a-stored-procedure)
Comment: Not sure why that requires you to constantly need more databases but I will just pass that as a different discussion.
Answer: In TSQL the general rule is you can't parameterize Data Definition Language (DDL) statements at all.  And you can't use parameters in place of identifiers in Data Manipulation Language (DML) statements.

SqlConnectionCommand ( CREATE DATABASE)


how to enhance ebean models in a jar

Question: i have this requirement to factor out the ebean models of a
project so they can be reused by other play projects. i thought about creating a
subproject containing only the models, but then that means i have to duplicate the
subproject in every project that depends on it which isn't DRY enough to me. so
then i created a jar of the subproject using publishLocal so the main project now
just includes it like any other library in the build.sbt file. everything compiles well
but when i run the main project i get this exception
java.lang.IllegalStateException: Bean class module.models.User is not enhanced.
how do i make sure the models in the jar are enhanced?
Answer: Probably best to use compile time enhancement. For example, the maven enhancer.
Refer: http://ebean-orm.github.io/docs/setup/enhancement#maven
<code>  <plugin>
    <groupId>org.avaje.ebeanorm</groupId>
    <artifactId>avaje-ebeanorm-mavenenhancer</artifactId>
    <version>4.8.1</version>
    <executions>
      <execution>
        <id>main</id>
        <phase>process-classes</phase>
        <configuration>
          <packages>org.example.domain.**,org.example.anotherdomain.**</packages>
          <transformArgs>debug=1</transformArgs>
        </configuration>
        <goals>
          <goal>enhance</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</code>

how to enhance ebean models in a jar


Month and Date stored the wrong way around in ASP to SQL Server

Question: I am creating a C# ASP page that takes dates set by the users in a text box (the date is cheosen using a calendar object and then sent to the text box) and saves them to an SQL server.  When the dates are entered, it stores them in MM-DD-YYYY instead of DD-MM-YYYY.  This obviously generates errors!  Can anyone help me to get the dates to store them in the format I want it in?
protected void Page_Load(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
        DateTime today = DateTime.Now;
        DateTime sevenDays = today.AddDays(7);
        btnDelete.Enabled = false;
        txtStart.Text = today.ToShortDateString();
        txtEnd.Text = sevenDays.ToShortDateString();
    }
    updateGrid();
}
protected void btnSave_Click(object sender, EventArgs e)
{
    if (sqlCon.State == System.Data.ConnectionState.Closed)
        sqlCon.Open();
    SqlCommand sqlCmd = new SqlCommand("MessageUpdateOrCreate", sqlCon);
    sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
    sqlCmd.Parameters.AddWithValue("@MessageID", (hfMessageID.Value == "" ? 0 : Convert.ToInt32(hfMessageID.Value)));
    sqlCmd.Parameters.AddWithValue("@Sender", txtSender.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Receiver", txtReceiver.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Message", txtMessage.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Yeargroup", ddYear.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Title", txtTitle.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Date", txtStart.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Expiry", txtEnd.Text.Trim());

    sqlCmd.ExecuteNonQuery();
    sqlCon.Close();
    string messageID = hfMessageID.Value;
    clear();

    if (messageID == "")
        lblSuccess.Text = "New message Success";
    else
        lblSuccess.Text = "Updated Success";
    updateGrid();
}

Comment: If your field's type are date, then you don't store them on MM-DD-YYYY or DD-MM-YYYY format, you store them on an internal binary (numerical) format. The MM-DD-YYYY or DD-MM-YYYY formats are applied by your application (your data components configuration) when you present that data.
Comment: What's the field data type in SQL Server?
Comment: You should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results...
Answer: Your problem is these two lines:
sqlCmd.Parameters.AddWithValue("@Date", txtStart.Text.Trim());
sqlCmd.Parameters.AddWithValue("@Expiry", txtEnd.Text.Trim());

You are passing strings to a stored procedure that almost certainly expects a date. Which means the string will be converted to a date in a way you don't control.
So you need to take control. You need to parse the date in the way you need it to be (e.g. dd/mm/yyyy or mm/dd/yyyy). These links will help you with that:

datetime.parse and making it work with a specific format
https://www.hanselman.com/blog/DateParseExactAndTheSubtleGooThatIsDateTimeFormatStrings.aspx

Once you have parsed the string as a date:

Check that the date result is what you expected it to be
Pass that date (rather than the existing string) to the stored procedure
Comment: And use explicit parameter types instead of `AddWithValue`.


file_usage_add issue for compound field

Question: I have created a custom compound field which contains a managed_file element in the field widget form.
The issue I am having is not with saving the file, but with adding the file usage information.
I picked hook_field_presave based on some research, but this is not working for new content or translating the node.
function MODULE_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

The issue here is that when I save a newly created node, at this point, $entity->nid has not been defined. This number is required by file_usage_add.
Is there another hook that I can use to do what I'm trying to do?
Answer: You could add the file usage by implementing hook_node_insert which gives you all node fields besides what you are looking for nid and the fid using file_load in that case you could add file usage
Answer: Since I'm dealing with fields, hook_node_insert was overkill, but it got me on the right track.
The answer is to remove the file_usage_add logic from hook_field_presave and put it in hook_field_insert and hook_field_update.
Remove from hook_field_presave:
function MODULE_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      // no file logic here
      break;
  }
}

Add to hook_field_insert:
function MODULE_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

Duplicate for hook_field_update:
function MODULE_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

file_usage_add issue for compound field


Script to replace line that contains text

Question: I found another discussion on this, where there were numerous different options available but most of them didn't seem to work for myself or the original poster. I did however find an example that is confirmed working, however I am struggling with getting it to work and hoping for help.
I need to find a line that begins with "ServerName=" and replace this with my own line. I have used the example that was found and modified it, but I am getting errors when using it.
PowerShell Command:
powershell -Command "(Get-Content 'KFGame\Config\PCServer-KFGame.ini') | Foreach-Object {$_ -replace '^ServerName.$', ('ServerName=Network BUF 12345 Normal')} | Set-Content  'KFGame\Config\PCServer-KFGame.ini'"

Error Message:

) was unexpected at this time
Comment: I can't reproduce your problem, but as a first step you may want to remove most of the parentheses in that line. Only the outer parentheses around `Get-Content` are required. Also, the error might be caused by code prior to that line.
Comment: I updated the original post, I realized my first issue was running it from a bat without prepending "powershell -Command" to it. With the update though, it is now reporting 'Foreach-Object' is not recognized as internal/external command, program or batch file, why I suspect its still not actually running as powershell
Comment: The pipe is handled by CMD, not PowerShell. To prevent that you need to put the entire PowerShell code in quotes or (better yet) in a script that you run via the `-File` parameter.
Answer: If you want to run complex PowerShell statements from CMD you need to put them in quotes so that CMD just sees a string and doesn't try to handle special characters (like pipes):
powershell -Command "(Get-Content 'C:\Host400.txt') | Foreach-Object {$_ -replace '^workstationID.*$', (""WorkstationID=$computerName""} | Set-Content  'C:\Host400.txt'"

Note that you need to either escape or replace double quotes within the command string.
A better approach is to put the PowerShell statement(s) into a .ps1 script and run that via the -File parameter:
powershell -File "C:\path\to\your.ps1"

Comment: Thank you very much, this information helped a lot. My exact PS script seems to run without error now but isn't actually replacing the line. Can you check the original post and see if you see any problem with it at this point?
Comment: @BrettPowell There's an asterisk missing in your regular expression. Change `^ServerName.$`to `^ServerName.*$`.


Problem with character encoding ( danish æ ø å ) when using page handler include files in hook_menu().

Question: When I use an .inc file to handle my page output, all the danish special characters (Æ, Ø and Å) shows up as question marks, i.e. they are rendered with the wrong character encoding.
This following module works as expected.
stack_exchange_minimal.module
<?php
/**
* Implements hook_menu().
*/
function stack_exchange_minimal_menu() {
  $items['mypage'] = array(
    'title' => 'Minimal example',
    'page callback' => 'mypage',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mypage() {
 return 'ÆØÅ - æøå'; //outputs 'ÆØÅ - æøå'
}

When I split the code up in two files, however, it doesn't.
stack_exchange_minimal.module
<?php
/**
* Implements hook_menu().
*/
function stack_exchange_minimal_menu() {
  $items['mypage'] = array(
    'title' => 'Minimal example',
    'page callback' => 'mypage',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'stack_exchange_minimal.pages.inc',
  );
  return $items;
}

stack_exchange_minimal.pages.inc
<?php
function mypage() {
 return 'ÆØÅ - æøå'; //outputs '��� - ���'
}

I have tried passing the text through a render array instead of just dumping a string as the return value, but whith the same results.
I'm using drupal core version 7.31
What can I do to work around this issue?
Comment: Check that the inc file is encoded in UTF-8.
Comment: That was indeed the problem, the .inc was created with the context menu in Windows, which defaults to ANSI. Converted to UTF-8 and now the output is correct.
Answer: The problem was, as Andy pointed out, that the file wasn't encoded in UTF-8.
The .inc file was created from the context menu in Windows: 'New' -> 'Text Document', which defaults to the ANSI encoding.
The solution is simply to convert the file to UTF-8, that can be done for example in Sublime Text by choosing 'File' -> 'Reopen with Encoding'. Other text editors have similar commands.


How to add a number to a group of rows in a column only when the rows are grouped and have the same value?

Question: I have a dataframe with multiple columns. One of these columns consists of boolean numbers. For example:
data = pd.DataFrame([0,0,0,0,1,1,1,0,0,0,0,0,1,1,0,0,0,0,1,1,1,1,0,0])

What I need to do is identify every group of 1s and add a constant number, except the first group of 1s.
The output should be a dataframe as follows:
0,0,0,0,1,1,1,0,0,0,0,0,2,2,0,0,0,0,3,3,3,3,0,0

Is there a way to make this without being messy and complicated?
Answer: Use a boolean mask:
# Look for current row = 1 and previous row = 0
m = df['A'].diff().eq(1)

df['G'] = m.cumsum().mask(df['A'].eq(0), 0)
print(df)

# Output
    A  G  # m
0   0  0  # False
1   0  0  # False
2   0  0  # False
3   0  0  # False
4   1  1  # True  <- Group 1
5   1  1  # False
6   1  1  # False
7   0  0  # False
8   0  0  # False
9   0  0  # False
10  0  0  # False
11  0  0  # False
12  1  2  # True  <- Group 2
13  1  2  # False
14  0  0  # False
15  0  0  # False
16  0  0  # False
17  0  0  # False
18  1  3  # True  <- Group 3
19  1  3  # False
20  1  3  # False
21  1  3  # False
22  0  0  # False
23  0  0  # False


Help Creating a bookmarklet out of this code

Question: I'm really stuck here and I've tried a bunch of different solutions to try to fix the problem, but I can't seem to find a solution. The problem is that I'm trying to create a bookmarklet (a button that you press on a website that activates JavaScript code ie: http://erkie.github.com/) out of this code:
(div style="position: absolute; top: 0px; left: 0px; height: 100%; width: 100%; z-index: 100; ")  (embed src="http://www.netdisaster.com/fla/ufo.swf?mode=ufo&movie=ufo&destruction=massive&control=on&son=&linkTarget=_self&acces=http://www.netdisaster.com/fla/" quality="high" wmode="transparent" width="100%" height="100%") (/div)

I've tried variations such as:
javascript:document.getElementsByTagName('html')[0].innerHTML+="  (divstyle='position:absolute;left:0;top:0;right:20;bottom:0;width:100%;height:100%;z-index:420;')  (embedsrc='http://www.netdisaster.com/fla/ufo.swf?mode=ufo&destruction=massive&control=on&son='quality='High'wmode='transparent')  (/embed)  (/div")

and other ways such as replacing the spaces with %20, but I still can't seem to get it to work.
I found this site: when you click on the word "we" it produces something similar. I had to get rid of the carrot signs since it won't show up on this website if I have them.
Answer: You can try jQuery Bookmarklet Generator
Answer: Here is your div bookmarklet:
javascript:
document.getElementsByTagName("head")[0].innerHTML += '
<embed src="http://www.netdisaster.com/fla/ufo.swf?mode=ufo&destruction=massive&control=on&son=" quality="High" wmode="transparent"></embed>
';
void(0);

Check for '/" problems! Also, you don't want to get rid of spaces, they help you understand the code. And, I've put the div into "head" instead of "html" as it is simpler.

Make the code in normal javascript.
Go to http://dean.edwards.name/packer/
Obfuscate the code so it is shorter.


How-to display a product variation field twice (or more)?

Question: I want simply display a field of a product variation type (commerce) two times with different render settings.
I have tried with a dynamic field (display_suite) but it not working... I would prefer to know a programmatically solution to accomplish this task and I want use the (Drupal core) Display Manager for designate my layout (not a template file) :)
Note: This product field do automatically refresh (ajax) like other when a different product variation is selected.
See this related "issue": https://www.drupal.org/node/1494192#comment-7031370
Answer: You should be able to use template_preprocess_node() to duplicate a field.
I've not run this code and just written it from memory but something like this should suffice:
function template_preprocess_node(&$variables) {

  // Check this is the node type for commerce products
  if($variables['node']['#type'] == 'product') {

    // Copy the existing field to a new item
    $variables['content']['YOUR_FIELD_2'] = $variables['content']['YOUR_FIELD'];

    // Now make any changes to how you want to render the duplicate field
  }

}


Is it usual for old violin to have an obvious line that separates the front plate into left and right?

Question: The picture of the front plate of an old violin below shows a very obvious line that separates the front plate into left and right parts.
While I understand that the violin has a two-part front plate, is it normal that the line of separation is this obvious? Or is it normal in old violin?
I am not sure whether it is caused by the wood used for the left and the right part having different colors, which is unusual.
Comment: It doesn't bother me, but it is unusual.  I've seen a noticeable juncture on the back, but generally it's symmetrical.  A luthier can probably even it out if it really matters to you.  But the beauty of the sound is what matters the most.
Comment: It is absolutely normal that the top is made from two pieces of spruces joined together. This would usually be barely visible if varnished correctly (c.f. your previous question). In this case the instrument is old and not in a particularly beautiful form, which causes this to be accented a bit.
Comment: @aparente001 A violin maker could strip off the varnish, sand of all the dirt and revarnish it, but it wouldn't be worth the effort if it was a cheap violin and it would be frowned upon if it was a better one.
Answer:
Yes, it is normal to have a 2-piece top on a violin (or really most stringed instruments).

Most luthiers will try to bookmatch the two pieces such that there is a consistent grain pattern centered at the glue joint. This was likely what we would refer to today as a b-stock instrument, made from lesser quality stock so as not to waste leftover wood.
Comment: The picture you've given would rather be for the back, you even see a light flaming :). The top needs to have very fine and straight grain (which also means that the need of bookmatching is much lower).


Form has a div within it. How can I add classes to this div?

Question: There's a div called .description in a form in the site I've inherited. I want to add a another class to the div.
The div's content is created within hook_form_FORM_ID_alter(), eg:
$form['#description'] = 'Please enter your full name';

I've tried adding a classed to it like:
$form['#description'] = [
    '#markup' => '
Please enter your full name
',
  ];

But this just results in "Array" being printed.
Would anyone know what I could do add a class to this element?
Comment: Why did you add an '`s`' in the second example? `#description` is not an element, its the description text - in this case it would be for the form itself. Does that text appear at the top of the form and not attached to anything?
Comment: @Kevin, oops typo. The text appears at the bottom of the form, but still within the form element, wrapped in it's own div `Please enter your full name`. (I don't know where the description class is coming from.)
Answer: That's not what you want. What you want to do is add it to the form structure like this:
$form['#attributes']['class'][] = 'my-class';

Since you didn't list an element on the form, I can only assume you want the class on the form itself. If you want to wrap an element with a div with a class on it, you can do:
$form['element']['#prefix'] = '
';
$form['element']['#suffix'] = '
';

That will wrap the entire element.
Comment: Thanks, yes this adds the class to the wrapping `` element, but I want to target the div element within that form element.
Comment: That comes from the core theming function theme_form_element: http://cgit.drupalcode.org/drupal/tree/includes/form.inc?h=7.x#n4261 it is hardcoded there. To get around that, you would need to change the theme wrapper for this element to point to a custom one or add JS to add the class on (not preferable). I am not sure if there is a contrib module to help this, I don't know of one off the top of my head.
Comment: Barring any overrides of this theming function, this div will appear for any element that has a `#description` key.


Why does tmux set TERM=screen?

Question: How does tmux set the terminal to use (as reflected in the TERM environment variable).
For example. If I log in via ssh bash reports:
>set | grep TERM
TERM=xterm-256-color

If I then run tmux and from within tmux and do the same:
>set | grep TERM
TERM=screen

I think this is not always the case though since noticing it I have not managed to make tmux say anything else.
This relates to fake/mock/background terminal for testing an ncurses application
Where I am I trying to understand how the terminal emulation affects the resulting behaviour of an ncurses app.
Answer: tmux sets TERM to screen for two reasons:

tmux (like GNU screen) is a terminal emulator.
The screen terminal description is close enough to tmux's behavior that it suffices if tmux's own terminal description is not available.

The manual page alludes to these two points, but does not really explain them:

The TERM environment variable must be set to 'screen' or 'tmux'
for all programs running inside tmux.  New windows will automatically have 'TERM=screen' added to their environment, but care must be taken not to reset this in shell start-up files.

Applications (other than hard-coded stuff) use terminal descriptions to find how to do similar operations on various terminals.
Since tmux's terminal description has been part of the terminal database since 2015, you would only see TERM=screen on systems which are either very old, or have only a small subset of the terminal database installed.
Answer: That's controlled by the default-terminal server option in .tmux.conf:
set -g default-terminal "screen-256color"

From the docs:

default-terminal terminal
Set the default terminal for new windows created in this
session - the default value of the TERM environment
variable.  For tmux to work correctly, this must be set to
'screen', 'tmux' or a derivative of them.

It is considered good practice to not touch the TERM variable directly (do not set it manually in .bashrc or .zshrc but instead rely on tmux to generate it from .tmux.conf).

Why does tmux set TERM=screen?


How to set width of a multiple select?

Question: I want to set default width of multiple select elements :

How to do that ?
Answer: Try this,
<select multiple="multiple" style="width: 200px;">

or
<select multiple="multiple" style="width: 10em;">

Answer: The same way as any other element. You write a selector that matches the element (e.g. a select element with a multiple attribute) and then use the width property.
Width applies by default to replaced inline elements (such as selects).
select[multiple] {
    width: 7em;
}

Answer: Try This in css
select[multiple=multiple] {width: <default width you want>px ;}

Answer: Take a look at the max-width property on style.
Ex:
<select name=countries  style="max-width:90%;">
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>

More information: How to control the width of select tag?
Answer: You can use "size" attribute like below:

<!DOCTYPE html>

<select size="3">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

How to set width of a multiple select?


Imagem com intervalo de tempo - Excel

Question: Preciso atribuir uma imagem que apareça a cada 1 hora no EXCEL, como?!
Provavelmente será necessário utilizar o VBA. Mas não sou muito familiarizado.
E que feche sozinha após 1 minuto.
Comment: Minha sugestão é que você utilize o Agendador de Tarefas do Windows para fazer essa tarefa. Você pode utilizá-lo para agendar ações para serem executadas de tempos em tempos. Na configuração da ação, você pode pedir para exibir uma imagem.
Comment: Onde a imagem está localizada? Na web ou no computador? Se no computador, mesma pasta do arquivo Excel?
Comment: Por favor, leia o [Manual de como NÃO fazer perguntas](https://pt.meta.stackoverflow.com/q/5483/75104), [Como devemos formatar perguntas e respostas?](https://pt.meta.stackoverflow.com/questions/1084/como-devemos-formatar-perguntas-e-respostas) e [Seja mais específico na pergunta](https://pt.meta.stackoverflow.com/a/1481/75104)
Comment: Perdão, eu fiz pelo celular no meio da linha de produção na empresa.
É, ela vai está localizada no computador. Quero que apareça uma imagem e fique durante 1 minuto, nesse 1 minuto é pros colaboradores fazerem exercícios de alongamento para a ergonomia, etc...
Comment: Melhor, tem como por em intervalos específicos de horário? Em vez de ser de 1 em 1 hora, pois tem intervalos, horário de almoço, etc... Teria como por horas específicas? 10:00 12:00 14:00, etc... Deu 10:00, pum, aparece a imagem que vai ficar durante 1 minuto pra lembrar sobre a ergonomia.
Comment: Procure por [agendar tarefas em VBA](https://stackoverflow.com/a/17632087/7690982) e depois como criar um [Sub para mostrar imagens](https://stackoverflow.com/q/41230570/7690982).
Comment: Fernando, poderia criar o exemplo do agendador  de tarefas? Estou desde ontem pesquisando e apenas falhei até o momento :/
Comment: Fernando? Ainda está ai? Poderia dar o exemplo? kk
Answer: Agendador
Use este código VBA para agendar tarefas no horário desejado:
Private Sub Workbook_Open()
    '-- Roda os Subs ou funções no horário agendado.
    'Deve ser colodado em EstaPastadeTrabalho

    Application.OnTime TimeValue("10:00:00"), "mostrarImagem"
    Application.OnTime TimeValue("12:00:00"), "mostrarImagem"
    Application.OnTime TimeValue("14:00:00"), "mostrarImagem"
End Sub

Mostrar Imagem
Este é usado para mostrar a imagem e o caminho da imagem deve ser escrito em strPath
Sub mostrarImagem()
    Debug.Print "mostrarImagem() rodou as " & Time
    On Error GoTo 0
    'INSERIR O CAMINHO DA IMAGEM AQUI
    strPath = "C:/Caminho/do/arquivo/de/Imagem.jpg"
Inicio:
    If Dir(strPath) <> "" Then
        ActiveSheet.Pictures.Insert (strPath)
        Application.ScreenUpdating = False
        Application.DisplayFullScreen = True
        Application.DisplayFormulaBar = False
        ActiveWindow.DisplayWorkbookTabs = False
        ActiveWindow.DisplayHeadings = False
        ActiveWindow.DisplayGridlines = False
        Application.OnTime Now() + CDate("00:01:00"), "fecharImagem"
    Else
        MsgBox "A imagem não pôde ser carregada - Escolha a imagem."
        strPath = EscolherImagem
        GoTo Inicio
    End If
End Sub

Escolher a imagem
Esta é uma função para lidar com erro, caso o caminho da imagem não encontre nada.
Public Function EscolherImagem() As String
    'Créditos: http://software-solutions-online.com/excel-vba-open-file-dialog/
    Dim intChoice As Long
    Dim strPath As String

    'only allow the user to select one file
    Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
    'make the file dialog visible to the user
    intChoice = Application.FileDialog(msoFileDialogOpen).Show
    'determine what choice the user made
    If intChoice <> 0 Then
        'get the file path selected by the user
        strPath = Application.FileDialog( _
                  msoFileDialogOpen).SelectedItems(1)
        'print the file path to sheet 1
        EscolherImagem = strPath
    End If
End Function

Fechar imagem
Este Sub é chamado 1 minuto após inserir a imagem.
Sub fecharImagem()
    'Sub agendado irá rodar por 1 minuto
    ActiveSheet.Shapes(1).Delete
    Application.DisplayFullScreen = False
    Application.DisplayFormulaBar = True
    ActiveWindow.DisplayWorkbookTabs = True
    ActiveWindow.DisplayHeadings = True
    ActiveWindow.DisplayGridlines = True
    Application.ScreenUpdating = True

    Debug.Print "mostrarImagem() parou as " & Time
End Sub

Imagem com intervalo de tempo - Excel


Compatibility between PyTables and h5py for HDF file format

Question: I started working with HDF file format on Python a few weeks ago, and first thing you realize when doing this is that there are two main libraries that are both great though slightly different: Pytables (which works well with ViTables tool for visualization) and h5py (which works well with HDFView and HDFCompass).
Sadly, this two libraries don't behave well together. I read in several places (like here or here) that the idea is to make them compatible by "placing" one on top the other in this way:

This was discussed at SciPy 2015, so my question is: does anyone know how is this going? What is the current situation?
Comment: Regarding the h5py/pytables integration, there was a workshop (in 2018?) where the developers investigated the challenges. The conclusion -- they decided not to proceed. Can't remember where I read that. Maybe on the PyTables forum?
Comment: This may not be the right place to ask that kind of question.  It sounds more like something that you'd find on the `issues` or developers discussions for the respective packages.  That closest I've come to looking  at the interaction of `h5py` and `tables` is this question: http://stackoverflow.com/questions/41173254/how-should-i-use-h5py-lib-for-storing-time-series-data/41174767#41174767.  I was able to read a `pandas.tohdf` file with `h5py`.
Comment: Yeah... I doubted about asking on some GitHub issue but I didn't find any _appropriate_ one. I just don't know where to look... So thanks for the comment.
About what you say of `pandas.tohdf`, it is true, but when you open a dataframe saved like this with `h5py` you see that it was stored as a group with several datasets inside (this is because of `tables`). This can be check with code or with HDFView. Even more, HDFCompass is not able to open files saved in this way I think.
Comment: What do you mean by "_don't behave well together_"? Do you have a workflow that requires multiple packages? I have used all of them to read and/or create HDF5 data, but can't think of a time when I needed 2 packages in the same program. In other words, I either use h5py, OR pytables, OR pandas. I have created files with pytables (or pandas), and read them with h5py. That said, you should be able to use them together (so long as the HDF5 library versions are compatible).
Answer: I don't have any concrete knowledge regarding the answer, but it seems unlikely that this change would be made. Apparently pytables has much faster write speeds than h5py and would lose that if implemented on top of h5py.


Menu dropdown top and bottom padding issue for items element

Question: I am working on a side project HTML and CSS. I did most of the work and I wanted to improve it. Now I'm trying to add a dropdown menu. I did it but the items inside for any reason don't react when I try to add margin-top or padding-top.
here is my code:

.navbar {
  background-color: var(--primary-color);
  color: #fff;
  height: auto;
}

.navbar .flex {
  justify-content: space-between;
}

.navbar ul {
  display: flex;
}

.navbar a {
  color: #fff;
  padding: 10px;
  margin: 0 5px;
}

.navbar a:hover {
  border-bottom: 2px solid #fff;
}

.sign-in {
  color: #fff;
}

.arrow {
  font-size: 15px;
  color: #fff;
}

.test {
  overflow: visible;
}

.drop {
  position: relative;
  margin: 0;
  padding: 0;
}

.droper {
  position: absolute;
  background-color: #fff;
  min-width: 190px;
  z-index: 1000;
}

.droper a {
  color: black;
  text-decoration: none;
}

.drop:hover .droper {
  display: block;
}

.droper a:hover {
  color: #1c3fa8;
  padding: 10px 16px;
}

Home

        Features ▿

          Hosting Opt 1
          Hosting Opt 2
          Hosting Opt 3

Documentation

the result in the browser:
the link
Can someone help me out with what is happening?
Answer: To resolve your issue, add this block of CSS. This sets the links to display as block.
.droper a {
  display:block;
}

Here is your snippet with the new class

.droper a {
  display:block;
}

.navbar {
  background-color: var(--primary-color);
  color: #fff;
  height: auto;
}

.navbar .flex {
  justify-content: space-between;
}

.navbar ul {
  display: flex;
}

.navbar a {
  color: #fff;
  padding: 10px;
  margin: 0 5px;
}

.navbar a:hover {
  border-bottom: 2px solid #fff;
}

.sign-in {
  color: #fff;
}

.arrow {
  font-size: 15px;
  color: #fff;
}

.test {
  overflow: visible;
}

.drop {
  position: relative;
  margin: 0;
  padding: 0;
}

.droper {
  position: absolute;
  background-color: #fff;
  min-width: 190px;
  z-index: 1000;
}

.droper a {
  color: black;
  text-decoration: none;
}

.drop:hover .droper {
  display: block;
}

.droper a:hover {
  color: #1c3fa8;
  padding: 10px 16px;
}

Home

        Features ▿

          Hosting Opt 1
          Hosting Opt 2
          Hosting Opt 3

Documentation


How to calculate likelihood for a bayesian model?

Question: I am trying to do Bayesian posterior predictive checking, whereby I calculate the DIC for my fitted model, and compare to DIC from data simulated from the fitted model. I can get the DIC out of winBUGS, however I am not sure how to calculate the likelihood (for the DIC) outside of winBUGS (i.e., without fitting new models). All of the literature is quite general with respect to discrepancy functions for model checking, and have notation like p(D|theta) which I understand, but doesn't help me when I want to actually do the calculation.
Given a set of parameter values, and a Y_rep data set - how do I calculate the likelihood?
Answer: The likelihood is numerically equal to $\operatorname{P}(D\vert\theta)$, where D is the data vector and theta the parameter vector. Well, strictly speaking it's only equal up to a multiplicative factor, but most software packages including WinBUGS define it as being equal - see Q1 of their FAQ on DIC. The distinction between likelihood and probability is made because instead of the probability of the data for given values of the parameters, the likelihood is considered to be a function of the parameters for a fixed set of data.
It's usually analytically simpler and more computationally stable to work with the log-likelihood, and that's what you'll need to calculate the DIC anyway.
ADDED In response to user2654's comment below:
$\operatorname{P}(D\vert\theta)$ depends on the model for the data. The simplest case is when the data are independent and identically distributed (iid), in which case $\operatorname{P}(D\vert\theta)$  becomes a product over all the data points, and therefore the log-likelihood is a sum over all the data points. The probability for each data point is calculated from the probability density function or probability mass function defined by your model.
Comment: Thanks - I know I will need the log-likelihood to get the DIC, but I still don't know how to actually calculate P(D|theta)
Comment: Thanks onestop - I suspected this was model dependent. So if I have a model that is say, a Poisson regression with a bunch of covariates, then for each Y_rep data point, I calculate the probability that it came from a Poisson(lambda) distribution? - where lambda is a fitted parameter value.
Comment: Yes, that's it.


What does an Added Variable Plot (Partial Regression Plot) explain in a multiple regression?

Question: I have a model of Movies dataset and I used the regression:
model <- lm(imdbVotes ~ imdbRating + tomatoRating + tomatoUserReviews+ I(genre1 ** 3.0) +I(genre2 ** 2.0)+I(genre3 ** 1.0), data = movies)
library(ggplot2)
res <- qplot(fitted(model), resid(model))
res+geom_hline(yintercept=0)

Which gave the output:

Now I tried working something called Added Variable Plot first time and I got the following output:
car::avPlots(model, id.n=2, id.cex=0.7)

The problem is I tried to understand Added Variable Plot using google but I couldn't understand its depth, seeing the plot I understood that its kind of representation of skewing based on each of the input variable related to the output.
Can I get bit more details like how its justifies the data normalization?
Comment: @Silverfish has given a nice answer to your question. On the small detail of what to do with your particular dataset, a linear model looks like a very bad idea. Votes is manifestly a highly skewed non-negative variable, so something like a Poisson model is indicated. See e.g. http://blog.stata.com/tag/poisson-regression/ Note that such a model doesn't commit you to the assumption that the marginal distribution of the response is exactly Poisson any more than a standard linear model commits you to postulating marginal normality.
Comment: One way of seeing that the linear model works poorly is to note that it predicts negative values for a substantial fraction of cases. See the region left of fitted $ = 0$ on the first residual plot.
Comment: I've already given a link which in turn gives further references. Sorry, but I don't understand the second half of your question with reference to "scenario based on dataset" and "polynomial regression". I suspect you need to ask a new question with much more detail.
Comment: Thanks Nick Cox, here I found that there is a highly skewed non-negative nature , I must consider Poisson model , so is there any link which gives me a proper idea about which model to use in which scenario based on dataset and I tried using Polynomial regression for my dataset , will that be a right choice here ...
Comment: What package did you install so that R recognize the function `avPlots` ?
Answer: For illustration I will take a less complex regression model $Y = \beta_1 + \beta_2 X_2 + \beta_3 X_3 + \epsilon$ where the predictor variables $X_2$ and $X_3$ may be correlated. Let's say the slopes $\beta_2$ and $\beta_3$ are both positive so we can say that (i) $Y$ increases as $X_2$ increases, if $X_3$ is held constant, since $\beta_2$ is positive; (ii) $Y$ increases as $X_3$ increases, if $X_2$ is held constant, since $\beta_3$ is positive.
Note that it's important to interpret multiple regression coefficients by considering what happens when the other variables are held constant ("ceteris paribus"). Suppose I just regressed $Y$ against $X_2$ with a model $Y = \beta_1' + \beta_2' X_2 + \epsilon'$. My estimate for the slope coefficient $\beta_2'$, which measures the effect on $Y$ of a one unit increase in $X_2$ without holding $X_3$ constant, may be different from my estimate of $\beta_2$ from the multiple regression - that also  measures the effect on $Y$ of a one unit increase in $X_2$, but it does hold $X_3$ constant. The problem with my estimate $\hat{\beta_2'}$ is that it suffers from omitted-variable bias if $X_2$ and $X_3$ are correlated.
To understand why, imagine $X_2$ and $X_3$ are negatively correlated. Now when I increase $X_2$ by one unit, I know the mean value of $Y$ should increase since $\beta_2 > 0$. But as $X_2$ increases, if we don't hold $X_3$ constant then $X_3$ tends to decrease, and since $\beta_3 > 0$ this will tend to reduce the mean value of $Y$. So the overall effect of a one unit increase in $X_2$ will appear lower if I allow $X_3$ to vary also, hence $\beta_2' < \beta_2$. Things get worse the more strongly $X_2$ and $X_3$ are correlated, and the larger the effect of $X_3$ through $\beta_3$ - in a really severe case we may even find $\beta_2' < 0$ even though we know that, ceteris paribus, $X_2$ has a positive influence on $Y$!
Hopefully you can now see why drawing a graph of $Y$ against $X_2$ would be a poor way to visualise the relationship between $Y$ and $X_2$ in your model. In my example, your eye would be drawn to a line of best fit with slope $\hat{\beta_2'}$ that doesn't reflect the $\hat{\beta_2}$ from your regression model. In the worst case, your model may predict that $Y$ increases as $X_2$ increases (with other variables held constant) and yet the points on the graph suggest $Y$ decreases as $X_2$ increases.
The problem is that in the simple graph of $Y$ against $X_2$, the other variables aren't held constant. This is the crucial insight into the benefit of an added variable plot (also called a partial regression plot) - it uses the Frisch-Waugh-Lovell theorem to "partial out" the effect of other predictors. The horizonal and vertical axes on the plot are perhaps most easily understood* as "$X_2$ after other predictors are accounted for" and "$Y$ after other predictors are accounted for". You can now look at the relationship between $Y$  and $X_2$ once all other predictors have been accounted for. So for example, the slope you can see in each plot now reflects the partial regression coefficients from your original multiple regression model.
A lot of the value of an added variable plot comes at the regression diagnostic stage, especially since the residuals in the added variable plot are precisely the residuals from the original multiple regression.  This means outliers and heteroskedasticity can be identified in a similar way to when looking at the plot of a simple rather than multiple regression model. Influential points can also be seen - this is useful in multiple regression since some influential points are not obvious in the original data before you take the other variables into account. In my example, a moderately large $X_2$ value may not look out of place in the table of data, but if the $X_3$ value is large as well despite $X_2$ and $X_3$ being negatively correlated then the combination is rare. "Accounting for other predictors", that $X_2$ value is unusually large and will stick out more prominently on your added variable plot.
$*$ More technically they would be the residuals from running two other multiple regressions: the residuals from regressing $Y$ against all predictors other than $X_2$ go on the vertical axis, while the residuals from regression $X_2$ against all other predictors go on the horizontal axis. This is really what the legends of "$Y$ given others" and "$X_2$ given others" are telling you. Since the mean residual from both of these regressions is zero, the mean point of ($X_2$ given others, $Y$ given others) will just be (0, 0) which explains why the regression line in the added variable plot always goes through the origin. But I often find that mentioning the axes are just residuals from other regressions confuses people (unsurprising perhaps since we now are talking about four different regressions!) so I have tried not to dwell on the matter. Comprehend them as "$X_2$ given others" and "$Y$ given others" and you should be fine.
Comment: Does a method exist for translating the units of residual on the horizontal and vertical axes into units of the underlying variables?
Comment: Not sure how to ask this, but is there anything that can really be said about the trends seen in the plots? For example does the goodness of fit of each trend relate to how independent each of the predictors are, or something like that?
Comment: @detly Thanks, changed!
Comment: This is such an excellent answer. But is there a typo in your first paragraph (predictor variables)? Should they be X2 and X3?
Comment: Silverfish, do you know the answer to @NicholasG question?  Is there any way to make the residuals interpretable in terms of units of the X-variable?
Answer:
is there anything that can really be said about the trends seen in the plots

Sure, their slopes are the regression coefficients from the original model (partial regression coefficients, all other predictors held constant)


calculating cubic root in python

Question: I'm trying to evaluate the following function in python:
f(x) = (1 + cos(x))^(1/3)

def eval( i ):
   return math.pow( (1 + math.cos( i )), 1/3)

why is it always returning me 1?
I'm trying to calculate the Right and Left approximation of an integral, and latter apply Simpson's Rule, but Python does not seem to like that expression.
Help?
*Complete Code *
import math

min = 0
max = math.pi / 2
n = 4
delta  = ( min + max ) / n

def eval( i ):
   return math.pow( (1 + math.cos( i )), 1/3)

def right( ):
   R = 0
   for i in range(1, n+1):
        R += eval( i )

   return R

def left():
   L = 0
   for i in range(0, n):
        print eval( i )
        L += eval( i )

Comment: The `^` operator means "bitwise exclusive OR".
Comment: It's probably not a good idea to define a function named eval since eval() is already in use by Python as a built-in function.
Answer: Use floating point math (1 / 3 truncates to zero). Also, no need for math.pow (** for exponentiation)...
(1 + math.cos(i)) ** (1 / 3.0)

Also, min, max and eval are built-in functions - you are shadowing them.
Also, the extra spaces you are adding in your function call arguments are against PEP-8 (Python Style Guide). Specifically this paragraph:
http://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements
Comment: Alternatively for Python 2: `from __future__ import division`
Comment: PEP-8 is for working on the Python code base itself.  @philippe is welcome to use whatever guidelines he'd like for his personal code. PEP-8: "This document gives coding conventions for the Python code comprising the standard library in the main Python distribution."
Comment: @Omegaman PEP-8 is widely used throughout the entire Python community.
Answer: Use
1/3.0

instead of
1/3

in your code. Otherwise your exponent will always be 0 due to integer truncation.
Whether to use ** or math.pow() is up to your preference, most would probably just use **.
It's probably not a good idea to define a function named eval since eval() is already in use by Python as a built-in function.
Background:
Note that you could also do  1.0 / 3  or 1.0 / 3.0 .. as long as one of the operands in the division is a float the result will be a float.
However, this  float(1/3) would not work since it would convert the 0 resulting from the integer division 1/3 into a float giving you 0.0
Under Python 3.x the division operator / would have worked as you expected (ie it would give you a float value even with two integer operands). To get integer division you would have to use //.
So had you run this under Python 3.x you would not have encountered this particular problem.
Answer: New in Python 3.11
The math module now includes a built-in cbrt for cube roots, so your function can be implemented as:
def f(x):
    return math.cbrt(1 + math.cos(x))

Answer: The 1/3 is an integer divide, evaluating to 0. Try 1./3
Comment: This depends on the version of Python. It changed from version 2 to 3.
Answer: I think it's because you're performing integer arithmetic where you really intend to perform floating-point arithmetic.  Try changing the [second] 1 to  1.0:
def eval( i ):
    return math.pow( (1 + math.cos( i )), 1.0/3)

calculating cubic root in python


Como faço para verificar o código de status da resposta http do servidor em java?

Question: Bom dia, pessoal.
Gostaria de saber como faço em java para verificar se a resposta recebida do servidor foi com sucesso ou não.
Alguém pode me ajudar com isso?
Comment: Qual código você tem até agora? poderia por favor postar ?
Comment: Nem comecei ainda, apenas queria saber qual metodo eh utilizade de alguma API do tipo HTTP em java. É assim, eu irei enviar uma request ao servidor, e queria saber apenas a resposta, se é 200, 404, 500 ou outra.
Answer: Sua questão está muito ampla, pois a resposta pode ou não te servir de acordo com o que você quer fazer, que você deveria explicar melhor.
Entretanto, vou tentar te ajudar do mesmo jeito. Por exemplo:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Download {
    public static void main(String[] args) throws IOException {
        HttpURLConnection c1 = (HttpURLConnection) new URL("http://grepcode.com").openConnection();
        int code1 = c1.getResponseCode();
        System.out.println(code1);

        HttpURLConnection c2 = (HttpURLConnection) new URL("http://grepcode.com/naoexiste").openConnection();
        int code2 = c2.getResponseCode();
        System.out.println(code2);
    }
}

Este código estabelece duas conexões e mostra o código de status HTTP. A primeira mostrará 200 (ok) e a segunda mostrará 404 (página não encontrada). Use os status 2xx para sucesso e 4xx ou 5xx para erros, aonde erros 4xx provavelmente são erros seus e erros 5xx provavelmente são problemas no servidor.
Se a conexão não puder ser estabelecida, um IOException será lançado. No seu, código é importante que você teste por eles e saiba tratá-los adequadamente.
É possível fazer-se mudanças e personalizações no objeto HttpURLConnection antes de chamar o getResponse(). Tais mudanças seriam para definir headers, alterar o método HTTP (por exemplo, usar POST ao invés de GET), definir que você gostaria de efetuar upload, configurar caches, proxies, timeouts, etc. Veja os javadocs para ver quais métodos você poderia utilizar neste caso.
Answer: Eu resolvi meu problema utilizando o WebResponse da seguinte forma:
WebClient client = new WebClient(BrowserVersion.getDefault());
HtmlPage paginaResponse = (HtmlPage) client.getPage("http://www.website.com");

WebResponse response = paginaResponse.getWebResponse();

      if (response.getStatusCode() == 200) {

         //codigo

      }

Resolvi fazer dessa forma, pois já estava utilizando o WebClient e o HtmlPage no método.


How to fix image height and width in webview for android

Question: I am developing image application,i am using WebView to display image, so I want to fix some height and width size for the image, this size applicable for all kind of size of images in WebView.
Any sample code is welcome,
Thanks All
Answer: If you are adding your image as an img src, here is the classical synthax :

Comment: @Thanks Sephy,i am not using img src,i am directly using img url in web view,i want fix some size for image and sit on web view...
Comment: What do you mean by "using url"? Do you download the image as an input stream for instance and display it or you simply connect to an url which points to an image on a server?
Comment: @i am displaying image using xml parsing and webview,so i said url, ok


Finding the domain of $\frac{1}{x}|x^2 - 1|$

Question: What is the domain of this function
$F(x)=\frac{1}{x}|x^2 - 1|$
Can someone please tell me how to find it ?
Comment: Where do things "go bad" (division by $0$)?
Comment: Is it $\frac{1}{x|x^2-1|}$ or $\frac{1}{x}|x^2-1|$?
Comment: I edited your question to add [MathJax formatting](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference). If this isn't the function you meant, feel free to correct it.
Comment: @DylanSp: I'm betting on $\dfrac{1}{x|x^2-1|}$.
Comment: @TonyK It's entirely possible; I edited the original statement back in to the question.
Answer: I assume you mean $F(x)=\frac{1}{x|x^2-1|}$.
Notice that $x|x^2-1|=x\cdot|x-1|\cdot|x+1|$.
Now $x\cdot|x-1|\cdot|x+1|=0$ exactly when $x=-1,0$, or $1$.  For those values of $x$ the function is not defined because you can't divide by zero.  So the domain is all other values of $x$, namely $(-\infty,-1)\cup(-1,0)\cup(0,1)\cup(1,\infty)$.
Comment: Could also be written $\mathbb{R} \setminus \{-1, 0, 1\}$.
Comment: @BrianTung Yes, that's true.


Raising file limits for a service rather than a user

Question: I have seen various posts here about raising the open file limit on Linux systems for specific users (which is performed in a variety of different ways depending on the Linux distro being talked about).
I have an Ubuntu 8.04.4 LTS server running Dovecot, under a user called "dovecot";
ps aux | grep dovecot
dovecot    473  0.0  0.0  14320  2152 ?        S    12:11   0:00 imap-login
dovecot   1619  0.0  0.0  14324  2096 ?        S    Jan25   0:05 imap-login
dovecot   2652  0.0  0.0  14180  1892 ?        S    13:44   0:00 pop3-login
dovecot   3627  0.0  0.0  14180  1892 ?        S    14:13   0:00 pop3-login
dovecot   3776  0.0  0.0  14180  1892 ?        S    14:16   0:00 pop3-login
dovecot   4056  0.0  0.0  14320  2112 ?        S    14:19   0:00 imap-login
.....

ps aux | grep dovecot | wc
    178

How can I raise the open file limit for a service? Do I perform the same actions for raising the limits of use, upon the user the service runs as?
So on this system I could increase the limit in /etc/security/limits.conf for the dovecot user, but how will this relate to my service. Would I need to restart the service for the new settings to effect, or as new processes spawn will they inherit the new settings?
I can't see how changing this limit will tie in with a long running service as opposed to a user who logs in and out.
Answer: For CentOS 7 (and I assume any other systemd-converts) you need to edit the service file. You can use this to simply override the service file so it's upgrade-safe:
systemctl edit dovecot.service

And then add:
[Service]
LimitNOFILE=4096

Change 4096 to whatever you like.
Answer: "Do I perform the same actions for raising the limits of use, upon the user the service runs as?" - Yes. The service is running under the user's limitations, so once the limits are raised and the service restarted, it will have the new limits.


Rationale behind Bayes rule for continuous random variables

Question: I was viewing a problem in Probability where there are two independent random variables $X,Y$ which were exponentially distributed with parameter $\lambda$ , $Z$ is r.v. such that $Z=X+Y$
I solved the problem and found $f_{X|Z} (x|z)$
$$f_{X|Z} (x|z) = \frac{ \lambda ^2 e^{-\lambda z}}{f_Z(z)} \qquad , 0 \le x \le z $$
 and got the correct answer but I could not understand the meaning of the result,
I mean how knowing the value of $Z$ will make the distribution of $X$ uniform? that is all outcomes became equally likely? as $f_{X|Z} (x|z)$ does not depend on $x$, so could anyone helps me giving a good reasoning for why this happened?
Answer: I don't have a good reasoning in the continuous case, but here is some reasoning in the discrete one. Hopefully, it gives an idea of why this is happening.
A discrete counterpart of exponential distribution is the geometric one, which means the number of the first success (heads) when flipping a (possibly, unfair) coin independently. So let $X$ and $Y$ be independent geometrically distributed with the same success probability $p$. Then the variables $X$ and $Z = X+Y$ can be understood as the number of the first and the second success when flipping a coin. And the question is: given that the second success is on the $n$th flip, what is the distribution of the first one? Well, due to the complete symmetry in the trials it must be obvious that the first success is equally likely to happen on the 1st, 2nd, ..., $(n-1)$th flip, so it is uniformly distributed on $\{1,2,\dots,n-1\}$.


How to find a point with positive integer coordinates which is closest to a line?

Question: Given the equation of a line, we need to find a point with positive integer coordinates$^*$ such that the distance of that point from the line is a minimum.
How can we go about it?
$^*$ i.e. both the $x$ and $y$ coordinates are positive integers
Comment: Are the line coefficients integers? In two or three dimensions?
Comment: I believe it is implied that we are working in two dimensions, since OP mentioned $x$ and $y$ coordinates in their post (but not $z$).
Comment: yes the coefficients will be integers.
Comment: yes, we are working in 2 dimensions here.
Answer: If the slope is irrational and the line does not go through integer points, you can't.  There will be integer points arbitrarily close to the line.  If the slope is rational, the distances will repeat with period the denominator of the slope.  If the slope is less than $1$ in absolute value, you can look at its inverse by making $x$ a function of $y$ and the repeat will be shorter.
Comment: between what is the 'distance' that is referred here ?
Comment: Normally the distance from a point to a line is perpendicular distance.
Comment: which points are referred here, whose distances with the line is periodic ?
Comment: The closest lattice points. If your line is $y=7x/5 + \sqrt 2$ you can find the closest points with $x=0,1,2,3,4$, compute their distances, and take the closest.  Those distances will repeat in that order, for example the closest distance with $x=5$ will be the same (with the $y$ higher by $7$) than the distance with $x=0$, so you will have found the minimum.
Comment: however if y = (100000001/100000000) *x + 2 , then it would be difficult to find, as in both case we need to see a large number of values.
Comment: Years ago, somebody commented on an answer of mine that search this long finite list doesn't sound very helpful, but compared to search this infinite list it is quite an improvement.  In your example $(100000000,100000003)$ is exactly on the curve.  There may be a way to use continued fractions to guide you, but I haven't found it.


Stopping CSC with a GPO

Question: I have network drives mapped to my users.
If they lose network connection for any reason, it pulls up the client side cached version of it and lets the user work in that.
Now some duplicate files are popping up and people are seeing inconsistent versions of things.
I want to make it so that when a user loses network connection, they can't access the files. Period.
EDIT
I forgot to mention that my file servers are Linux-based samba shares
Answer: You don't need a GPO.  You just need to turn off the caching support on the shares they're connecting to.  The following instructions will vary slightly depending on the version of Windows hosting the shares, but the gist is the same.  They were written from a 2008 R2 server.

Open the Properties for the shared folder they're connecting to
Go to the Sharing tab
Click Advanced Sharing
Click Caching
Select the option for "No files or programs from the shared folder are available offline"
Comment: That makes a bunch of sense and I'll use that when I get put in my Windows-based file server structure, but I forgot to mention that my file servers are Linux-based
Answer: If you don't need "Offline Files" on any of your clients just disable it entirely using Group Policy. The "Allow or Disallow use of the Offline Files feature", located at "Computer Configuration\Administrative Templates\Network\Offline Files" in Group Policy will disable the feature computer-wide.
If you want to prevent caching of specific shares on your Samba servers you can use the "csc policy" configuration parameter in your smb.conf. You can find details here: http://www.samba.org/samba/docs/man/manpages-3/smb.conf.5.html#id2481437

Stopping CSC with a GPO