Documenting Job Schedules?

Question: Once upon a time, I thought I found the perfect way to document all scheduled jobs across all servers. I used Google Calendar and created a cal for each server and then added all the jobs as scheduled events. Worked really slick! (more details if curious).
Today I learned that repeating events on GCal max at 365, at which point you have to re-create or duplicate them. Since I've been adding new repeating events for the past year, they'll be "randomly" aging off for the next 11 months. I'm very sad.
Time to find a better way to document scheduled jobs!
How do you do it? I'm looking for a method that makes it pretty easy to see what tasks are scheduled for a server and/or what's scheduled for a certain time of day.
I have a few dozen servers to document, so the old "swim lane" style visio diagram is a bit too cumbersome.
[Edit]
Good suggestions so far, but I was hoping to learn that maybe I was making job sched documenting too tough and that there are tons of options out there... Not the case?
[Edit2] Feb 2010 -- I see that we can now repeat events up to 1000 times. That's a nice boost.
Comment: The response was simply -- what are all those tasks -- simply pure curiosity.  This site is about learning.
Comment: They are the tasks that keep my little empire running :-)  Backups, code promotions, various service restarts, etc. etc.  I know _what_ they are, I want to come up with a good way to document their schedules.
Answer: My second thought was to export the calendar files from google and use a script to create future files for re-import. (and add that to the jobs list ;-) That would depend on the maximum periodicity of the items I think.
Comment: Well, that may be easiest(?). I'm kind of looking for an option besides GCal... thoughts?
Comment: Thanks, Mike.

For the moment, I'll probably go with something along this suggestion. I'll confess, I was kind of hoping to get suggestions of other tools/methods, but since the cal thing [mostly] works...
Answer: I would think you'd be able to do something fairly similar by setting up your own CalDAV server and using a compatible client.  I think iCal, Kontakt (from KDE), Evolution, and maybe even exchange can read those files.
After reading your article, depending on your wiki software you might be able to find a plugin that reads the iCalendar format.
I thought about this a little more and I checked out a couple of the more popular wikis (mediawiki and tikiwiki) and it turns out that if you go the route of actually hosting your own calendars, you're in luck.  There are two plugins for mediawiki :
The Kenyu73 Calendar extension which actually reads the vCal/iCalendar format and The Barrylb calendar extension which doesn't mention if it does (I would suspect it does not).
Additionally, tikiwiki seems to have support for calendars built in (along with nearly everything else) and should probably support vCal/iCalendar format since its billed as a CMS/Groupware solution.
Answer: How do you want to use this information? Do you want alerts or are you simply looking for what amounts to as a daily to-do list? If Google's calendar isn't suitable there are any number of alternatives. As you've already mentioned Visio I'll assume you have at least some Windows in your environment, so what's wrong with Outlook's calendar? If you also have OWA it can be accessed from anywhere, should the need arise.
But... Do you really need a calendar at all? To my way of thinking nearly everything should be automated, coupled with a monitoring system to ensure it all works correctly, so there should be very little need for a calendar. Instead, just document the automation.
Comment: Good questions!
Ideally, I want to be able to see what's running where and when -- reasonably, at a glance. When I bring up a new server and need to schedule jobs I want to be able to spot the "open" times. If someone calls at 7PM and says everything is slow, I want one place to look to see what I have scheduled to run at 7PM (or 6:30).
Documentation!

Documenting Job Schedules?


Lemma 1.30 in Evan Chen's EGMO book

Question:
Page-15, Lemma 1.30: Points $A,B,C$ lie on a circle with center $O$. Show that $\measuredangle OAC= 90 - \measuredangle CBA$

Here we $\measuredangle CBA$ means the directed angle. I've seen this post and linked already but I think neither has solutions in the way which was intended by the hint for the question.
I think so I got the idea how to solve it, but I'd like my solution be checked because this is one of my first times working with directed angles. Here goes:
Proof:
Begin by constructing the reflection of $A$ about $O$, call it $A'$. Notice that $\triangle  ACA'$ is right angled at $C$, hence:
$$ 90 +\measuredangle A_o A C + \measuredangle CA_o A=0$$
And by the inscribed angle theorem, I note that $ \measuredangle CBA = \measuredangle CA_o A$ and also $\measuredangle A_o A C= \measuredangle OAC$, upon substituting, I get:
$$ \measuredangle OAC  + \measuredangle CBA = 90$$
Is my solution well written? How could I make it better?
Here is a drawing I used for 'thinking' about the set up(slight error , reflected should be $A'$ not $A_o$):

And for $B$ on other side:

Turns out that exact same argument as said for the other case applies here (if the first proof was valid).

Note: Acc. to Evan chen's book sum of directed angle is zero,

page-12
Comment: Your first equation with your three angles has two issues. It should equal 180 since you're talking about the angles in a triangle and also you switched your notation of the reflected point from $A'$ to $A_0$. Other than that, this seems fine to me.
Comment: Hmm I am using the directed angles @X Stanton
Comment: Okay, then it is fine as others have said.
Answer: Here is an alternative approach -

Say $\angle ABC = \theta \ $. By inscribed angle theorem,
$\angle AOC = 2 \angle ABC = 2 \theta$.
As $OA = OC$, $\triangle AOC$ is isosceles triangle. So,
$\angle OAC = \angle OCA = \dfrac{180^0-2\theta}{2} = 90^0 - \theta$
Comment: Hi Math Lover, in the book I"m using it is said as a property of directed angles that the total angle sum in a triangle is zero
Comment: @Buraian yes my mistake. You mentioned directed angles. As we use opposite signs for clockwise and anti-clockwise angles, it will  add to zero.
Comment: Ah, does my proof look logically correct? @Math Lover
Comment: @Buraian yes your proof is fine. You may also want to consider the case when $B$ is on the other side of $AC$.
Comment: Hi!! @Math Lover I did as you told and found it gave the same result. I'll upload a pic for that
Comment: @Buraian looks good. Yes it would give the same result but to complete the proof, considering both case may be nice and hence suggested.

Lemma 1.30 in Evan Chen's EGMO book


Resources for developing prognostic index-scores

Question: I am looking for online resources or books explaining how to develop prognostic indexes-scores step by step. I am mainly wondering about model validation and transformation of regression coefficients into scoring systems.
Answer: The following may be good places to start.

Clinical Prediction Models: A Practical Approach to Development, Validation, and Updating by Dr. E.W. Steyerberg
Regression Modeling Strategies: With Applications to Linear Models, Logistic Regression, and Survival Analysis by our moderator, Dr. Frank E. Harrell

I particularly like case studies. Dr. Harrell's book has one on "Predicting Cause of Death" and "Survival of Titanic Passengers". Dr. Steyerberg's book has a number of helpful case studies as well.


Weighted harmonic mean vs weighted geometric mean

Question:
Possible Duplicate:
Weighted geometric mean vs Weighted mean

I searched for the differences between WHM and WGM.
When to use each of them? when not?
Comment: The answers you got to [your previous question](http://stats.stackexchange.com/questions/37399/weighted-geometric-mean-vs-weighted-mean) are general enough to address this one, too.
Answer: Both mean functions are so-called generalized mean: f_s = ( (x1^s + ... + xn^s)/n )^(1/s).
For harmonic mean s=-1.0; for geometric mean s=0.0;  In general, for smaller s values, the generalized mean will move closer to smaller values in {x1,...,xn}. Thus, the harmonic mean will give you a mean value that biases more towards smaller values. Notice that if s is -infinite or +infinite, the generalized mean will give the minimum or maximum value in your values.
Comment: What if one of the values is zero ?
Comment: @Mohammed: if they are not all positive, you should consider whether either a geometric or a harmonic mean is meaningful
Comment: If your data is not all positive you can shift you data to positive range (ie. adding certain constants), then shift back after the mean operator. Actually, even all your data are positive you can consider shifting your data to appropriate range for what ever your purpose.


Carregar modal apenas uma vez

Question: Tenho um modal que é carregado depois do login (automatico), porem a cada refresh o modal abre, eu preciso que ele abra somente uma vez depois de logar.
<rich:modalPanel id="modal" autosized="true" width="500" height="200" showWhenRendered="#{true}">
        <f:facet name="controls">
            <h:graphicImage value="/img/fechando.png" onclick="Richfaces.hideModalPanel('modalMensagem')"
                id="botaoFechar" />
        </f:facet>
        <f:facet name="header">
            <h:panelGroup>
                <h:outputText value="Olá" />
            </h:panelGroup>
        </f:facet>

        <h:outputText value="#{bean.mensagem}" escape="true" style="font-size:15px;"/>
    </rich:modalPanel>

tela2.xhtml
<ui:define name="conteudo">
    <h:form id="main">
        <rich:messages styleClass="msgerro" globalOnly="true" />

            Olá

    </h:form>

    <ui:include src="/modal/modalMensagem.xhtml"/>
</ui:define>

BEAN
public String getMensagem() {
    return MENSAGEM;
}

Preciso de um metodo que entre de fato no false, pra abrir somente uma vez? Ja que o showWhenRendered por padrao é true.
Comment: Se você quer abrir apenas uma vez após o primeiro login, vai ter que gravar no banco de dados uma flag dizendo que já abriu uma vez. Caso você deseje abrir a primeira vez por sessão, pode colocar essa flag como um atributo da sessão e utilizar ele como condicional para não abrir a popup.
Comment: Tem algum exemplo, pra eu verificar como faz? Algum tutorial...
Comment: Caso não queira gravar no banco de dados, você pode gravar no local storage do usuário.
Comment: Algum exemplo? Pois não sei se criar um metodo setando false resolveria...
Answer: Eu adotaria a seguinte abordagem:
<rich:modalPanel id="modal" autosized="true" width="500" height="200" showWhenRendered="#{homePageMB.showWelcomeModal()}">
    <f:facet name="controls">
        <h:graphicImage value="/img/fechando.png" onclick="Richfaces.hideModalPanel('modalMensagem')"
            id="botaoFechar" />
    </f:facet>
    <f:facet name="header">
        <h:panelGroup>
            <h:outputText value="Olá" />
        </h:panelGroup>
    </f:facet>
    <h:outputText value="#{bean.mensagem}" escape="true" style="font-size:15px;"/>
</rich:modalPanel>

E em seu managed bean (o que eu dei o nome carinhosamente de HomePageMB), você teria uma checagem mais ou menos assim:
public class HomePageMB {
    ...

    private static final String CHECKED_WELCOME_MODAL = "checkedWelcomeModal";

    public boolean showWelcomeModal() {
        Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();

        if(sessionMap.get(CHECKED_WELCOME_MODAL) == null) {
            sessionMap.put(CHECKED_WELCOME_MODAL, true);
            return true;
        }

        return false;
    }
    ...
}

Com isso caso seja o primeiro login, a flag vai estar nula na sessão, e após ao voltar para a home page ele já vai ter a flag na sessão, e a modal não será aberta.
Como mencionei no comentário, existem outras soluções para este problema, depende da sua necessidade.
Comment: Bom demais sua ajuda, mas dessa forma, o modal não abre...
Comment: Eu não postei uma configuração completa do managed bean, você aplicou em um que está funcionando em seu projeto?
Comment: Sim, fiz no seu modelo implementando no meu.
Comment: Chegou a debugar pra ver se está retornando `true`? Se não está sendo realizado o evaluate depois da renderização da tela?

Carregar modal apenas uma vez


How to calculate different percentage of weight and round up or down depending on value

Question: I'm creating an app in JS that outputs the weight I should be lifting in the gym based on a weight I provide in an input element. The 'calculator' app for this will have predetermined values based on specific workout programs stored in  objects within an array. These will be called based on what workout is selected from the dropdown box.
One workout program for example utilizes unduluating periodization and so week one would be 65, 75 and 85% calculated from a training max. I understand I just need to do (weight / 100) * percentage to get the result. However, this doesn't factor in values that are not rounded/whole numbers, such as 102.5 or 112 for example, 117.5, 22.5 etc.
How could I implement this into my app?
EXAMPLE:
65% of 125(kg) is 81.25(kg)
PROBLEM:
81.25(kg) is not a weight you can put on the bar in most gyms, the closest weight would be either 80kg or 82.5kg
SOLUTION: Depending on choice, increase to 82.5(kg) or lower to 80(kg)

const workouts = [
  {
type: "531",
supp: "bbs",
amrap: true,
sets: {
  main: {
    percentages: {
      week1_1: 65,
      week1_2: 75,
      week1_3: 85,
      week2_1: 70,
      week2_2: 80,
      week2_3: 90,
      week3_1: 75,
      week3_2: 85,
      week3_3: 95,
    },
  },
  supp: {
    reps: 5,
    set1: 65,
    set2: 65,
    set3: 65,
    set4: 65,
    set5: 65,
  },
},
  },
];

function calculateNow(opt) // opt is this and this is input element with an oninput event listener {
  const allRadios = document.querySelectorAll(".drop-radio");
  const allText = document.querySelectorAll(".drop-result");
  const optParent = opt.classList[1];
  const inputWeight = opt.value;
  allRadios.forEach(function(radio) {
    if (radio.checked) {
      switch (optParent) {
        case "di-1":
          if (radio.classList.contains("r-1")) {
            const calcWk1S1 =
              (inputWeight / 100) * workouts[0].sets.main.percentages.week1_1 // 65;
            const number = calcWk1S1 % 1;
            console.log(calcWk1S1);
            if (number < 0.5) {
              allText[0].textContent = Math.floor(calcWk1S1);
            } else {
              allText[0].textContent = Math.ceil(calcWk1S1);
            }
            const calcWk1S2 =
              (inputWeight / 100) * workouts[0].sets.main.percentages.week1_2 // 75;
            allText[1].textContent = calcWk1S2;
            const calcWk1S3 =
              (inputWeight / 100) * workouts[0].sets.main.percentages.week1_3 // 85;
            allText[2].textContent = calcWk1S3;
          }
      }
    }
  });
}
Comment: Are you able to provide some kind of detail of some expected inputs and their equivalent outputs, along with what you have now that is incorrect? I wasn't quite able to tell from the question
Comment: Can you update to provide what `opt` is also along with the expected results previously asked for
Comment: FWIW I would suggest `calcWk1S1` be changed to avoid confusion with `calcWklSl` or `calcWk151`etc.
Comment: You should always lift a multiple of 750Lbs :) be superman
Comment: `workouts` is not defined here
Answer: Quick Answer
If you want to ensure all weight outputs are integers, you can just apply the Math.round() function before printing to the screen.
Also the const number = calcWk1S1 % 1; will always return 0 since all numbers mod 1 are equivalent to 0, so you need to remove that ;)
Updated code
Your final formula may look something like this:
const calcWk1S1 =
  (inputWeight / 100) * workouts[0].sets.main.percentages.week1_1;
