Python and Selenium, cannot click on a submit button

Question: In this scenario, I am trying to click on the submit button with Selenium webdriver but so far have been unable to click the element.
<button type="submit" class="pcty-button pcty-size-medium pcty-button-full-width pcty-button-full-width-mobile pcty-size-responsive submit-button login-button">Login</button>

The code that I have to locate the button as it is now reads as:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@type='submit' and normalize-space()='Login']"))).click()
I thought that this code was covering all of the bases and expected it to click the button, but have had no luck so far. Every error I have seen with other code has raised that no element existed or it was unable to locate.
The error that I get is:

raise TimeoutException(message, screen, stacktrace)
  selenium.common.exceptions.TimeoutException

I've used some answers to try and find a solution from these threads: 1 and 2 but as of right now I have no clue what I am doing wrong.
I have been asked for a larger part of the HTML of this webpage for context.
If I need to expand even more of it, I am happy to do so. The answers provided have been tested and come up with the same timeout errors.

            <input type="checkbox" checked="checked" data-val="true" data-val-required="The IsRememberingUser field is required." id="IsRememberingUser" name="IsRememberingUser" value="true">Remember My Username

      <button type="submit" class="pcty-button pcty-size-medium pcty-button-full-width pcty-button-full-width-mobile pcty-size-responsive submit-button login-button">Login</button>

