Persistence entities not serializable

Question: I am getting following error:
SEVERE: null
javax.jms.MessageFormatException: [C4017]: Invalid message format.
at com.sun.messaging.jmq.jmsclient.MapMessageImpl.checkValidObjectType(MapMessageImpl.java:653)
at com.sun.messaging.jmq.jmsclient.MapMessageImpl.setObject(MapMessageImpl.java:632)
at buyer.Main.sendCart(Main.java:287)

after I try to send Persistence object through MapMessage in JMS system. And I am not quite sure why it happens since MapMessage accepts only serializable objects for value, and Persistence entities are serializable. I would appreciate any help! My Java code is following.
package entities;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@Table(name = "carts")
@NamedQuery(
    name = "carts.findAll",
    query = "select c from Cart c"
)
public class Cart implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "buyer_id")
private Long buyerId;

@Column(name = "card_id")
private Long cardId;

@Column(name = "successful")
private boolean successful;

@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@PrimaryKeyJoinColumn(name = "buyer_id")
private Buyer buyer;

@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@PrimaryKeyJoinColumn(name = "card_id")
private Card card;

@OneToMany(mappedBy = "cart", cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
private List<CartItem> cartItems;

public Cart() {
}

public Cart(Long buyerId, Long cardId, boolean successful) {
    this.buyerId = buyerId;
    this.cardId = cardId;
    this.successful = successful;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public Long getBuyerId() {
    return buyerId;
}

public void setBuyerId(Long buyerId) {
    this.buyerId = buyerId;
}

public Long getCardId() {
    return cardId;
}

public void setCardId(Long cardId) {
    this.cardId = cardId;
}

public boolean isSuccessful() {
    return successful;
}

public void setSuccessful(boolean successful) {
    this.successful = successful;
}

public Buyer getBuyer() {
    return buyer;
}

public void setBuyer(Buyer buyer) {
    this.buyer = buyer;
}

public Card getCard() {
    return card;
}

public void setCard(Card card) {
    this.card = card;
}

public List<CartItem> getCartItems() {
    return cartItems;
}

public void setCartItems(List<CartItem> cartItems) {
    this.cartItems = cartItems;
}

@Override
public int hashCode() {
    int hash = 7;
    hash = 53 * hash + Objects.hashCode(this.id);
    hash = 53 * hash + Objects.hashCode(this.buyerId);
    hash = 53 * hash + Objects.hashCode(this.cardId);
    hash = 53 * hash + (this.successful ? 1 : 0);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Cart other = (Cart) obj;
    if (this.successful != other.successful) {
        return false;
    }
    if (!Objects.equals(this.id, other.id)) {
        return false;
    }
    if (!Objects.equals(this.buyerId, other.buyerId)) {
        return false;
    }
    if (!Objects.equals(this.cardId, other.cardId)) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "Cart{" + "id=" + id + ", buyerId=" + buyerId + ", cardId=" + cardId + ", successful=" + successful + '}';
}
}

Relevant method that sends message.
private static Buyer sendCart(Cart cart, String tempId, Buyer buyer) {
    JMSContext context = connectionFactory.createContext(2);

    try {
        Destination queue = context.createQueue("mediator");
        JMSProducer producer = context.createProducer();

        MapMessage message = context.createMapMessage();

        message.setObject("data", cart);
        message.setObject("tempid", tempId);
        message.setObject("type", MessageType.BUYER_SENDING_CART);

        producer.send(queue, message);

    } catch (JMSException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Comment: I just want to mention that error is occurring on `message.setObject("data", cart);` line.
Comment: MapMessage can only (compiletime) check, that the object that' s the parameter is serializeable. However, if there are related Objects that are not serializeable that will fail at runtime... Are Card, Buyer, CartItem (and their related classes) serializeable to? Also, is the used implementation of List serializeable? Would start checking that ...
Comment: They are all Persistence entities, so they are all serializable...
Comment: Then Serialization shouldn't be a Problem ... seems like C0417 could be something else too... "Cause The client runtime encountered an error when processing a JMS Message; for example, during data type conversion." I'd try to get more Logoutput from MapMessage ...
Answer: The Problem is the MapMessage. According to JavaDoc:

A MapMessage object is used to send a set of name-value pairs. The
  names are String objects, and the values are primitive data types in
  the Java programming language. The names must have a value that is not
  null, and not an empty string. The entries can be accessed
  sequentially or randomly by name. The order of the entries is
  undefined. MapMessage inherits from the Message interface and adds a
  message body that contains a Map.

And:

They may also be read or written generically as objects.

So even if MapMessage offers an "setObject" Method, the parameter used must be a primitive Type.
To pass non-primitive Types use ObjectMessage
Comment: I need to use MapMessage because it has acknowledgeThisMessage() method, ObjectMessage only has acknowledge() method that acknowledges all messages and one part of my system depends on acknowledgeThisMessage() method because I need to acknowledge only the current message. If there is some alternative to it, I would gladly change it all to ObjectMessage. Do you know about some alternative? Some way to acknowledge only the last received message with ObjectMessage?
Comment: Hmm are you sure acknowledgeThisMessage doesn't work on ObjectMessage? Seems like you have to cast anyway to get that Method ( `((com.sun.messaging.jms.Message)message).acknowledgeThisMessage();`), should work on ObjectMessage too? (At least _The com.sun.messaging.jms.Message interface defines enhanced capabilities of a JMS Message in Sun Java System Message Queue._ from the JavaDoc would suggest that)
Comment: Thank you so much, I have started modifying the system and soon I will know the result, but all looks good for now!
Comment: It did! You are awesome!

Persistence entities not serializable


Using a method as callback function for a filter affects scope of the callback

Question: I ran into an issue in angular where my method loses its scope by being called as a callback function. Can someone explain why this changes to undefined?
@Component({...})
export class SomeClass {
  public status = 'any';

  public filter_account_accesses() {
    console.log( this.status );
    let account_accesses = [...];
    return account_accesses.filter( this.status_filter )
  }
  private status_filter( account_access ): boolean {
    console.log( typeof this );
    // this is undefined!
    return true;
  }
}

PS: I already know I can work around the issue by passing this as an argument. I want to know why the change of scope is happening. And optionally how I can prevent it.
Answer: Value of this in a function depends on how that function is called. Let's look at a simple example:
function A() {}
A.prototype.foo = function() {
  // do something
}

const a = new A();

If foo is called like this, the value of this inside will be the a object:
a.foo();

But if you store a reference to the foo function to some other variable, it won't be bound to the a instance anymore and the value of this will be undefined:
const f = a.foo;

f(); // <- value of this inside is undefined

This is similar to what you're doing in your code snippet: you're passing a reference to the instance method status_filter to the filter function and it's not bound to your instance, that's why when the filter callback is called the value of this inside is undefined.
You can bind the function to your instance by using bind:
return account_accesses.filter( this.status_filter.bind(this) )

It will create a copy of your function where this points to your instance.
Also, I'm recommending you this great and thorough article about how this works in JS: http://dmitrysoshnikov.com/ecmascript/chapter-3-this/
Answer: Because your function is called with array filter. There is 2 ways to do it without losing this:

Using arrow function

return account_accesses.filter(value => this.status_filter(value));

Using bind

return account_accesses.filter(this.status_filter.bind(this));


Hosted SharePoint privacy

Question: I was wondering if there is anyway to have a hosted SharePoint that is not accessible by the hosting company.
I've spoken to 2 vendors so far and one can access the site but has a audit list and the other claims that they can only access it with the administrator credentials
Because our company is almost entirely telecommuting we need somewhere to host data such as employee information (name bdate social government clearance) b.
Is this something i should be suspiciousness of? or am i just being paranoid?
Answer: Such a standard like PCI would be the best bet, this compliance regulation is not only for credit cards when looking at a host because it goes beyond in demonstrating a provide that follows the proper precautions and security to host sensitive data such as financial records, credit cards, medical files, etc.
It is understandable for paranoia when having such sensitive data and your business critical information.  Ultimately your provider should never be looking at your content however if you need more reassurance a host that practices compliance regulations might be better fitted.
If you need some recommendations feel free to reach out to me.
Comment: I need recommendations
Comment: shoot me an email firstname.lastname@example.com

Hosted SharePoint privacy


How to change $ Cx^2 + Dy^2 + Ex + Fy + G = 0$ to$ (x-h)^2/a^2 ± (y-k)^2/b^2=1 $ using only the variables C, D, E, F, and G

Question: Or, state the terms a,b,h,and k in terms of C, D, E, F, and/or G
$Cx^2 + Dy^2 + Ex + Fy + G = 0$
$(x-h)^2/a^2 ± (y-k)^2/b^2=1$
Answer: $$\begin{array}{rcl}
\\ Cx^2+Dy^2+Ex+Fy+G&=&0
\\ C(x^2+ \frac EC x)+D(y^2+\frac FD y)&=&-G
\\ C(x+\frac E{2C})^2-\frac{E^2}{4C}+D(y+\frac F{2D})^2-\frac{F^2}{4D}&=&-G
\\ C(x+\frac E{2C})^2+D(y+\frac F{2D})^2&=&-G+\frac{E^2}{4C}+\frac{F^2}{4D}
\end{array}$$
So
$$\begin{array}{cr}
\\ h=-\frac E{2C}
\\a^2= \frac{-G+\frac{E^2}{4C}+\frac{F^2}{4D}}{C}
\\ k=-\frac F{2D}
\\b^2= \frac{-G+\frac{E^2}{4C}+\frac{F^2}{4D}}{D}
\end{array}$$


the code of JavaScript files in the master page not running in web forms

Question: In Web Application Solution, I have a master page that is located in the root folder. I also have web forms that use this master page and are located in a folder in the root folder.
master page ----located----> root folder
web forms--------located----> root folder/forms
I have JavaScript that cannot run in the web form because this code can't access the source file in the scripts folder.
I used the following:

However, it results in this error:

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

How can I insert the JavaScript, that is located in a separate folder, into the master page?
Answer: Please add runat="server" to the head tag like this

Also please use Page.ResolveUrl like this

Answer: Add another asp:contentplaceholder in the  section of the Master Page where the Webforms can place their Javascript references and code.


How to set up a desktop GUI with an Amazon EC2 instance?

Question: I need to get familiar with some software that doesn't run on any of my home machines (windows/mac). So I decided to spin up an EC2 instance and try it there.
However, getting EC2 to support a remote desktop session is proving to be harder than it has a right to be.  I have tried techniques found through web searches but all are out of date and no longer relevant.
So far I have tried all these suggested solutions - none have worked so far:

This one fails with timeout, even with port open, logs say nothing.
With this one, the packages suggested are not available.

[firstname.lastname@example.com ~]$ yum groups list
Loaded plugins: priorities, update-motd, upgrade-helper
Installed groups:
   Editors
   Legacy UNIX compatibility
   Mail Server
   Network Servers
   Perl Support
   System Tools
Available Groups:
   Console internet tools
   DNS Name Server
   Development Libraries
   Development tools
   FTP Server
   Java Development
   MySQL Database
   MySQL Database client
   NFS file server
   Networking Tools
   PHP Support
   Performance Tools
   PostgreSQL Database client (version 8)
   PostgreSQL Database server (version 8)
   Scientific support
   TeX support
   Technical Writing
   Web Server
   Web Servlet Engine
Done

Nothing that says it will give me an X session.

Tried some other things such as this: The community ami he suggests does not exist anymore.
Tried this as well: freenx is no longer around, no machine server is now 4.3 and doesn't seem to work in the free version.
x2go fails also.
also tried this one: https://www.nomachine.com/AR10K00710.  Xvfb is not available.

Has anybody worked the kinks out of the setup and got it working recently?
P.S. A few people asked why not use a VirtualBox VM - forgot to mention that I definitely tried that first and for whatever reason none of them worked.  I started with the most recent and worked backwards through each version - could not get them to launch or run.  (My machine is a Cintiq Companion with Windows 8).
Comment: There is nothing "special" about an ec2 instance. It's a linux server. As long as you install the requisite software and ensure that firewall rules are not interfering, you can easily use a GUI. As an aside, though, why not just install VirtualBox on your machine and play with a local VM?
Comment: +1 for using a local VM. That said, `yum repolist` will tell you what repos you're subscribed to, you're probably just missing one that has the X11/gnome/kde packages you want.
Comment: +1 somewhat awesome username.
Comment: I have managed to get this working before using an Ubuntu instance and VNC.  The method I used was similar to the following:  http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2.html
Comment: @Matt.  Thank you - I tried your suggested link - still had to fiddle and funk around but got something going at last
Comment: @EEAA agreed, why bother with EC2 for something that simple when VMs are local, fast, and you get full control?
Comment: Ah, forgot to mention that I tried to use a VM - I spent days installing every version working backwards from the latest to several major releases back.  None would work on my machine.   I have a Cintiq Companion with Windows 8 and could not for the life of me get any version of virtual box to work.
Comment: I would recomend a local VM too, but if you really want to use X on EC2, why not install VNC-Server on it?
Answer: Following suggestion from Matt in the comments
Set up an SSH tunnel plus a local private key using instructions from this link:  http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2-page-2.html
on ec2 ran these installers (not sure which ones are overkill - only that it eventually worked)
sudo apt-get update
sudo apt-get install ubuntu-desktop
sudo apt-get install vnc4server
sudo apt-get install x11vnc
x11vnc -storepasswd
sudo apt-get install gnome-core gnome-session-fallback

vncserver
vncserver -kill :1  #(to get the default xstartup file)

edit $HOME/.vnc/xstartup to look like this:
#!/bin/sh

# Uncomment the following two lines for normal desktop:
unset SESSION_MANAGER
#exec /etc/X11/xinit/xinitrc
gnome-session --session=gnome-classic &

[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &
#x-terminal-emulator -geometry 80×24+10+10 -ls -title "$VNCDESKTOP Desktop" &
#x-window-manager &

had to set a password for the ubuntu user (gnome desktop seems to need this?)
sudo passwd ubuntu

had to reboot the instance
then ran
 sudo x11vnc -xkb -noxrecord -noxfixes -noxdamage -display :0 -auth /var/run/lightdm/root/:0 -usepw

Then I could connect via TightVNC and see the Ubuntu desktop
Not sure what other troubles I may run into, but at least I got this far
Thank you Matt
Comment: I followed every step of yours. could you please elaborate how too cnnect using tightVNC?
Answer: I noticed you said you tried X2Go but it failed; I am using it successfully right now on two Ubuntu 14.04 instances, one is an EC2 micro on AWS, the other is a small DigitalOcean droplet (it also works on a number of other distros, but you'll have to modify step 3 below based on these instructions). While VNC will certainly work, X2go is faster and much more responsive, as well as supporting SSH proxy by default.
I went through the exact same frustration of finding outdated or irrelevant articles and suggestions for setting up a cloud desktop, but once I figured out the X2Go solution, its actually very simple to get up and running in ~10 mins.
Here are the steps I used to set everything up:

SSH key -- since it's a remote server, you should already be able to login via SSH normally, but if not, you'll need an SSH login via RSA key for a user with sudo privileges
System update -- not required, but depending on when you last updated the remote machine, doing so now may avoid incompatibilities or headaches:
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get autoremove

Install X2Go Server -- create a new file on the remote machine and paste the following contents into it:
#!/usr/bin/env bash
# note: this script may take some time to run, particularly
# the steps involving the install of xubuntu as it has many
# packages included as dependencies

printf "\ninstalling required packages...\n"
sudo apt-get install python-software-properties
sudo apt-get install software-properties-common

printf "\ninstalling xubuntu...\n"
sudo apt-get install xubuntu-desktop

printf "\nadding x2go ppa repository...\n"
sudo add-apt-repository ppa:x2go/stable
sudo apt-get update

printf "\ninstalling x2go server...\n"
sudo apt-get install x2goserver x2goserver-xsession

printf "\nxubuntu and x2go server have been installed.\n"
echo "don't forget to reboot your instance as well!"

Execute the file to install everything (. ./<filename>); you may need to modify the file permissions first to make it executable -- typically I've had it take between 5-10 minutes, however, ymmv
Install X2Go Client -- the last step is to install the client for the OS you want to access the remote machine from; installation instructions for Windows, Mac, and various flavors of Linux can be found here

Now you can use the client to connect to the machine via your configured host, user, key, port and access your GUI cloud desktop; make sure you select XFCE as the session type when setting up the connection.
Answer: If you are using NoMachine on an Amazon instance, you should follow the instructions here:
https://www.nomachine.com/AR10K00710 (NoMachine on headless servers)
Comment: Welcome to Server Fault! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: forgot to include that one in the list of things I already tried.  Xvfb  is not available
Answer:
No, you can't. Amazon Linux does not have a Repo for X-server packages. Also, It was meant to be used for Server side roles and hence all he X related stuff is not available.

Thanks slayedbylucifer
Form https://stackoverflow.com/a/21273694/1105231


How to compare all elements of a list with each other?

Question: How can I do this in a Java lambda stream, avoiding duplicates?
List<SubItem> tempSplitFilesList = new ArrayList<>();
List<SubItem> splitFilesList = new ArrayList<>();

for (SubItem item1 : tempSplitFilesList) {
    for (SubItem item2 : tempSplitFilesList) {
        if (item1.getStop().equals(item2.getStart())) {
            splitFilesList.add(item2);
        }
    }
}

Answer: Yes.  But I wouldn't say it is better than what you have.  And what you have also contains duplicates as does this.
List<SubItem> splitFilesList = tempSplitFilesList.stream()
        .flatMap(item1 -> tempSplitFilesList.stream()
                .filter(item2 -> item1.getStop()
                        .equals(item2.getStart()))) // .distinct() if no dups
        .collect(Collectors.toList());

If you want to eliminate duplicates you can put a .distinct() method call after the filter.  This will work since equals, even by default, will return true if the same objects are compared.
Answer: IMHO you can swap the inner and outer loop (or stream) and use filter and anyMatch methods:
public static void main(String[] args) {
    List<SubItem> list = List.of(
            new SubItem("123", "111"),
            new SubItem("234", "222"),
            new SubItem("345", "333"),
            new SubItem("456", "444"),
            new SubItem("567", "123"),
            new SubItem("678", "234"),
            new SubItem("789", "345"));

    List<SubItem> list2 = list.stream()
            .filter(item1 -> list.stream()
                    .anyMatch(item2 -> item1.getStart()
                            .equals(item2.getStop())))
            .collect(Collectors.toList());

    // output
    list2.forEach(System.out::println);
    //SubItem{start='123', stop='111'}
    //SubItem{start='234', stop='222'}
    //SubItem{start='345', stop='333'}
}

public static class SubItem {
    String start, stop;

    public SubItem(String start, String stop) {
        this.start = start;
        this.stop = stop;
    }

    public String getStart() { return start; }
    public String getStop() { return stop; }

    @Override
    public String toString() {
        return "SubItem{start='" + start + "', stop='" + stop + "'}";
    }
}


Spring-Boot @Autowired variable is null

Question: I'm trying to get a repository into a class annotated with @Service using the @Autowired annotation in a Spring-boot class. However, the repository turns up as a null.
Here's the relevant code:
@Service
public class ImportLicenses {

    @Autowired
    private LicenseRepository licenseRepository;

   public static void main (String[] args) {
            ImportLicenses importLicenses = new ImportLicenses();
            importLicenses.listFiles("/Users/admin/Licenses/licenses");
    }

  private void processLicense (Path path) {

        try {
            count++;
            BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
            FileTime fileTime = attr.lastModifiedTime();

            Permission permission = new Permission(readLineByLineJava8(path.toFile().getAbsolutePath()));

            LicensePojo licensePojo = new LicensePojo(permission, path);

            Optional<License> licenseOptional = licenseRepository.findById(licensePojo.getId());

at which point it gets an NPE since licenceReposity is null.
I am able to access the licenseRepository in a controller class with this constructor
public LicenseController(LicenseRepository licenseRepository,
                         UserRepository userRepository) {
    this.licenseRepository = licenseRepository;
    this.userRepository = userRepository;
}

However, since I'm calling the constructor directly in the static main method, this doesn't seem like it's available. What's the best way to get the repository into this class?
Edit: Thanks for the responses. To clarify the question, I'm trying to pull this class into the structure of the existing Spring Boot application, instead of creating a separate one.
Option 1: Create a button or menu selection on the UI, and create a new controller class to run the import. This would be the simplest, but I don't want to necessarily have that on the UI.
Option 2: Code the import class create another Spring Application
@SpringBootApplication
public class ImportLicenses implements ApplicationRunner {

    private final Logger logger = LoggerFactory.getLogger(LicenseGenApplication.class);

    @SpringBootApplication
    public static void main() {
        main();
    }

    public static void main(String[] args) {

        SpringApplication.run(ImportLiceneses.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

        listFiles("/Users/admin//licenses");

    }

    public void listFiles(String path) {

        try {
            Files.walk(Paths.get(path))
                    .filter(ImportLicenses::test)
                    .forEach(p -> processLicense(p));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ....

}

Option 3 - Create a non-executable jar file from the existing application for use in the new application to avoid duplicating code.
Option 1 is the quickest, I'm not sure if option 2 work, Option 3 I'll take a look at to see if it's do-able.
Comment: You're missing the point. If you're initializing the object yourself, obviously Spring isn't involved, whether the rest of the objects are "operating within the context of Spring" or not. It very much is a duplicate. You're not using Spring to create your instance. The answer is to use Spring to create your instance, if what you want is Spring to inject beans appropriately.
Comment: You are not instating Spring Boot, you should go with some starters: https://start.spring.io/
Comment: @Sotirios Delimanolis: The question you referred has completely different reason. It describes a case when an instance was created without Spring. But it is a Spring application, and the target bean is managed by Spring. Where as in this case Spring is not used at all, Spring is not even initialized. This case is definitely **not a duplicate**.
Comment: This is a Spring Boot application, as I referenced in LicenseController entry. I will edit to make it more obvious.  The problem is I'm trying to run a separate class to import data and would prefer not to make a separate application out of it.
Comment: @JackBeNimble: The class `ImportLicenses` that you show is *not* a Spring application.
Comment: Yes, that's clear. I'm trying to figure out how to use the existing Spring application to create the instance.
Comment: @JackBeNimble: Start by eliminating field injection and using constructor injection. That is usually sufficient for the compiler/IDE to identify to you where you need to make adjustments.
Answer: Your application is a usual Java application. It is not a Spring Boot application.
What should you do? Make a Spring Boot application of it. For instance, create a demo app at https://start.spring.io/, compare your main class to the main class in the demo application, then adjust your main class correspondingly. Also compare your Maven or Gradle config to the config of the demo app and adjust correspondingly.
At least, your application should have an annotation @SpringBootApplication. Also, it should be launched via SpringApplication.run(...). This is a minimum. Depending on what you need, you may want to use @EnableAutoConfiguration and other configuration options.
Comment: Thanks for your answer. I'm going with a GUI link for this. It's a one-off, so I don't really need to create a whole separate application for it. It's kind of a utility function, and for a more fully-fleshed out app I probably would have and admin section, so it kind of belongs on a GUI anyway.
Comment: You cannot initialize a Spring bean without initializing Spring context. It doesn't have to be *the whole* Spring application. You can create an alternative "light" context. But in any case you need to initialize Spring context.

Spring-Boot @Autowired variable is null


what difference beat value makes in time signature

Question: I am trying to understand the intuition behind the time signature. My confusion is as below :

My first confusion was why in general every metronome beat is considered a quarter beat, but what I realized as I read more, is that usually it's a standard but it's not necessary. I mean it's usually mentioned, (for example) that the tempo is 60 bpm and each beat is a quarter/whole/half beat. Please correct me if I'm wrong here.

Now coming to time signature, Let's say my music is in 4/4 and is 60bpm. That means every beat is a quarter note. From this I understand that my music is going to feel like it's structured in 4 beats or pulses at a time. The pulse is going to feel like 1-2-3-4, 1 having more accent.

Now lets say my music is in 4/2 and is 60bpm. I am unable to understand  what difference this change in beat value will bring in my rhythmic feel, because All I can think of, is that if I put that in a metronome, every tick is a half beat now; then there is no difference between what I was playing previously, (for example, 4/4 in point 2), and if I say that the metronome beat is still a quarter beat, then its just going to make my music sound slower.

Please help me in clearing this confusion.
Thanks.
:)
Comment: Have you ever seen a _metronome marking_, for example "♩=60"? What would you guess, what might the quarter note symbol on the left side of the equals sign denote? What if the marking had a half note instead, how would its meaning change? How about an eight-note symbol, "♪=60", what might that mean? https://www.musicteachers.co.uk/ezone/file/music-theory/rhythm-and-tempo/tempo/download6.pdf
Comment: We can (and do) set the metronome to whatever we wish. It could be set to tick on every crotchet, quaver, minim at 60bpm. it could be set to tick on the 'off beat', or even once per bar. Or in triplet timee, so there's 12 ticks per bar in 4/4.
Comment: Hi Tim, Yes Im aware of that but I was taking about the pulse when I said 4 ticks. Since its more about being equivalent to 4 quarter beats, there can be more ticks as well. But sorry, thats not actually what I meant to ask.

Thanks for the answer :)
Answer: Changing your time signature will change your tempo.
Having a time signature of 4/4 at 120 BPM for 20 bars will give you a song 20 seconds long.
Having a time signature of 3/4 at 120 BPM for 20 bars will give you a song 15 seconds long.
Having a time signature of 2/4 at 120 BPM for 20 bars will give you a song 10 seconds long.
If there are less beats in a bar, (or measure) your bars (or measures) will go by much faster, because you must complete 120 beats in a minute.
If you want a song with a length of 1 minute that has a tempo of 120 and a time signature of 4/4, it will take 30 measures.
If you want a song with a length of 1 minute that has a tempo of 120 and a time signature of 3/4, it will take 40 measures.
Time signature is important to many things, especially the repetition of a certain measure(s). If I were making a song in 4/4 but all my rhythms restarted at the 3rd beat, (equivalent to 3/4)then it would be very hard to count the measures because having the song divided into measures would then be useless and unhelpful. having a time signature of 3/4 allows me to use quarter notes and 8th notes and still achieve my 3-note rhythm due to the time signature. A correct time signature will make dividing the song into measures useful again.
Another important reason behind time signatures, is the measure indication of a metronome. If you were playing a 3-note rhythm in 4/4, your metronome will indicate the start of the next measure at the wrong time. having a 3-note rhythm and a metronome set to 3/4 will make your metronome indicate the start of the next measure at the correct time.
Comment: If you would like to check my math you can use https://toolstud.io/music/song-length.php?bpm=120&bpm_unit=4%2F4&repetitions=30&repetitions_unit=bars to calculate the length of you song.
Comment: @MusicMan 4/4 time signature is 4 beats per 4 measures. 4/2 time signature is 4 beats per 2 measures, making it twice as fast as 4/4.
Comment: Could you site your information for those numbers you ended up with?
Comment: cite my information on the numbers... my brain?
Comment: Add that into the answer, like, "you can use ___ to calculate tempo" or something.
Comment: sure, I can do that. (it's a calculator for song **length**)
Comment: I am aware of differences in these cases
I am trying to understand difference between 4/4 and 4/2 time signature
Comment: 4/4 is 4 beats divided into 4. 4/2 is 4 beats divided into 2.
Comment: Leading by talking about tempo doesn't make sense.  Sure things like 2/2, 4/4, and 8/8 have certain tempos that will make you choose one or the other, but there's a lot more going on.  If you are using # of measures and tempo to determine your time signature that really doesn't make much sense. 3/4 and 4/4 __feel__ different as do most time signatures from each other.
Comment: Having a time signature of 4/4 at 120 BPM for 20 bars will give you a song 20 seconds long. ---> it should be 40 seconds because we have 4 x 20 bars = 80 beats in total, the number of second is 80/120 x 60 = 40 secs instead of 20 secs as you mentioned


How many ways can you put 8 red, 6 green and 7 blue balls in 4 indistinguishable bins?

Question:
Assume all balls with the same color are indistinguishable.
The order in which balls are put in a bin does not matter.
No bins are allowed to have the same distribution of balls!

For example, this configuration
{RRGGGB} {RRRRGBBBB} {RGB} {RGB}
is not ok, because the two last bins contains the same distribution of balls: one Red, one Green, one Blue.
Actualy I'm most intressted in the procedure for solving this problem where the number of balls, colors and bins are much larger numbers.
Comment: No, not what I know of. But I think the solution to this problem can be used to find all ways a number can be written as a product of k distinct integers, where k is the number of bins and balls corresponds to prime factors.
Comment: Is this from some programming contest?
Comment: What exactly do you mean by indistinguishable bins?
Comment: I just mean that the bins are unlabeled. If two bins switched position, that should not be counted as a "new way".
Answer: This problem is a straightforward application of the Polya Enumeration
Theorem. Suppose we  treat the case of $r$ red  balls, $g$ green balls
and $b$  blue balls and $n$  indistinguishable bins where  no bins are
left empty.
Recall the  recurrence by Lovasz for  the cycle index $Z(P_n)$  of the
set   operator  $\def\textsc#1{\dosc#1\csod}   \def\dosc#1#2\csod{{\rm
#1{\small #2}}}\textsc{SET}_{=n}$  on $n$  slots, which is  $$Z(P_n) =
\frac{1}{n}      \sum_{l=1}^n      (-1)^{l-1}      a_l      Z(P_{n-l})
\quad\text{where}\quad Z(P_0) = 1.$$
We need to employ the set operator because the elements of a distribution
are supposed to be unique.
We have for example,
$$Z(P_3) = 1/6\,{a_{{1}}}^{3}-1/2\,a_{{2}}a_{{1}}+1/3\,a_{{3}}$$
and
$$Z(P_4) = 1/24\,{a_{{1}}}^{4}-1/4\,a_{{2}}{a_{{1}}}^{2}
+1/3\,a_{{3}}a_{{1}}+1/8\,{a_{{2}}}^{2}-1/4\,a_{{4}}.$$
Applying PET it  now follows almost by inspection that the
desired count is given by using the repertoire
$$-1 + \sum_{q=0}^r R^q \sum_{q=0}^g G^q
\sum_{q=0}^b  B^q$$
with $Z(P_n)$ to get
$$[R^r G^g  B^b]  Z\left(P_n; -1  +
\sum_{q=0}^r  R^q \sum_{q=0}^g  G^q \sum_{q=0}^b  B^q \right).$$
The minus one term cancels empty bins.

The  answer for  eight red,  six green  and seven  blue balls  in four
indistinguishable bins turns out to be
$$60040.$$
The  following   Maple  code  implements  two   routines,  q1  and
q2. The first of these computes the value for $(r,g,b)$ and $n$ by
brute force (enumerate  all configurations) and can be  used to verify
the correctness of the PET formula for small values of the parameters.
The second  one uses  the PET for  instant computation of  the desired
coefficient.

Observe that  we can compute values  that are utterly out  of reach of
brute force  enumeration, e.g. with ten  balls of each  color and five
bins we obtain
$$7098688.$$
With twenty balls of each color and six bins we get
$$194589338219.$$

with(combinat);

pet_cycleind_set :=
proc(n)
option remember;

    if n=0 then return 1; fi;

    expand(1/n*
           add((-1)^(l-1)*a[l]*pet_cycleind_set(n-l), l=1..n));
end;

pet_varinto_cind :=
proc(poly, ind)
local subs1, subs2, polyvars, indvars, v, pot, res;

    res := ind;

    polyvars := indets(poly);
    indvars := indets(ind);

    for v in indvars do
        pot := op(1, v);

        subs1 :=
        [seq(polyvars[k]=polyvars[k]^pot,
             k=1..nops(polyvars))];

        subs2 := [v=subs(subs1, poly)];

        res := subs(subs2, res);
    od;

    res;
end;

allparts :=
proc(val, size)
    option remember;
    local res, els, p, pp, q;

    res := [];

    for p in partition(val) do
        if nops(p) <= size then
            pp := [op(p), 0$(size-nops(p))];
            res := [op(res), pp];
        fi;
    od;

    res;
end;

q1 :=
proc(RC, GC, BC, n)
    option remember;
    local p, q, pr, pg, pb, res,
    sr, sg, sb, dist;

    pr := [];
    for p in allparts(RC, n) do
        pr := [op(pr), op(permute(p))];
    od;

    pg := [];
    for p in allparts(GC, n) do
        pg := [op(pg), op(permute(p))];
    od;

    pb := [];
    for p in allparts(BC, n) do
        pb := [op(pb), op(permute(p))];
    od;

    res := {};

    for sr in pr do
        for sg in pg do
            for sb in pb do
                dist :=
                {seq(R^sr[pos]*G^sg[pos]*B^sb[pos],
                     pos=1..n)};

                if nops(dist) = n and
                not member(1, dist) then
                    res := res union {dist};
                fi;
            od;
        od;
    od;

    nops(res);
end;

q2 :=
proc(RC, GC, BC, n)
    option remember;
    local q, rep, sind;

    rep := add(R^q, q=0..RC)
    * add(G^q, q=0..GC)
    * add(B^q, q=0..BC);

    sind := pet_varinto_cind(rep-1,
                             pet_cycleind_set(n));

    coeff(coeff(coeff(expand(sind), R, RC),
                G, GC), B, BC);
end;
Comment: Thank you Marko for the great and detailed answer. I have not studied the Polya Enumeration Theorem, so I have some noobish follow-up questions :). I'm a bit uncertain about the square-bracket notation here: [R^rG^gB^b], and what are the difference between captial R and and lower case r? Also, what are the definition/values of the a_n coefficients? Finally, I don't fully understand the Newton binomial series expression, what does the square-bracket notation and Mu mean here? Thanks again.
Comment: Thanks. I don't have the time for a detailed reply at the moment but I suggest you study the Maple code, which should make it clear what the variables mean. Not only does it compute values it is also a commentary on the text. There are many more PET examples including introductory ones at [MSE Meta](http://meta.math.stackexchange.com/questions/1868/list-of-generalizations-of-common-questions#13335).
Comment: What's the complexity of this algorithm?
Answer: Here is a simpler example to explain the mechanism above.
Suppose we have a rectangle marked in every corner with several points, such that the sum of points is 7 and each distribution fixes the rectangle, otherwise being acted by the Klein group.
The asymmetry cycle index is
$Z(rectangle) = 1/4 \ a_1^3 - 3/4 \,a_2^2 + 1/2 \ a_4$
The asymmetry cycle index goes back to Rota 1964 and, totally counterintuitive, it involves negative terms as well as 4-cycles.
We can securely use the pet_varinto_cind procedure delivered above.
pet_varinto_cind (poly, Z(rectangle))
The polynomial would be $poly = (p+p^2+p^3+...p^{10} + ..+p^m)$. In fact, power 10 is more than enough to follow the example, and there is no need to sum too many terms.
We then extract the desired coefficient representing the sum of points over the four corners.
sum of points 5 -----> 1 fixed rectangle
sum of point 6 -----> 1 fixed rectangle
sum of points 7 -----> 5 fixed rectangles
sum of points 8 -----> 7 fixed rectangles
for 7 points, the fixed rectangles are
4111, 3211, 3121, 3112 and 2221
Counting partitions without equal parts follows the same mechanism.
Note the asymmetry series/polynomial is not a function of cycle index only, because it depends on some lattice of subgroups, not uniquely characterized by the cycle index.


A graded ring is Noetherian equivalence

Question: If $R$ is a graded ring then $R$ is Noetherian if and only if $R_0$ is Noetherian and $R$ is finitely generated as an $R_0$-algebra.
If $R$ is Noetherian then $R_0 = R/R_+$ is Noetherian and $R_+ $ is finitely generated, but for the converse I don't know what to do.
Maybe I need to use the following: A subset of homogeneous elements generates $R$ as an algebra if and only if they generate $R_+$ as an ideal of $R$, but I don't know how.
Answer: If $R$ is finitely generated as an $R_0$-algebra, then there exists an $n\geq 0$ and a surjection
$$
R_0[x_1,\dots, x_n]\to R.
$$
$R_0[x_1,\dots, x_n]$ is a polynomial algebra over a noetherian ring, and hence noetherian, which implies that $R$ is noetherian, as it is a quotient of a noetherian ring.
Comment: does the surjection exist because $R$ is a f.g $R_0$-algebra?
Comment: @allizdog Yes, $A$ is a finitely generated $R$-algebra (essentially by definition) if there is a surjection $R[x_1,\dots, x_n]\to A$ for some $n$.

A graded ring is Noetherian equivalence


Image upload & gallery

Question: Is there a way to limit the number of imagefield fields present in a node?
I am using iTweak Upload, which allows to upload an unlimited number of images, but I need something that can limit the number of uploads.
I want to make a gallery per node with the uploaded files; what module do you recommend?
Comment: Are you interested on still using _iTweak Upload_, or are you interested in using a different module?
Answer: If you use standard CCK imagefield, you can set the number of images that can be uploaded within one field. For example, you could allow just one image, or up to 10 images, or an unlimited number of images.
Providing you don't have hundreds of images per node, CCK imagefield is fine for having a gallery of images on each node, and we've implemented galleries quite successfully in this way.
Answer: You could take a look at my CCK Gallery module - http://drupal.org/project/cck_gallery - for some ideas. It's out of date now, and should probably be a Feature - there is no intention to resurrect it, but it might be a good starting point.
I don't really understand "limit the number of imagefield fields" - I mean, you can limit the number of permitted uploads on a field already, so I guess that's not what you mean, but I can't work out what you do mean.

Image upload & gallery


Solution of the linear differential equation: $\frac {dy}{dx} + P(x) \cdot y=Q(x)$. What is the error in this approach?

Question: Derive the solution of the linear differential equation: $\frac {dy}{dx} + P(x) \cdot y=Q(x)$
Rewriting the given differential equation, we obtain: $(Py-Q) dx+1 \cdot dy=0$.
Let $M=Py-Q, N=1$. Then : $\dfrac {\partial M }{\partial y}=M_y=P$
and $\dfrac {\partial N}{\partial x}=N_x=0$.
Thus $\dfrac{M_y-N_x}{N}=P(x)$. Thus, the integrating factor is $I.F= e^{\int P dx}$. Therefore  $e^{\int P dx}(Py-Q) dx+e^{\int P dx} \cdot dy=0$ is an exact differential equation.
The solution of this exact differential equation is $\int_{\text {treat y as constant} } M dx + \int \text{terms in N not containing x}~~ dy= $ constant
$\implies \int e^{\int P dx}(Py-Q)~ dx + 0=c$

$\implies y \int P~ e^{\int P dx}~dx = \int e^{\int P dx} Q ~dx + c.~$
But the solution of the differential equation in almost every textbook is given as $\implies y e^{\int P dx}~dx = \int e^{\int P dx} Q ~dx + c$

What is the error in the above steps. Thanks a lot for your help.
Comment: What is the $I$ here?
Comment: Is it possible that the second $dx$ in the first member of the last equality you have written should not be there? If that is the case, I think both expressions of the solution are equivalent.
Comment: @Nick Which $I$ are you talking about? is it the $I.F$?
Comment: @ABC I believe it should be there if one goes step by step.
Comment: @Isham The solution of an exact differential equation is $\int_{\text {treat y as constant} } M dx + \int \text{terms in N not containing x}~~ dy= $ constant
Comment: @MathMan But the $dx$ in the last equality "does not have its corresponding integral sign"
Comment: @ABC I am sorry, Could you please pin point which one exactly?
Comment: @MathMan In the coloured box there are two equalities. I am referring to the second one. In its first member there is an extra $dx$ I think
Answer: $$\implies \int e^{\int P dx}(Py-Q)~ dx + 0=c$$
$$ \int e^{\int P dx}Pydx-\int e^{\int P dx}Qdx=c$$
$$ y\int e^{\int P dx}Pdx-\int e^{\int P dx}Qdx=c$$
you have a derivative in the first integral:
$$ y e^{\int P dx}-\int e^{\int P dx}Qdx=c$$
Therefore:
$$ y e^{\int P dx}=\int e^{\int P dx}Qdx+c$$
Comment: yw @MathMan your formula is correct it's just another formulation.
Comment: Thanks. Got it.


Find the x-coordinate of a tangent to a curve when it meets the curve again

Question: Working through a pure maths text book - as my hobby is - I found the following question:
Find the equation of the tangent to the curve $y=\frac{5}{12}x^3-\frac{13}{9}x$ at the point P at which $x = x_0$. Show that the x-coordinate of the point Q where this tangent meets the curve again is $-2x_0$ and find the values of $x_0$ for which the tangent at P is the normal at Q.
I worked out the first part OK. I found the tangent to be $y=(\frac{5}{4}x_0^2-\frac{13}{9})x - \frac{5}{6}(x_0^3)$
I thought for the second part I need to solve this equation:
$(\frac{5}{4}x_0^2-\frac{13}{9})x - \frac{5}{6}(x_0^3)=\frac{5}{12}x-\frac{13}{9}x$
But I cannot solve it to get the answer in the text book, which is $\pm\frac{1}{3}\sqrt5,\pm\frac{2}{3}\sqrt2$
My workings took me to:
$x=\frac{45x^3-156x+90x_0^3}{135x_0^2-156}$
but this seems a dead end.
Comment: I am not sure the solution you mentioned for the first part is right. Can you please check it again?
Comment: Specifically, why does it pass through the given point?
Comment: The curve is not a conic section so the tags need editing.
Answer: Your first part of the solution is correct. For the second part, you need to equate $y$ value of the curve and the tangent line.
$ \displaystyle \left(\frac{5}{4}x_0^2-\frac{13}{9}\right)x - \frac{5}{6}x_0^3=\frac{5}{12}x^3 -\frac{13}{9}x$
$ \displaystyle \frac{5}{4}x_0^2 \ x - \frac{5}{6}x_0^3=\frac{5}{12}x^3$
$ \displaystyle 3 x_0^2 \ x - 2 x_0^3 = x^3$
$x^3 - 3 x_0^2 \ x + 2 x_0^3 = 0$
$(x- x_0)^2 (x + 2x_0) = 0$
and hence $x = - 2 x_0$ is the x-value of intersection point $Q$.
Now for the third part, find slope of the tangent at $Q$, just like you did for first part.
Product of the slopes of tangents at $P$ and $Q$ should be $-1$ as the tangent at $P$ is normal to the curve at $Q$. Find at what value of $x_0$, that happens.
Comment: Thank you.  I would not have been able to make the step from $x^3 - 3 x_0^2 \ x + 2 x_0^3 = 0$ to $(x- x_0)^2 (x + 2x_0) = 0$. It's obvious now you have done it but how does one see the connection in the first place? Or it just practice or intuition? or is there some rule? I thought of the factor theorem but $x$ and $x_0$ are different from each other.
Comment: @Steblo A bit of cheating helps here. It is a cubic equation. As the line is tangent to the curve at $x = x_0$, I know $(x - x_0)$ will be a root. Also the question asks to show $x = - 2x_0$ is the intersection point. So I already know $(x + 2 x_0)$ will also be a root.
Comment: Also an additional point, when you solve such equations, the point of tangency will be a double root. That is why $(x - x_0)^2$. But even if you just knew that we should look for roots $(x - x_0)$ and $(x + 2 x_0)$, that would work.


Generate sample from poisson distribution with fixed sum

Question: I want to generate a random sample of size n from poisson distribution with parameter l but the sum of these samples should be equals to some number say y. Is there any way to achieve this? i dont want to generate n-1 samples and subtract the sum of these from y.
Answer: Since
$$(Y_1,\ldots,Y_n)\sim\mathbb P(Y_1=y_1,\ldots,Y_n=y_n)=\dfrac{\lambda^S\exp\{-\lambda\}}{y_1!\cdots y_n!}$$
when $$s=y_1+\cdots+y_n$$
the conditional pmf of $(Y_1,\ldots,Y_n)$  given $S=s$ is
$$\mathbb P(Y_1=y_1,\ldots,Y_n=y_n|S=s)\propto\dfrac{1}{y_1!\cdots y_n!}\mathbb I_{y_1+\cdots+y_n=s}$$
This corresponds to a Multinomial $\mathcal M(n,s,1/n)$ distribution, whose simulation is given in Henry's response.
Comment: Congrats on 100k reputation coming soon :)
Comment: A shout out for @Xi'an for the feat. The community is indebted for your contribution. Any other day, would have made a congratulatory post (but now it is discouraged). You have been mentioned in [chat](https://chat.stackexchange.com/transcript/message/63791077#63791077) too. Best wishes and we are looking for many years of your contributions ahead.
Comment: @RichardHardy: I just noticed..!
Comment: @User1865345-solidarityMods: Thank you for your kind words.
Answer: When conditioning on the sum $y$ the Poisson parameter becomes irrelevant, so you in effect want to sample from a multinomial distribution, but may find it easier to do binomial samples:

Start with $y$ and $n$

Sample a single $x_{i}$ from $\text{Bin}(y_{i}, \frac1{n_{i}})$

Move forward by letting $y_{i+1}=y_i-x_i$ and $n_{i+1}=n_i-1$ and repeat 2

As an alternative approach,

Generate $y$ values uniformly from $[0,n)$

Count the number in each of $[0,1)$, in $[1,2)$, etc. up to $[n-1,n)$

In fact you could just sample $y$ times uniformly with replacement from $\{1,2,3,\ldots,n\}$  (or from  $\{0,1,2,\ldots,n-1\}$ if you think that way) and see how often you get each of the $n$ values.  As an example in R:
<code>set.seed(2023)
y <- 40
n <- 10
table(factor(sample(n, y, replace=TRUE), levels=1:n))
</code>
gives
<code> 1  2  3  4  5  6  7  8  9 10
 2  6  2  5  5  0  6  7  5  2
</code>
and the second row is what you want


For the purpose of creating content, how do block_view and the page callback defined in the menu hook relate?

Question: I'm slightly confused as to how I should get my content on the page from a custom module. I thought I would normally do it with the block_view hook, but apparently another way is the page callback function. While I think I understand the former, I'm not quite sure how the latter works, and what I should return from it. Should I use one or the other method? When shoul dI use which? Can I use both?
Answer: hook_block_view() and hook_menu() aren't related at all, they're two completely independent concepts.
hook_block_view() is for defining blocks, which can be assigned to regions within the page template.
Items defined in hook_menu() are pages, for which a page callback is required to build up the content for that page.
I guess the slight confusion is that in Drupal 7 the page content is automatically assigned to a block in the main system region. Whatever you return from your page callback function for a menu item will be assigned to that main system block when you access the defined page.
A block is not accessible through a URL; it is a contextual piece of information that you add to different pages/regions when you need to. Think of the shopping cart in an e-commerce site as a perfect example of a block.
A menu item defines a page that is accessible through a URL, and may well contain any number of blocks within it.


How to alter commerce checkout form in a custom module?

Question: I'm using commerce and want to alter the checkout form in a custom module to prepopulate certain fields and hide them.
However, I'm not able to do this using hook_form_alter() as well as hook_commerce_checkout_pane_alter().
Here's my sample code:
function MYMODULE_form_alter($form, &$form_state, $form_id) {
  global $user;

  switch ($form_id) {
    case 'commerce_checkout_form_checkout':
      // Rename the button for example.
      $form['buttons']['continue']['#value'] = t('Overridden value');
      break;
  }
}

How can I edit fields that are displayed on checkout?
Is there some other hook I should use?
Thanks!
Answer: I think you're looking for commerce_checkout_form() (commerce_checkout_form_checkout doesn't exist as far as I can tell from greping Commerce's code):
function MYMODULE_form_commerce_checkout_form_alter($form, &$form_state, $form_id) {
  ...
}

or
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form':
      ...
    break;
}

Comment: Oh right...it'll be this then: `MYMODULE_form_alter($form`. Can't alter an external var unless you pass by reference :)
Comment: Thanks for your answer, but I'm running into the same issue - the hook works and I can `dpm()` the form, but nothing is altered for real. Will try this now on a clean install and see if I can narrow down the issue. Will post back shortly.
Comment: Yep, that was it - I was missing the `&` in the `$form` argument :) Thanks!
Answer: Use form_alter to customize commerce checkout page submit button values.
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form_checkout':
      if (isset($form['buttons']['continue']['#value'])) {
        $form['buttons']['continue']['#value'] = t('Overridden value');
      }
      break;
  }
}


Example of quasi-compact, non-quasi seperated scheme where qcqs fails?

Question: The qcqs lemma (in Ravi Vakil's notes) says that if $X$ is a quasi-compact (qc) and quasi-separated (qs) scheme, for any global section $f$, the natural map from $\Gamma(X, O_X)_f \to \Gamma(X_f, O_X)$ is an isomorphism.  (We are defining $X_f$ to be the complement of the set where $f(p) = 0$, i.e. where $f = 0$ in $O_{X,x} / m_x$. So the natural map is the one guaranteed by the universal property of localization as $f$ becomes a unit over $X_f$.)
The proof of this lemma uses in a crucial way these finiteness assumptions in order to take advantage of the willingness of localization to commute with finite products. (One builds the exact sequence describing the global sections via the sheaf axioms, plugs a finite affine cover with a finite affine cover of the overlaps into it. Then localizing this sequence expresses $\Gamma(X, O_X)_s$ as the kernel of the exact sequence describing $\Gamma(X_s, O_X)$, bootstrapping off of the case of this theorem in the affine case.)
I want counter examples in the situation when this hypothesis has been dropped.
Here is what I have been thinking so far:
I tried the example of the only qc but not qs scheme that I know: the infinite affine space with a doubled origin. The functions on this space and on any open subscheme are the same as functions on the corresponding open $\mathbb{A}^{\infty}$, since the gluing identifies the variables on a dense open set. So I don't think this will provide an example (but I am not sure - now after thinking about this I am more convinced that this example would provide a counter example, but I don't see how). Here one would (obviously) need to use that infinitely many affines are required to cover the intersection of the two $\mathbb{A}^n$ in order to produce something...
I think I found an example of a quasi-seperated non-quasi compact scheme that provides a counter example. Essentially the point is that localization doesn't commute with infinite products in general, so one can take the infinite disjoint union of $Spec Z / (2^i)$, for all $i \geq 0$, and try to invert the element $2$. $X_2 = \emptyset$, but $(\Pi Z / 2^i)[2^{-1}] \not = 0$, since for instance $(1,1,1,1, \ldots)$ is not 2-torsion.
Comment: Yes, the non-qc example you give works and is fairly classical. I probably would have taken an infinite disjoint union of $\mathbb A^1$s lying over $\operatorname{Spec}(k[t])$, and invert $t$ (i.e. invert $(t,t,\ldots)$).
Comment: @Remy Do you think you could explain your example some more? I don't really understand. Those $A^1$ are $\operatorname{Spec}( k[t,x] )$ with a structure map down to $\operatorname{Spec} ( k[t] )$?
Comment: @Remy Also, any comments on a non-quasi separated but quasi-compact example? Thanks for your help!
Answer: Let me give a two-part answer: I will give a counterexample when $X$ is not quasi-compact, and I will prove that for $X$ integral and quasi-compact the result holds (without quasi-separatedness).
To ease notation, since the only sheaf we use is $\mathcal O_X$, I will just write $\Gamma(X)_f \to \Gamma(X_f)$. (You'll thank me later.)
Example. Let $X = \coprod \mathbb A^1_k = \coprod \operatorname{Spec} k[t]$, where the disjoint union is indexed over $\mathbb N$. Let $f = (t, \ldots) \in \Gamma(X)$. Then
$$\Gamma(X)_f = \left(\prod k[t]\right)_{(t,\ldots)} \subsetneq \prod k[t]_t = \Gamma(X_f)$$
is the subset of sequences $(P_i)$ with bounded denominator, i.e. there exists $n \in \mathbb N$ such that $t^n P_i \in k[t]$ for all $i$.
Lemma. For $X$ integral and $f \in \Gamma(X)$, the map $\Gamma(X)_f \to \Gamma(X_f)$ is injective.
Proof. Let $\{U_i \subseteq X\}$ be an open cover of $X$ by affines. We know that $X_f \cap U_i = (U_i)_f$, and the map
$$\Gamma(U_i)_f \to \Gamma((U_i)_f)$$
is an isomorphism. The sheaf condition and exactness of localisation gives a commutative diagram
$$\begin{array}{ccccc} 0 & \rightarrow &\Gamma(X)_f & \rightarrow & \left(\prod \Gamma(U_i)\right)_f \\
 & & \downarrow & & \downarrow \\
0 & \rightarrow & \Gamma(X_f) & \rightarrow & \prod \Gamma(U_i)_f
\end{array}$$
with exact rows. I claim that the second vertical map is injective. For $f = 0$ both sides are $0$, so assume $f \neq 0$. Since $X$ is connected, $f$ does not vanish identically on any nonempty open. Hence, $f|_{U_i} \neq 0$. This implies that the second vertical map is injective: if $(x_i)_i/f^j$ maps to $0$, then each $x_i/f^j$ is zero, so $x_i = 0$ (here we use that $X$ is integral). Hence, the first vertical map is injective as well. $\square$
Remark. The lemma also holds for $X$ quasi-compact without the integrality assumption: in this case we can choose a finite such covering, and the second vertical map is actually an isomorphism.
Remark. The lemma fails for general $X$, cf. OPs example $\coprod \operatorname{Spec} \mathbb Z/2^i$ (with $f = 2$).
Corollary. If $X$ is integral and quasi-compact, then the map $\Gamma(X)_f \to \Gamma(X_f)$ is an isomorphism.
Proof. Cover $X$ by finitely many open affines $U_i$. The sheaf condition gives a commutative diagram with exact rows
$$\begin{array}{ccccccc} 0 & \rightarrow &\Gamma(X)_f & \rightarrow & \left(\prod \Gamma(U_i)\right)_f & \rightarrow & \left(\prod \Gamma(U_i \cap U_j)\right)_f \\
 & & \downarrow & & \downarrow & & \downarrow\\
0 & \rightarrow & \Gamma(X_f) & \rightarrow & \prod \Gamma((U_i)_f) & \rightarrow & \prod \Gamma((U_i \cap U_j)_f).
\end{array}$$
By the affine case and the finiteness of the cover, the second vertical map is an isomorphism. The third vertical map is injective by the lemma (and finiteness of the cover). Thus, the result follows from the five lemma. $\square$
This should give a bit of a hint of in what direction to look for a counterexample: we need affine opens $U, V \subseteq X$ whose intersection is 'something like' $\coprod \operatorname{Spec} \mathbb Z/2^i$. As long as we don't have a conclusive answer, it would also be interesting to come up with more examples where the map is not injective.
There will be zero-divisors.
Comment: Thanks! I don't understand what the finiteness of the cover has to do with the third vertical map in the final diagram being injective - doesn't injectivity follow in each component from your lemma anyway? (I went and edited a $\Pi$ in, but maybe I am misunderstanding...?) Otherwise it makes sense to me.
Comment: Well, 'each component' — localisation does not commute with infinite products, so you'd need an extra argument to get the injectivity. You can find the argument in the first revision I made (but then I realised it was unnecessary because the product is finite).
Comment: Also, I am still dissatisfied with the non-integral case. I think it's good to either post a separate question about this, or to unaccept my answer.


What is the intuition behind pi in the PDF of a Normal Distribution ? Is it related to some sort to a circle / sphere

Question: The PDF of a Normal distribution is given as below

I am aware of the various properties of Normal distribution and how the two parameters mu and sigma affect the shape of the distribution.
What is not intuitive for me is, How come there is a pi in the PDF of Normal distribution. Is there any relation to circle ?
Comment: See https://stats.stackexchange.com/search?tab=votes&q=Box%20muller.  Also see [questions relating spheres and normal distributions](https://stats.stackexchange.com/search?q=sphere+normal), and [the connection between Normal and Beta distributions](https://stats.stackexchange.com/questions/85916/distribution-of-scalar-products-of-two-random-unit-vectors-in-d-dimensions/85977#85977).
Answer: Comment: Here are a couple of fairly elementary normal models that
involve simple geometry. Both have been of some practical importance.
Suppose you have a target for archery practice. Maybe a pretty good archer
shooting from a distance misses the bull's eye by amounts that can be described as follows:

The distance $R$ (in whatever direction) from the bull's eye has a
Rayleigh distribution with $\sigma=1.$ This means that the archer hits within 1 foot about 34% of the time. [The square of this Rayleigh distribution is chi-squared with 2 degrees of freedom.]
The angle $\Theta$ that a line from the bull's eye to the hit point makes counterclockwise from the horizontal is $\mathsf{Unif}(2, 2\pi).$ So misses
are symmetrically scattered about the bull's eye.

If you convert from polar coordinates $(R,\Theta)$ to rectangular coordinates $(X,Y),$ then it turns out that $X$ and $Y$ are independently standard normal.
[For some years, this math was used to allow computers to sample from
a standard normal distribution. It's called the Box-Muller method. See the link for equations and figures.]
Suppose you have 12 independent random variables $U_i$ independently distributed as
$\mathsf{Unif}(0,1).$ Then $S = \sum_{i=1}^{12} U_i $ has $E(S) = 6, V(S) = 1,$
and by the Central Limit Theorem, $Z = S - 6 \stackrel{aprx}{\sim} \mathsf{Norm}(0,1).$ That $Z$ is nearly standard normal is not a surprise. However, with a limit theorem about converging to normal as $n \rightarrow \infty,$ one does not necessarily expect excellent results for $n = 12,$ and
the degree to which $Z$ matches standard normal is surprising.
A simple simulation shows this:
set.seed(1234)
z = replicate(10^6, sum(runif(12))-6)
hist(z, prob=T, br=50, ylim=c(0,.4), col="skyblue2")
  curve(dnorm(x), add=T, lwd=2, col="red")

The Shapiro-Wilk test for normality will handle at most 5000 observations.
Results of the W-S test on the first 5000 of the million values simulated
shows that they are consistent with normal.
shapiro.test(x[1:5000])

        Shapiro-Wilk normality test

data:  x[1:5000]
W = 0.9969, p-value = 0.4585

For $n < 12,$ this link to the Irwin-Hall distribution gives some
equations and graphs.
[Pseudorandom number generators produce results that are very hard to distinguish from independent samples from a standard uniform distribution. In the early
days of computation, when adding was about the only cheap operation, this method of getting one standard normal distribution by adding 12 independent 'standard uniform' variates was widely used.]
Comment: See [this page](https://math.stackexchange.com/questions/384893/how-was-the-normal-distribution-derived) for an explanation of the constant of integration in the standard normal distribution (including $\pi).$ Somewhat related to the first example in my Answer.
Comment: Thanks for your answer @BruceET . What is your take on this answer. https://www.quora.com/q/bzxvjykyriufyfio/What-is-math-pi-math-and-while-were-at-it-whats-math-e-math?ch=10&share=6c2f5a09
Comment: It's OK to the extent that it makes the point that whenever you see $\pi$ you can't assume it came from a circle.


Predict results of Elections

Question: I have information on the votes in my town and in the country.

I want to predict the results in the country's elections knowing the results in my town. What methods I can use?
I have thought of linear models, but I don't know exactly how to do it:
summary(lm(Country~MyTown))

The results in R are:
Call:
lm(formula = Country ~ MyTown)

Residuals:
      1       2       3       4       5       6
-0.8968  3.5258 -2.2629 -1.3784 -0.9361  1.9484

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  -7.3710     2.7238  -2.706 0.053749 .
MyTown        1.4423     0.1516   9.516 0.000681 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.496 on 4 degrees of freedom
Multiple R-squared:  0.9577,    Adjusted R-squared:  0.9471
F-statistic: 90.56 on 1 and 4 DF,  p-value: 0.0006807

And I would like to get the estimate for all the parties. Is a linear model a good idea? Are there more methods for it?
Comment: From *which* data do you want to predict *which* information? From results of all parties in your town all results of all parties in the country? (this leaves you will $n$ features and $n$ target variables). Do you assume that the relation between all features and their target variables *is the same*? If no, modelling your problem this way might be a bad idea at all. BTW: even if you might be able to model things this way, be aware that your model might not be able to work the same way on *future* elections.
Comment: @ geekoverdose, Yes, exactly, I want to predict from the results in my town the results of the country. It is only for fun, I asume, that the results will be different for the next years
Comment: Why would you expect a linear relationship? Election results must add up to 100 %. You need a model that ensures this.
Answer: As @Roland mentioned you should first check if your expectation of a linear relationship is applicable with your problem:
# use semi-linear dummy data
d <- mtcars[,4:3]
names(d) <- c('town', 'country')
# visualize relation
plot(d)

If the relation turns out to be (semi) linear you can fit a linear model to it. Be aware that depending on what you want to do with that model, the fitting and evaluation process would need to be adapted (e.g. if you want to predict the votes in the country for some parties from the relation you derived from other parties before, using a partitioning approach like repeated CV or LOOCV would be useful). This example is very similar to what you already did, but additionally uses LOOCV to obtain a realistic RMSE estimate for your model:
library(caret)
model <- train(x = data.frame(d$town), y = d$country, method = 'lm', metric = 'RMSE', trControl = trainControl(method = 'LOOCV'))
print(model)

    Linear Regression

    32 samples
    1 predictors

    No pre-processing
    Resampling:

    Summary of sample sizes: 31, 31, 31, 31, 31, 31, ...

    Resampling results

    RMSE  Rsquared
    84.6  0.532

Using the model (which in the end is trained on all data provided to caret::train) you can also visualize the relation between predicted and observed values on your training and/or test data:
plot(predict(object = model, newdata = data.frame(d$town)), d$country)
abline(0,1)

Looking at a problem this way will give you a better understanding if the model actually is and does what you would expect and want it to be.

Predict results of Elections


How to change field_tags in hook_form_alter?

Question: I have the field_tags set to be a select box (not auto-complete). Inside hook_form_alter, how can I change the default value of the field_tags select box? So far, I have:
function autotag_custom_form_alter(&$form, &$form_state, $form_id){

    if($form_id == 'article_node_form'){
      //change default value here
    }

}

But I don't know how to access the field_tags element and then change the default value. Please help! Thanks.
Comment: I suggest you install the [devel module](http://drupal.org/project/devel).  With it, you can print out your `$form` using `dpm($form)` and inspect the variable to see what is in it and figure out what you need to change. See guide and screenshots at http://ratatosk.net/drupal/tutorials/debugging-drupal.html
Comment: I did install it. I'm not that familiar with PHP, so I'm having trouble with it. I see in Devel that there's a 'field_tags' variable only when editing an article. But I don't see one when I create a new article (there's no Devel tab when creating a new article). Does that  mean it's not possible to change the field_tags value here? If not, what function should I implement?
Comment: You can add `dpm($form);` line to where you have `//change default value here` in your code above to print the form and inspect the form elements. Perhaps you should also mention why you're doing this programatically instead of setting defaults in the field setting through the interface.
Comment: When I do dpm($form), I see field_tags >> #attributes >> field-widget-options-select.

How do I change the default option?

I tried to install various modules, but none of them did what I needed. I need to assign the tag to the article automatically, based on the author's role. So I wanted to do this once the article is being created.
Comment: Actually, I think I want something like this (but this doesn't work):

$form['field_tags']['und']['#default_value'] = $form['field_tags']['und']['#options'][2];
Comment: Nevermind, I think I got it. Thanks!! I just changed the right side of the "=" to '3'
Comment: If you want to assign tags automatically, you don't want to do it in `hook_form_alter`.  That changes the default when the form is presented to the content creator, but he/she can always change it before saving it.  You may be looking for [`hook_node_presave`](http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_presave/7) instead.
Comment: Try the following $form['field_tags'][LANGUAGE_NONE]['#default_value'] = array('option key');
Answer: The field_tags element is likely a widget from the Field API. You can surely alter it from a form alter hook, but be aware that it would not be your average Form API element. The Field API adds post-processor, pre-rendered, etc. functions of its own. These functions may expect things you may want to alter.
You can however, change the default value of the field from the configuration interface of your content type (you need to enable the Field UI module for this). You should also be able to select a different widget (ie. a select box) from there.
Comment: I have Field UI enabled. I'm not sure how this can be configured to do what I want?

I was able to create a barebones "module" (more of a hack) that sets the default value based on user role. Currently it just does this programmatically by hardcoding specific roles and specific tags. What I think I need is to create a Configuration page that allows me to choose a role and then pick the default tag that appears.
Comment: You should update your question to explain that you need different default value depending on the current user's role.


Differentiablilty of function with inequality

Question:
Let $f:\mathbb{R}\to\mathbb{R}$ be a function satisfying $$\vert f(x)-f(y)\vert\le\frac{1}{2}\vert x+y\vert$$ for any $x,y\in\mathbb{R}$.

One can easily deduce that $f$ is continuous uniformly on $\mathbb{R}$.
How about the differentiability of $f$ on $\mathbb{R}$ or some subset of $\mathbb{R}$?
Can anyone give some insight or advice? Thank you!
Comment: Or did you mean $\vert f(x)-f(y)\vert\le\frac{1}{2}\vert x-y\vert$?
Comment: @MartinR Yes. Put in $y=-x$. Then, $f(x)=f(-x)$ for all $x\in\mathbb{R}$. From this, we have $\vert f(x)-f(y)\vert=\vert f(x)-f(-y)\vert\le\tfrac{1}{2}\vert{x+(-y)}\vert=\frac{1}{2}\vert{x-y}\vert$ for all $x,y\in\mathbb{R}$. So, $f$ is continuous uniformly on $\mathbb{R}$ since it satisfies the Lipschitz condition.
Comment: I see. Then it is differentiable almost everywhere: https://math.stackexchange.com/questions/2609765/is-a-lipschitz-function-differentiable
Comment: Are you sure about the (uniform) continuity?
Comment: Assuming the previous suggestion by @MartinR, just compute $ \frac{f(x+h) - f(x)}{h}$ for some $h > 0$ and prove that the limit as $h \to 0$ exists (which is the basic definition of being differentiable).
Comment: If it is indeed $|x+y|$ on the right-hand side, you might still be able to obtain something on some subset of $\mathbb{R}$ from the inequality $| |x| - |y| | \leq |x - y|$
Answer: The limit $$\lim_{x\rightarrow y}\frac{f(x)-f(y)}{x-y}$$ need not exist everywhere (all that you know is that this is uniformly bounded), so differentiability is not guaranteed. You can't generally prove that contractions are differentiable on the whole real line, such as $\frac{1}{2}|x|.$ It really boils down to differentiability of Lipschitz functions, which is true almost everywhere. This is the content of Rademacher's theorem: https://en.wikipedia.org/wiki/Rademacher%27s_theorem.


Difference between GMM classification and QDA

Question: I know that every class has the same covariance matrix $\Sigma$ in linear discriminant analysis (LDA), and in quadratic discriminant analysis (QDA) they are different. When using gaussian mixture model (GMM) in supervised classification, we fit a Gaussian with its own mean and variance to each class in data. So what is the difference between QDA and GMM?
Is my understanding of GMM wrong? Maybe I should fit more than one Gaussian to each class in order to model subgroups in it. But I am not sure if this is true or not.
Comment: Please don't forget, when asking a question, to expand your abbreviations.
Comment: A discriminant analysis is not only a classification but also a dimensionality reduction. In DA, classifiers are the discriminants extracted, not the input variables.
Comment: So, if we consider just the classification part, are QDA and GMM the same?
Answer: If you're given class labels $c$ and fit a generative model $p(x, c) = p(c) p(x|c)$, and use the conditional distribution $p(c|x)$ for classification, then yes you're essentially performing QDA (the decision boundary will be quadratic in $x$). Under this generative model, the marginal distribution of the data $x$ is exactly the GMM density (say you have $K$ classes):
$$p(x) = \sum_{k \in \{1,...,K\}} p(c=k) p(x|c=k) = \sum_{k=1}^K \pi_k  \mathcal{N}({x};{\mu}_k, {\Sigma}_k)$$
"Gaussian mixture" typically refers to the marginal distribution above, which is a distribution over $x$ alone, as we often don't have access to the class labels $c$.


what is done first balancing data or cross validation?

Question: I want to classify  imbalance data in two class and I want to use oversampling, undersampling and Synthetic data generation methods .for tuning my model i want use k-fold cross validation what should i do first?
balancing data and then use cross validation or vice versa?
Comment: The answer is neither. You do the oversampling/undersampling within the cross validation. That is, you split the data, oversample the training set only, and leave the validation/test set alone. If you are oversampling because there is a class distribution problem, then when splitting the data use stratified sampling so that your test set is reflective of what you observe in your data.
Answer: Without addressing the question of whether over-sampling or under-sampling is an appropriate approach, over-sampling before CV will cause data-leakage, as the same data point might be present in both the CV-test and training set.


Flex - search for string in TextArea

Question: I have a TextArea that allows user input. I also have TextInput that the user can type a string into and I want to be able to search through the TextArea for the string in the TextInput. I've never done anything like this before, searching for strings, so I don't know which functions to use or how to go about it.
Could someone please explain how to do this, or even give a small code snippet showing the process involved. Thanks.
EDIT:
protected function searchBtn_clickHandler(event:MouseEvent):void
            {
                text = mainTextField.text;
                search_Str = searchTxt.text;

                var search_result:int = text.search(search_Str);
                trace(search_result);
            }

Answer: First retrieve the texts from the text area and input field, for example:
var text       = $('#textarea_id').val();
var search_str = $('#input_id').val();

And then we'll do the seach:
var search_result = text.search(search_str);

Now search_result has the beginning index of the search_str in the text, or -1 if the search_str wasn't found.
Comment: Darn, beat me to it. +1 for this
Comment: Huh? Am I missing something here? This question is about Flex, yet the answer seems to be using some JS library...
Comment: Glad to help. It's using JQuery to select the text elements, but you can do that also with plain javascript (document.getElementById()), if Flex does not use JQuery (I'v never used is, so dunno).
Comment: I easily converted the idea to Actionscript for Flex. This was a huge help! :D
Comment: I've updated my post with the code I'm using for anyone that's interested.
Comment: Oh, i confused Flex with Adobe Edge (HTML5 framework). Well, luckily Actionscript is almost same as JS. :)

Flex - search for string in TextArea


http basic auth using .htacces/.htpasswd allowing slightly incorrect passwords

Question: I've got a few sites with directories protected by http basic auth implemented via .htaccess files paired with .htpasswd files. I've noticed that with a password ending in "et!" I can get in by omitting the "t!", or replacing the ! with a 1.
Contents of my .htaccess file:
<code>AuthType Basic
AuthName "administration"
AuthUserFile /var/www/conf/mysitename.com.pw

require valid-user
</code>
I have two users in mysitename.com.pw.
Obviously this behavior isn't wanted. Any idea what's going on?
Comment: specifying SHA1 or MD5 (htpasswd -s or -m) was the solution.
Answer: Have a look at: http://httpd.apache.org/docs/2.1/misc/password_encryptions.html
It sounds to me like you're using CRYPT format passwords (the default on most platforms). CRYPT passwords only use the first 8 characters of the password.
I suspect your password exceeds 8 characters in length and the "slightly incorrect" part are characters in the ninth or greater position (which aren't actually checked as part of the password).
Comment: the man page doesn't mention the default on linux systems. is CRYPT default when using the htpasswd binary without -m, -d, or -s?
Comment: Try changing the hashing algorithm to SHA1 or MD5, see if that fixes it.
Answer: I would try erasing and recreating the .pw file first. This is a really strange problem...
If that doesn't fix it, check for bug reports related your version of Apache. I HIGHLY HIGHLY doubt it is a bug, though.
I wish I knew where to go from there. Hopefully when you remove/recreate the file it fixes the problem. If not, hopefully an Apache expert wanders this way soon...


Does the batsman get runs on No ball when the team requires only 1 run to win?

Question: Suppose, A batsman is on strike with 98 runs. The scores are level so the batting team requires only 1 run to win. Now suppose in the next ball, the bowler bowls a No ball and the batsman hits FOUR or SIX. Will the batsman reach to his century or not?
Answer: I found it! When the batting team requires only 1 run to win and batsman scores run(s) on No ball it does not count towards batsman's runs. So in the given case the batsman will remain on 98 and batting side will win the match.
Real Case:
In the 3rd match between Sri Lanka and India in Sri Lanka Triangular Series, 2010 (between Sri Lanka, India and New Zealand), India required 1 run to win and Virender Sehwag was on strike with 99 runs. Suraj Randiv was the bowler. He bowled a No ball and Sehwag smashed a Six but still Sehwag remained on 99 runs because India won the match before he score runs. Have a look at commentary on Cricinfo (see from 35th over).
Comment: There you go, what a bizarre rule. I'll see if I can find the exact wording in the rules. It seems the no-ball was deliberate and this is a common occurance in sub-continental cricket. You'd never see that happen in Australia, for one because it would be considered bad sportsmanship and two because the bowler would cop a bat to the skull.
Comment: Here is the rule on this, as far as I can tell although it doesn't make it very clear:6. Winning hit or extras
(a) As soon as a result is reached as defined in 1, 2, 3, 4 or 5(a) above, the match is at an end. Nothing that happens thereafter, except as in Law 42.17(b) (Penalty runs), shall be regarded as part of it. Note also 9 below.
(b) The side batting last will have scored enough runs to win only if its total of runs is sufficient without including any runs completed by the batsmen before the completion of a catch, or the obstruction of a catch, from which the striker could be dismissed.
Comment: (c) If a boundary is scored before the batsmen have completed sufficient runs to win the match, the whole of the boundary allowance shall be credited to the side's total and, in the case of a hit by the bat, to the striker's score.
Comment: So the rules are clear that all runs from any boundary count, even if they are excess, but I guess once a ball is a no-ball then part (a) applies and the game is over, regardless of what the batsmen does. It seems from the article @hims056 linked to that the players are as bemused by this as I am. Very odd rule.
Comment: http://www.lords.org/laws-and-spirit/laws-of-cricket/laws/law-21-the-result,47,AR.html see part 6.
Comment: Bad Sportsmanship by Randiv, now he is only remembered for this incident.
Comment: @Bogdanovist - I am also searching for this rule. But couldn't find it yet. And yes [the no-ball was deliberate](http://www.google.com/#hl=en&safe=off&tbo=d&sclient=psy-ab&q=sehwag+randiv+no+ball&oq=sehwag+randiv+&gs_l=hp.3.0.0j0i10i30j0i30l2.152.5727.0.66126.96.36.199.0.0.0.315.2843.0j7j5j1.13.0.les%3B..0.0...1c.1.yyD98ZiLVZM&pbx=1&bav=on.2,or.r_gc.r_pw.r_qf.&bvm=bv.41248874,d.bmk&fp=943d5119ba67d312&biw=1280&bih=909).
Comment: @Bogdanovist - Nice. Please give a link of these rules.
Comment: and the ball was not counted to the balls faced by the batsman, since the match got the result before the batsman facing the ball
Comment: @SportsFan - I also believe this but in the given case the ball was counted as one faced by the batsman. :( See the last paragraph starting with *A technical question to MCC, though*
Answer: No,it won't go to the batsman,it will be counted as extras.
UPDATE:
As per Wikipedia:

A no ball does not count as one of the six balls in an over, but it
  counts as a ball faced by the batsman.  When a no ball is bowled, a
  number of runs are awarded to the batting team, the number varying
  depending on local playing conditions in force. In Test cricket and
  One Day International cricket the award is one run; in some domestic
  competitions, particularly one-day cricket competitions, the award is
  two runs. These runs are scored as extras and are added to the batting
  team's total, but are not added to any batsman's total. For scoring,
  no balls are considered to be the fault of the bowler (even if the
  infringement was committed by a fielder), and since the early 1980s,
  are recorded as a negative statistic in a bowler's record.
Comment: Welcome to Sports SE! Thanks for your answer. Is this reflected within the rules of cricket?
Comment: @edmastermind29 see updated answer.
Comment: Hi, the excerpt you have quoted is referring to the extra runs of the NoBall itself (usually the 1 run), and not to the runs scored by the batsman. If you read a few lines below: "If the batsman hits the ball he may take runs as normal. These are scored as runs by the batsman, as normal..."
Answer: yes it is possible because according to cricket law you can take run on no ball unless you got run out and your second point that  the next ball, the bowler bowls a No ball and the batsman hits FOUR or SIX. Will the batsman reach to his century or not? .. the answer is that the batsman will reach his century either it is no ball.
Answer: When the batting team requires only 1 run and batsman  require only two runs to complete the century and bowler bowls a no ball in last ball and batsman hits the four or six then  it will not count the score towards the batsman but one run due to no ball will count towards the team.
Answer: No, a batsman never gets a run into his account in case of NO BALL, WIDE BALL, leg bye or there are many such situations where the runs are counted for the team but not for the batsman. A batsman gets a run only when he hit the shot for a run. So, no matters whether it is the last ball of a first ball of the match the rules remains the same for every ball.
Let's take an example.
This is similar to what happened to Virendra Sehwag in the match against Sri Lanka when Suraj Randiv deliberately bowled a huge front foot no ball when India needed 1 run to win and Sehwag needed 1 run to complete his century. Though Sehwag hit a six, that six was not counted as the ball became dead at the moment that no-ball happened as the team had already won the match there.
And similarly, if the batsman is stumped when only 1 run is needed to win in 1 ball and the bowler bowls a wide, the batting side will win as the team wins the moment the ball is bowled wide and the ball becomes dead and the wicket does not count. So you can even re-frame the question as "If a cricket team needs 1 run to win with only 1 ball  left, and the team is 9 wickets down, and the bowler bowls a wide, but the batsman got stumped, who will win?"
Answer: The batting side


Strings em python

Question: Sei o básico de codificação de strings em Python, mas não ainda não consigo avançar e concluir toda a exigência do enunciado.
Não sei codificar as quantidades que exige na questão.
Segue enunciado:
Leia strings do teclado até que uma string vazia seja lida.
Escreva em tela :

(A)  a quantidade de vogais lidas;
(B) a quantidade de dígitos lidos;
(C) qual foi a string de maior comprimento lida. Caso haja empate, escreva uma delas;
(D) a quantidade de strings palíndromes lidas.

Definição:
Uma string é dita palíndrome se e somente se, quando lida do primeiro para o último caractere for igual a string lida do último para o primeiro caractere.
Por exemplo:
"AMA", "POP", "SOCORRAMMESUBINOONIBUSEMMARROCOS", "" e "Z" são palíndromes.
Comment: `len(minha_string)` dá lhe o tamanho da string. Ainda assim a sua questão está vaga. Tentar dar exemplos mais concretos do que pretende, de preferência com algum código que já tenha escrito
Comment: M.xy, vi que atualizou completamente a pergunta, mas mesmo assim não postou nenhum código. Mesmo com as respostas atuais você não conseguiu entender nem o mínimo para tentar? Se for, por favor, descreva suas dúvidas na pergunta.
Answer: Se a intenção, que não ficou clara na pergunta, for, de fato a leitura de múltiplos textos do usuário até que o mesmo não digite algo, você deverá fazer um laço de repetição infinito até que a condição de parada seja satisfeita. De certa forma, é o que o código da outra resposta faz, porém, na minha opinião, não é a melhor maneira a se fazer.
x = 'algo'

while x != '':
    x = input()

Podemos supor que o leitor, inicialmente, não saberá que o objeto x será o responsável por receber o texto do usuário. Logo na primeira linha x recebe um valor constante. Ao ler, é natural pensar algo como "x recebe este valor porque em algum lugar irá precisar utilizá-lo" (o que já é uma interpretação errada do código, mas o leitor não saberia disso ainda). Na próxima linha, há o laço de repetição com a condição x != '' e, obviamente, o leitor pensará algo como "mas se x é constante, ele sempre será diferente de '', então esse laço será infinito?", o que, de novo, será uma interpretação errada do código. Somente ao ler a última linha, onde x recebe a entrada do usuário, que o código fará sentido.
Como não há como prever quantas vezes o usuário irá entrar com um texto diferente de vazio, o correto é criar o laço infinito com while True; depois, você faz a leitura da entrada do usuário e faz a verificação, se for um texto vazio, pare o laço. O código ficaria:
while True:
    x = input("Digite algo:")
    if not x:
        break
    print("Tamanho do texto", len(x))

Assim como comentado, foi utilizado a função len para obter o tamanho do texto.
Answer: Olá. Vou fazer o exemplo mais simples possível, pois acho que assim fica mais fácil de entender. Depois é com você incrementar, fazer testes e aprender mais.

Como codificar leitura de strings do teclado até que uma string vazia
seja lida?

x = 'algo'

while x != '':
    x = input()

Como escrever em tela as quantidades de letras de uma string?

string = "minha string"

print(len(string))

ou ainda, caso você prefira loop:
string = "minha string"
cont = 0

for x in range(string.__len__()):
    if string[x] != 0:
        cont +=1

print('Minha string tem {} caracteres' .format(cont))

Adendo: Vi em outra pergunta que você está bem perdida com a linguagem. Não se preocupe, isso é normal e todo mundo tem que começar do 0 um dia.
Comment: O correto é usar a função `len` - a ideia é que o Python sempre vai chamar os métodos mágicos apropriados de uma classe quando existirem. Então `next` em vez de `.__next__`, `str` em vez de `__str__`,usar o operador `in`  em vez de chamar `__contains__`, etc.
Comment: Realmente não há necessidade de utilizar o método `__len__`. Ou melhor, ele até prejudica o código quando comparado com a função `len` pois prejudica a legibilidade. E você não precisa do `range` para iterar sobre string, elas são iteraveis por si só naturalmente.
Comment: Assisto as aulas do Guanabara sim e estou gostando... mas ainda estou organizando os estudos para avançar mais. Agradeço os comentários. Me ajudou bastante.
Comment: Espero que essas aulas não incentivem o uso de `__len__` e semelhantes
Comment: pq não usar print(len(string))
Comment: @GlaucioFonseca Explicação completa do porquê usar o .__len__ você encontra nesta pergunta https://pt.stackoverflow.com/questions/201701/afinal-para-que-serve-a-fun%C3%A7%C3%A3o-repr-no-python/201751#201751, mas em resumo, usando o seu método ou o meu método vai dar no mesmo já que, internamente, o Python vai interpretar com o .__len__ pois este é o método built-in
Comment: Como faz pra iterar diretamente com ela? Não sabia dessa, mas vou alterar o código

Strings em python


Question on 1/4 notes and 1/8 notes on same chord

Question: I have a simple question on the following image. How would I know if the first C is a quarter note or eighth note?
Could this ever be considered a tie between the two C's ?

Additional: This is the 2nd measure of Pomp and Circumstance from the book Funtime Piano Classics.
FYI, I googled an alternate arrangement, and found

which leads me to believe that it is meant to be a tie - and yet another way to write it :(
Comment: This is poor notation, as the answers suggest.  It's certainly a written eight-note, which it should not be (should be a quarter)
Answer: Whilst it looks like a tie, it must be a slur, which ought to be over the top notes rather than under it all. It seems to be a poor example of writing, as there doesn't need any tie to be there; the first C could have been written as a minim, with the stem down, indicating a different voice, which it should be anyway.
Were the first C only a quaver, it could't be tied to the second, as there is then a missing quaver rest. Putting that rest in would negate the tie.
Comment: The mark is stylised as a tie, so it's intended to be a tie, but the second eigth note should be a C-G chord, not just a G, and the tie **must** be between adjacent notes (so you need two smaller ties here). tl;dr: this is **invalid** musical notation, but you can fix it up with a pencil yourself ☺ as the intent is… sort of clear enough.
Comment: @user1079505 - don't you think the slur mark in the 1st example is the slur mark in the second, but written properly? There's no point at all in not using a minim for the C note - that actually does last the 2 beats needed. So maybe it's *meant* to be a tie, but a slur over all (3 top) notes makes more sense. That apart, the 1st C looks far more like a quaver than a crotchet, hence my answer. 1st one is just badly written - and actually amounts to nothing. Yes, maybe it should be a tie, but it's a badly written tie. In your second example, all of what I say becomes clear - the minim, and ...
Comment: ...the slur/phrase mark. What else?
Comment: @user1079505 - the tie mark is used wrongly, so could easily actually be the slur, as shown in the 2nd example. Yes, the C needs holding for the whole minim, but that's not shown well, in example 1. And, funnily enough, in the video, that C **is** actually played **twice**. So where's the tie now? Watch, check, and respond, please!
Comment: "The" video? I found at least five. OK, at least three played by apparently competent adults.
Comment: @DavidK - and were there any where the C gets held over, not played agan? Doubt it.
Comment: I wouldn't swear to it in court, because the camera angle and sound quality make it hard both to see and hear, but https://www.youtube.com/watch?v=bl5cGfHhjvE appears to hold the C. There is at least a moment when both the C and G keys are simultaneously held down. On the other hand it's possible the pianist released the C just in time to strike it again along with the A, that is, played as the notation in the other answer would be if the tie were deleted. For what it's worth, if I had to interpret this terrible notation *as written* I would choose the same answer as you did.
Comment: @DavidK - agreed. But listen to the second time it gets played - definitely no tie there, but not sure what the dots say there. I like 'on the other hand' - except it's not !
Comment: The second time around the C key is even harder to see, but I do hear it being struck a second time -- which tends to suggest it wasn't struck twice on the first time through that phrase. I don't have a copy of the book so I don't know if it's written differently the second time or just played differently by this pianist.
Comment: Also, checking out the original score, it makes no sense to me that you would arrange this for piano so that the C is held for the entire bar. Every instrument is either playing in time with the melody or plays two quarter notes.
Comment: @DavidK - it's a march after all - so two separate beats/notes in the accompaniment makes even more sense.
Comment: @user1079505 - at which point I will cancel my dv. Funny that OP preferred that answer!
Comment: I just wrote another answer......
Answer: I'm writing another answer, after reading the comments, and doing some research. I am going to delete my previous answer, as I now realize it's misleading.
The measure comes from an arrangement of part of March no. 1 from "Pomp and Circumstance" by Edward Elgar. If the book doesn't mention it, it's not good.
Elgar composed the marches for an orchestra. Arrangements for piano were done by other people. In such case it's always good to check the original composition.
An example recording can be found at:

and the score at:
http://cantorion.org/music/552/Pomp-and-Circumstance-March-No.-1-Full-score
section I.
There are only two rhythmic layers in that section: a melody, and a steady, quarter note accompaniment. No voice plays a half note in the measure in question.
This answers the question: the C belongs to accompaniment. It is supposed to be played twice, as a quarter note each time.
The piano notation you showed is bad for several reasons:

the curvy line is supposed to be a slur and it's supposed to refer to the top notes in the example. It should be therefore printed above the top notes
the line is stylized as a tie. I'm not an expert of typography, and I'm not sure if strict rules exist, but after seeing many scores in my life, visually the line in the example looks more like a tie than a slur. For example Musescore draws slurs more curved than ties, and it seems right to me.
even if we correctly interpret the slur correctly, there is one more issue: each of the C notes should be of the same length, quarter note, rather than an eight note followed by an eight-note pause.

This is a correct notation of the measure:

All this hints issues with the book you're using.
I'd like to also draw the community attention to a question I once asked on Meta: Could SE ask for more details on the scores in questions
Comment: Interesting, that your other answer, although inaccurate, garnered 9 upvotes. Can't help wondering how many of those were prompted by OP accepting that answer. Just a thought...
Comment: @Darren Yes, looking at many questions asked at SE I often see people asking questions assuming that music notation is always perfect and unambiguous. In fact various abbreviations, markings specific for given style, instrument, or even composition, and plain bad practice and mistakes are quite common. It's therefore important to know the context. For arrangements, even good ones, learning about the original is invaluable.
Comment: Thanks for the detailed answer! With regard to the comment about whether the question had enough detail, I thought that I was asking an academic question about how to interpret the music notation as it was written, and whether there was any ambiguity in its interpretation. But the community went after the wider question of whether the measure is in fact written correctly (which requires a lot more context). In any case, I am glad the question wasn't closed out of hand since it led to an interesting discussion and I think we all learned something.