allText[0].textContent = Math.round(calcWk1S1);
const calcWk1S2 =
  (inputWeight / 100) * workouts[0].sets.main.percentages.week1_2;
allText[1].textContent = Math.round(calcWk1S2);
const calcWk1S3 =
  (inputWeight / 100) * workouts[0].sets.main.percentages.week1_3;
allText[2].textContent = Math.round(calcWk1S3);

Optional optimization for readability and scalability
Or reduce the copy-paste by changing the hard-coded constants from:
workouts = [
  {
    sets: {
      main: {
        percentages: {
          week1_1: number,
          week1_2: number,
          week1_3: number
        }
      }
    }
  }
];

...to an array like this:
workouts = [
  {
    sets: {
      main: {
        percentages: {
          week1: [ number, number, number ]
        }
      }
    }
  }
];

And then you can reduce your code down to this:
allText.forEach((element, index) => {
  const weight = inputWeight * workouts[0].sets.main.percentages.week1[index] / 100;
  element.textContent = Math.round(weight);
});


Refresh a table after a selection of records

Question: I want to write a module with a textfield, a submit button and a table.
The starting page displays an empty textfield, the button and the table that shows all the records.
When the user writes something in the textfield, and clicks the button, the web page refreshes itself; then the table should contain only the records with the same Name Field as the string that the user wrote. Unfortunately, it doesn't works: The new page displays the same records shown before, even if the query produced a correct table.
This is the code I use.
function prova_db_advanced_list($form, &$form_state) {

  $form = array();

  $form['textfield_input'] = array(
    '#type' => 'fieldset',
    '#title' => t("Compilare i campi in base alla ricerca che si desidera effettuare.")
  );

  $form['textfield_input']['nome'] = array(
    '#type' => 'textfield',
    '#title' => t('Inserisci un nome'),
    '#size' => 15,
  );
  $form['textfield_input']['submit'] = array(
    '#type' => 'submit',
    '#value' => t("Find"),
  );

  $select = db_select('persone_prova_db', 'p');

  // Join the users table, so we can get the entry creator's username.
  $select->join('indirizzi_prova_db', 'i', 'p.residenza = i.id');

  // Select these specific fields for the output.
  $select->addField('p', 'id');
  $select->addField('p', 'cognome');
  $select->addField('p', 'nome');
  $select->addField('p', 'codice_fiscale');
  $select->addField('i', 'id');
  $select->addField('i', 'via_piazza');
  $select->addField('i', 'civico');
  $select->addField('i', 'comune');
  $select->addField('i', 'provincia');

  // Make sure we only get items 0-49, for scalability reasons.
  $select->range(0, 50);

  // Get all entries in the prova_db table.
  $entries = $select->execute()->fetchAll(PDO::FETCH_ASSOC);

  if (!empty($entries)) {
    $rows = array();
    foreach ($entries as $entry) {

      // Sanitize the data before handing it off to the theme layer.
      $rows[] = array_map('check_plain', $entry);
    }

    // Make a table for them.
    $header = array(t('Id Persona'), t('Cognome'), t('Nome'), t('Codice Fiscale'),
                t('Id Indirizzo'), t('Via/Piazza'), t('Num. Civico'), t('Comune'), t('Provincia'));
  }else {
    drupal_set_message(t('No entries meet the filter criteria.'));
  }

  $form['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('Empty Rows')
  );
 return $form;
 }
 function prova_db_advanced_list_submit($form, &$form_state) {
  drupal_set_message(t("Tabella"));
  drupal_set_message(t("Il nome inserito è @name_to_find",  array('@name_to_find'=>$form_state['values']['nome'])));
  $name_to_find = $form_state['values']['nome'];
  $select = db_select('persone_prova_db', 'p');

  // Join the users table, so we can get the entry creator's username.
  $select->join('indirizzi_prova_db', 'i', 'p.residenza = i.id');

  // Select these specific fields for the output.
  $select->addField('p', 'id');
  $select->addField('p', 'cognome');
  $select->addField('p', 'nome');
  $select->addField('p', 'codice_fiscale');
  $select->addField('i', 'id');
  $select->addField('i', 'via_piazza');
  $select->addField('i', 'civico');
  $select->addField('i', 'comune');
  $select->addField('i', 'provincia');
  $select->condition('p.nome', $name_to_find);

  // Make sure we only get items 0-49, for scalability reasons.
  $select->range(0, 50);

  // Get all entries in the prova_db table.
  $entries = $select->execute()->fetchAll(PDO::FETCH_ASSOC);

  if (!empty($entries)) {
    $rows = array();
    foreach ($entries as $entry) {
      // Sanitize the data before handing it off to the theme layer.
      $rows[] = array_map('check_plain', $entry);
    }
    drupal_set_message(t("Table: @rows", array('@rows' => $rows)));
    $form['table']= array('#type' => 'value', '#rows' => $rows);
      $form_state['rebuild'] = TRUE;
  }else {
    drupal_set_message(t('No entries meet the filter criteria'));
  }
}

I don't understand where I'm wrong. I searched if someone else have the same trouble, but I haven't found the way to solve this problem.
Can anyone help me?
Comment: As side note, the string passed to `t()` needs to contain English words, as the translation is done from English to the language currently for the site.
Answer: $form is an array that is not passed as reference to the form submission handler; therefore, any change done to $form from the submission handler is local to the form submission handler. This is similar to what happens with the following code.
$array = array('a' => 10);
$array = update_array($array);
check_array($array);

function update_array($array) {
  return $array + array('b' => 20);
}

function check array($array) {
  $array['b'] = 30;
}

After that code is executed, $array['b'] is still equal to 20.
The only parameter that is passed by reference is $form_state. If you want to pass a value back to the form builder, from the form submission handler, or the form validation handler, you need to use $form_state, which mean the form submission hander should use code similar to the following one.
$form_state['table_rows'] = $rows;