```

Comment: Your xpath is correct.Check the button element is available inside any `iframe`?
Answer: Instead of normalize-space(), I would try using just contains(text(), 'Login'):
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Login')]"))).click()

Since the above solution doesn't seem to be working for you, I also wrote up a fully-working code sample that successfully runs against the page link you provided. I was able to successfully send credentials and click the login button using the following:
from selenium import webdriver
from time import sleep
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver=webdriver.Chrome()
driver.get("https://access.paylocity.com/")

# company id - send keys
WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "CompanyId"))).send_keys("test_company_id")

# username - send keys
WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "Username"))).send_keys("test_username")

# password - send keys
WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "Password"))).send_keys("test_PASSWORD")

# login - click button
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Login')]"))).click()

# result: "The credentials provided are incorrect", meaning login button click succeeded

sleep(10) # explicit sleep here so i can visually observe the results on browser
driver.close()
driver.quit()

My code snippet uses the exact line of code I provided at the top of this answer, so I'm not sure why it wouldn't work for you. If the full sample in this answer works for you, but the single line of code does not work in the context of your own code, then something else must be interfering that is causing this issue.
If the full sample in this answer does not work for you, then the issue may be outside of Selenium.
Comment: Hi, I added more of the HTML from the page I have working with. Will you take a look and tell me if there is something present that would explain the errors currently? Thank you.
Comment: Based on the sample, I don't see anything that could be wrong. We will probably need to see the full page HTML or a link to the page you are automating -- my guess, like another user has suggested, could be hidden `iframe`.
Comment: Interesting, I was able to navigate to the website and send test credentials and successfully click the login button using the code sample I provided. Not sure what the issue is here -- I provided my full, working code sample that may hopefully give some insight. I ran this against the URL you provided with success.
Comment: it is the only `button` on the starting page, can you not find it by tag name rather than XPATH?
Comment: It's better practice in general to use more specific XPaths like the one from my sample. If the website develop ever adds another button on the page, the`find_by_tag_name` code will not work anymore. Why bother with refactoring when you can just write a specific XPath to begin with?
Comment: If you are just going to reference IDs in your locators, it's better if you just use By.ID instead of XPath. It's better supported, clearer to read (more clearly indicates intent, etc.)
Comment: I originally went with XPath because Login button did not have an ID, but `By.ID` for the other fields (company, username, password) is better practice.
Answer: To click() on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.pcty-button.pcty-size-medium.pcty-button-full-width.pcty-button-full-width-mobile.pcty-size-responsive.submit-button.login-button[type='submit']"))).click()

Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='pcty-button pcty-size-medium pcty-button-full-width pcty-button-full-width-mobile pcty-size-responsive submit-button login-button' and text()='Login']"))).click()

Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


When I click a radio button its value should display in textfield

Question:
Above is the sample screenshot of my form where I would like to do is:
When I click/check on radio button "One" then its value should display in  textfield of "Display".
Code:

function test_radio_menu() {
  $items['test_radio'] = array(
    'title' => 'test_radio',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_radio_form'),
    'access arguments' => array('access content'),
    'access callback' => TRUE,
    );
  return $items;
}

/**
* Implements hook_form().
*/

function test_radio_form($form, &$form_submit){

/* the options to display in our form radio buttons */
$options = array(
  'one' => t('One'),
   'two' => t('Two'),
);

$form['count'] = array(
  '#title' => t('Count'),
  '#type' => 'radios',
  '#options' => $options,

);

$form['display'] = array(
'#title' => t('Display'),
'#type' => 'textfield',
'#value' => ,
  );

$form['submit'] = array(
'#value' => t('PROCEED'),
'#type' => 'submit',
  );

return $form;
}

Answer: You should use drupal ajax form
 try this code
function test_radio_form($form, &$form_submit){

/* the options to display in our form radio buttons */
$options = array(
  'one' => t('One'),
   'two' => t('Two'),
);

$form['count'] = array(
  '#title' => t('Count'),
  '#type' => 'radios',
  '#options' => $options,
  '#ajax' => array(
            'callback' => 'myid_print_all_submitted_id_callback',
            'wrapper' => 'myid_print_search_idnumber_wrapper',
  ),

);

$form['display'] = array(
'#title' => t('Display'),
'#type' => 'textfield',
'#value' => isset($form_state['values']['count']) ? $form_state['values']['count'] : '',
'#prefix' => '
',
'#suffix' => '
',
  );

$form['submit'] = array(
'#value' => t('PROCEED'),
'#type' => 'submit',
  );

return $form;
}
function myid_print_all_submitted_id_callback($form, $form_state)
{
      return $form['display'];
}

Answer: it should work like this
html :
  <input type="radio" name="mode" id="radio"   class="test1" value="text" onclick="BT('#message')" />

js
function BT (id) {

    $('.Bt')..attr('id', 'your-id-value');

}

Comment: hi madman thanks for your reply, but i want to make in drupal 7.
Comment: its jquery you can add it to you template file and see the result its should not make problem . but if the page created by drupal you need to add js to header file then add html in your editor useing html code editor
Comment: -madman- thanks for your suggestion i will try it soon.


Getting "Class cannot be resolved to a type" for Cucumber.class while setting up JUnit

Question: I'm using Cucumber 1.2.2 jar and getting error "Class cannot be resolved to a type" for the below code.
Could someone suggest the solution.
Eclipse Code
Answer: You should have this import - import cucumber.api.junit.Cucumber;.
These options should be displayed by Eclipse on hovering over the error.
Comment: Your next thing to do is to upgrade to a modern Cucumber. 1.2.2 is almost two years old.
Comment: You made my day :) ...on mouse hover its only saying like Class cannot be resolved to type but not suggesting to import any package. Anyways its working for "import cucumber.api.junit.Cucumber".
Answer: I Remove the scope for cucumber-junit dependency in pom.xml file and the error "the import cucumber.api.junit cannot be resolved" will be resolved.
Answer: I was facing the same issue. I just made the "C" from the cucumber.class in lower case, and made it to Upper case again. When I made it in Uppercase it prompted me to do an import. And Finally I did the import and the issue was resolved.
Here is what I imported.
import io.cucumber.junit.Cucumber;
I am using newer version of the Cucumber dependencies.
I had tried all the solutions mentioned on stackoverflow, like removing the scope, downgrading the dependancy to match lower version of java installed on machine etc etc. Nothing worked. Only the solution which I provided worked.
Comment: was in the same situation with java 1.8. Tried the above case change after wasting 1 day. This finally worked!!
Answer: import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
//The import cucumber.api.junit cannot be resolved
import cucumber.api.junit.Cucumber;
////Receiving an error message as Class<Cucumber> cannot be resolved to a type
@RunWith(Cucumber.class)

@CucumberOptions(
        features = "C:\\Users\\achelimi\\eclipse-workspace\\FirstAppl\\src\\main\\java\\feature\\login.feature",
        glue = {"stepDefinition" },
        plugin = { "pretty", "html:test-outout", "json:json_output/cucumber.json",
                "junit:junit_xml/cucumber.xml" },
        monochrome = true,
        strict = true,
        dryRun = false)
public class TestRunner {

}

//Added below Dependencies for POM.xml

    <dependencies>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-picocontainer</artifactId>
                <version>1.2.5</version>
            </dependency>
            <dependency>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-java</artifactId>
                <version>4.2.0</version>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-jvm</artifactId>
                <version>1.2.5</version>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>net.sourceforge.cobertura</groupId>
                <artifactId>cobertura</artifactId>
                <version>2.1.1</version>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-jvm-deps</artifactId>
                <version>1.0.5</version>
            </dependency>
            <dependency>
                <groupId>net.masterthought</groupId>
                <artifactId>cucumber-reporting</artifactId>
                <version>1.0.0</version>
            </dependency>
//Added below Dependencies for POM.xml
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>gherkin</artifactId>
                <version>2.12.2</version>
            </dependency>
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-all</artifactId>
                <version>2.0.2-beta</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
//Added below Dependencies for POM.xml
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-java</artifactId>
                <version>3.0.1</version>
            </dependency>

            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>gherkin-jvm-deps</artifactId>
                <version>1.0.2</version>
            </dependency>

            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-html</artifactId>
                <version>0.2.3</version>
            </dependency>
   //Added below Dependencies for POM.xml

 //Added below Dependencies for POM.xml
        <dependency>
            <groupId>com.sun</groupId>
            <artifactId>tools</artifactId>
            <version>1.6</version>
            <scope>system</scope>
            <systemPath>C:\Program Files\Java\jdk1.8.0_202\lib\tools.jar</systemPath>
        </dependency>
    </dependencies>

Comment: Please find below dependencies added to pom.xml


Como faço um sistema de cadastro onde o usuário em um primeiro momento informe apenas o e-mail?

Question: Gostaria de saber como faço para criar um sistema de cadastro onde o usuário em um primeiro momento informe apenas o e-mail, logo após ele será direcionado para outra página, onde irá completar o cadastro com o e-mail já preenchido.
Comment: Bom, você deve primeiro escolher uma  linguagem  de programação a qual deseja tarablhar como php c#(asp.net) java e por ai vai, apos isso também  necessitará de um banco de dados, para amazenar os dados, sua pergunta ficou  muito  generica poderia especifica-la melhor e qual linguage utiliza ?
Comment: Qual linguagem de servidor vc usa? (ex., PHP)
Comment: utilizo a linguagem PHP, o problema não e realizar o cadastro do usuário, primeiro seria exibido ao usuário apenas um input type mail, logo após preencher o e- mail ele será direcionado para outra página para finalizar o seu cadastro.  minha duvida é cmo salvar o e-mail informado é continuar a preencher os dados em outra pagina, onde o campo e-mail já deve está preenchido. AQUI TEM UM EXEMPLO https://www.baratosuplementos.com.br/checkout/
Comment: Acredito que nesse exemplo de site que vc deu @DiegoLima seja para verificar a existencia de algum registro no mesmo email
Comment: Acho que armazenar o email em $_SESSION é uma boa
Answer: Como questão de cadastro envolve muitas validações etc., vou apenas abordar os passos básicos que você pode usar.
Funcionaria basicamente da seguinte forma usando 3 páginas:

cadastro1.php

A primeira página onde o usuário informa apenas o e-mail para ir para a página cadastro2.php. Nesta página haveria um formulário tal como:
<form method="post" action="cadastro2.php">
   <input required type="email" name="email" placeholder="Informe seu e-mail">

   <button>Prosseguir</button>
</form>

cadastro2.php

Nesta segunda página você vai receber o e-mail informado na primeira página via POST. Nesta página e na terceira, você deve verificar se as informações foram enviadas da página anterior; caso não, você redireciona para a primeira página, porque o usuário pode tentar acessar a página sem passar pela anterior:
<?php
$email = $_POST['email']; // pego o campo "email" enviado pela primeira página

if(empty($email)){ // verifico se está vazio
   header('Location: cadastro1.php'); // se estiver vazio, redireciona para a 1ª página
}
?>

<form method="post" action="cadastro3.php">
   E-mail: <?php echo $email?>
   <input type="hidden" name="email" value="<?php echo $email?>">
   ...
   resto dos campos do formulário
</form>

Nesta segunda página você já tem o e-mail do usuário armazenado na variável $email. No exemplo acima você pode criar um input hidden e preencher com o e-mail para ser enviado junto com o formulário.

cadastro3.php

Nesta última página, você irá receber todos os campos enviados pelo formulário da página cadastro2.php e finalizar enviando para o banco de dados as informações.

Isto é apenas um esquema bem básico de como você poderia fazer. Claro que existem formas mais eficientes e enxutas para usuários mais avançados. Mas como a sua pergunta quer saber apenas como enviar um e-mail de uma página à outra, creio que isso possa lhe ajudar a ter a noção de como funciona.
Comment: Muito Obrigado, era isso mesmo que eu estava procurando, me ajudou a ter uma noção do que fazer!
Comment: Diego, finalize a pergunta marcando ✓ na resposta. Se houver dúvidas de como fazer isso, por favor nos informe.


Changing table name at query run time in a Rails application

Question: I have a fat multi-tenant Rails app on Apache + mod_passenger that outputs product prices from a PostgreSQL table as follows:
Table "public.products"
Column | Type
id     | bigint
name   | character varying(100)
price  | numeric(8,2)

Then inside products.rb I have...
class Product < PostgresDatabase
     self.table_name = "products"

     # ... yadda yadda

end

What I want is to partition the "products" table in a very specific way so that I end up with something like products_TENANT-ID for each tenant (basically views of the main products table but that's another story) and be able to query like this:
Products.for_tenant(TENANT-ID).where(:name => "My product")......

I figure I can just create a method:
class Product < PostgresDatabase
     self.table_name = "products"

     # ... yadda yadda
     def for_tenant(tid)
          self.table_name = "products_" + tid.to_s
          self
     end
end

But what kind of impact could this have on the application considering there's lots of traffic (thousands of requests per second)? Is there something I am missing? Should I try a different strategy?
Thank you very much for any feedback/thoughts!
Answer: The method
def self.for_tenant(tid)
  self.table_name = "products_" + tid.to_s
  self
end

makes sense, however, it has a side effect: it changes table name for Product class. When this class is used later in the same request, for example, in this way:
Product.where(name: "My other product") ...

the table name won't be products as you may expect; it will stay the same as changed by for_tenant method previously.
To avoid this ambiguity and keep code clean you can use another strategy:
1) Define a module which holds all logic of work with tenant partitions:
# app/models/concerns/partitionable.rb

module Partitionable
  def self.included(base)
    base.class_eval do
      def self.tenant_model(tid)
        partition_suffix = "_#{tid}"

        table = "#{table_name}#{partition_suffix}"

        exists = connection.select_one("SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = '#{table}')")
        unless exists['exists'] == 't' || exists['exists'] == true  # different versions of pg gem give different answers
          return self # returning original model class
        end

        class_name = "#{name}#{partition_suffix}"

        model_class = Class.new(self)

        model_class.define_singleton_method(:table_name) do
          table
        end

        model_class.define_singleton_method(:name) do
          class_name
        end

        model_class
      end
    end
  end
end

2) Include this module in your model class:
class Product < PostgresDatabase
  include Partitionable

  ...
end

3) Use it the same way as you intended:
Product.tenant_model(TENANT_ID).where(name: "My product")...

What's happened there:
Method tenant_model(TENANT_ID) creates another model class for the tenant with ID TENANT_ID. This class has name Product_<TENANT_ID>, works with table products_<TENANT_ID> and inherits all methods of Product class. So it could be used like a regular model. And class Product itself remains untouched: its table_name is still products.
Comment: Hope one day it will be implemented :) Thanks!
Comment: This answer should be in a hall of fame or something.
Comment: Yes, it works too.
I wrote that check in a bit more complex way since my code should work with different versions of Rails.
Comment: Hi Ilya. Very nice answer, thank you for that. I do not mind if the table name stays changed within the same request since this same request comes from an user of a specific tenant (website). It will only become a problem if table_name gets set in one request and stays the same for other requests(users). I plan on refactoring all controllers to use Products.for_tenant(TENANT-ID) anyway. Should I still implement your module in this particular scenario, or can I just go with my original idea? Basically this reduces the question to determining the exact way self.table_name behaves vs requests.
Comment: You decide :) My work experience tells me that methods with side effects usually are not a good idea.
If you don't like to use this module, and pretty sure that user request should work with one tenant only, there is another strategy: define a filter for you base controller, which will set table name for Product class, and use this class later without any additional methods. Thus all controllers inherited from that base controller will have Product class tuned for that particular tenant.
Comment: Thanks Ilya, you are awesome! Too bad SO doesn't allow sending people beer!
Comment: Very doubtful, they're all too stiff. Someone should start a clone with more elaborate user incentive features. I even had this on a to-do list at some point.
Comment: Yup. Actually I use similar module in my project, but in my case I create a table in case it doesn't exist. Just a sec, I'll correct my answer.
Comment: I did a "return self if !PostgresDatabase.connection.table_exists? table". In R5 it would be like data_source_exists I think.
Comment: Yours does an extra query per hit?
Comment: You mean 'select_one' which check if the table exists? Yes, I do. Otherwise there is no way to know if there is a table or not.
To reduce these checks I call ```tenant_model``` method only once, store model class to a variable and use it later where required, with all ```where``` queries.


Implementing a dynamic submenu in VB.Net

Question: On a Windows Form in .Net 3.5 I have created a menu object and populated it with ToolStripMenuItems. One of these items has a DropDown object attached. The DropDown should appear when the mouse hovers over the parent ToolStripMenuItem and disappear when the mouse leaves the ToolStripMenuItem unless it is "leaving" the parent by entering the parent's DropDown.
Also, I don't want the DropDown to automatically close when the user makes a selection in it, so I have set its "AutoClose" property to False.
Getting the DropDown to appear was easy.  I just set up a handler for a "MouseEnter" event on the parent ToolStripMenuItem.  But I'm stuck trying to make the DropDown disappear at the right time. If I set up a handler to close the it when the mouse leaves the parent ToolStripMenuItem, it becomes impossible to use the DropDown, because moving the mouse into the DropDown means "leaving" the parent ToolStripMenuItem, and so the DropDown closes as soon as the user tries to hover over it!
I haven't been able to figure out how to detect if the mouse has really left the whole ToolStripMenuItem / DropDown assembly (in which case the DropDown should close) or has only "left" the ToolStripMenuItem by entering the DropDown (in which case the DropDown should not close).
This seems like a common design - a drop down that appears / disappears when the mouse hovers over / leaves the parent element - so how is it normally done? Grateful for any suggestions.
Answer: Still surprised that this is apparently not a problem that was solved a long time ago, but here's the solution I came up with:
Quick summary
The class below inherits from ToolStripMenuItem.  Use it if you want the item to have a child DropDown menu that appears when the user's mouse hovers over it.
Terms I use below
ToolStripMenuItem: an item in a ToolStripDropDownMenu.  It is both a member of a ToolStripDropDownMenu (the "parent menu"), and it also has access to another ToolStripDropDownMenu via its "DropDown" property (the "child menu").
Statement of the problem and soltion
The child ToolStripDropDownMenu that appears when you hover over the ToolStripMenuItem should normally close when the mouse leaves that ToolStripMenuItem and/or when it leaves the parent ToolStripDropDownMenu that contains it. However, it should not close if the mouse leaves the parent menu by entering the child menu at the same time.  In that case, the "MouseEnter" event on the child menu should cancel the normal behavior of the "MouseLeave" event on the parent menu (i.e., the DropDown should not close).
The problem when you try to set this up in a normal, straightforward way is that the "MouseLeave" event on the parent menu fires before the "MouseEnter" event on the child menu, and the child menu closes before the mouse can enter it.
The solution below shunts the call to DropDown.Close() into a separate thread, where the "Close" action is delayed by a few seconds.  In that short window, the "MouseEnter" event on the child DropDown (which is still on the main thread) has a chance to set a globally accessible dictionary value to True.  After the delay, the value of this dictionary entry is checked in the separate thread, and the child menu is either closed (by calling the thread-safe "Invoke" method) or not.  The program then goes on to check whether the parent menu also needs to be closed, whether that menu's parent menu needs to be closed, and so on.  This code allows floating submenus to be nested as deep as any reasonable person would want.
There are separate handlers for "MouseEnter" and "MouseLeave" events for the individual menu item, its parent menu, and its child menu.  They all check on each other to decide on the right course of action.
In conclusion
In posting this I wanted to provide an elegant working solution to this problem for which I had previously been unable to find much help. Still, iIf anyone has any tweaks for it, I'd love to hear them.  Until then, please use this class if it helps you.  When you instantiate it you need to send it a string for the text that will appear on it, a pointer to the main form, and a pointer to the parent ToolStripDropDownMenu to which you are adding it. After that, just use it as you would a normal ToolStripMenuItem.  I also added a flag that can be set to True if you want the child DropDown menu items to behave like radio buttons (only one selectable at a time).  -- Noel T. Taylor
<code>Public Class ToolStripMenuItemHov
  Inherits ToolStripMenuItem

  ' A shared dictionary that reflects whether the mouse is currently
  ' inside the area of a given ToolStripDropDownMenu.
  Shared dictContainsMouse As Dictionary(Of ToolStripDropDownMenu, Boolean) = New Dictionary(Of ToolStripDropDownMenu, Boolean)

  ' A shared dictionary that maps a given ToolStripDropDown menu to
  ' the ToolStripDropDownMenu one level above it.
  Shared dictParents As Dictionary(Of ToolStripDropDownMenu, ToolStripDropDownMenu) = New Dictionary(Of ToolStripDropDownMenu, ToolStripDropDownMenu)

  ' This thread can be started from multiple places in the code; it is
  ' shared so we can check if it's already running before starting it.
  Shared t As Threading.Thread = Nothing

  ' We need to pass this in so we can use the form's "Invoke" method.
  Private oMasterForm As Form

  ' This is the DropDownMenu that contains this ToolStripMenu *item*
  Private oParentToolStripDropDownMenu As ToolStripDropDownMenu

  ' A boolean to track of whether the mouse is currently inside this
  ' menu item, as distinct from whether it's inside this item's parent
  ' ToolStripDropDownMenu (for which we use "dictParents" above).
  Private fContainsMouse As Boolean

  ' If true, only one option in the DropDown can be selected at a time.
  Private p_fWorkLikeRadioButtons As Boolean

  ' We only need this because VB doesn't support anonymous subroutines
  ' (only functions).  Silly really.
  Private Delegate Sub subDelegate()

  Public Sub New(ByVal text As String, ByRef form As Form, ByVal parentToolStripDropDownMenu As ToolStripDropDownMenu)
    Me.Text = text
    Me.oMasterForm = form
    Me.oParentToolStripDropDownMenu = parentToolStripDropDownMenu

    Me.fContainsMouse = False
    Me.p_fWorkLikeRadioButtons = False
    Me.DropDown.AutoClose = False

    dictParents(Me.DropDown) = parentToolStripDropDownMenu
    dictContainsMouse(parentToolStripDropDownMenu) = False
    dictContainsMouse(Me.DropDown) = False

    ' Set the parent's "AutoClose" property to false for correct behavior.
    Me.oParentToolStripDropDownMenu.AutoClose = False

    ' We need to know if the mouse enters or leaves this single menu item,
    ' this menu item's child DropDown, or this menu item's parent DropDown.
    AddHandler (Me.MouseEnter), AddressOf MyMouseEnter
    AddHandler (Me.MouseLeave), AddressOf MyMouseLeave
    AddHandler (Me.DropDown.MouseEnter), AddressOf childDropDown_MouseEnter
    AddHandler (Me.DropDown.MouseLeave), AddressOf childDropDown_MouseLeave
    AddHandler (Me.oParentToolStripDropDownMenu.MouseEnter), AddressOf parentDropDown_MouseEnter
    AddHandler (Me.oParentToolStripDropDownMenu.MouseLeave), AddressOf parentDropDown_MouseLeave
  End Sub

  Public ReadOnly Property checkedItem() As ToolStripMenuItem
    ' This is only useful if "p_fWorkLikeRadioButtons" is true
    Get
      Dim returnItem As ToolStripMenuItem = Nothing
      For Each item As ToolStripMenuItem In Me.DropDown.Items
        If item.Checked Then
          returnItem = item
          Exit For
        End If
      Next
      Return returnItem
    End Get
  End Property

  Public Property workLikeRadioButtons() As Boolean
    Get
      Return Me.p_fWorkLikeRadioButtons
    End Get
    Set(ByVal value As Boolean)
      Me.p_fWorkLikeRadioButtons = value
    End Set
  End Property

  Private Sub myDropDownItemClicked(ByVal source As ToolStripMenuItem, ByVal e As System.EventArgs) Handles Me.DropDownItemClicked
    If Me.workLikeRadioButtons = True Then
      For Each item As ToolStripMenuItem In Me.DropDown.Items
        If item Is source Then
          item.Checked = True
        Else
          item.Checked = False
        End If
      Next
    End If
  End Sub

  Private Sub MyMouseEnter()
    Me.fContainsMouse = True
    If Me.DropDown.Items.Count > 0 Then
      ' Setting "DropDown.Left" causes the DropDown to always appear
      ' in the correct place. Without this, it can appear too far to
      ' the left or right depending on where the user clicks on the
      ' trigger link. Interestingly, it doesn't matter what value you
      ' set it to, as long as you set it to something, so I naturally
      ' chose 74384338.
      Me.DropDown.Left = 74384338
      Me.DropDown.Show()
    End If
  End Sub

  Private Sub MyMouseLeave()
    Me.fContainsMouse = False
    If t Is Nothing Then
      t = New Threading.Thread(AddressOf maybeCloseDropDown)
      t.Start()
    End If
  End Sub

  Private Sub childDropDown_MouseEnter()
    dictContainsMouse(Me.DropDown) = True
  End Sub

  Private Sub childDropDown_MouseLeave()
    dictContainsMouse(Me.DropDown) = False
    If t Is Nothing Then
      t = New Threading.Thread(AddressOf maybeCloseDropDown)
      t.Start()
    End If
  End Sub

  Private Sub parentDropDown_MouseEnter()
    dictContainsMouse(Me.oParentToolStripDropDownMenu) = True
  End Sub

  Private Sub parentDropDown_MouseLeave()
    dictContainsMouse(Me.oParentToolStripDropDownMenu) = False
    If t Is Nothing Then
      t = New Threading.Thread(AddressOf maybeCloseDropDown)
      t.Start()
    End If
  End Sub

  ' Wait an instant and then check if the mouse is either in this
  ' menu item or in this menu item's child DropDown.  If it's not
  ' in either close the child DropDown and maybe close the parent
  ' DropDown (i.e., the DropDown that contains this menu item).
  Private Sub maybeCloseDropDown()
    Threading.Thread.Sleep(100)
    If Me.fContainsMouse = False And dictContainsMouse(Me.DropDown) = False Then
      Me.oMasterForm.Invoke(New subDelegate(AddressOf Me.DropDown.Close))
      maybeCloseParentDropDown(Me.oParentToolStripDropDownMenu)
    End If
    t = Nothing
  End Sub

  ' Recursively close parent DropDowns as long as mouse is not inside.
  Private Sub maybeCloseParentDropDown(ByRef parentDropDown As ToolStripDropDown)
    If dictContainsMouse(parentDropDown) = False Then
      Me.oMasterForm.Invoke(New subDelegate(AddressOf parentDropDown.Close))
      If dictParents.Keys.Contains(parentDropDown) Then
        maybeCloseParentDropDown(dictParents(parentDropDown))
      End If
    End If
    t = Nothing
  End Sub

End Class
</code>


Different frequency response despite having similar waveforms

Question: I'm just comparing two pedals that generated square waves by using Audacity. The pedals are Homenoise Effects Serpent Cult silicon fuzz and Metasonix F1 distortion pedal.
First is the waveforms and frequency analysis of Homenoise Effects Serpent Cult silicon fuzz.

Next, we have the Metasonix F1 distortion pedal.

As you can see, both pedals are producing square waves but one of them the frequency spectrum of Homenoise Effects Serpent Cult didn't go to 22000 hz and beyond while the other did. Btw, I also generated 12544 hz square waves with Audacity and check its frequency analysis and it also extend to 22000 hz and beyond.

Can anyone explain why the frequency spectrum of Homenoise Effects Serpent Cult didn't extend to 22000 hz? I thought square waves have harmonics extended to ultrasonic frequency range. Is it because it have more higher pitched frequency extension or what? There are also other fuzz pedals I checked with Audacity in order to see the frequency analysis and they don't extend to 22000 hz but some of them did. Maybe due to sound quality again? Not sure.
Comment: What is the sampling frequency? With 44.1 kHz, because of Nyquist, do not expect something "beyond" 22k ;)
Comment: The project rate (same thing as sampling frequency, right?) is 44100 hz. The Metasonix frequency analysis did extend to 22000 hz, to be exact 22038 hz when I increase the size and axis to linear frequency.
Comment: Yes, I will not be able to go further than half the sampling frequency : 44.1/2=22.05kHz
Answer: This is a guess, at one should look at the circuit to be sure.
Because of aliasing and the way we sample signals, you usually do not want significant power above 22kHz, because if you have, it will get folded back in the hearing range and sounds quite bad. This apply to synthesizers and actually all electronic devices dealing with audio.
In order to avoid that, manufacturers usually put a hard low pass filter on the output stage. The exact cutoff of this filter can be different, such as its attenuation by decade, it's up to the manufacturer. What you see here, is probably the manifestation of this filter, with different designs for the two manufacturers.
Hope it helps,
Comment: So, the difference is due to how circuits are set up and the higher frequencies of the Serpent Cult fuzz is deliberately removed by the designer?
Comment: That's likely. Anti aliasing filters are a must have for a circuit generating something as crunch as a square wave... Implementation though, are different. Serpent maybe wanted to be sure and thus removed more higher frequencies to have *nothing* above Nyquist frequency for standard sampling frequency.


Why does SaveAs Method throw error?

Question: I have the following vba code is part of a larger script. The issue I am having is that that the SaveAs function continuously throws an error even though the Outlook message has been saved to a directory on the system. Inspection of the the Err object yields no results as everything is either blank or 0.
Another weird issue is that when the error handling code is commented out as it is below, the script executes correctly without any error being thrown. To me it seems that the error handling code itself causes the issue. VSTO is NOT an option at the moment.

Are there alternatives to the
approach below?
Can you provide some
useful debugging tips to aid this
situation?

This is the code I'm using
For Each itm In itemsToMove
    Dim mItem As MailItem
    Set mItem = itm

    ' On Error Resume Next
    sSubject = mItem.Subject
    sDate = Format(mItem.CreationTime, "yyyymmdd_hhnnss_")
    FNme = DirName & sDate & StripIllegalChar(sSubject) & ".msg"
    **mItem.SaveAs FNme, olMSG**
    iCount = iCount + 1

    'ErrorHandler:
    '            MsgBox ("The email " & FNme & " failed to save.")
    '            MsgBox Err.Description & " (" & Err.Number & ")"
    '            Set objNameSpace = Nothing
    '            Set objOutlook = Nothing
    '            Set objNameSpace = Nothing
    '            Set objInbox = Nothing
    '            Set objInbox = Nothing
    '            Set itemsToMove = Nothing
    '            Set itemsToMove = Nothing
    '            Exit Sub
 Next

Solution:
Sub SomeSub
....
....
For Each itm In itemsToMove
    Dim mItem As MailItem
    Set mItem = itm

    On Error GoTo ErrorHandler
    sSubject = mItem.Subject
    sDate = Format(mItem.CreationTime, "yyyymmdd_hhnnss_")
    FNme = DirName & sDate & StripIllegalChar(sSubject) & ".msg"
    mItem.SaveAs FNme, olMSG
    iCount = iCount + 1
 Next
End If
Exit Sub

ErrorHandler:
   MsgBox ("The email " & FNme & " failed to save.")
   MsgBox Err.Description & " (" & Err.Number & ")"
   Set objNameSpace = Nothing
   Set objOutlook = Nothing
   Set objNameSpace = Nothing
   Set objInbox = Nothing
   Set objInbox = Nothing
   Set itemsToMove = Nothing
   Set itemsToMove = Nothing
   Resume Next
End Sub

Answer: Place an Exit Sub/Function before the ErrorHandler.
Your code is executing correctly, but you are executing the ErrorHandler always.
You only want the error code to execute on error, not always. You need to exit the Function/Sub if no error Occurs.
Something like
...
iCount = iCount + 1

NoError:
    Exit Sub

ErrorHandler:
...

From Error Handling In VBA
Something like
On Error Goto ErrHandler:
N = 1 / 0    ' cause an error
'
' more code
'
Exit Sub 'THIS IS WHAT YOU ARE MISSING
ErrHandler:
' error handling code
Resume Next
End Sub

Comment: How so? Wont that just exit the Sub every time?
Comment: That should be a next, shouldn't it?
Comment: Correct, I refactored the error handler to the end of the Sub, the main reason being is that I did not want to completely exit until all items have been processed
Comment: You might want to then move the code within the for loop to another Sub/Function that handles a single item a time, and hanles the errors there.
Comment: Most definitely agree with that. In this case though would Resume return control back to the For Loop even if the new Sub has errors?
Answer: You will have to make sure your errorhandler only executes when an error actually has occured. I'd try something like this, but you'll have to adapt it to the rest of the sub:
Sub ...
  // ...
  On Error goto errorhandler
  For Each itm In itemsToMove
    //...
    mItem.SaveAs FNme, olMSG
    iCount = iCount + 1
  Next

  Exit Sub
ErrorHandler:
   // ...
End Sub

An alternative might be:
  For Each itm In itemsToMove
    On Error goto errorhandler
    //...
    mItem.SaveAs FNme, olMSG
    iCount = iCount + 1
    goto NoError

    ErrorHandler:
      //...
      Exit sub
    NoError:
  Next

Answer: Working just fine in my environment, slightly modified from yours above (I removed the StripIllegalChar routine as it wasn't posted):
Sub SaveAsItems()
Dim MAPINS As NameSpace
Set MAPINS = Application.GetNamespace("MAPI")
Dim inboxFolder As Folder
Set inboxFolder = MAPINS.GetDefaultFolder(olFolderInbox)
Dim itemsToMove As items
Set itemsToMove = inboxFolder.items
Dim mItem As MailItem
DirName = "C:\Users\Me\Desktop\files\"
For Each itm In itemsToMove
    Set mItem = itm
    sSubject = mItem.Subject
    sDate = Format(mItem.CreationTime, "yyyymmdd_hhnnss_")
    FNme = DirName & sDate & ".msg"
    mItem.SaveAs FNme, olMSG
Next
End Sub

Why does SaveAs Method throw error?


printing array of numbers as 3*3 matrix c++

Question: i function to print an array normally which works. it is an array of 9 ints.
i am trying to display it as a 3*3 matrix.
For example:
normal print:
1 2 3 4 5 6 0 0 0

expected output:
1 2 3
4 5 6
0 0 0

Here is the code that first came to mind because for the life of me i could not find a way to use loops to achieve this
  void printArray (int arr[], int n)
{
    cout << arr[0] << " " <<arr[1] << " " <<arr[2] << endl;
    cout << arr[3] << " " <<arr[4] << " " <<arr[5] << endl;
    cout << arr[6] << " " <<arr[7] << " " <<arr[8] << endl;
}

i am only using a 1D array.
Comment: So what exactly is the question?
Comment: `for ( int r = 0; r < 3; ++r ) { for ( int c = 0; c < 3; ++c ) { cout << arr[r * 3 + c]; } cout << endl; }` typing this on phone, so might not be correct, but idea is there.
Comment: @ChrisMM thankyou, this worked for me. if you would like to post it as an answer so i can accept it
Comment: See also [C++: "std::endl" vs "\n"](https://stackoverflow.com/questions/213907/c-stdendl-vs-n)
Answer: You can use the modulus operator to decide whether to print a space or a newline after each item, something like:
void printArray (int *arr, int nRows, int nCols) {
    for (int i = 0; i < nRows * nCols; ++i) {
        cout << arr[i] << ((i % nCols) == nCols - 1) ? '\n' : ' ';
    }
}

Where nCols is three, for example, a space will be printed after all items except the ones at indexes {2, 5, 8, ...}. Those ones will be followed by a newline.

As an aside, you probably don't want to be using endl after every single element. It both outputs a newline and flushes buffers, something that's going to affect performance if you do it a lot. Better to just output the newlines and, if you want to force a flush, do it after the loop with cout.flush().
Answer: You can also convert the 1-D arr to 2-D array and access them by p[row][col]
    int (*p)[3] = (int (*)[3])arr;

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++ ) {
            cout << p[i][j] << " ";
        }
        cout << endl;
    }

output:
1 2 3
4 5 6
0 0 0


Modify parent entity from within custom field formatter

Question: How can I modify parent entity's output from within my custom field. I am writing a custom field that adds css class to blocks. Everything is set, except I don't know how to modify the parent entity.
Comment: Your approach is totally wrong. But you can still access the entity from a field with getEntity() method.
Comment: How should I have approached this?
Answer: You can do this from inside the field formatter.  Each of the $items passed into the viewElements method has a getEntity() method that will give you the entity.
class MyFieldFormatter extends FormatterBase {

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $entity = $items[0]->getEntity();
  }

}

However, this is not recommended since it inverts the normal control flow. In normal situations, everything needed to render a field is a value on a column in the field itself.  Grabbing the entity is icky, but is definitely possible for strange edge cases.
Comment: I wrote a field formatter that needed to grab a value from an other field (this field could be configured on the formatter settings). This approach was a lot easier than trying to define a new field type that combined the functionality of both. Because that would also require me to write a widget that combined the functionality of two other widgets. In this case it was about a text field and an entity reference field.
Your answer was useful to me. Thanks.
Comment: `$entity = $items->getEntity();`
Answer: It's not possible to do this from inside the field.
To modifiy the classes of the parent entity use hook_entity_view().
Check, if the field is in $build and then add the classes to the entity:
$build['#attributes']['class'][] = 'new-class';


Trying to make a console application run at 20 frames per second

Question: I'm trying to create a timing mechanism so that a console application that I'm working on runs at roughly 10 frames a second. When I run this code, rather than being a smooth 20 frames a second it is stuttery and freezes often. I'm having trouble debugging this due to the fact that it relies on the DateTime.Now.Millisecond function, so whenever I insert a break into the code it messes up the timings of the application.
do
{
    frameTimer = DateTime.Now.Millisecond;

    if (firstLoop == true)
    {
        timeTillNextFrame = frameTimer + 100;

        firstLoop = false;
    }

    if (timeTillNextFrame < DateTime.Now.Millisecond && DateTime.Now.Millisecond < 901)
    {
        Console.Clear();

        grid.removeFromGrid(ball.xPos, ball.yPos);
        ball.newPos(gridSizeX, gridSizeY, grid.gridArray);
        grid.addToGrid(ball.xPos, ball.yPos, ball.symbol);

        grid.gridDraw(gridSizeX, gridSizeY);

        timeTillNextFrame = DateTime.Now.Millisecond + 50;

        if (timeTillNextFrame >= 1000)
        {
            timeTillNextFrame -= 1000;
        }

    }

Comment: The console was not meant for this.
Comment: You're seeing the console redrawing itself. You're basically spamming CLS in a command prompt.
Comment: You probably want `DateTime.Now.TotalMilliseconds` everywhere, right? And I'm not sure what the `< 901` comparison is meant to do. `timeTilNextFrame` also seems like a misleading name. Maybe it should be `timeOfNextFrame`?
Comment: Why not just use a timer?  Also, how long does griddraw take to execute, you need to account for that...
Comment: I also don't see where/how you wait until the time of the next frame.
Comment: (If you do switch to `TotalMilliseconds`, be sure to remove the `if >= 1000 ... -= 1000` code.)
Comment: @smarx Thank you, I'll make these changes and see how it goes. :)
Comment: @Trey I don't think the grid draw time is a problem but I will take it into account, thank you!
Comment: @Amy No, but I want to try and use it for this.
Comment: Alternatively you could create your own (more or less) emulated console which supports higher refresh rates. Like @Amy said, the console was not made for this purpose.
Comment: Oh, `DateTime.Now.TotalMilliseconds` doesn't exist, sorry. :-) See https://stackoverflow.com/questions/4016483/get-time-in-milliseconds-using-c-sharp for a couple options. `Stopwatch` is probably the best idea (more likely to give you the precision you need).
Comment: @Smarx Thanks, using that now.
Comment: Just a random opinion, but your `removeFromGrid` method should just be named `Remove`, and it should have an overload that takes a `Ball` object, so the code would look like: `grid.Remove(ball);` (and the counterpart, `grid.Add(ball);`. Makes for much easier to read (and write) code.
Answer: You don't want DateTime.Now.Millisecond, you want the total milliseconds:
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

var totalMilliseconds = DateTime.Now.ToUniversalTime().Subtract(Epoch).TotalMilliseconds

Comment: I can't find the namespace that I need to implement this, any hints?
Comment: I am getting an error saying there's no extension method for 'TotalMilliseconds'?
Comment: Yeah sorry, mixed up TimeSpan and DateTime. Edited the answer.
Comment: @Trey This is my first actual attempt at coding something so I have very little knowledge on anything, I thought this would be a fun project to try and complete in a day or two.
Comment: Fair enough.  Good luck to you sir.


Let $\sum\limits_{n = 0}^{\infty} \| x_{n+1} - x_{n} \| $ converges, then $ x_n $ is a fundamental sequence?

Question: Let $\sum\limits_{n = 0}^{\infty} \| x_{n+1} - x_{n} \| $ converges, then $ \{x_n\}_{n = 0}^\infty $ is a fundamental sequence?
Comment: Welcome to StackExchange! People here prefer that the questions asked have some context behind them. What have you tried? Why does this interest you? You can add this info in an [edit](https://math.stackexchange.com/posts/3487373/edit).
Comment: For large $A,B$ you have $\epsilon>\sum_{n=A}^{B}\|x_{n+1}-x_n\|\geq\|\sum_{n=A}^{B}(x_{n+1}-x_n)\|=\|x_{B+1}-x_A\|$.
Comment: What is a fundamental sequence?
Comment: That is **Cauchy sequence**
Answer: Yes, since for all $n>m\geq M$:
$$\|x_m-x_n\|\leq \sum_{k=m}^{n-1}\|x_{k+1}-x_k\|\leq \sum_{k=M}^\infty \|x_{k+1}-x_k\|$$
and this tail sum goes to zero as $M \to \infty$.


PrimeUI dropdown button cutted

Question: I a trying to use the dropdown component, but the dropdown button looks like cutted and the submit button isn't aligned with the dropdown. I taked a screenshot. Take a look:

With PrimeUI, I am using other libraries:

Bootstrap 3.3.2;
jQuery 2.1.3;
jQuery UI 1.11.2;

These libraries are added in this order:
{{ HTML::script('jquery/jquery-2.1.3.min.js') }}
{{ HTML::script('bootstrap/js/bootstrap.min.js') }}
{{ HTML::script('jqueryui/jquery-ui.min.js') }}
{{ HTML::script('primeui/primeui-1.1-min.js') }}

{{ HTML::style('bootstrap/css/bootstrap.min.css') }}
{{ HTML::style('bootstrap/css/bootstrap-theme.min.css') }}
{{ HTML::style('jqueryui/jquery-ui.min.css') }}
{{ HTML::style('primeui/themes/bootstrap/theme.css') }}
{{ HTML::style('primeui/primeui-1.1-min.css') }}

My HTML:

Perfis Cadastrados

        <select id="perfilSelecionado">
            @foreach($perfisDisponiveis as $perfil)
            <option value="{{$perfil->perfil}}">{{$perfil->perfil}} - {{$perfil->descricao}}</option>
            @endforeach
        </select>
        <button type="submit" id="btnAdicionarPerfil">Adicionar</button>

Answer: Found the problem and a workaround. There's a incompatibility with bootstrap. So, if I remove the bootstrap CSS from my code, more specifically, this line:
{{ HTML::style('bootstrap/css/bootstrap.min.css') }}

The button layout works like a charm. However, I can't remove the bootstrap from my project, then I added a custom CSS to fix this little problem. Here the CSS I used:
.pui-dropdown .pui-dropdown-trigger {
    padding: 0px;
    width: 20px;
}

PrimeUI dropdown button cutted


How can I properly use vibrato on the first chord of "Slow Dancing in a Burning Room"?

Question: The opening guitar part of John Mayer's "Slow Dancing in a Burning Room" features a fair amount of vibrato. I'm trying to master this part, but I'm having difficulty with the first chord (C#m).
The way I was taught to vibrato is to apply the motion from the wrist. However, due to the thumb wrap for the C# (9th fret of the low E string), I find it very difficult to move my wrist correctly to achieve a pleasant-sounding vibrato. It seems to be alright for the G# (11th fret of the A string), but I'm getting almost no vibrato on the E (9th fret of the G string).
This video clearly shows how John does it. Can anyone provide tips for how I can play it more like he does? Thanks!
Comment: John has big hands and particularly long thumbs. That makes the "wrap the thumb around the neck" very comfortable for him and gives the rest of the hand lots of space for the vibrato. I can't do that at all, so I need to re-finger everything when I play a JM song.
Answer: I knew most of what I know about guitar before John got big, so I've never really dug into him, but everything I've seen tells me I should take a look.
Chord vibrato is tough, and off the top of my head, I can't think of another song that features it. Beyond "search for videos of people trying to teach it" and "search for live versions of John playing it with better views off his hands", my take is that he's using left-right vibrato, which comes more from the elbow.
Vibrato is very personal, and while I can describe certain options, telling you what he's doing and what you should without hearing you is going to try be difficult. Keep at it and good luck.
Comment: Thanks for the answer! Can you tell me a little more about doing vibrato from the elbow?
Comment: Wow! I just tried it, and it makes a huge difference. I did notice my elbow doesn't actually move much, but thinking about applying the motion from the elbow rather than the wrist makes it a lot easier. It also sounds a lot smoother. Thanks for the tip!
Answer: John looks like he's turning a key with his left hand/arm to apply that vibrato. It's not wrist motion, it's from the elbow.
Using very light gauge strings will help. Probably having ridiculously large hands does too, but I wouldn't know.
Comment: glad it is working better for you!
Comment: Thanks for the answer! Can you tell me a little more about doing vibrato from the elbow? (Edit: I actually took another look at the video, and it doesn't really look like John's elbow moves much at all. I'm not sure he's doing from the elbow, but I'll give it a try!)
Comment: Wow! I just tried it, and it makes a huge difference. I did notice my elbow doesn't actually move much (just like I mentioned for Mayer), but thinking about applying the motion from the elbow rather than the wrist makes it a lot easier. It also sounds a lot smoother. Thanks for the tip!
Comment: Thanks! I definitely still have a lot of practicing to do on it, but I'm happy it's already making a difference.


Multiplying two integrals becomes a double integral?

Question: I ran by this in a textbook:
\begin{align*}
I^2 & =\left(\int_{-\infty}^\infty e^{-x^2/2}dx\right)\left(\int_{-\infty}^\infty e^{-y^2/2}dy\right)\\
& =\int_{-\infty}^\infty\int_{-\infty}^\infty e^{-x^2/2}e^{-y^2/2}dxdy=\int_{-\infty}^\infty\int_{-\infty}^\infty e^{-(x^2+y^2)/2}dxdy
\end{align*}
How come this is valid? I assume it's not generally true because it doesn't seem like you can just go around mashing integrals together. Does it only work because they are independent variables? And therefore constants with respect to each other?
Comment: Yes, that's right.
Comment: you are not changing something, the first expression is exactly the same than the last one
Answer: Yes:\begin{align}\int_a^b\int_c^df(x)g(y)\,\mathrm dx\,\mathrm dy&=\int_a^bg(y)\int_c^df(x)\,\mathrm dx\,\mathrm dy\\&=\left(\int_a^bg(y)\,\mathrm dy\right)\left(\int_c^df(x)\,\mathrm dx\right).\end{align}


error using plotly " more elements in the method signature (2) than in the generic signature (1) for function 'asJSON'"

Question: My error here is similar to this post, but I couldn't understand how to use the solution for that post for my situation.- I am using xtabs to convert data in columns to a matrix for a plotly surface plot as per this. In the real df, there is more than one value in the second column (the dataset was created using expand.grid to get some model predictions).
An example:
df <- read.table(text =
  "WtavR  WcsavR      pred
1  18.62672 0.03825 0.6113332
2  18.73131 0.03825 0.6079856
3  18.83590 0.03825 0.6046379
4  18.94049 0.03825 0.6012903
5  19.04508 0.03825 0.5979427
6  19.14967 0.03825 0.5945950
7  19.25426 0.03825 0.5912474
8  19.35885 0.03825 0.5878998
9  19.46344 0.03825 0.5845521
10 19.56803 0.03825 0.5812045
11 19.67262 0.03825 0.5778568
12 19.77721 0.03825 0.5745092
13 19.88180 0.03825 0.5711616
14 19.98639 0.03825 0.5678139
15 20.09098 0.03825 0.5644663
16 20.19557 0.03825 0.5611187
17 20.30016 0.03825 0.5577710
18 20.40475 0.03825 0.5544234
19 20.50934 0.03825 0.5510758
20 20.61393 0.03825 0.5477281", header = T)

p6 <- plot_ly(z = ~xtabs(pred ~ WtavR + WcsavR, data = df)) %>% add_surface()

p6

This gives the following error

Error in matchSignature(signature, fdef) :
more elements in the method signature (2) than in the generic signature (1) for function 'asJSON'

I would appreciate any help. I am just after a surface plot of model predictions.
Answer: xtabs() produces an object of class xtabs rather than a plain matrix.
By removing that class, I found that I could get plotly to behave:
df      <- expand.grid(x=0:9, y=0:9) %>% mutate(z=x*y)
surface <- unclass(xtabs(z ~ x + y, data = df))
plot_ly(z = ~surface) %>% add_surface()

Comment: Thanks for that David :)

error using plotly " more elements in the method signature (2) than in the generic signature (1) for function ‘asJSON’"


Pegar valores de checkbox num array

Question: Como consigo pegar o valor do checkbox no código abaixo?
É uma lista de presença e esse código eu modifiquei para um que uso um pouco diferente e desse jeito que está eu não sei como pegar os valores dos checkboxes marcados para poder em cada nome na tabela lançar a data em cada nome.
Tipo eu trago os nomes da tabela e os que estiverem presentes eu marco o checkbox e, quando salvar, a data vai ser escrita em cada nome que estiver marcado.
Segue o código:

              <?php

  $getfamilia = "SELECT * FROM $tabela";
  $getfamiliaquery = $mysqli->query($getfamilia);
  while($getfamilialine = mysqli_fetch_array($getfamiliaquery))
  {
   $fn1="Em Andamento";
   $familia = $getfamilialine['nome'];
   $familia_id = $getfamilialine['id'];
   $fn=$getfamilialine['finalizado'];
   if(strcasecmp($fn, $fn1) == 0)
   {
   echo "

     $familia
      <input type='checkbox' name='op'>

   ";
   }
  }

  echo "
"; /*fecha a tabela apos termino de impressão das linhas*/
print_r($mysqli->error);
if($mysqli->connect_errno)
{
 echo"Falha na conexao";
}

else
{

}
 ?>

     <input type="submit" value="SALVAR" />

Comment: Kelly, tentou passar o valor do ID no input: ``
Comment: tive essa ideia mas n cheguei a fazer pois ia pesquisar se podia fazer isso no value do checkbox vou ver aki
Comment: tentei pegar pelo id mas da erro na linha do update pq o id e um array. fiz isso aki mas n sei se ta certo.
query("UPDATE $tabela SET d1 = '$data' WHERE id = $item");

  print_r($mysqli->error);

}
if($mysqli->connect_errno)
    {
    echo"Falha na conexao";
    }

   else
    {

    echo"";
    echo "";
    }

?>
Comment: Kelly, postarei uma resposta.
Comment: http://pt.stackoverflow.com/questions/92898/deletar-apenas-checkbox-selecionados-php/92917#92917
Comment: coloquei o codigo respondendo minha pegunta.... na tabela eu tenho as colunas d1 a d7 na qual tem q ir a data da presença de quem estiver presente. andei mexendo mas so entra no for. n entra em nenhum if. se a quantidade for igual a quantidade x insere a data na coluna correta
Answer: Você deve colocar nome do Checkbox com []
Exemplo:
<input type='checkbox' name='op[]'>

e para pegar os dados, já criada a array, basta você dar
implode(',', $_POST['op']);

Caso queira saber mais, veja:
http://php.net/manual/en/faq.html.php#faq.html.arrays
Answer: Kelly, apenas não passei os valores para as variáveis $familia e $familia_id, fiz direto, mas fique à vontade.
O conceito é exatamente aquele que comentamos, a mágica está em  value='".$getfamiliaquery["id"]."' name='op[]' value armazena o id da família no loop (while), e name armazena a cada loop montando índices que será resgatado via POST assim: $_POST['op'][0], $_POST['op'][1], $_POST['op'][2], e assim por diante.
<form action="" method="POST">

            <?php

            $getfamilia = "SELECT * FROM $tabela";
            $getfamiliaquery = $mysqli->query($getfamilia);

            while($getfamilialine = mysqli_fetch_array($getfamiliaquery)) {
                if($getfamilialine["finalizado"] == "Em Andamento") {
                    echo "

                            ".$getfamilialine["nome"]."
                            <input type='checkbox' value='".$getfamilialine["id"]."' name='op[]'>

";
                }
            }

            echo "
";
            ?>

            <input type="submit" name="salvar_ok" value="SALVAR" />

    <?php
        // Aqui imprime o resultado retornado via POST
        if($_POST["salvar_ok"]) { // Se clicar no botão SALVAR executa o bloco abaixo
            for($i = 0; $i < count($_POST["op"]); $i++) { // Loop enquanto houver conteúdo na array
                echo $_POST["op"][$i]."
"; // $_POST["op"][0], $_POST["op"][1], $_POST["op"][2], $_POST["op"][3]........
            }
        }
    ?>
</form>

Comment: essa parte aki
 ".$getfamiliaquery["nome"]."

";

tive q tirar do jeito q vc fez e deixar do meu jeito pq assim nao apareceu o nome e o chekbox.

o que mostra no for eu joguei em outra pagina q é a q executa tudo o cadastro no banco e tals...
Comment: troquei e nao ta cadastrando no banco o pq eu nao sei. nao consegui testa no meu pc pelo localhost nao sei mas a pagina n abre direito pra mim. joguei em um servidor q é onde eu to pondo o site porem fala q cadastra mas quando puxo os dados nao tem nada porem eu nao to conseguindo acessa o servidor pra ver a minha tabela.... mas vou ir tentando aki qualquer coisa eu posto
Comment: Perdão Kelly, como tive que simular seu banco de dados para testar o código, inverti as variáveis rsrsrs. Corrigi o código na resposta. Desculpe.
Comment: eu nao estou conseguindo inserir os dados no banco de dados pelo for. meu cadastro chama um a outra pagina q é a q faz a inserção no banco. ele entra no for mas nao entra nas condições pra compara e fazer a inserção mas se eu ponho um echo ele mostra o q ta na variavel.
Comment: Consegue adicionar à sua resposta o conteúdo do código da outra página que faz o insert/update no banco de dados? Aí ficará mais fácil lhe auxiliar.
Comment: @KellyCris vi o restante do código que postou. Agora acredito que eu já não esteja entendo o objetivo. O que pude compreender é que primeiramente o form (checkbox) é listado a partir de uma consulta SQL em seu BD, portanto o que entendi que quer fazer é apenas um UPDATE no status, tipo de "Em Andamento" para "Finalizado", não seria isso?
Comment: seria o termino do tratamento mas eu ja resolvi o problema de cadastro ja esta funcionando.
Answer: Antes de mais nada, seu código precisa de alguns ajustes, vou reformatá-lo abaixo. Para você pegar uma coleção através de um método post, você precisa tratar seus inputs como array e capturá-los da mesma forma, para fazer isso, formatei seu código da seguinte maneira:
<?php

if ($mysqli->connect_errno) {
    echo "
Falha na conexão:\n";
       print_r($mysqli->error);
    echo '
'; die();
}

if ($_POST) {
  if (count($_POST['op'])) {
       foreach ($_POST['op'] as $key => $selecionado) {
          $familia_id = $_POST['familia_id'][$key];
          $familia    = $_POST['familia'][$key];
          $status     = $_POST['status'][$key]
          $addFamily  = "INSERT INTO $tabela (id, nome, finalizado)
                         VALUES ('$familia_id','$familia','$status')";
          $addFamilyQueryByStatus = $mysqli->query($addFamily);
      }
  }
  echo "
Salvamento processado com sucesso!
";
 die();
}

$getfamilia = "SELECT * FROM $tabela where finalizado = 'Em Andamento'";
$getfamiliaquery = $mysqli->query($getfamilia);

 ?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post" name="salvar">

        <?php
        if ($getfamiliaquery) {
            while ($getfamilialine = mysqli_fetch_array($getfamiliaquery)) {
               $fn1        = "Em Andamento";
               $familia    = $getfamilialine['nome'];
               $familia_id = $getfamilialine['id'];
               $fn         = $getfamilialine['finalizado'];

                echo "

                    {$familia}

                      <input type=\"checkbox\" name=\"op[]\" value="1">
                      <input type=\"hidden\" value="{$fn}" name=\"status[]\">
                      <input type=\"hidden\" value="{$familia}" name=\"familia[]\">
                      <input type=\"hidden\" value="{$familia_id}" name=\"familia_id[]\">

                ";
            } //fim do loop
        } else {
          echo "
Não há dados em andamento para serem processados.
";
        }
       //ob: você já fechou a tabela logo abaixo.
    ?>

          <input type="submit" value="SALVAR" />

</form>

Uma observação: eu refatoraria sua tabela trocando o nome de "finalizado" para "status".
Answer: o codigo q ta na outra pagina

<?php
$nome=$_POST['familia'];
$data=$_POST['date'];
$id=$_POST['familia_id'];
$tabela=$_SESSION['tabela'];
$qtd=$_SESSION['qtd'];

if($_POST["salvar_ok"]) {
            for($i = 0; $i < count($_POST["op"]); $i++)

   {
               echo"$data";
      echo"$qtd";

      if($qtd=="NULL")

      {

      $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d1) VALUES('$data')");

      echo"$data";

         print_r($mysqli->error);

      }

      if($qtd=='1')

      {

      $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d2) VALUES('$data')");

         print_r($mysqli->error);

      }
      if($qtd=='2')

      {

      $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d3) VALUES('$data')");

         print_r($mysqli->error);

      }
      if($qtd=='3')

      {

      $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d4) VALUES('$data')");

         print_r($mysqli->error);

      }
      if($qtd=='4')

      {

      $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d5) VALUES('$data')");

         print_r($mysqli->error);

      }
      if($qtd=='5')

      {

      $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d6) VALUES('$data')");

         print_r($mysqli->error);

      }
      if($qtd=='6')

      {

      $fn="sim";
      $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d7, finalizado) VALUES('$data', '$fn')");

         print_r($mysqli->error);

      }

            }
        }

if($mysqli->connect_errno)
    {
    echo"Falha na conexao";
    }

   else
    {

    }

print '
';
var_dump($_SESSION);
print '
';

?>

Pegar valores de checkbox num array


How to make a mock object throw an exception in Google Mock?

Question: With Google Mock 1.7.0, I have a mock object with a method, and I want to expect it to be called, and in this case the mocked method should throw an exception.
ObjectMock object_mock_;
EXPECT_CALL(object_mock_, method())
  .Times(1)
  .WillRepeatedly(???);

Is there a Google Mock action that throws an exception?  I did not find it in the documentation, yet I doubt that nobody has needed it so far.
Thanks!
Answer: Just write a simple action that throws an exception:
ACTION(MyThrowException)
{
    throw MyException();
}

And use it as you would do with any standard action:
ObjectMock object_mock_;
EXPECT_CALL(object_mock_, method())
  .Times(1)
  .WillRepeatedly(MyThrowException());

There's also a googlemock standard action Throw(), that supports throwing exceptions as action taken (Note that MyException must be a copyable class, to get this working!):
ObjectMock object_mock_;
EXPECT_CALL(object_mock_, method())
  .Times(1)
  .WillRepeatedly(Throw(MyException()));

Find the full documentation for ACTION and parametrized ACTION_P<n> definitions in the GoogleMock CookBook.
Comment: error: macro "ACTION_P" requires 2 arguments, but only 1 given
Comment: @user1735594 Sorry, indeed `ACTION_P` is intended to receive extra parameters, which aren't needed in your case. I'll edit my answer accordingly.
Comment: I fairly don't get why this answer received a downvote? That can't have really something to do with it's content, but was probably meant personally.
Comment: Can you tell us what #include we need for Throw to work? It isn't found when I include `#include ` and
`#include `
Answer: The syntax for this is Throw(exception), where exception is any copyable value.
ObjectMock object_mock_;
EXPECT_CALL(object_mock_, method())
  .Times(1)
  .WillRepeatedly(Throw(exception));


Step By Step how to graph trig from local maxima and minimum

Question: Question
The Secant Graph has the local minimum point at $(-0.75,-1.5)$ and it has a local maximum at $(2.25,-2.5)$
Give the equation in the form: $y=A \sec(Bx+C)+D$
My thought process&steps until I got stuck
First I find the Period
I do this by finding the horizontal distance from the minimum and maximum and multiply that number by $2$ to get the distance aka the period. that means the distance from the minimum to the maximum is $3$ so the period is $6$.
Then I find $B$
As anyone knows, the way you get the period is to do $\frac{2\pi}{B}$ that means $\frac{2\pi}{B}=6$. then we can deduce that $B$ is going to be $\frac{\pi}{3}$. We also recognize the fact that ($\frac{\pi}{3}(x)+c)=0$ sets up the beginning of the primary period.
Then I find the amplitude
This fairly easy, i just found it to be $0.5$
What I have so far
we have the following right now: $\frac{1}{2}\sec(\frac{\pi}{3}x+C)-2$
Now my question is how to find what is $C$?
After that i plug in -0.75 into the equation as follows:
$\frac{1}{2}\sec(\frac{\pi}{3}(\frac{-3}{4})+C)-2=1.5$
Answer: $y=\frac12\sec(\frac\pi3x)-2$ has a minimum at $(0,-1.5)$ and a maximum at $(3, -2.5)$. You only need to shift your graph to the left by $0.75$. Hint: To shift a graph to the left by $C$, change $f(x)$ to $f(x+C)$.