The form builder should use the following code.
if (!empty($form_state['table_rows']) {
  $rows = $form_state['table_rows'];
}
else {
  // Execute the query that gets every row in the database table.
  // Assign the found rows to $rows.
}

$form['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('Empty Rows')
);

The values you are placing in $rows is wrong. What you are using in an array similar to the following one.
array(
  'column 1 name' => 'column 1 value',
  'column 2 name' => 'column 2 value',
)

The array theme_table() is expecting is one of the following.
  array(
    'column 1 value', 'column 1 value', 'column 2 value'
  )

 array(
    'data' => array('column 1 value', array('data' => 'column 2 value', 'colspan' => 2)), 'class' => array('column-class')
  )

Supposing the changes to the content of $form would be propagated externally to the form submission handler, the code for the form builder is writing $form['table'] without first checking if$form['table']is set; this would mean losing the value for$form['table']` set from the form submission handler.


How to change a text on the click of a button in android?

Question: I need to set text of a button by taking value from edit text ,when button is clicked it has to change its text to the text specified in Edittext.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button btn=(Button)findViewById(R.id.button);
    assert btn != null;
    btn.setOnClickListener(
            new View.OnClickListener(){

                public void onClick(View v)
                {
                    TextView txt=(TextView)findViewById(R.id.editText);
                    btn.setText((CharSequence) txt);

                }
            }

    );
}

Comment: This "text" you are talking about is in what format? A label or in a text field??
Answer: you just need define EditText variable instead of TextView and call getText method of editText and then toString method like this:
final Button btn=(Button)findViewById(R.id.button);
assert btn != null;
btn.setOnClickListener(
        new View.OnClickListener(){

            public void onClick(View v)
            {
                EditText txt = (EditText)findViewById(R.id.editText);
                btn.setText(txt.getText().toString());
            }
        }

);

Answer: Declare your views globally
Button btn;
EditText txt;

set your id in onCreate method
btn=(Button)findViewById(R.id.button);
txt=(EditText)findViewById(R.id.editText);

keep your onclicklistener as follow
    btn.setOnClickListener(
            new View.OnClickListener(){

                public void onClick(View v)
                {
                 final String newText=txt.getText().toString().trim();
                 if(newText.length()>0){
                    btn.setText(newText);
                 }

                }
            }

    );

Answer:         final Button btn = (Button)findViewById(R.id.button);
        if (btn != null) {
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    EditText et = (EditText)findViewById(R.id.editText);
                    if (et != null){
                        Button btn = (Button)view;
                        btn.setText(et.getText());
                    }
                }
            });
        }


set references in the XML file to XSLT and XSD files which are packed into archive

Question: Is it possible to set references in the XML file to XSLT and XSD files which are packed into some archive? If so, how can you do it?
Answer: From what I can tell, there is no generic, platform independent, interoperable way to set this up.
Each framework (Java, .NET, etc.) would have its own out of box approaches (or not), which is typically linked with:

supported URI schemes
how XML parsers resolve external references;
support for external references.

It also depends a lot on how you expect these references to work for you, how you want the references to look like, which drives how those can be resolved at parsing time.
If you want everything done by the XML parser, you may want to look at XInclude and alike, using a URI scheme supported for your archive; if there is one, e.g. in Java you could try jar://, then this is your solution.
If your scheme is not supported but your platform allows to define new handlers, or override existing ones, for URI schemes, then it might be solved simply with your custome handler.
Another alternative is to build you own helper "service" that augments the standard parsing, and while at it, it scans the XML for your specific external reference nodes, and it replaces those reference nodes with content pulled from your external references, coming from your archive.
The only other serious problem I see is when your XSLT and XSD are authored across multiple files.
Comment: @Bush, I believe browsers are pretty limited to what they would be able to reference, say in an xml-stylesheet processing instruction; if the XSD is to be referenced for validation purposes, through schemaLocation or noNamespaceSchemaLocation, then browsers typically don't process these attributes. XML content is generally opaque to browsers, except for processing instructions, or when the mime type is something for which they have a plugin defined. It is still not clear to me exactly how the interaction would be between these: browser, XML, external references...
Comment: it is necessary for me, that it worked in the browser, without necessity of installation of additional platforms and libraries.


Multiple select (drop down list) Laravel using Laravel Collective

Question: Hey guys I have a project-create form where I want an the ability to select multiple users for a project
So far I've achieved this much:
Hey guys, so here's my code and what I want is different

 User :

    @foreach($users as $value)
     {{ Form::checkbox('user[]', $value->id, false,
    array('class'=>'name')) }}
            {{ $value->name }}

    @endforeach

My ProjectController.php
 public function create()
  {
    //
    $users = User::all();

    return view('admins.projects.create', compact('users'));
  }

Now this works just fine, the thing is I get multiple checkboxes and it's messy.
I'm using Admin LTE and I want to use the following html snippet instead of Checkbox code:

   Multiple
      <select class="form-control select2" multiple="multiple" data-
 placeholder="Select a State" style="width: 100%;">
       <option>Alabama</option>
       <option>Alaska</option>
       <option>California</option>
       <option>Delaware</option>
       <option>Tennessee</option>
       <option>Texas</option>
       <option>Washington</option>
      </select>

This design is a better and less messy alternate to checkboxes.
I am not able to make it work by changing it to
LaravelCollective docs:
Form::select('size', array('L' => 'Large', 'S' => 'Small'), null,
array('multiple' => true));

Can someone help me?
Answer: Something I always use is:

     {!! Form::label('users[]', 'Role') !!}
     {!! Form::select('users[]',$users,  null, ['class' => 'form-control', 'multiple']) !!}

Where you have to hold the CTRL button to select multiple users. The [] is important because php otherwise will not reconize the input as an array.
If you want something more fancy you can try something like this: https://github.com/davidstutz/bootstrap-multiselect
Comment: Thanks for your response, I'll try bootstrap-multiselect


Creating static pages on production from a local module

Question: This question could have multiple types of answers, so I'll take anything you guys have to offer.
I have to transform an XML feed into a set of Pages (content-wise).  Currently, I have a module I'm developing locally using PHP and SimpleXML in order to dynamically simulate these pages (so, each page being rendered is a completely dynamic thing controlled by the module).
I need to take this output and create a set of static pages on a production server.  One painful thought I had was to render each page, copy the generated HTML, and physically create a new node.  As there are a lot of pages being generated, this would be a long and drawn out process.
What would be nice is for some method to render all these pages in one go, and then somehow push them to my production Drupal installation.
A caveat, which would be more in the nice to have category is that it is possible for the XML feed to change.  So, it'd be nice to, for instance, mark the changed text in a different color, or produce a new revision, or something along those lines.
I am using Drupal 6 (with no plans to upgrade).

I'll add an extra specific on this question.  At present, I am using SimpleXML to walk through my feed, and using PHP to dynamically create an HTML tags I need.  Essentially, I'm building up a string of HTML that gets returned from the module (in a _module_generate() function), which is then displayed by Drupal.  If there is an easy way to take this, perhaps turn it into a Cron job, and have it produce some kind of output for the Feeds module (thanks @Clive), then that may be the easiest thing for me to do.
Comment: Have you come across the [Feeds module](http://drupal.org/project/feeds)? That plus the [Diff module](http://drupal.org/project/diff) should get you most of the way there I think
Comment: I have, but the issue is that I have to do some pretty hefty transformations to the XML feed (hence the local PHP module)
Comment: So @Clive, I read a bit more into Feeds and saw that it can easily import data from CSV and other formats.  Is there an easy way to convert my dynamically created HTML pages (essentially just a string of HTML being returned from the module), to such a format for Feeds to read?
Answer: Method I ended up using:

Procedurally create nodes on local environment, parsing XML feed with SimpleXML
Hardlink to production server when crosslinking nodes
Use Node Export to export/import nodes from local to production server
Use pathauto on production to create node aliases


Customize class attribute on div tag using ExtJS

Question: What is the best way to customize the class attribute on a div tag. For example, when using Ext.Component, the div tag that gets generated by default is

...

But I just want to create a component with a custom class, like

...

What would be the best way to approach doing that?
If I do use something like
Ext.create('Ext.Component', {
    ...
    baseCls: 'some-class'
});

I still get

...

I don't really have to use the Ext.Component object if something better is recommended. Im just starting with what I know.
Any help is greatly appreciated. Thank you.
Answer: "some-class-default" is coming from the ui cls which resolves to 'default' by default.
Take a look at this fiddle where I've overriden Component to not add the default ui.
Ext.define('Overrides.Component', {
    override: 'Ext.Component',

    baseCls: 'myComponent',
    borderBoxCls: '',
    setUI: function(ui) {
        var me = this;
        if (me.rendered) {
            me.updateLayout();
        }
    }
});

Ext.application({
    name : 'Fiddle',

    launch : function() {
        Ext.create('Ext.Component', {
            itemId:'myComponent',
            html:'My Component',
            renderTo:Ext.getBody()
        })
    }
});

Comment: So you've just defined a new class and instead of extending it, you used the override attribute. That was very helpful. Thank you.


How to read the notations in the proof of the inclusion-exclusion principle?

Question: This question is a follow up to this question.
How do I create a sequence from this formula?

$\sum\limits_{i=1}^{n} P(A_i) - \sum\limits_{1\le i < j \le n-1}P(A_i \cap A_j) + \dots + (-1)^n P(A_1 \cap A_2 \cap \dots \cap A_{n-1})  - \left[ \sum\limits_{i=1}^{n-1}P(A_i \cap A_n) - \sum\limits_{1\leq i < j \leq n-1}^{n-1}P(A_i \cap A_j \cap A_n) + \dots + (-1)^nP(A_i \cap A_2 \cap \dots \cap A_{n-1}\cap A_n)\right]$

My confusion is in interpreting $(-1)^n P(A_1 \cap A_2 \cap \dots \cap A_{n-1})$ and $(-1)^nP(A_i \cap A_2 \cap \dots \cap A_{n-1}\cap A_n)$.
Take $(-1)^n P(A_1 \cap A_2 \cap \dots \cap A_{n-1}$ as an example. I don't know where $n$ should begin. I thought it is $1$ but if $n=1$ then the first term, $\sum\limits_{i=1}^{n}P(A_i)$, should have a negative sign because $(-1)^1=-1$. Since this is not the case, it must mean that $n$ starts from 2. But this not mentioned anywhere in the theorem.
Lastly, based on Antoine's answer, how do I formally complete the proof? I can see that the missing terms in the first line can be found in the second line and that the final term in the second line will always be the last term as per the theorem. But I don't know the sequence of steps to write so that the end of this proof is a formula as per the theorem.
Comment: Notice how this is $$P(A_1 \cap \ldots \cap A_{n-1})$$ And $A_0$ isn't really defined at all; you get $P(A_1)$ with $n=2$
Comment: Note for $n=1$ you have $P(\emptyset) = 0$ so all is fine.
Comment: @AlexR I thought if $n=1$, then I should end up with $P(A_1)$. If that is not the case, how do I get $P(A_1)$ from this formula?
Comment: @AlexR Thanks. I understand it now. But I still don't know how to formally complete the proof. Would you be able to help?
Comment: Well, just take the $(-1)$ in front of the brackets and multiply it. notice $i\leq n-1 \Rightarrow i<n$ to complete.
Answer: $$\sum\limits_{i=1}^{n} P(A_i) - \sum\limits_{1\le i < j \le n-1}P(A_i \cap A_j) + \dots + (-1)^n P(A_1 \cap A_2 \cap \dots \cap A_{n-1})  - \left[ \sum\limits_{i=1}^{n-1}P(A_i \cap A_n) - \sum\limits_{1\leq i < j \leq n-1}^{n-1}P(A_i \cap A_j \cap A_n) + \dots + (-1)^nP(A_i \cap A_2 \cap \dots \cap A_{n-1}\cap A_n)\right] = \sum_{k=1}^n \sum_{|\alpha| = k} (-1)^{k + 1} P\left(\bigcap_{i=1}^{|\alpha|}A_{\alpha_i}\right)$$
Where $\alpha \in ([1,n]\cap\mathbb N)^{k}$ is a multiindex with $i < j \Leftrightarrow \alpha_i < \alpha_j$ and $|\alpha|=k$ is its length.
Just try to formalize it a bit. You'll notice that for example
$$\sum_{1\leq i<j\leq n-1} P(A_i\cap A_j) + \sum_{i=1}^{n-1} P(A_i \cap A_n) = \sum_{1\leq i<j \leq n} P(A_i \cap A_j) = \sum_{|\alpha| = 2} P(A_{\alpha_1} \cap A_{\alpha_2})$$

See here, page 215 for a brief explanation ("principle of inculsion and exclusion")
Comment: The notation $\alpha \in [1,n]_{\mathbb N}^{k}$ is new to me. Is there some online site I can read up to better understand it (along with examples)?
Comment: $[a,b]_{\mathbb N}$ is a short version of $$[a,b] \cap \mathbb N$$
The exponent $k$ is just the $k$-dimensional carthesian product of the set. $\alpha$ is a vector of length $k$ containing strictly increasing natural numbers between $1$ and $n$.

@mauna I also added a reference in the post ([this](http://www.math.dartmouth.edu/archive/m19w03/public_html/Section6-2.pdf)). Does it help?
Comment: yes, I finally got it! Thanks so much for your help.


Proof that $[x+n] = [x] + n$ for all reals $x$ and all integers $n$

Question: Let
$$[x] := \sup \{n \in \mathbb{Z} \mid n \leq x \}$$
for all reals $x$.
I want to prove that, if $x$ lies in $\mathbb{R}$ and $n$ lies in $\mathbb{Z}$, then
$$[x+n] = [x] + n.$$
Nevertheless,
by definition I have
$$[x] + n \leq x + n,$$
and
$$[x+n] \leq x+n.$$
But then?
What do I miss?
Answer: Suppose $\;k\le x<k+1\;,\;\;k\in\Bbb Z\;$ , then
$$\forall\,n\in\Bbb Z\;,\;\;k+n\le x+n<(k+1)+n\implies$$
$$\lfloor x+n\rfloor=k+n=\lfloor x\rfloor+n$$
Comment: @Kurt My pleasure. Its simplicity adds to its beauty, imo.
Answer: $$\begin{align*}[x+n]&=\sup\{k\in \mathbb Z\mid k\le x+n \}=\sup\{k\in \mathbb Z \mid k-n \le x\}\overset{k-n\to m}=\\&=\sup\{m+n \in \mathbb Z \mid m \le x\}=\\&=n+\sup\{m\in \mathbb Z\mid m \le x\}=\\&=n+[x]\end{align*}$$


Validate twitter URL

Question: I am trying to validate a twitter url, so that at least it contains a username. I do not care if it exists or not, just that there is one.
I am using the below javascript regex
var re = new RegExp('((http://)|(www\.))twitter\.com/(\w+)');
alert(re.test('http://twitter.com/test_user'));

but it is not working.
The strange thing is that I created and tested the above regex at this URL
http://www.regular-expressions.info/javascriptexample.html
where it works just fine.
Any ideas?
Thanks
Answer: function isTwitterHandle(handle) {
  if (handle.match(/^((?:http:\/\/)?|(?:https:\/\/)?)?(?:www\.)?twitter\.com\/(\w+)$/i) || handle.match(/^@?(\w+)$/)) return true;
  return false;
}

Comment: This may be the correct solution, but I think a little explanation of the code would be good for better understanding.
Answer: You need to escape the backslashes in the escape sequences too:
var re = new RegExp('((http://)|(www\\.))twitter\\.com/(\\w+)');

And I would recommend this regular expression:
new RegExp('^(?:http://)?(?:www\\.)?twitter\\.com/(\\w+)$', 'i')

Comment: Thank you all for the clarification
Much appreciated
Answer: It's because of the way you're defining the regex by using a string literal. You need to escape the escape characters (double backslash):
'^(http://)?(www\.)?twitter\.com/(\\w+)'

In the above, I also changed the start so that it would match http://www.twitter.com/test_user.
Alternatively, use the RegExp literal syntax, though this means you have to escape /:
var re = /^http:\/\/)?(www\.)?twitter\.com\/(\w+)/;

Answer: -http://twitter.com/username (this is http)
-https://twitter.com/username (this is https)
-twitter.com/username (without http)
-@username( with @)
-username (without @)
var username  = "@test";
    var r1 = new RegExp('^((?:http://)?|(?:https://)?)?(?:www\\.)?twitter\\.com/(\\w+)$', 'i');
            if (r1.test(username) == false) {
                var r2 = new RegExp('^@?(\\w+)$', 'j');
                if (r2.test(username) == true)
                    return true;
                else
                    return false;
            } else {
                return true;
            }

Validate twitter URL


Install GD Library for PHP in GoDaddy VPS with CentOS???

Question: When I tried to install php-gd library in my GoDaddy VPS with CentOS, It gives:
$ yum install php-gd
Loaded plugins: fastestmirror
Determining fastest mirrors
addons                                                    | 951 B     00:00
base                                                      | 2.1 kB     00:00
extras                                                    | 2.1 kB     00:00
update                                                    | 1.9 kB     00:00
Excluding Packages in global exclude list
Finished
Setting up Install Process
No package php-gd available.
Nothing to do

Answer: First, check if the package wasn't excluded. Open up the yum config with vi /etc/yum.conf and look for a line starting with exclude=if php-gdor php*is mentioned, remove it.
Sometimes VPS-hosters won't allow you to use some packages because they hog memory. So you might want to check you aliases by running aliasand check if there is no alias for yumwith an exclude-option.
Otherwise you could use RPMForge to install this package:
wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.i386.rpm
rpm -Uhv rpmforge-release-0.5.2-2.el5.rf.i386.rpm
yum update && yum install php-gd

Answer: This is the command that failed:
yum --exclude=kernel* -y install gettext automake19 libpng-devel openssl libpng-dev zlib-devel autoconf261 libidn-devel gmake libidn libXpm openssl-devel automake coreutils patch libstdc++-dev libltdl3-devel libltdl libopenssl0.9.7-static-devel libtool-ltdl-devel libXpm-devel sed libXpm-dev lsof krb5-dev flex glibc-dev expat-dev krb5-devel xorg-x11-devel libtool-ltdl libssl-dev pam-devel libopenssl0-devel zlib1-devel expat-devel libopenssl0-dev glibc-devel expat gcc-c++ zlib libstdc++ bison libstdc++-devel libjpeg-devel libtool-libltdl-devel libtool openssl-dev libopenssl0 libz-devel libjpeg-dev pam-dev fileutils libltdl-devel libopenssl0.9.7-devel e2fsprogs-devel ca_root_nss make libX11-devel libstdc++-devel.x86_64 gd cpp xorg-x11-dev gcc ssl-dev autoconf lex

Since EasyApache was unable to resolve it automatically you should:
         1) Manually run the failed YUM command (shown above) via SSH
         2) See if your particular error is addressed at http://www.cpanel.net/support/could_not_ensurepkgs.htm
         3) Resolve the YUM problem manually
         4) Re-run EasyApache

When running that command as suggested by the output
above, you would see openssl conflicts between the i386 and
i686 packages:
Transaction Check Error:
 package openssl-0.9.8e-12.el5_5.7.i686 is already installed
 file /lib/.libcrypto.so.0.9.8e.hmac from install of openssl-0.9.8e-12.el5_5.7.i686 conflicts with file from package openssl-0.9.8e-12.el5_5.7.i386
 file /lib/.libssl.so.0.9.8e.hmac from install of openssl-0.9.8e-12.el5_5.7.i686 conflicts with file from package openssl-0.9.8e-12.el5_5.7.i386
 file /lib/libcrypto.so.0.9.8e from install of openssl-0.9.8e-12.el5_5.7.i686 conflicts with file from package openssl-0.9.8e-12.el5_5.7.i386
 file /lib/libssl.so.0.9.8e from install of openssl-0.9.8e-12.el5_5.7.i686 conflicts with file from package openssl-0.9.8e-12.el5_5.7.i386
 file /usr/bin/openssl from install of openssl-0.9.8e-12.el5_5.7.i686 conflicts with file from package openssl-0.9.8e-12.el5_5.7.i386
 file /usr/lib/openssl/engines/lib4758cca.so from install of openssl-0.9.8e-12.el5_5.7.i686 conflicts with file from package ( ... )
To fix this for you, I ran this command:
# rpm -e --nodeps --justdb openssl.i386

Next, I ran the yum command again, and it was successful.
Finally, I ran /scripts/easyapache, and it is running now. When
complete, there will be support for the gd php module.
Answer: its definitely a package in Centos 5.5
is this vps cpanel? if so you have to install the gd library from the easyapache installer available in whm because by default on cpanel it disables php packages from being installed as it will break cpanel or parts of it
Answer: EasyApache on WHM only installs Zlib under GD. No info about how to install GD2 [for image manipulation for CodeIgnitor v2.0] in goDaddy Linux VPS cpanel


Cannot store oauth token in session (rails)

Question: K guys, so I was workign with the dialybooth api, and OAauth, so first, I had straight up
 #first redirect the user to the authorize_url
  redirect_to dailybooth.authorize_url

 #on user return grab the code from the query string
 dailybooth.oauth_token(params[:code])

 #make request to the api
 pp dailybooth.get('/users.json')

Problem was, it would constant redirect, because it wasn't even checking if the oauth_token was set, so then I did this;
unless dailybooth.oauth_token(params[:code])
 #first redirect the user to the authorize_url
 redirect_to dailybooth.authorize_url

 #on user return grab the code from the query string
 dailybooth.oauth_token(params[:code])
end

#make request to the api
pp dailybooth.get('/users.json')

Now, this send me to the dailybooth authorization page, the user authorized, then was sent to my page, and I gained access to their account (an array with the user info was returned), thing is if you refreshed the token did not exist anymore, and the user had to re-authorize.
So what I tried was to store the oauth_token in a session,
if session[:oauth_code]  #If session is set
  dailybooth.oauth_token(session[:oauth_code]) #sign in using cookie
else
  if params[:code]
    @oauth_token_ = params[:code]
    session[:oauth_code] = @oauth_token_
  else
      #first redirect the user to the authorize_url
      redirect_to dailybooth.authorize_url
  end
end

#make request to the api
@info = dailybooth.get('/users.json')

if @info['error']
  if @info['error']['error_code']
    if @info['error']['error_code'] == 302 #if getting invalid token, request another token.
      session[:oauth_code] = nil
      #first redirect the user to the authorize_url
      redirect_to dailybooth.authorize_url

    end
  end
end

I'm still getting the same thing, when I first go to my website, and I'm redirected to the authorization page, it authorities, then I get access to the account, but when I try to go back to the index, it says the oauth_token is invalid. Any help?
Answer: I'll be honest, I'm not 100% sure (and DailyBooth's API documentation is...lacking, to say the least), but I believe that you use the "token" (the one you're getting from params[:code] and storing in @oauth_token_) to get an access token, and then store the access token (e.g. store the result form dailybooth.oauth_token(session[:oauth_code]) instead, or at least a portion of it, if it's an object/array).
unless session[:oauth_code] #unless the session is set
  if params[:code]
    session[:oauth_code] = dailybooth.oauth_token(params[:code])
  else
    #first redirect the user to the authorize_url
    redirect_to dailybooth.authorize_url
  end
end

#make request to the api
@info = dailybooth.get('/users.json')

if @info['error']
  if @info['error']['error_code']
    if @info['error']['error_code'] == 302 #if getting invalid token, request another token.
      session[:oauth_code] = nil
      #first redirect the user to the authorize_url
      redirect_to dailybooth.authorize_url

    end
  end
end

I hope this points you in the right direction.


Powers of infinite cardinals in the generic extension

Question: Let $\kappa, \lambda,\theta$ be infinite cardinals of $M$ where $M$ is a transitive model of ZFC. Let $\mathcal{P}=Fn(\kappa\times \omega,2)$ (finite functions from $\kappa\times \omega$ to 2) and G is a (M,P)-generic set. I want to show $(\lambda^\theta)^{M[G]}=(max(\kappa,\lambda)^\theta)^M$. One direction is easy $(\lambda^\theta)^M \leq (\lambda^\theta)^{M[G]}$ and $(\kappa^\theta)^M\leq (\kappa^\theta)^{M[G]}\leq ((2^\omega)^\theta)^{M[G]}=(2^\theta)^{M[G]}\leq (\lambda^\theta)^{M[G]}$ where $(\kappa \leq 2^\omega)^{M[G]}$ is by the forcing construction. But now I am not quite sure how to get the other direction. Any thoughts?
Comment: a small typo - it should be $\kappa \le 2^\omega$ in the last claim.
Comment: @Eran: Definitely!
Answer: This is exercise (G1) in K.Kunen "Set Theory".

If $\lambda \le \theta$ then $\lambda^\theta = 2^\theta$ and using lemma VII 5.13 we get the result.
If $\lambda \gt \theta$ then using lemma 5.5 we can approximate this power in V ("up to $\omega$"), hence $(\lambda^\theta)^{M[g]} \le ( (\lambda^\omega))^\theta )^M = (\lambda^\theta)^M$
Comment: Thanks. I understand the second point. But I'm not sure if I get the first point. Is there a formal way of stating this?
Comment: I have edited my answer. Hopefully now it works.
Comment: For the second point, in $M[G]$ each $f:\theta \mapsto \lambda$ will have a corresponding $F\in M$: $\theta \mapsto \lambda^\omega$, but this may not be 1-1 right?
Comment: nope, but it doesn't really matter as we count all options (worst case is if it is 1-1).
Comment: I see. Each $F\in M$ can accommodate at most $\theta^\omega$ (in M) different functions in M[G].


Domain Key not showing up in DNS query

Question: *SOLVED - See bottom of this post *
So problem here is that I have been trying to set up a domain key for several days. I've done it successfully in the past, but I just can't get it to work this time.
Now the problem I am currently wrestling with is that when I try and look up the domain key in my DNS record, nothing appears.  For example, when I go to protodave, and search for my selector (default) at my domain, here is what I get:
 DNS QUERY: default._domainkey.palabama.com
 QUERY STATUS: No DNS TXT Record found
 TXT RECORD:

When I try and dig the record, I get no answer section.
When I go to DKIMcore, I get the following:
 This is not a good DKIM key record. You should fix the errors shown in red.
 DNS query failed for 'default._domainkey.palabama.com':NOERROR
 A public-key (p=) is required

Thing is, I have set up the DK on my registrat's DNS, which is the assigned dns (namecheap).
After several different tries, here is my setup on namecheap
 default._domainkey.mail.palabama.com.   TXT  v=DKIM1; g=*; k=rsa;      p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0kOjYjN2gAfTuQgsyS/rGUcMbZ3zg5Pf5pHyN735OufSnkLbpYgnDJcIyQTjhbeGBPoPwlvL1fOa1/TOsp2vT9fFIFtgGXg8yVpSKrttdOCX7a3CYkQIO4WQU+2MAzT+Z3IBroTBDmjS61fhRSyoUlPBhUYTECodVu3GENkoLUQIDAQAB

 default._domainkey.palabama.com.   TXT  v=DKIM1; g=*; k=rsa;      p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0kOjYjN2gAfTuQgsyS/rGUcMbZ3zg5Pf5pHyN735OufSnkLbpYgnDJcIyQTjhbeGBPoPwlvL1fOa1/TOsp2vT9fFIFtgGXg8yVpSKrttdOCX7a3CYkQIO4WQU+2MAzT+Z3IBroTBDmjS61fhRSyoUlPBhUYTECodVu3GENkoLUQIDAQAB

I threw that mail.palabama.com. record in thinking that maybe, because my MX record is set to mail.palabama.com. that it would help, originally that line was not in the DNS, and that didn't change anything.
When I verify the actual string at DKIMcore, it tells me everything is valid.  It's just like the damn record doesn't exist.  It's set to a TTL of 300 btw.
Here is the dig for my MX record
 dig palabama.com MX
 ; <<>> DiG 9.8.4-rpz2+rl005.12-P1 <<>> palabama.com MX
  ;; global options: +cmd
 ;; Got answer:
 ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 12713
 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

 ;; QUESTION SECTION:
  ;palabama.com.                  IN      MX

 ;; ANSWER SECTION:
 palabama.com.           1800    IN      MX      10 mail.palabama.com.

What am I doing wrong? I'm pulling my hair out with this one.
EDIT: SOLVED!!!
I have fixed it!  Hallelujah!  Thanks to TheCompWiz for his answer, which basically confirmed to me that I was not crazy and that barring all user mistakes, the problem was on my DNS server's end.  I tried something as an experiement...instead of putting in
 default._domainkey.palabama.com

I eliminated the palabama.com, leaving only
 default._domainkey

in my server record.  And boom, just like that it worked.
I think that it's important, though, to find out if that is actually how the entry should read, and all that I read was wrong, or its a quirk of namecheap's DNS servers that the domain should be left off the string.  And also if that is the case for any other servers.
Comment: Welcome to Server Fault!  Per our Q&A structure, we recommend that instead of editing solutions into your question, you add your own answer - this way, you can get reputation for your solution!
Comment: DNS names end with periods or assume your origin. Sounds like namecheap is properly titled.
Comment: Having the same problem with Namecheap... When you changed the TXT records to `default._domainkey` did you have to wait for the DNS to propagate?
Comment: your updated answer saved my day
Answer: Whether or not you added them to your registrar's DNS servers... I cannot say.  What I can say, is that the records are not publicly resolvable.  Are you sure you didn't define the records as SRV or A records?  If you're 100% sure you added them properly... it's time to call Namecheap... and talk to them.  Maybe they have issues hosting TXT records.
Comment: I solved it by changing default._domainkey.palabama.com to just default._domainkey  Should I have done this all along or is that just a quirk of namecheap?  Thanks again
Comment: sounds like a quirk with namecheap.  Ending a DNS name with a dot means it's a FQDN... whereas... just the hostname is typically interpreted as a child of the current zone.  i.e. "www" in the example.com domain vs "www.example.com."  Glad you got it figured out.  And FWIW... MX is just another record type.  It would not affect any TXT records.
Comment: I did, absolutely made them TXT.  Does the MX configuration make any difference in how it gets looked up?  Thanks!
Comment: That is good to know. I am sure I'll need to set dk up again sometime. Thanks again for your help and the follow up.
Answer: As indicated in the edit to the question, changing from e.g. default._domainkey.example.com to default._domainkey resolves the problem.
It looks like Namecheap appends the domain name, so default._domainkey.example.com becomes default._domainkey.example.com.example.com.
To test this theory I did a DNS lookup:
nslookup -q=TXT default._domainkey.example.com.example.com

Sure enough, there was the TXT record. A quick check of TXT records on MXToolBox confirmed it as well.
Answer: [SOLVED] Basically, I had the same issue. Added DKIM (CNAME) and SPF (TXT) records in Namecheap for Mailchimp integration but got this message from Mailchimp.
We tried to verify your DNS changes and did not detect the right values
The issue is Mailchimp asks for this string to be added in the host field.
k1._domainkey.domainname.com
But as someone suggested above, in Namecheap you don't need to include the domainname. In my case for mailchimp, just k1._domainkey was enough. I double-checked with the Namecheap guys. They confirmed it and pointed me to this guide.
https://www.namecheap.com/support/knowledgebase/article.aspx/9845/2208/how-to-connect-a-domain-to-mailchimp
Just one more trick. Mailchimp continued to show me the error even after DKIM check was right. (Tool here: https://toolbox.googleapps.com/apps/dig/#CNAME/k1._domainkey.dasubhashitam.com)
What I did was remove the verification in mailchimp and do it again as suggested in the guide. Voila! Things worked. And I wasted two days on this.
Hope it helps somebody.
Answer: What solved for me was NOT using the domain name as selector name. Never have a DNS entry that's like
website._domainkey.website.com.

using
def._domainkey.website.com.

worked for me!
Answer: A solution that worked for me on GoDaddy's DNS Manager was to use:
"dkim._domainkey" in the Host section (no quotations)
"v-DKIM .... " in the TXT Value, with the entire key included.
Before, I was simply using "_domainkey" and that wasn't working.
Answer: What you were missing from the beginning was the trailing (dot) in default._domainkey.palabama.com it should have been default._domainkey.palabama.com.

Domain Key not showing up in DNS query


Transition of SVG circle position results in truncation while moving

Question: I have a number of <circle> elements each inside their own <g>.  To move the circles around I'm applying a "translate" transform on each <g>.
What I notice is that as the circles are moving, some of them seem to get slightly truncated.  As soon as they come to rest they look just fine so it is just while they are in motion. The truncation effect looks something like what you'd see if you had a square viewport the same size as the circle and then moved the circle slightly out of centre.  It just flattens slightly on one side.
This is what one of my element groups looks like:
<g class="datapoint dot" transform="translate(360,56)">
    <circle class="rendering" style="fill: #3182bd; stroke: #225b84; stroke-opacity: 1; fill-opacity: 1; " r="7"></circle>
</g>

When I run the transition watching the debugger I can see the values in "translate" change but everything else stays the same.  So it doesn't seem to be something I'm doing wrong, but you can never be sure of that. :)
One final comment is that I do see this in multiple browsers (tried Chrome and Firefox so far).
Has anybody encountered this kind of thing before?
Comment: I've noticed this as well and was curious about it
Answer: Probably a bit late for you but I've noticed similar things when using transform: scale(). The SVG shape is limited to the files original size. If the shape gets enlarged bigger than this then it will be cropped.
My fix was to make the bounds of the SVG bigger than the shape itself so that it has some room to expand into.


Splitting a dataframe column row-wise with boolean conditions into multiple columns with fixed headers in Pandas

Question: I downloaded a dataset from this website https://aps.dac.gov.in/APY/Public_Report1.aspx One has to make selections and on the basis of my selection, I got a file that contained data for the year 2017-2018 for all the states and all the crops. This is how the dataset looks like after importing using read_excel()
State/Crop/District             Season  Area (Hectare)  Production (Tonnes) Yield (Tonnes/Hectare)
0   Andaman and Nicobar Islands NaN             NaN     NaN                 NaN
1   Arecanut                    NaN             NaN     NaN                 NaN
2   1.NICOBARS                  Rabi            534.10  125.23              0.234469
3   2.NORTH AND MIDDLE ANDAMAN  Rabi            1744.00 4639.44             2.66023
4   3.SOUTH ANDAMANS            Rabi            1220.20 10518.7             8.62047
6   Arhar/Tur                   NaN             NaN     NaN                 NaN
7   1.NORTH AND MIDDLE ANDAMAN  Rabi            1.20    0.6                 0.5
9   Black pepper                NaN             NaN     NaN                 NaN
10  1.NICOBARS                  Rabi            12.40   0.42                0.033871
11  2.NORTH AND MIDDLE ANDAMAN  Rabi            8.76    2.13                0.243151
12  3.SOUTH ANDAMANS            Rabi            69.46   349.72              5.03484

The first column which is named State/Crop/District contains three different values which according to me should have been in three different columns but are not. What's also interesting is that not all the crops are grown in all the districts. My goal is to have it in the following way.
State                       Crop     District                 Season    Area    Production    Yield
Andaman and Nicobar Islands Arecanut Nicobars                 Rabi      534     125.23        0.2344
Andaman and Nicobar Islands Arecanut North and Middle Andaman Rabi      1744    4639.44       2.66023

and so on. There are around 27 states like Andaman and Nicobar Islands and around 54 distinct crops and numerous districts. I tried three ways to solve this problem, but couldn't get success in any of them.

I used pivot function in pandas but it made a dataframe containing around 12000 columns. That's not what I want.
I used melt on the first column and values_vars for others. The result was similar to the first run.
I created a custom function that scans for the row which contains the word Total. This is where two crops are separated in the raw file I downloaded, but I couldn't scale it to the other states.

Some of the answers recommend using stack() and unstack() but I am not able to see how can that be used here because I don't see multiple indices. I am a newbie to Pandas and using Python 3. Help would be appreicated.
Answer: Here's a full demo for how to do this... it's a little clunky, but I don't think there's a builtin pandas function to really achieve the explosion of "State/Crop/District" into respective columns. Besides the for loop it's not too bad :)
import pandas as pd
from io import StringIO

data = """State/Crop/District             Season  Area (Hectare)  Production (Tonnes)  Yield (Tonnes/Hectare)
Andaman and Nicobar Islands  NaN             NaN     NaN                 NaN
Arecanut                    NaN             NaN     NaN                 NaN
1.NICOBARS                  Rabi            534.10  125.23              0.234469
2.NORTH AND MIDDLE ANDAMAN  Rabi            1744.00  4639.44             2.66023
3.SOUTH ANDAMANS            Rabi            1220.20  10518.7             8.62047
Arhar/Tur                   NaN             NaN     NaN                 NaN
1.NORTH AND MIDDLE ANDAMAN  Rabi            1.20    0.6                 0.5
Black pepper                NaN             NaN     NaN                 NaN
1.NICOBARS                  Rabi            12.40   0.42                0.033871
2.NORTH AND MIDDLE ANDAMAN  Rabi            8.76    2.13                0.243151
3.SOUTH ANDAMANS            Rabi            69.46   349.72              5.03484"""

df = pd.read_table(StringIO(data), sep="\s\s+")
l = list(zip(df.iloc[:, 0], df.iloc[:, 1]))
out = []
for i, (j, k) in enumerate(l):
    if str(k) == "nan":
        if str(l[i + 1][1]) == "nan":
            state = j
        else:
            crop = j
    else:
        district = j
    try:
        out.append([state.title(), crop.title(), district[2:].title()])
    except NameError:
        pass
df1 = pd.DataFrame(columns=["State", "Crop", "District"], data=out)
df_final = pd.concat([df1, df.dropna().iloc[:, 1:]], 1).dropna()

Output (print(df_final.to_string())):
                          State          Crop                  District Season  Area (Hectare)  Production (Tonnes)  Yield (Tonnes/Hectare)
2   Andaman And Nicobar Islands      Arecanut                  Nicobars   Rabi          534.10               125.23                0.234469
3   Andaman And Nicobar Islands      Arecanut  North And Middle Andaman   Rabi         1744.00              4639.44                2.660230
4   Andaman And Nicobar Islands      Arecanut            South Andamans   Rabi         1220.20             10518.70                8.620470
6   Andaman And Nicobar Islands     Arhar/Tur  North And Middle Andaman   Rabi            1.20                 0.60                0.500000
8   Andaman And Nicobar Islands  Black Pepper                  Nicobars   Rabi           12.40                 0.42                0.033871
9   Andaman And Nicobar Islands  Black Pepper  North And Middle Andaman   Rabi            8.76                 2.13                0.243151
10  Andaman And Nicobar Islands  Black Pepper            South Andamans   Rabi           69.46               349.72                5.034840

Comment: Try: `out.append([str(state).title(), str(crop).title(), str(district)[2:].title()])`
Comment: Thanks for the solution. Here you are importing the `data` while writing it beforehand. If I want to use a CSV file, I have to use `read_csv()` But when I do that I get an error `AttributeError: 'float' object has no attribute 'title'`
Comment: Why don't you just use `read_excel` like you said in your question...?
Comment: Maybe it's misleading because I am overwriting the original dataframe... I'll change that
Comment: I am still getting this error `AttributeError: 'float' object has no attribute 'title'`
Comment: It worked. Thanks. Yes, I was thinking on similar lines.
Answer: Processing flow:.

Split the data frame by NA
Extend the data frame as a header from the index
Fill the NA with the column name of method='ffill' in the extended column.
Combine the header data frame and the split data frame
Modify the column names and add the 'state' column
Delete the first character of the 'District' column

There may be room for improvement, but the following code will do.
tmp = df[df['Season'].isnull()]
tmp2 = df[~df['Season'].isnull()]
new_index = np.arange(0, df.index.max()+1)
header1 = tmp.reindex(new_index)
header1 = header1['State/Crop/District'].fillna(method='ffill')
final = pd.concat([header1, tmp2], axis=1)
final.dropna(axis=0, inplace=True)
final['State'] = df['State/Crop/District'][0]
final.columns = ['Crop', 'District', 'Season','Area (Hectare)', 'Production (Tonnes)', 'Yield (Tonnes/Hectare)','State']
final = final[['State','Crop', 'District', 'Season','Area (Hectare)', 'Production (Tonnes)', 'Yield (Tonnes/Hectare)']]
final['District'] = final['District'].str.replace(r'^\d\.','')

final
|    | State                       | Crop         | District                 | Season   |   Area (Hectare) |   Production (Tonnes) |   Yield (Tonnes/Hectare) |
|---:|:----------------------------|:-------------|:-------------------------|:---------|-----------------:|----------------------:|-------------------------:|
|  2 | Andaman and Nicobar Islands | Arecanut     | NICOBARS                 | Rabi     |           534.1  |                125.23 |                 0.234469 |
|  3 | Andaman and Nicobar Islands | Arecanut     | NORTH AND MIDDLE ANDAMAN | Rabi     |          1744    |               4639.44 |                 2.66023  |
|  4 | Andaman and Nicobar Islands | Arecanut     | SOUTH ANDAMANS           | Rabi     |          1220.2  |              10518.7  |                 8.62047  |
|  7 | Andaman and Nicobar Islands | Arhar/Tur    | NORTH AND MIDDLE ANDAMAN | Rabi     |             1.2  |                  0.6  |                 0.5      |
| 10 | Andaman and Nicobar Islands | Black pepper | NICOBARS                 | Rabi     |            12.4  |                  0.42 |                 0.033871 |
| 11 | Andaman and Nicobar Islands | Black pepper | NORTH AND MIDDLE ANDAMAN | Rabi     |             8.76 |                  2.13 |                 0.243151 |
| 12 | Andaman and Nicobar Islands | Black pepper | SOUTH ANDAMANS           | Rabi     |            69.46 |                349.72 |                 5.03484  |

Comment: This worked! However, I had to do some post-processing to make it the way look I wanted. It didn't take much time. Thanks


div border bottom is overlapped with something

Question: I a div that is full of content and I gave it box-shadow. Everything was ok till I make that div slider using slick slider. Now my problem is that after using slik slider, the bottom shadow of div is not displaying and I guess it's overlapped with something. I applied many changes but no benefit! How can I fix that? Following is my minimal of code:
HTML:

CSS:
#recent-posts{
    /*height: 350px;*/
    /*display: flex;*/
    /*justify-content: center;*/
    position: relative;
    /*flex-wrap: wrap;*/
    margin-bottom: 100px;
}
.posts{
    display: flex;
    flex-direction: column;
    max-height: 375px;
    margin-top: 20px;
    position: relative;
    border-radius: 5px;
    box-shadow: 1px 1px 5px #888888;
    margin-left: 20px;
    margin-right: 20px;
}
.posts img{
    width: 100%;
    border-radius: 5px 5px 0 0;
    cursor: pointer;
    max-height: 200px;
    min-height: 200px;
}

Script:
$('#recent-posts').slick({
        dots: false,
        slidesToShow: 2,
        slidesToScroll: 1,
        infinite: true,
        responsive:[
            {
                breakpoint: 770,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    dots: false
                }
            }]
    });

JSFiddle
Comment: That's because your div has margin-top, margin-left and margin-right set to 20px but no similar margin-bottom rule.
Comment: @Pyromonk Oh, You're Right!
Answer: Fiddle: https://jsfiddle.net/j8upvh3c/4/
Setting margin 20px from all side should fix the issue. You were applying for top, right, left but not bottom.
.posts{
    margin: 20px;
    display: flex;
    flex-direction: column;
    max-height: 375px;
    position: relative;
    border-radius: 5px;
    box-shadow: 1px 1px 5px #888888;
}

Answer: Just set margin-bottom to your .posts element to gain some bottom margin which overflows from parent div.
.posts{
    display: flex;
    flex-direction: column;
    max-height: 375px;
    margin-top: 20px;
    position: relative;
    border-radius: 5px;
    box-shadow: 1px 1px 5px #888888;
    margin-left: 20px;
    margin-right: 20px;
    margin-bottom:20px; //this here
}

Updated fiddle


FormsAuthentication.RedirectToLoginPage() not working

Question: I am a new to ASP.Net. Please, explain me what I need to add.
I clicked this page before login to take user to login page by "FormsAuthentication.RedirectToLoginPage();". But After Page_Load , it goes to "dsRequestList_Selecting". I assumed it goes directly to Login page, but here some reason it goes to login page after dsRequestList_Selecting(). What do I need to do?
protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
            }

        }
        else
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
            }
        }
    }

protected void dsRequestList_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
       //Selecting
    }

Answer: Don't go this way.
Use Web.config (or, for MVC, the [Authorize] attribute) to secure pages. You don't need this kind of code and you don't want the susceptibility to errors (in every page) that it brings.
You only need
<configuration>
    <system.web>
       <authorization>
         <deny users="?" />
       </authorization>

       ...
    </system.web>

    ....
</configuration>

to secure all your pages in the same folder as this web.config. The loginform is automatically excepted.
Answer: Even though an answer has been accepted, I wanted to add to this to clarify and answer the original question.
The reason why additional code on the page is being executed is due to the specifics of how FormsAuthentication.RedirectToLoginPage() works.
From the FormsAuthentication.RedirectToLoginPage MSDN:

Unlike the HttpResponse.Redirect method, this method does not end the request by calling HttpResponse.End. This means that code that follows the RedirectToLoginPage method call will run.

What Henk Holterman said is accurate though, you shouldn't be handling authentication in a page itself, or ideally in the code at all (recompiling just to change access is silly).  The web.config example he posted is sufficient.
Also, I'll post a revised version of your code that wouldn't allow dsRequestList_Selecting to be called but still handle authentication at the page level (which again, is unadvised).
protected void Page_Load(object sender, EventArgs e)
{
    //No need to check IsPostBack if your action is the same either way.
    if (!HttpContext.Current.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
        //Note: Using CompleteRequest() over Response.End() is significantly quicker
        //This is because it avoids raising the ThreadAbortException.
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        //So if you use CompleteRequest(), you want the return statement after.
        //Unless you wrap the rest of the Page_Load logic in an else statement, like the alternate solution below
        return;
    }
    //All other Page_Load logic
}

Alternate, more costly way (due to exception):
protected void Page_Load(object sender, EventArgs e)
{
    if (!HttpContext.Current.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
        Response.End();
    }
    else
    {
        //All other Page_Load logic
    }
}


Is there any midi software that can display in real-time the notes I play next to the "real" score?

Question: I'm pretty new to the Piano, and pretty bad at sight-reading (but getting better:))
Still, sight-reading a new score takes me an awfull lot of time, especially when I don't "hear" the thing I'm supposed to play.
I know there's some software you can use to play a piano score, and there's also software you can use to capture what you're playing on a keyboard on a computer (through a MIDI interface)
so I was wondering if there was a software that could bring those two worlds together and display in real-time the notes I'm playing next to the piano score. Ideally, the software would be clever enough to guess the part I'm trying to play, and advance at my pace !
Answer: I think you're looking for something like PianoBooster. It displays parts on a scrolling stave in-time with your playing, using standard MIDI files. It can wait for you to hit the correct note, can play the left-hand or right-hand part for you, and lets you adjust the speed to suit you. You can also transpose a part up or down.
PianoBooster is free and open source under the GNU General Public License (GPL) v3, available for Windows, Mac, and Linux. The Mac version is a "universal binary" and requires SimpleSynth or similar software.
Answer: I found another one (Sheet Music Trainer). This one is for android.
It appears to work with most instruments. There is a full list on there website.
Answer: The guy in this video uses MidiKeyz for the digital keyboard and GarageBand for the scrolling score. Both seem to be for the Mac though. And they are not freeware.
Comment: GarageBand for Apple Macintosh has some built-in lessons that do exactly this for piano. You can purchase additional lessons online.
Answer: I just found http://synthesiagame.com/

As a motivation feature there's even an online highscore list...
Answer: my http://pianocheetah.com program will do that.
Freeware on windows.
It'll record your playing, wait for you, display notes in piano roll (tipped 90 degrees) but not standard notation.  and show the notes you play on TOP of the notation, too.  It'll load any midi file.
email me if you need any help email@example.com

http://pianocheetah.com/tutorial/_screenshot.html
Comment: update - sorry, but I've taken out standard notation.  But it still displays what you're playing on top of the piano roll notation live.  notes to play are colored according to scale so you can easily see octaves, 5ths, etc.  Your recording is displayed as a black bar on top of the notation.
Answer: Have you tried Just Play, by Pentagrom? Its simple but solves exactly your problem, because it turns your smartphone into an instrument in the shape of written music, so that to read the notes of any score you just press the dots on the lines. I use it to practice for my choir, to know if Im singing the notes right (I dont worry about the rhythmn because I already know how that goes).
Answer: I couldn't find a simple program to do this, so I wrote one for myself:
pianoboi
As at the date of this post, it's in development, but with some basic commands you can easily get it to run on Windows or Mac.
Answer: I use MidiIlustrator. Very good app. You can compose  or re-write any music sheet. Once you learn how to use it. This one is the best.  It change page for you, too. Music note is good too but it doesn't change page.
Comment: Not found in Android Play Store. For iOS only?


How many VPS do I need for my website?

Question: I made a website which aims at simulating a trading market. There are a list of prices and corresponding volumes that people want to purchase. Users can purchase at any price any time. My website retrieves the prices and volumes from my database every 2 seconds (I have to update the user's browser frequently to allow them to see the current market). Users' database INSERT query can be sent any time if they purchase.
I used ajax to post or get data from my database (sometimes nested ajax calls). So, every 2 seconds, each user will send or retrieve data by using more than 20 database queries (in order to show a users the current prices and volumes). Also, I may have 200 users at a time.
I was not using VPS before, and I got banned because of using too much CPU resources on my host. Now, I've purchased VPS*2 from a hosting servers. I have:
CPU Speed: 2000 Mhz
Memory: 2048 MB
Disk Space: 20000 MB
Bandwidth: 2000 GB
Connection: 40 Mb/s
Dedicated IP's 2 IP's
Is this enough for my 200 users? Also, which VPS OS is suitable for me?
Thank you.
Answer: Should be plenty so long as you set things up right and code it intelligently.
I've only ever used CentOS, so that'd be my go-to recommendation.  They're all much of a muchness really, just pick the one that you're most familiar with.  Time is expensive.

How many VPS do I need for my website?


Could not find a declaration file for module error in react

Question: Typescript beginner here, trying to implement splitter to my project, i'm using SplitPane from "react-split-pane/lib/SplitPane"
and Pane from "react-split-pane/lib/Pane" in my typescript project but its giving me this error:

Could not find a declaration file for module 'react-split-pane/lib/Pane'. 'C:/.../node_modules/react-split-pane/lib/Pane.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/react-split-pane` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-split-pane/lib/Pane';`ts(7016)

it is working correctly without problem but still giving me that, it suggests to try
'@types/react-split-pane' but that is not working anymore 'https://www.npmjs.com/package/@types/react-split-pane' 'This package has been deprecated'.
as i said in comments i imported it like this :
import SplitPane from "react-split-pane/lib/SplitPane";
import Pane from "react-split-pane/lib/Pane";
Any idea how to get rid of error ?
English is not my mother language so the could be mistakes.
my splitpane module:
Comment: Typescript can import it just fine https://tsplay.dev/mL45vm How are you importing and using this library?
Comment: @AlexWayne i tried this : 'import SplitPane, { Pane } from "react-split-pane";' and getting this : 'Uncaught Error: Module build failed: Error: ENOENT: no such file or directory, open 'C:\...\node_modules\react-split-pane\dist\index.esm.js''
Comment: Are you sure it's installed? Did you run `npm install`? Maybe try removing your `node_modules` folder and reinstalling everything.
Comment: yes it is installed thats why it works... but in code under that import is red, i want to get rid of it
Answer:
i'm importing it like this : import SplitPane from "react-split-pane/lib/SplitPane"; import Pane from "react-split-pane/lib/Pane";

You really should never go drilling into the directory structure of libraries for imports, unless the documentations specifically tells you to.
According to the index file of that library, that's now how you are expected to import the values. The library exports like this:
export default SplitPane;
export { Pane };

And that means you should import those two values like this:
import SplitPane, { Pane } from 'react-split-pane'

Playground
It also works in a code sandbox with a full project:
Comment: others have imported it also same way as i did : https://github.com/tomkp/react-split-pane/issues/233
Comment: They probably are not using typescript. This package contains type information, but that's only valid for when you import from the root package name. Since this project is not written in typescript, then Typescript doesn't know the types of the individual files inside the library.
Comment: is there anyway to fix it or bypass ?
Comment: It works in that code sandbox link I posted. So you may need to figure out why your project is different from that sandbox. I can't really do that for you.
Comment: here someother has exact same problem and he fixed by ignoring: https://giters.com/tomkp/react-split-pane/issues/541
Comment: That solution will not import the types. But, honestly, [that issue](https://github.com/tomkp/react-split-pane/issues/541) has been open for two years. This library seems like a mess, at least with its typescript support. It looks like the project has been abandoned. I would look for another solution entirely, if I were you.
Comment: i dont need types for it i need that just to work, which it does
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/241705/discussion-between-walee-and-alex-wayne).


Confusion regrading Stokes' and Gauss Divergence Theorem while evaluating $\iint(\nabla \times F)\cdot dS$

Question: Suppose, $F$ be a smooth vector field. Now, we want to evaluate $\iint(\nabla \times F)\cdot dS$ where $S=\{(x,y,z)|x^2+y^2+z^2=1,z\le0\}$ i.e. $S$ is lower half part of unit sphere.

Now suppose we add the lower part on the $xy$-plane (which is $\{(x,y,z)|x^2+y^2\le1,z=0\}$$=S''$(say)) to S and call it $S'$. Now, $S'$ forms a closed and bounded region in $\Bbb{R}^3$.
So,  $\iint(\nabla \times F)\cdot dS'=\iiint\nabla\cdot (\nabla \times F)dV=0$ (by Gauss Divergence Theorem and the fact $\nabla\cdot (\nabla \times F)=0$)
Now, since $S\cup S''=S'$, we can write $\iint(\nabla \times F)\cdot dS=\iint(\nabla \times F)\cdot dS'-\iint(\nabla \times F)\cdot dS''=-\iint(\nabla \times F)\cdot dS''$ $\cdots$ (1)
Now recall $S''=\{(x,y,z)|x^2+y^2\le1,z=0\}$, from (1) and by Stokes' Theorem, we have $\iint(\nabla \times F)\cdot dS=-\oint_{c} F.dr$ where $c(t)=(\cos t,\sin t), t\in[0,2\pi]$ (since outward normal for $S''$ is $\hat k$ and by right hand rule orientation of the boundary of $''$ will be counter clockwise).
Thus, we finally get $\iint(\nabla \times F)\cdot dS=-\oint_{c} F.dr$ $\cdots$ (2)
Again, if we apply Stokes' Theorem directly in the problem we will get
$\iint(\nabla \times F)\cdot dS=\oint_{c} F.dr$ where $c$ is the boundary parametrized by $c(t)=(\cos t,\sin t), t\in[0,2\pi]$.
Comparing this and (2), we have  $\oint_{c} F.dr=-\oint_{c} F.dr$!!!
Can anybody clear this confussion? Where is the falacy?
Answer: When you use Gauss' Theorem, you're measuring outward flux.  On your $S$, this would be downward.  Using the right-hand rule on your curve, you're now orienting the flux upward.  That would change the sign.
Comment: I cannot understand. I have applied Gauss Theorem only on $S'$.
Comment: $S^\prime$ includes $S$.  Gauss's theorem measures outward flux.  That would be downward for the bottom part of $S^\prime.$
Comment: Yes, we want to find the integral taking outward normal to $S$, so outward normal for $S$ will be downward. So, where is the fallacy? Could you please write the expressions?
Comment: If you want downward normal, then you need to parametrize the circle in the opposite direction.
Comment: Ok, I understand.
Answer: Your closed surface $S'$, as you've correctly noticed, is made up of two separate oriented components $S$ and $S''$ which share the same border, but induce on it two opposite orientations: the border of $S''$ is $\partial S''$, the unit circle traversed in the counterclockwise sense, the border of $S$ is $\partial S$, the same as $\partial S''$ but traversed in the clockwise sense. As the integrand $\nabla \times F$ is the same on both surface components, Stokes' theorem ensures that the two contributions cancel out:
$$\iint_{S'} (\nabla \times F)\cdot da = \oint_{\partial S} F \cdot d\ell + \oint_{\partial S''} F \cdot d\ell = \oint_{\partial S} F \cdot d\ell - \oint_{\partial S} F \cdot d\ell = 0. $$
Just like computing the volume integral of the divergence had indicated.
Comment: I think you have missed out the notations, $S''$ is the disc on $xy$-plane, $S'$ is the closed region and $S$ is the given lower half part of the unit sphere. Can you please update your answer?
Comment: Sorry for the mixup. I've updated my answer


Estimating entropy of multidimensional variable through dimension reduction

Question: Is there anything inherently wrong with trying to estimate the entropy of a multidimensional random variable by first transforming it (by some method) into a single-dimensional variable?
Answer: If $X$ is a random vector, and $Y=g(X)$, the Doob-Dynkin Lemma says that the sigma-field generated by $Y$ is contained in the sigma-field generated by $X$. This implies that $H(Y)\leq H(X)$. Hence, your idea may in general produce a guess for the entropy of $X$ that is too small.
Comment: Thanks Zen. I'm not knowledgeable enough to understand the details of the explanation, and I couldn't access the proof that the entropy of the subset sigma-field is always less than that of the superset one, but consensus indicates that your answer is good, and the final result answers my question, so I've accepted it. Again, thanks
Comment: @user3557985: The proof for discrete random variables is very accessible and is outlined on page 43, exercise 5, of this excellent book chapter https://web.cse.msu.edu/~cse842/Papers/CoverThomas-Ch2.pdf


how to config Kestrel Concurrent Number more than 256

Question: Now, I was make 1000 websocket connections , and the server is dotnet core 2.x,
but , when I connected 256 webosket instance , the other cannot connect dotnet
core server .
Who can tell me how to config this, thanks very much.
Answer: You need to set
MaxConcurrentUpgradedConnections
<code>    .UseKestrel(options =>
{
    options.Limits.MaxConcurrentConnections = 100;
    options.Limits.MaxConcurrentUpgradedConnections = 100;
});
</code>


Drawing/coloring application - flood fill algorithm/clipping region

Question: I have to develop a coloring application. Basically the user is presented with an image. An outline of a character maybe and the user can fill it using different colors. I've looked at a few options but I can't seem to find a good one.
Could someone tell me how to fill the bitmap image.
Is there any sample code I can use? or an open source project?
It has to be done in
Answer: Look for some good Java Image processing Libraries like the ones listed here https://stackoverflow.com/questions/4078479/what-android-3rd-party-libraries-are-there . Its not an Android question but more about Image processing
Answer: The Wikipedia entry on Flood Fill has the classical algorithm in pseudo-code, a few variants and optimizations and links to source code in several languages.


Alinha pseudo element a direta na barra de navegação

Question: Estou com um dificuldade em alinhar a barra do :before à direita. Alguém pode me ajudar com isso?
Estou usando este código:
.nav-romeu li:before {
    content: '';
    width: 50px;
    height: 2px;
    background: #000;
    position: absolute;
    top: 70px;
    float: left;
}

O meu site é: amem.romeuadv.com.br
Desde já obrigado!
Comment: Meu anti-virus está me impedindo de entrar na página. Poderia colocar mais do código aqui? O html do menu completo com o CSS, ao menos.
Comment: https://jsfiddle.net/o3zj7mwy/
Answer: Obrigado pelo Fiddle. Se entendi bem você quer que as linhas fiquem coladas na direita do espaço, correto?
Se esse for o caso, você resolve com as seguintes adições ao seu CSS:
li {
    position: relative;
}
.nav-romeu li:before {
  right: 0;
}

Segue o exemplo:

* {
  margin: 0;
  padding: 0;
  outline: none;
  text-decoration: none !important;
  list-style-type: none !important;
}

li {
  position: relative;
}

body {
  font-family: Helvetica;
  margin-bottom: 0 !important;
  -webkit-font-smoothing: antialiased;
}

.header-fixed {
  height: 110px;
  width: 100%;
  line-height: 108px;
  background: #fff;
  border-bottom: 3px solid rgb(142, 21, 29);
}

.header-fixed img {
  display: block;
  margin: 10px 0;
}

.nav-romeu {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
}

.nav-romeu li a {
  font-family: "Helvetica";
  font-size: 18px;
  text-transform: uppercase;
  font-weight: bold;
  color: rgb(142, 21, 29);
  font-smooth: always;
  display: block;
  padding: 0 15px;
}

.nav-romeu li:before {
  content: '';
  width: 40px;
  height: 2px;
  background: #000;
  position: absolute;
  top: 70px;
  right: 0;
}

teste

teste

teste

teste


eigen decomposition of an interesting matrix

Question: Lets define:
$U=\left \{  u_j\right \} , 1 \leq j\leq N= 2^{L},$ the set of all different binary sequences of length $L$.
$V=\left \{  v_i\right \} , 1 \leq i\leq M=\binom{L}{k}2^{k},$ the set of all different gaped binary sequences with $k$ known bits and $L-k$ gaps.
$A_{M*N}=[a_{i,j}]$ is a binary matrix defined as following:
$$a_{i,j} = \left\{\begin{matrix}
1 & \text{if } v_i \text{ matches } u_j \\
0 & \text{otherwise }
\end{matrix}\right.$$
now, the question is: What are the eigenvectors and eigenvalues of the matrix $S_{M*M}=AA^{T}$?
Here is an example for $L=2, k=1$:
$$U = \left \{  00,01,10,11\right \} $$
$$V = \left \{  0.,1.,.0,.1\right \}  ^*$$
$$ A = \begin{bmatrix}
1 & 1 & 0 &0 \\
0 & 0 & 1 &1 \\
1 & 0 & 1 &0 \\
0 & 1 & 0 &1
\end{bmatrix}$$
$$ S = \begin{bmatrix}
2 & 0 & 1 &1 \\
0 & 2 & 1 &1 \\
1 & 1 & 2 &0 \\
1 & 1 & 0 &2
\end{bmatrix}$$
For the special case $k=1$, is has been previously solved by joriki and the solution can be found here. See the same reference for a graph analogy of matrix $S$.
Furthermore, it has been shown here by joriki that: $$\text{rank}(AA^{T})=\text{rank}(A)=\sum_{m=0}^k\left({L\atop m}\right)\;\;$$
As for the eigenvalues, numerical values suggest that $AA^{T}$ has $\binom{L}{m}$ eigenvalues equal to $\binom{L-m}{k-m}2^{g}, m=0,..,k$, where $g=L-k$ is the number of gaps.
any comments or suggestion is appreciated.
$^{*}$ here dots denote gaps. a gap can take any value, and each gaped sequence with $k$ known bits and $(L−K)$ gaps in $V$, exactly matches to $2^{L−k}$ sequences in U, hence the sum of elements in each row of $A$ is $2^{L−k}$.
Answer: The eigenvectors corresponding to the non-zero eigenvalues can be listed as follows. For each $m=0,1,...,k$, pick $m$ bit positions from the total $L$. This can be done in $\binom {L} {m}$ ways. Define vector x, with $i^{th}$ element, $x_i$, given by
$x_i =
\begin{cases}
1, & \text{if } v_i \text{ has no gaps among the m bits and has even number of 1s among these m bits} \\
-1, & \text{if } v_i \text{ has no gaps among the m bits and has odd number of 1s among these m bits} \\
0, & \text{otherwise}
\end{cases}
$
This is an eigenvector for $S = AA^T$ with eigenvalue $\binom {L-m}{k-m}*2^{L-k}$. To show this, we first see that $S_{ij}$ ($ij^{th}$ entry in $S=AA^T$) is the number of elements in $U$ which match both $v_i$ and $v_j$. From the construction of $x$, we can make two observations. First, if $x_i \neq 0$, then $x_j = x_i$ whenever $v_i$ has a common match with $v_j$, that is, whenver $S_{ij}$ is non-zero. Second, if $x_i = 0$, then for each $j_1$ with $S_{ij_1} \neq 0$ and $x_{j_1} \neq 0$, we can find a unique $j_2$ such that $S_{ij_1} = S_{ij_2}$ and $x_{j_1} = - x_{j_2}$. This is because, $x_i = 0$ implies there is a gap among the $m$ bits in $v_i$. So toggling that bit in $v_{j_1}$ gives a $v_{j_2}$ with $S_{ij_1} = S_{ij_2}$ and $x_{j_1} = -x_{j_2}$.
It follows from the second observation above that if $x_i = 0$, then $i^{th}$ entry in $Sx$ is 0. And from the first observation, if $x_i = 1$, then $i^{th}$ entry in $Sx$ is the number of elements in $U$ which match both $v_i$ and $v_j$, summed over all $j$ with $x_j = 1$. This is same as the number of $v_j$ which match $u$, summed over all $2^{L-k}$ different $u$ which match $v_i$. This number can be shown to be $\binom{L-m}{k-m}* 2^{L-k}$. Similar result can be shown for $x_i = -1$ case. So $x$ described above is an eigenvector for $S$ with eigenvalue $\binom{L-m}{k-m}* 2^{L-k}$. As we could choose $m$ bits in $\binom{L}{m}$ ways, we get $\binom{L}{m}$ vectors with this eigenvalue. These vectors can be shown to be mutually orthogonal, hence are linearly independent.
With $m$ varying from $0$ to $k$, we get as many eigenvectors as the rank of the matrix, each with a non-zero eigenvalue.  So this gives all the eigenvectors with non-zero eigenvalues.
Comment: thanks Siva. For a related question, please also see this: http://math.stackexchange.com/questions/32490/any-pattern-here-revised
Comment: there seems to be a typo on eigenvalue on first line following $x_i$ definition. It should be $\binom{L-m}{k-m}$ instead of $\binom{L}{k-m}$
Comment: yes.. thanks for the correction
Comment: just added a new post for the general case: http://math.stackexchange.com/questions/32843/eigen-decomposition-of-an-interesting-matrix-general-case


Best configuration for a software RAID 10 SSD for VM xenserver

Question: I have xenserver servers.
For storage of virtual machines, I use the software RAID 10 (the disks are directly in the servers).
I would like to know the best configuration for 4 SSD disk in RAID 10 software (it is general public
  discs, yes I did this stupidity 1 year ago ..)
Because I made a RAID 10 with 512K and I feel that it is bad.
thank you in advance
Answer: Back in the days, Linux software RAID (MDRAID) used 64K chunks for RAID 0/10 layouts. Small chunk size, while favoring sequential transfers, proved to be suboptimal for mechanical HDDs facing random I/O access pattern so common in server (and hypervisor) workload, leading to the decision to increase the default to 512K chunksize.
In other words, while you are using SSDs rather than HDDs, I do not think your perceived slowness is related to your current RAID 10 chunk size (512K). Rather, consumer SSDs are quite poor at handling synchronized writes (ie: the kind of writes issued by databases and filesystem journals). If you have an fsync-rich workload, you may be facing this specific issue.
Comment: So what do you advise? 64 KB?


Embedding a view for search and redirection

Question: I have set up a view for searching using Search API. In my specific setup, I need this search to be context sensitive, i.e. I have several pages /foo/search, /bar/search, ... and these return different results.
Currently, I do this by making a content type which has a field containing the necessary information and additionally a search processor, which alters the query accordingly.
Additionally, I use Twig Tweak to embed the search view in this content type as described here. This works if I load the search with the query string, e.g. localhost/foo/search?search_api_fulltext=something.
My problem is now that if I click the "Apply" button in the search, I am being redirect to the page created by the view. This page is lacking the content type's data and I no longer get the context sensitive search results.
Is it possible to change this behaviour of the view's Apply button or do you know another way this could be implemented?
Thanks!
Answer: Following this reply on drupal.org and this answer on SO, I added a hook:
<code>function my_module_views_pre_build(ViewExecutable $view) {
  if ($view->id() == 'my_view_id') {
    $view->override_url = Url::fromRoute('<current>');
  }
}
</code>
Some of the assumptions in Drupal and the workarounds are so annoying. Days wasted. :(
Comment: Why Page display over Block?
Comment: @Kevin: I tried to use a block on my content type but I didn't get the search field and button, just the results. Or do you mean something else?