Effect of adding more sample data on Maximum Likelihood estimator

Question: I have samples $\{x_1, x_2, x_3, \dots , x_n\}$ of a random variable $X$. I compute Maximum Likelihood Estimator $\hat{\theta}_n$ using the sample data.
Now, if I collect one more sample $x_{n+1}$ and compute the MLE $\hat{\theta}_{n+1}$ again with $n+1$ samples. Would it be possible to prove that $\hat{\theta}_{n+1}$ is a better estimate of true parameter than $\hat{\theta}_{n}$?
Please note that I am only adding one more sample $(x_{n+1})$ to the existing sample set $\{x_1, x_2, \dots , x_n\}$. I am not sampling n+1 data points again.
Comment: With 'better estimate' you mean lower expected mean squared error?
Comment: Do you mean whether $\hat\theta_{n+1}$ is better than $\hat\theta_{n}$, *unconditional* on $\hat\theta_{n}$? When $\hat\theta_{n}$ happens to be close to, or equal to $\theta$, then  $\hat\theta_{n+1}$ won't necessarily be better. So it is not true for every specific case/realization.
Comment: While Xi'ans example is for an unbiased estimator, the same works for the MLE. There will always be a non-zero number of possible results for $x_{n+1}$ that will lead to a worse estimator, or at least not better (the uniform distribution $\mathcal{U}(0,\theta)$ is actually an, not so common, interesting case where an extra sample point can't make the MLE worse). An example is the sample mean for a sample from a normal distributed population, which can get further away from the population mean when you increase the sample size.
Comment: No, not for all possible realisations of the $n+1$ sample.
Comment: @Xi'an Can you please elaborate on that? I am not sampling (n+1) data points again. I am only sampling one more data point and adding to the set. Are there any conditions on the (n+1)th sample to make sure that the MLE gets improved.
Comment: @MartijnWeterings With better estimate I mean if there are any theoretical guarantees that the estimate $\theta_{n+1}$ would be closer to the true parameter when compared with $\theta_n}. I am not looking for the limiting case when n tends to be infinite.
Comment: @Xi'an Yes I am aware of the term.
Comment: @neo89 there are both probabilities of getting closer and further. How do you wish to compare/weigh these? You need to specify it more precisely to get rid of ambiguities.
Comment: For instance, if the $n$-sample is an iid sample from $\mathcal U(0,\theta)$, the best unbiased estimator is $(n+1)x_{(n)}/n$. Observing a new observation $x_{n+1}$ such that $x_{n+1}<x_{(n)}$ leasd to a _worse_ estimator since $(n+2)x_{(n)}/(n+1)<(n+1)x_{(n)}/n$.
Comment: @MartijnWeterings Thank you for the clarification. That makes sense. I was looking for a metric analogous to consistency of an MLE but for finite data.
Comment: @neo89, I believe that you could achieve something like that when you formulate it different. For instance, I am sure that there will be some reasonable conditions such that $$E ((\hat\theta_{n+1}-\theta)^2)<E((\hat\theta_n-\theta)^2)$$Or when you start from some particular $\hat\theta_{n} $ there will be some non zero finite $k $ such that $$ E ((\hat\theta_{n+k}-\theta)^2)<(\hat\theta_n-\theta)^2$$
Answer: If you add an extra point to the data then the estimate may get worse, or at least is not neccesarily becoming better.
There will always be a non-empty set of possible results for $x_{n+1}$ that will lead to a worse estimator, or at least not better.

An example where an extra point can't make the MLE worse (but there are still points that won't make it better) is the uniform distribution
$\mathcal{U}(0,\theta)$ where an extra sample point can't make the MLE worse (since the MLE is the sample maximum which won't decrease upon adding an extra point). However, as Xi'an showed in his comment, the the least variance unbiased estimator for this case can get worse when you add an extra point to the sample.
An example where the MLE can get worse is the sample mean which is the MLE in the case of estimating the mean for a normal distributed population. The sample mean can get further away from the population mean, get worse, when you increase the sample size.


How to set python-docx paragraph alignment to rtl

Question: I am trying to write a docx file using python, and I need the text to be rtl.
found some information in documentation, but for some reason it does not work..
my code:
import docx

doc = docx.Document()

style = doc.styles.add_style('rtl', docx.enum.style.WD_STYLE_TYPES.PARAGRAPH)
style.font.rtl = True

p = doc.add_paragraph(style='rtl')
p.add_run('my rtl aligned text')

doc.save(path)

Comment: *but for some reason it does not work..* How so?
Comment: the alignment is still ltr when i open the file... @Kasramvd
Answer: You should use the following instead
style = doc.styles.add_style('rtl', WD_STYLE_TYPE.CHARACTER)


How do I display the title of the entities to which the user has no access?

Question: I created a new content type with entity references to standard pages. I am using the Taxonomy Access Control module to control the access to these pages.
When users view a node of that content type, they unfortunately do not see page titles for which they do not have access (the title is a teaser). I want all entities to be listed (with the links to the pages), even if the users do not have access to actual page. Is that possible?
Answer: It doesn't make sense to list links because if users follow it they will only see the Access denied page.
But you can create a Views list with the titles and disable the node access check for those Views. You have to be really careful not to reveal something unintentionally!
In d8 you can disable the node access check under Query options > Disable SQL rewriting, it may be called differently in D7 but it will be in approximately the same location.


Probability and Counting

Question: Suppose You are ordering two pizzas.A pizza can be small,medium,large or extra large,with any combination of 8 possible toppings( getting no toppings is allowed, as is getting all 8) How many possibilities are there for your two pizzas?
Answer:- My answer is $1,048,576$ possibilities
You can select any one of the four sizes in 4 ways. You can select any combination of 8 possible toppings in $(2)^8=256$ ways. For one pizza total possibilities are $4*256=1024$.So, for two pizzas, $(1024)^2=1,048,576$ possibilities.
If we treat sizes and toppings of two pizzas indistiguishable, then we can select 6 combinations of pizzas as per sizes.
These combinations are 1)Small-Medium 2)Small-Large 3)Small-Extra Large 4)Medium-Large 5)Medium-Extra Large 6)Large-Extra Large.
Each combinations can have 255*256=65280 different toppings from the 8 types of toppings. So the total possibilities for two pizzas are 3,91,680.
Comment: Actually it depends if the pizzas are distinguishable or not.
Comment: I want to know my answer is correct or not. I don't have the  correct answer for confirmation.
Comment: First, try it for S and L pizzas with or without mushrooms & with or without sausage.
Comment: This is a `[self-study]` question, so please tell us how did you tried to solve it and where are you stuck? What kind of help you need from us? I see that you edited your question to delete the attempted solution, but it would really help if you've shown what have you tried, even if it is incorrect.
Comment: @Tim, i was not confident about the previously attempted solution, so when i got correct solution after some logical thinking, i deleted the wrong solution and added correct solution.
Comment: @jsk The answer is right as it's ((2^8)*4)^2 = 2^20 = 1.048.576
Comment: Expanding on @gunes' point: you're distinguishing between the cases in which (1) the 1st pizza is a small one topped with ham & the 2nd a large one topped with mushrooms, & (2) the 1st pizza is a large one topped with mushrooms & the 2nd a small one topped with ham.
Comment: @Scortchi,  Yes, I am distinguishing these case of pizzas.if pizzas are indistinguishable, what would be your answer?
Comment: First divide your $1024^2$ pairs into cases where (1) the pizzas have the same size & topping & (2) cases where they differ. Then work out what proportion of case-2 pairs are indistinguishable. It could help to start off by working it out when there's a small no. types of pizza.
Answer: So... If you only want to know whether the answer is right or wrong.... It's right! Good job!
But for the next time, consider using http://math.stackexchange.com since your question has nothing to do with statistics or probability
EDIT: As @gunes pointed out, you must divide by two if the order of the pizzas does not matter
Comment: I see - sorry! But is it not the case then that to get the number of distinct unordered pairs, you divide only the count of distinct ordered *unalike* pairs by two and add that to the count of distinct ordered like pairs? So with just two types of pizza, A & B, there are three distinct unordered pairs: A-A, B-B, & A-B?
Comment: @David. If you roll two distinguishable dice, there are 36 possible rolls. However, if they are not distinguishable, and 1,2 is same as 2,1, then you have 21 possible rolls 1,1 2,2,..6,6 were each only counted once, so they weren't double counted. A good trick in these problems is to make the problem simple enough that you can enumerate the possibilities and check your logic.
Comment: Or, sticking with pizza, if there are just two types, A & B, then the $2^2$ distinct ordered pairs are A-A, B-B, A-B, & B_A. How many distinct *unordered* pairs are there?
Comment: @David Do the math for the situation that scorchi described. By your logic, you would multiply 2×2=4 (squaring the possibilities for 1st and 2nd pizza) then divide by 2 to remove the duplicates leaves you with an answer of 2, which is wrong because the 3 distinct possibilities are AA, AB, and BB. You are correct that some possibilities are double counted, but wrong about how to remove the duplicates.
Comment: I think you need to try to explain why you'd divide by two - you'll probably see then why you wouldn't.
Comment: Well, there are two possible ways of ordering two pizzas (A-B and B-A) which would be indistinguishable. Please note that the original poster is just asking for a check on whether his answer is right/wrong, not a full in-detail explanation of how to get the result
Comment: @Scortchi You are ordering two pizzas. Pizza A and Pizza B. You cannot have A-A nor B-B. You either have A-B or B-A which are the same!
Comment: If you can't have two of the same type of pizza (an odd restriction, not imposed by pizzerias in my neck of the woods), then there are only $1024^2 - 1024=1\,047\,552$ possibilities when the order does matter.
Comment: @Scorchi You're getting my point wrong. Let's say I order two pizzas: one a margarita (A) and the other one with bacon (B) If I am ordering "B-B", I am ordering two bacon pizzas, which is already considered as a distinct case, not a permutation of my margarita-bacon combination

Probability and Counting


Returning boolean from oracle function or procedure with out parameter

Question: I need to develop a web application with php.For login process , .Normally I would use select statement with id and password , if row returns then it is successful login.But I want to use stored procedure and don't want to get any row from database but simple boolean value.The signature of PL/SQL process is below.
procedure successful_login(cit_id in citizens.citizen_id%type,
                           pass in varchar2,v_login_successful out boolean)

I won't bloat page with code but procedure changes v_login_successful to true or false depending on successful login, in PL/SQL.But I want to call this procedure from PHP.If I bind a php variable to v_login_successful parameter and execute procedure from PHP, will PL/SQL engine return changed version of v_login_successful variable back to PHP?
Answer: PL/SQL has Boolean datatype, but SQL doesn't have. Which means, you can

use it in functions, procedures, anonymous blocks.
use it as parameters in procedures and functions, only if they are used in PL/SQL context.

When you are calling the procedure from php, it will be a sql statement. You will get, expression is of wrong type exception.
Instead, you can use CHAR(1) (Y or N) or NUMBER(1) (0 or 1) datatype for out parameter.


Is negative floating point zero guaranteed to evaluate to false in C?

Question: I know that 0.0 == -0.0 and that the C standard says if(a) is equivalent to if(a!=0), but:
Is if(-0.0) guaranteed to evaluate as false by the standard? Would an implementation be buggy if if(-0.0) is evaluated as true?
I guess the key point here is whether the if(a!=0) meaning of if(-0.0) must be understood as exactly the same != operator as in floating point, in which case there would be guarantee that it must be false.
Comment: Sometimes using +0.0 and -0.0 have a [different](https://stackoverflow.com/questions/25332133/what-operations-and-functions-on-0-0-and-0-0-give-different-arithmetic-results) arithmetic result in code, but not with `if()`.
Comment: Note: `-0.0` is a double value, not a floating point value.  To make it a floating point value write it as: `-0.0f`  Notice the trailing 'f'
Comment: @user3629249 : Both `double` and `float` are floating point types, just like all the formats defined by IEEE 754.
Answer: C 2018 188.8.131.52 specifies the behavior of the if statement, with its if … else form. Paragraph 2 says:

In both forms, the first substatement is executed if the expression compares unequal to 0…

Per the floating point model in C 2018 184.108.40.206.2 paragraphs 2 and 3 (which contain mathematical typography I will not reproduce here but say a floating-point number is defined by multiplying a sign +1 or −1 by a scaled power of the floating-point base and a sum of its digits each appropriately scaled for its position), the mathematical value of −0 is zero, the same as +0, so it compares equal to zero. Therefore if (-0.) will not execute the first substatement.


Evaluation of $\int\frac{1}{\prod_{k=0}^{n}(x+k)}dx$

Question: Evaluation of $\displaystyle \int\frac{1}{\prod_{k=0}^{n}(x+k)}dx$
$\bf{My\; Trial::}$We can write
$\displaystyle \int\frac{1}{\prod_{k=0}^{n}(x+k)}dx = \int \frac{1}{(x+0)\cdot(x+1)\cdot (x+2)..........(x+n)}dx$
Now Using Partial fraction.......
$\Rightarrow \displaystyle \frac{1}{(x+0)\cdot (x+1)\cdot (x+2).........(x+n)} = \frac{A_{1}}{x}+\frac{A_{2}}{(x+1)}+\frac{A_{3}}{(x+2)}+....+\frac{A_{n}}{(x+n)}.$
Now How can I solve after that
Help Required
Comment: Do you know how to integrate $1/x$?
Answer: HINT:
Multiply either sides by $\prod_{r=0}^n(x+r)$
Set $\displaystyle x+s=0\iff x=-s,0\le s\le n$ to find $$1=A_{s+1}\left(\prod_{r=0,r\ne s}^n{r+n}\right)$$
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
Note that
\begin{align}
&\Gamma\pars{x}={\Gamma\pars{x + 1} \over x}
={\Gamma\pars{x + 2} \over x\pars{x + 1}}
=\cdots={\Gamma\pars{x + n + 1} \over x\pars{x + 1}\ldots\pars{x + n}}
\\[3mm]\mbox{such that}&\quad
{1 \over x\pars{x + 1}\ldots\pars{x + n}}
={\Gamma\pars{x} \over \Gamma\pars{x + n + 1}}
\end{align}

\begin{align}&\color{#c00000}{\int{\dd x \over x\pars{x + 1}\ldots\pars{x + n}}}
=\int{\Gamma\pars{x} \over \Gamma\pars{x + n + 1}}\,\dd x
={1 \over n!}\int{\Gamma\pars{x}\Gamma\pars{n + 1}\over
\Gamma\pars{x + n + 1}}\,\dd x
\\[3mm]&={1 \over n!}\int\int_{0}^{1}t^{x - 1}\pars{1 - t}^{n}\,\dd t\,\dd x
={1 \over n!}\int_{0}^{1}\pars{1 - t}^{n}\int t^{x - 1}\,\dd x\,\dd t
\\[3mm]&={1 \over n!}\ \overbrace{%
\int_{0}^{1}\pars{1 - t}^{n}{t^{x- 1} \over \ln\pars{t}}\,\dd t}
^{\ds{\mbox{Set}\ t \equiv \expo{-\xi}\ \imp\ \xi = -\ln\pars{t}}}\ =\
{1 \over n!}\int_{\infty}^{0}\pars{1 - \expo{-\xi}}^{n}{\expo{-\pars{x- 1}\xi}\over -\xi}\,\pars{-\expo{-\xi}}\,\dd\xi
\\[3mm]&={1 \over n!}\int_{0}^{\infty}\pars{1 - \expo{-\xi}}^{n}\expo{-x\xi}\,{\dd\xi \over \xi}
\\[3mm]&=-\,{1 \over n!}\int_{0}^{\infty}\ln\pars{\xi}\bracks{%
n\pars{1 - \expo{-\xi}}^{n - 1}\expo{-x\xi}
-x\pars{1 - \expo{-\xi}}^{n}\expo{-x\xi}}\,\dd\xi
\\[3mm]&={1 \over n!}\bracks{%
x\int_{0}^{\infty}\ln\pars{\xi}\pars{1 - \expo{-\xi}}^{n}\expo{-x\xi}\,\dd\xi
-n\int_{0}^{\infty}\ln\pars{\xi}\pars{1 - \expo{-\xi}}^{n - 1}\expo{-x\xi}\,\dd\xi}
\end{align}

\begin{align}
&\int_{0}^{\infty}\ln\pars{\xi}\pars{1 - \expo{-\xi}}^{m}\expo{-x\xi}\,\dd\xi
=\sum_{k = 0}^{m}{m \choose k}\pars{-1}^{k}
\int_{0}^{\infty}\ln\pars{\xi}\expo{-\pars{k + x}\xi}\,\dd\xi
\\[3mm]&=\sum_{k = 0}^{m}{m \choose k}\pars{-1}^{k}
\lim_{\mu \to 0}\partiald{}{\mu}\int_{0}^{\infty}
\xi^{\mu}\expo{-\pars{k + x}\xi}\,\dd\xi
=\sum_{k = 0}^{m}{m \choose k}\pars{-1}^{k}
\lim_{\mu \to 0}\partiald{}{\mu}\bracks{%
\Gamma\pars{\mu + 1} \over \pars{k + x}^{\mu + 1}}
\\[3mm]&=\sum_{k = 0}^{m}{m \choose k}\pars{-1}^{k + 1}\,
{\gamma + \ln\pars{k + x} \over k + x}
\end{align}

\begin{align}&\color{#c00000}{\int{\dd x \over x\pars{x + 1}\ldots\pars{x + n}}}
\\[3mm]&={1 \over n!}\bracks{x\sum_{k = 0}^{n}{n \choose k}\pars{-1}^{k + 1}\,
{\gamma + \ln\pars{k + x} \over k + x}
-n\sum_{k = 0}^{n - 1}{n - 1 \choose k}\pars{-1}^{k + 1}\,
{\gamma + \ln\pars{k + x} \over k + x}}
\end{align}

$\ds{\large\tt\mbox{It will continue}\ldots}$
Answer: Partial Fractions gives
$$
\begin{align}
\int\frac1{\prod_{k=0}^n(x+k)}\,\mathrm{d}x
&=\int\sum_{k=0}^n\frac{(-1)^k}{k!(n-k)!}\frac1{x+k}\,\mathrm{d}x\\
&=\frac1{n!}\sum_{k=0}^n(-1)^k\binom{n}{k}\log(x+k)+C
\end{align}
$$


How to print proprely in python using for loops

Question: I was wondering if I'm just trying to do something the wrong way or if I'm close to a viable solution.
I have to print a chess board from a Dictionary given by the teacher.
This is my code so far :
def printBoard(board):
x = 0
for x in range(0,7):
    print("|-------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|")
    print("|             |             |             |             |             |             |             |             |")
    print("|",board[0,x],"|",board[1,x],"|",board[2,x],"|",board[3,x],"|",board[4,x],"|",board[5,x],"|",board[6,x],board[7,x])
    print("|             |             |             |             |             |             |             |             |")

print("|-------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|")

board =   {
                (0,0):"Rook[B]",(1,0):"Knight[B]",(2,0):"Bishop[B]", (3,0):"Queen[B]",   (4,0):"King[B]", (5,0):"Bishop[B]", (6,0):"Knight[B]",(7,0):"Rook[B]",
                (0,1):"Pawn[B]",(1,1):"Pawn[B]",    (2,1):"Pawn[B]",(3,1):"Pawn[B]",    (4,1):"Pawn[B]",(5,1):"Pawn[B]",(6,1):"Pawn[B]",    (7,1):"Pawn[B]",
                (0,2):"EMPTY",   (1,2):"EMPTY",       (2,2):"EMPTY",   (3,2):"EMPTY",       (4,2):"EMPTY",   (5,2):"EMPTY",   (6,2):"EMPTY",       (7,2):"EMPTY",
                (0,3):"EMPTY",   (1,3):"EMPTY",       (2,3):"EMPTY",   (3,3):"EMPTY",       (4,3):"EMPTY",   (5,3):"EMPTY",   (6,3):"EMPTY",       (7,3):"EMPTY",
                (0,4):"EMPTY",   (1,4):"EMPTY",       (2,4):"EMPTY",   (3,4):"EMPTY",       (4,4):"EMPTY",   (5,4):"EMPTY",   (6,4):"EMPTY",       (7,4):"EMPTY",
                (0,5):"EMPTY",   (1,5):"EMPTY",       (2,5):"EMPTY",   (3,5):"EMPTY",       (4,5):"EMPTY",   (5,5):"EMPTY",   (6,5):"EMPTY",       (7,5):"EMPTY",
                (0,6):"Pawn[N]",(1,6):"Pawn[N]",    (2,6):"Pawn[N]",(3,6):"Pawn[N]",    (4,6):"Pawn[N]",(5,6):"Pawn[N]",(6,6):"Pawn[N]",    (7,6):"Pawn[N]",
                (0,7):"Rook[N]",(1,7):"Knight[N]",(2,7):"Bishop[N]", (3,7):"Queen[N]",   (4,7):"King[N]", (5,7):"Bishop[N]", (6,7):"Knight[N]",(7,7):"Rook[N]",
                }

printBoard(board)

My problem is that I cannot align my column.
Maybe I should just send the dictionary into 8 different list and print them that way ?
Thanks!
Edit  :
Output :
Answer: Use the methods ljust and rjust on str and unicode objects to make sure a string always prints in constant length with a padding character of your choosing. In your case:
board[0, x].ljust(11)

which evaluates to e.g.
'Pawn[B]      '

So a row would be printed like
print("|", board[0, x].ljust(11), "|", board[1, x].ljust(11, ' '), ...)

but a more compact version would be:
for x in range(8):
    row = [board[y, x] for y in range(8)]
    print('|%s|' % '|'.join(cell.lpad(13) for cell in row)

NOTE1: the range needs to be range(0, 8) not range(0, 7) because it's a non-inclusive range; also, range(0, N) is equivalent to just range(N).
NOTE2: if you need to pad using a string other than ' ', you can pass an optional second parameter to ljust (and rjust).
Comment: thanks for the tip I added the .ljust and a sep='' at the end and it works
Comment: @SKTLZ: why the `sep=''` though?


Share de produto de loja virtual para o Facebook

Question: Estou com problema pra fazer o share de um produto de uma loja virtual para o facebook.
Estou colocando as meta tags na página do produto:
<meta property='og:title'...
<meta property='og:url' ...
<meta property='og:site_name' ...
<meta property='og:type' content='website'/>
<meta property='og:image' ...
<meta property='og:description' ...

E o script que uso para abrir a janela de share está assim:
$("#btn_facebook").bind('click', function (event) {
          var twtTitle = document.title;
          var twtUrl = location.href;
          var imagem = 'http://www.meusite.com.br' + $("#Share_Image").val();
          var twtLink = 'http://www.facebook.com/sharer/sharer.php?u=' + twtUrl;
          window.open(twtLink,'', '_blank', 'location=no, menubar=no, resizable=yes, width=575, height=520, fullscreen=yes, status=no, titlebar=no, toolbar=no');
});

Até abre a janela de share corretamente com a foto e descrição do produto, mas, quando clico em compartilhar, na postagem no facebook, vão todas descrições e texto, mas, a imagem não carrega e não aparece. Aparece apenas um quadro branco sem a foto que antes apareceu.
Alguém pode me ajudar a identificar esse problema ou tem alguma solução?
Obrigado,
Alex
Answer: Isto foi porque na altura havia um bug no url scrapper do Facebook.
A razão pela qual as imagens de apresentação (og:image) não estavam a aparecer nas publicações juntamente com o resto das informações (og:title, og:descriptino etc) foi devido a este bug.
Embora para algumas pessoas este bug possa ter desaparecido no final do próprio dia (30/04/2015) enquanto se tratava do mesmo,
este erro foi totalmente corrigido e o ticket dado como resolvido uns dias depois. Mais precisamente dia - 7 de Maio 2015:
URL Scrapper Bug Status
Answer: Nesse exato momento o Facebook deve estar passando por algum problema. Tenho um site aqui que faz exatamente isso mas agora as vezes carrega e as vezes não. Esse site está a uns 2 meses online funcionando exatamente desse maneira que você mencionou. Mudando apenas o fato de no meu caso eu deixo a url https://www.facebook.com/sharer/sharer.php?u=... no próprio href com um target _blank, o Facebook que se encarrega de abrir um popup.
Ps.: Em um outro caso o Facebook não exibia de jeito algum minha imagem setada na metatag, depois descobri que era a imagem que estava pesada que levava alguns segundos para ser carregada e por isso o Facebook não exibia. Tipo um timeout da requisição. Troquei por uma imagem leve e funcionou.
Comment: A imagem que estou tentando compartilhar tem apenas 13kb, então o problema não é o peso da imagem.
Comment: E com respeito à esta instabilidade temporária do facebook, acredito que não seja o caso, pois conheço diversos sites que estão funcionando.
Comment: Ainda ontem a imagem de compartilhamento do site voltou a funcionar, no meu caso...


Design by contract tools for actionscript

Question: Are there tools for AS-3, like iContract for Java,
which can help in Design by Contract(DBC)?
(Drawing inspiration from The Pragmattic Programmer).
Answer: Adobe provides "Design by Contract Library" as a part of Cairngorm 3
Cairngorm Libraries section: http://sourceforge.net/adobe/cairngorm/wiki/CairngormLibraries/
Answer: try this simple class: http://blog.sebaslab.com/design-by-contract-class/
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes.
Comment: true, the fact is that the answer is practically the source code of the library.
Answer: From what I know there is nothing like this until now.


Adicionar nome a Chave json

Question: Nesse meu código a baixo ele me retorna json com a chave "serviços:"  porem não estou conseguindo colocar um nome   "Flight:"  na segunda chave.  como posso fazer com que essa chave seje nomeada
$final['servicos'] = [];
$fli['flight'] = [];

foreach($list as $t) {
 $data = new stdClass;

 $data->id = $t->id;
 $data->cliente = $t->comp_name;
 $data->pax = $t->firstName;
 $data->phone = $t->phone;
 $data->origin = $t->origemida;
 $data->destiny = $t->destinoida;
 $data->status = $t->tra_status;
 $data->info = $t->comments;

 //voo Flight:
 $fli = new stdClass;
 $fli->flightNumber = $t->voo;
 $fli->flightCompany = $t->cia;
 $fli->flightEnd = $t->cia;
 $fli->flightGate = $t->voo;

array_push($final['servicos'], $data,$fli);

       }

 echo json_encode($final);

a Baixo segue minha saida json
{
"servicos": [
{
  "id": 507,
  "cliente": "C2RIO OFFICE NITEROI",
  "pax": "Robert",
  "phone": "",
  "origin": "Airport GIG -RJ",
  "destiny": "Hotel Hilon Barra",
  "status": "3",
  "info": ""
},
  {
  "flightNumber": "GOL4568",
  "flightCompany": "GOL",
  "flightEnd": "GOL",
  "flightGate": "GOL4568"
  } ] }

Meu problema está aqui  teria que aparecer assim        Flight: {
   ???????{
  "flightNumber": "GOL4568",
  "flightCompany": "GOL",
  "flightEnd": "GOL",
  "flightGate": "GOL4568"
  } ] }

Answer: Se entendi a pergunta você quer adicionar um par chave/valor na representação JSON do objeto $data. Para fazer isso basta criar uma propriedade e passar o valor desejado.
<?php
$final = [];

$data = new stdClass;

$data->id = '507';
$data->cliente = 'C2RIO OFFICE NITEROI';
$data->pax = '';
$data->phone = 'Robert';
$data->origin = 'Airport GIG -RJ';
$data->destiny = 'Hotel Hilon Barra';
$data->status = '3';
$data->info = '';

//voo Flight:
$fli = new stdClass;
$fli->flightNumber = "GOL4568";
$fli->flightCompany = "GOL";
$fli->flightEnd = "GOL";
$fli->flightGate = "GOL4568";

$final['servicos'][] = $data; // Equivale a array_push($final['servicos'], $data);
$data->Flight = $fli; // Cria o par chave/valor desejado

echo json_encode($final, JSON_PRETTY_PRINT);

Que vai resultar em:
{
    "servicos": {
        "id": "507",
        "cliente": "C2RIO OFFICE NITEROI",
        "pax": "",
        "phone": "Robert",
        "origin": "Airport GIG -RJ",
        "destiny": "Hotel Hilon Barra",
        "status": "3",
        "info": "",
        "Flight": {
            "flightNumber": "GOL4568",
            "flightCompany": "GOL",
            "flightEnd": "GOL",
            "flightGate": "GOL4568"
        }
    }
}

Ou então caso você queira que a representação JSON de $final seja um array com dois itens:
<?php
$final = [];

$data = new stdClass;

$data->id = '507';
$data->cliente = 'C2RIO OFFICE NITEROI';
$data->pax = '';
$data->phone = 'Robert';
$data->origin = 'Airport GIG -RJ';
$data->destiny = 'Hotel Hilon Barra';
$data->status = '3';
$data->info = '';

//voo Flight:
$fli = new stdClass;
$fli->flightNumber = "GOL4568";
$fli->flightCompany = "GOL";
$fli->flightEnd = "GOL";
$fli->flightGate = "GOL4568";

$final['servicos'][] = $data;
$final['Flight'][] = $fli;

echo json_encode($final, JSON_PRETTY_PRINT);

Que resulta em:
{
    "servicos": {
        "id": "507",
        "cliente": "C2RIO OFFICE NITEROI",
        "pax": "",
        "phone": "Robert",
        "origin": "Airport GIG -RJ",
        "destiny": "Hotel Hilon Barra",
        "status": "3",
        "info": ""
    },
    "Flight": {
        "flightNumber": "GOL4568",
        "flightCompany": "GOL",
        "flightEnd": "GOL",
        "flightGate": "GOL4568"
    }
}

Comment: @FabioHenrique faltou colocar um `[]` ao fazer o array push.
Comment: ok era exatamente isso.... mais está afetando algo no loop.  só esta  fazendo um loop
Comment: Perfeito funcionou perfeitamente obrigado
Answer:  "Flight":[
{
  "flightNumber": "GOL4568",
  "flightCompany": "GOL",
  "flightEnd": "GOL",
  "flightGate": "GOL4568"
  }
 ] }

Comment: Gabriel, sua resposta pode ser útil, entretanto recomendo que explique-a melhor. Aconselho a fazer o  [Tour](https://pt.stackoverflow.com/tour)
Comment: è exatamente assim que queria... mais como fazer essa saida utilizando meu codigo acima

Adicionar nome a Chave json