How do I get an out a value from an ArrayList from the user typing it in?

Question: The question the user would see it "Which car would you like?"
And I want to be able to call that specific car in the array list and have it print on one line.
I'm using an if statement so that the user types in certain letters and it will spit out the specific car from the array by itself.
ArrayList<Car> carList = new ArrayList<Car>();
carList.add(new Car("Nikolai", "Model S", 2017, 54999.90));
carList.add(new Car("Fourd", "Escapade", 2017, 31999.90));
carList.add(new Car("Chewie", "Corvette", 2017, 44989.90));

carList.add(new UsedCar("Hyonda", "RichardPryor", 2015, 14795.50, 35987.6));
carList.add(new UsedCar("GC", "Chirpus", 2013, 8500.00, 12345.00));
carList.add(new UsedCar("GC", "Witherell", 2016, 14450.00, 3500.3));

String userInput = "";

for (Car theList : carList) {

    System.out.printf(theList.getMake() + "\t " + theList.getModel() + "\t " + theList.getYear() + "\t "+ "$" + theList.getPrice());
}

System.out.println("Which car would you like? (Please type the name)");
userInput = scnr.nextLine();

if (userInput.equalsIgnoreCase("ni")) {
    System.out.println(carList.get(0));
} else if (userInput.equalsIgnoreCase("fo")) {
    System.out.println(carList.get(1));
} else if (userInput.equalsIgnoreCase("ch")) {
    System.out.println(carList.get(2));
} else if (userInput.equalsIgnoreCase("hy")) {
    System.out.println(carList.get(3));
} else if (userInput.equalsIgnoreCase("qu")) {
    System.out.println(carList.get(6));

    if (userInput.equalsIgnoreCase("gc")) {
        System.out.println("Chripus or Witherell?");
    }
    if (userInput.equalsIgnoreCase("chr")) {
        System.out.println(carList.get(4));
    } else
        System.out.println(carList.get(5));
}

I expected the System.out.println(carList.get()) to print out the corresponding array list excatly when the for loop runs. (Which I know the for loop works...)
Comment: @ScaryWombat: GMTA
Comment: If you want to extract an object based on a "key" input String, then best not to use an ArrayList at all, but rather use a Map of some sort, such as a `HashMap`. then you could get the appropriate Car easily via `map.get(keyString)`
Comment: `System.out.println(carList.get(0));` - I assume that you have overriden `toString` ?
Comment: why not use a `map` ?
Comment: Well, the instructions say to store all the care and used car instances together in the same arrayList. I just thought that since I had to use an arrayList I had to pull from it.
Comment: BTW, `} else if (userInput.equalsIgnoreCase("qu")) {
    System.out.println(carList.get(6));

    if (userInput.equalsIgnoreCase("gc")) {` will work work as you are not getting new input from the user
Comment: finally, retrieving based upon the `index` is not a very expandable method.
Comment: I believe so, there is an toString in the Car class
Comment: I actually don't get the weird (hash?) coding....it just prints the name of the car at best but not the entire array line.
Comment: so change the `toString` method or create a new method - anyway, what is your actual question?
Answer: As mentioned by @Scary Wombat in the comments, if you really want to use ArrayList the easiest way is to implement/override the toString method. Since you say that the toString method currently only prints the name of the car, you can change it to something like this:
public String toString() {
    return this.getMake() + "\t " + this.getModel() + "\t " + this.getYear() + "\t "+ "$" + this.getPrice();
}

To be even clearer, a full working Car might be the following:
import java.util.ArrayList;
import java.util.Scanner;

class Car {

    private String make;
    private String model;
    private int year;
    private double price;

    public Car(String make, String model, int year, double price) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.price = price;
    }

    public String getMake() {
        return this.make;
    }

    public String getModel() {
        return this.model;
    }

    public int getYear() {
        return this.year;
    }

    public double getPrice() {
        return this.price;
    }

    public String toString() {
        return this.getMake() + "\t " + this.getModel() + "\t " + this.getYear() + "\t "+ "$" + this.getPrice();
    }

    public static void main(String[] args) {
        ArrayList<Car> carList = new ArrayList<Car>();
        carList.add(new Car("Nikolai", "Model S", 2017, 54999.90));
        carList.add(new Car("Fourd", "Escapade", 2017, 31999.90));
        carList.add(new Car("Chewie", "Corvette", 2017, 44989.90));

        String userInput = "";
        System.out.println("Which car would you like? (Please type the name)");
        Scanner scnr = new Scanner(System.in);
        userInput = scnr.nextLine();

        if (userInput.equalsIgnoreCase("ni")) {
            System.out.println(carList.get(0));
        } else if (userInput.equalsIgnoreCase("fo")) {
            System.out.println(carList.get(1));
        } else if (userInput.equalsIgnoreCase("ch")) {
            System.out.println(carList.get(2));
        }
    }
}

Assuming that UsedCar inherits from Car, you can also override the toString method in UsedCar to something like:
public String toString() {
    return super().toString();
}

This toString method is necessary because otherwise you are just printing the Car object hashcode value when you get it from the ArrayList. By overriding the toString method, the java compiler will call your toString method and print the information encapsulated in the Car instead. Hope that this example helps to clear things up!


How can I let a group of users edit anything in a specific section?

Question: Our content editor wants to let the various authors have rights to edit things in only specific sections, and it will often be multiple people assigned to a given section.  What's the best way to do this?   (And sections do NOT map neatly to content-types.  They're based on the menu/site structure.)
Answer: It's not clear to me what your rule is for determining access control. I'm going to guess it's menu paths.
I had a similar problem recently. I needed to ensure that users trying to access /somePathName/* were of a certain role. This is a bit of an odd scenario in that any path in the system could be aliased under one of my UAC paths and it will automatically become access controlled whether it was a term, node, user, whatever.
I looked into existing solutions and found none. I wrote my own module that managed access control based on "arg(1)" and a user's roles.
Access control in Drupal is one of those pieces that you understand after a few hours of studying, do the work, then completely forget how you did it. Or maybe that's just me.
d.org documentation is pretty good on this topic. And be sure to install devel and enable the node access modules it provides. These are very useful.


How to allow Linux networking into the internet on Hetzner cloud server while the routing table contains only 169.254.0.0 IP?

Question: i am having virtual server from Hetzner and after installing the CentOS 6 linux, i do not know how to make the default installation available from the internet, how to setup the routing. The Hetzner says that the gateway IP should be 172.31.1.1 (https://wiki.hetzner.de/index.php/CloudServer/en#What_are_Routes.3F - "The special private IP Address 172.31.1.1. This IP address is being used as a default gateway of your servers public network interface. ")
At first following worked: /sbin/route add default gw 172.31.1.1 eth0
but now one day later it says SDIOCADDRT: Network is unreachable.
Current routing table (route -n) contains only one rule:
169.254.0.0/16 dev eth0 scope link metric 1002
Config file for the eth0 interface is: https://i.postimg.cc/9Qc6VwK7/ifcfg-eth0.gif
Please can you tell me which commands should make the routing table be done properly? Or what is wrong in my eth0 interface config. file?
UPDATE: i was told i should use static configuration on CentOS 6, but i am having problem with the route-eth0 file as i am unable to create it:
cp /etc/host.conf /etc/sysconfig/network-scripts/route-eth0
perl -pi -e s/multi on/172\.31\.1\.1\/32 dev eth0\\ndefault via 172\.31\.1\.1 dev eth0/g /etc/sysconfig/network-scripts/route-eth0
The error is: Substitution pattern not terminated at -e line 1.
(i can not use echo or tee or vim because Hetzner console do not work with | " ' $ > characters and Ctrl key)
Comment: It's best to avoid posting images if possible, but if you must do, then please upload images here. Many readers will not be able to visit external image hosting sites as they will be blocked at their workplace.
Comment: i was told i should use static configuration on CentOS 6: https://wiki.hetzner.de/index.php/Cloud_IP_static/en#Fedora_.2F_CentOS
Comment: Link-local IP addresses (`169.254.0.0/16` for IPv4 and `fe80::/10` for IPv6) are, by definition, not forwardable (routable). Also, a gateway needs to be in the same network as the host address, otherwise you would need a gateway to reach the gateway.
Answer: They told me i need to use static configuration and it worked (after restarting network / rebooting).
(Note that the IPs under that link are likely specific only to a Hetzner servers)
Adjusting the configuration files was very difficult via Hetzner console (which does not accept Ctrl key, | > $ " ' etc.).
These were the commands i had to run (will almost certainly work only on Hetzner + CentOS 6 and after replacing myvpspubliciphere. But can give idea for anyone using limitted web console like one from Hetzner):
perl -pi -e s/BOOTPROTO=dhcp/BOOTPROTO=static/g /etc/sysconfig/network-scripts/ifcfg-eth0
perl -pi -e s/IPV6INIT=no/IPADDR=myvpspubliciphere/g /etc/sysconfig/network-scripts/ifcfg-eth0
perl -pi -e s/ONBOOT=yes/ONBOOT=yes\\nNETMASK=255.255.255.255\\nDNS1=184.108.40.206\\nDNS2=184.108.40.206/g /etc/sysconfig/network-scripts/ifcfg-eth0
cp /etc/host.conf /etc/sysconfig/network-scripts/route-eth0
perl -pi -e s/multi\ on/172.31.1.1\\/32\ dev\ eth0\\ndefault\ via\ 172.31.1.1\ dev\ eth0/g /etc/sysconfig/network-scripts/route-eth0
service network restart

(the cp command was used to get a small file with just a two words which i can use for easily replacing its content by what i needed)


Issue getting Doxygen to document an enum in C

Question: I have a rather odd problem with Doxygen (1.6.1 on Mac OS X Snow Leopard) in that it does not seem to document my enums no matter what I do. I am programming in C and have followed the instructions in the manual. Here is my code:
/**
 * \enum dccp_pkt_type
 * \brief specifies the available DCCP packet types
 */

enum dccp_pkt_type
{
    DCCP_REQUEST    = 0,    /**< DCCP Request Packet */
    DCCP_RESPONSE,          /**< DCCP Response Packet */
    DCCP_DATA,              /**< DCCP Data Packet */
    DCCP_ACK,               /**< DCCP Ack Packet */
    DCCP_DATAACK,           /**< DCCP Data Ack Packet */
    DCCP_CLOSEREQ,          /**< DCCP Close Request Packet */
    DCCP_CLOSE,             /**< DCCP Close Packet */
    DCCP_RESET,             /**< DCCP Reset Packet */
    DCCP_SYNC,              /**< DCCP Sync Packet */
    DCCP_SYNCACK,           /**< DCCP Sync Ack Packet */
    DCCP_RESERVED,          /**< DCCP Reserved Packet Type - Receivers MUST
                         ignore any packets with this type */
};

It should according to the doxygen manual produce properly documentated output but instead it produces nothing. I am most likely missing something simple, if anyone could point me in the right direction I would be grateful.
Comment: General comment not addressing the question: Your [Doxygen] comments for individual enum values (perhaps with the exception of
 the "ignore" note for DCCP_RESERVED) do not add anything useful, just clutter the view.
Answer: From the Doxygen manual:

Let's repeat that, because it is often
  overlooked: to document global objects
  (functions, typedefs, enum, macros,
  etc), you must document the file in
  which they are defined. In other
  words, there must at least be a
/*! \file */ or a
/** @file */ line in this file.
Answer: My experience is the same using EXTRACT_ALL=NO and SHOW_INCLUDE_FILES=NO with doxygen 220.127.116.11 - global enum types were not listed nor linked even though /*! \file */ is present and the global enum is referenced by a documented compound structure.
To work around this, I ended up defining an Enumerations group:
/*!
    \defgroup Enumerations
        Public enumeration types
*/
and for the enum types I used \ingroup Enumerations to include the enums in the new group.  Doxygen then was able to autolink from the compound structures to the enum types.
Comment: I'm finding this too in version 1.8.11.
Answer: If memory serves correctly, enum documentation doesn't show up unless the file is also documented.  Try adding a @file section.


Fazer redirecionamento pra versão mobile do site via javascript ou design responsivo, qual é a melhor opção?

Question: Fazer um redirecionamento via javascript para uma versão mobile do site ou fazer um design responsivo?
Comment: Pense que se for fazer um site para cada opção terá que fazer pelo menos 4 sites (celulares, tablets, computadores e tvs), e, mesmo assim, poderá ficar ruim em alguns dispositivos, fora a duplicata de código, imagine que mesmo uma pequena alteração no backend fará com que você altere o frontend em todos os sites
Answer: Acredito que seja melhor fazer um responsivo, assim não terá que fazer dois sites (no caso um para computador e um para mobile). E também por ter mais vantagens: usabilidade, velocidade e gerenciamento. (Ref: http://www.shapeweb.com.br/blog/2017/02/07/5-vantagens-para-ter-um-site-responsivo/)
Comment: Vi que editou sua pergunta colocando os títulos do link e o removendo, você pode manter o link como referência, só não pode deixar sua pergunta refém do link
Comment: Sugiro que coloque o conteúdo relevante do link aqui, respostas somente com links podem ser invalidadas
Comment: Ah, obrigado pela dica.


How to solve this simultaneous equations which involves exponents: $2^x - 2^y = 1$, $4^x - 4^y = \frac53$?

Question: I am trying to find $x-y$ when:
\begin{cases}
2^{x} - 2^{y} = 1 \\
4^{x} - 4^{y} = \frac{5}{3}\\
\end{cases}
Simultaneously. From the second equation I factorized to get $$(2^x + 2^y)(2^x - 2^y) = \frac53$$
and from the first equation, since $(2^x - 2^y) = 1$, I deduced that $$ (2^x + 2^y)\cdot 1 = \frac53 \to (2^x + 2^y) = \frac53$$
Now I am a little stuck on how to proceed. Any ideas how to carry on with explanations please?
Comment: I have edited to add in what you really want - always wise to ask the whole question, because then you will get better help. I've also updated my answer.
Answer: Try adding the equations $2^x-2^y=1$ and $2^x+2^y=\frac 53$
To go further per your comment:
This gives $2\cdot 2^x=\frac 83$
Subtracting the equations gives $2\cdot 2^y=\frac 23$
Now recall that $\frac {2^a}{2^b}=2^{a-b}$ and divide in an appropriate way to make further progress.
Comment: Thanks. How would I determine what $x - y$  is? Because the original homework question was to determine the value of $x-y$ so I thought it would be a good idea to find the values of x and y but that will not help me determine the value of $x - y$ because I don't know anything about log and I can't use a calculator.
Answer: Well, now it's really simple because you have
\begin{cases}
2^x - 2^y = 1 \\
2^x + 2^y = \frac53 \\
\end{cases}
so $$ 2^x - 2^y + 2^x - 2^y = 2\cdot 2^x = 1+\frac53 = \frac83 \Rightarrow 2^x = \frac43 \Rightarrow x = log_2{\frac43}$$
Finally, since $2^x = \frac43$, $$ 2^y = \frac53 - \frac43 = \frac13 \Rightarrow y = log_2{\frac13}$$ The solution is $\left(log_2{\frac43} , log_2{\frac13}\right)$.


ip_queue: full on an SUSE application server. What to do?

Question: An application server (SUSE 64bit) that has my app. on it is emitting "ip_queue: full" message and is refusing connection (e.g. can't ping).
My app. is an EJB application that uses JBoss5, and it doesn't do anything special with regard to network (just some regular Servlets).
Since JBoss handles all the low-level network stuff and it being a very well tested AS, I'm suspecting that some kernel parameters are not appropriate, but I couldn't find as much information as I hoped for on the internet.
Could somebody advice on how I should go about this?
Thanks.
Answer: Kernel queue is full, when send the packet to user space.

check network statistics: netstat -s
increase the queue length(/proc/sys/net/ipv4/ip_queue_maxlen)
check system performance(top,free,iostat,vmstat)
check running daemon and who send/receive traffic


When using tweepy cursor, what is the best practice for catching over capacity errors?

Question: I'm gathering information on a large number of users using Python's Tweepy library. I've the API initialized as follows

api = tweepy.API(auth,wait_on_rate_limit=True,
  wait_on_rate_limit_notify=True)

where auth contains my tokens. This code responds well to rate limit errors, but doesn't work for some other errors. For example, I sometimes see the following exception.

tweepy.error.TweepError: [{'message': 'Over capacity', 'code': 130}]

I can handle this exception using a try except, but I was wondering if there is a way to handle this exception within the cursor like I'm handling rate limit exceptions. I see parameters like retry_count, but I'm not sure if they will work for this case as they seem designed for HTTP errors.
Answer:
I see parameters like retry_count, but I'm not sure if they will work
  for this case as they seem designed for HTTP errors.

Well, according to the docs, some of the parameters have an HTTP code correspondent, which indicates that it will work. (Whole list below my answer)
Out of the whole list, you are interested in
Over capacity which Corresponds with HTTP 503. Twitter is temporarily over capacity
So what you need is to provide a retry_errors param when instantiating the API. This will tell the API which HTTP status codes to retry. An example:
retry_count=10, retry_delay=5, retry_errors=set([503])

Whole list of codes:
+------+--------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Code |                                               Text                                               |                                                                                Description                                                                                |
+------+--------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|    3 | Invalid coordinates                                                                              | Corresponds with HTTP 400. The coordinates provided as parameters were not valid for the request.                                                                                |
|   13 | No location associated with the specified IP address                                             | Corresponds with HTTP 404. It was not possible to derive a location for the IP address provided as a parameter on the geo search request.                                                                                |
|   17 | No user matches for specified terms                                                              | Corresponds with HTTP 404. It was not possible to find a user profile matching the parameters specified.                                                                                |
|   32 | Could not authenticate you                                                                       | Corresponds with HTTP 401. There was an issue with the authentication data for the request.                                                                                |
|   34 | Sorry, that page does not exist                                                                  | Corresponds with HTTP 404. The specified resource was not found.                                                                                |
|   36 | You cannot report yourself for spam.                                                             | Corresponds with HTTP 403. You cannot use your own user ID in a report spam call.                                                                                |
|   44 | attachment_url parameter is invalid                                                              | Corresponds with HTTP 400. The URL value provided is not a URL that can be attached to this Tweet.                                                                                |
|   50 | User not found.                                                                                | Corresponds with HTTP 404. The user is not found.                                                                                |
|   63 | User has been suspended.                                                                         | Corresponds with HTTP 403 The user account has been suspended and information cannot be retrieved.                                                                                |
|   64 | Your account is suspended and is not permitted to access this feature                            | Corresponds with HTTP 403. The access token being used belongs to a suspended user.                                                                                |
|   68 | The Twitter REST API v1 is no longer active. Please migrate to API v1.1.                         | Corresponds to a HTTP request to a retired v1-era URL.                                                                                |
|   87 | Client is not permitted to perform this action.                                                  | Corresponds with HTTP 403. The endpoint called is not a permitted URL.                                                                                |
|   93 | This application is not allowed to access or delete your direct messages                         | Corresponds with HTTP 403. The OAuth token does not provide access to Direct Messages.                                                                                |
|   99 | Unable to verify your credentials.                                                               | Corresponds with HTTP 403. The OAuth credentials cannot be validated. Check that the token is still valid.                                                                                |
|  120 | Account update failed: value is too long (maximum is nn characters)                              | Corresponds with HTTP 403. Thrown when one of the values passed to the update_profile.json endpoint exceeds the maximum value currently permitted for that field. The error message will specify the allowable maximum number of nn characters.                                                                                |
|  130 | Over capacity                                                                                | Corresponds with HTTP 503. Twitter is temporarily over capacity.                                                                                |
|  131 | Internal error                                                                                | Corresponds with HTTP 500. An unknown internal error occurred.                                                                                |
|  135 | Could not authenticate you                                                                       | Corresponds with HTTP 401. Timestamp out of bounds (often caused by a clock drift when authenticating - check your system clock)                                                                                |
|  144 | No status found with that ID.                                                                    | Corresponds with HTTP 404. The requested Tweet ID is not found (if it existed, it was probably deleted)                                                                                |
|  150 | You cannot send messages to users who are not following you.                                     | Corresponds with HTTP 403. Sending a Direct Message failed.                                                                                |
|  151 | There was an error sending your message: reason                                                  | Corresponds with HTTP 403. Sending a Direct Message failed. The reason value will provide more information.                                                                                |
|  160 | You've already requested to follow user                                                          | Corresponds with HTTP 403. This was a duplicated follow request and a previous request was not yet acknowleged.                                                                                |
|  161 | You are unable to follow more people at this time                                                | Corresponds with HTTP 403. Thrown when a user cannot follow another user due to some kind of limit                                                                                |
|  179 | Sorry, you are not authorized to see this status                                                 | Corresponds with HTTP 403. Thrown when a Tweet cannot be viewed by the authenticating user, usually due to the Tweet's author having protected their Tweets.                                                                                |
|  185 | User is over daily status update limit                                                           | Corresponds with HTTP 403. Thrown when a Tweet cannot be posted due to the user having no allowance remaining to post. Despite the text in the error message indicating that this error is only thrown when a daily limit is reached, this error will be thrown whenever a posting limitation has been reached. Posting allowances have roaming windows of time of unspecified duration. |
|  186 | Tweet needs to be a bit shorter.                                                                 | Corresponds with HTTP 403. The status text is too long.                                                                                |
|  205 | You are over the limit for spam reports.                                                         | Corresponds with HTTP 403. The account limit for reporting spam has been reached. Try again later.                                                                                |
|  215 | Bad authentication data                                                                          | Corresponds with HTTP 400. The method requires authentication but it was not presented or was wholly invalid.                                                                                |
|  220 | Your credentials do not allow access to this resource.                                           | Corresponds with HTTP 403. The authentication token in use is restricted and cannot access the requested resource.                                                                                |
|  251 | This endpoint has been retired and should not be used.                                           | Corresponds to a HTTP request to a retired URL.                                                                                |
|  261 | Application cannot perform write actions.                                                        | Corresponds with HTTP 403. Thrown when the application is restricted from POST, PUT, or DELETE actions. Check the information on your application dashboard. See How to appeal application suspension and other disciplinary actions.                                                                                |
|  271 | You can't mute yourself.                                                                         | Corresponds with HTTP 403. The authenticated user account cannot mute itself.                                                                                |
|  272 | You are not muting the specified user.                                                           | Corresponds with HTTP 403. The authenticated user account is not muting the account a call is attempting to unmute.                                                                                |
|  323 | Animated GIFs are not allowed when uploading multiple images.                                    | Corresponds with HTTP 400. Only one animated GIF is allowed to be attached to a single Tweet.                                                                                |
|  324 | The validation of media ids failed.                                                              | Corresponds with HTTP 400. There was a problem with the media ID submitted with the Tweet.                                                                                |
|  325 | A media id was not found.                                                                        | Corresponds with HTTP 400. The media ID attached to the Tweet was not found.                                                                                |
|  326 | To protect our users from spam and other malicious activity, this account is temporarily locked. | Corresponds with HTTP 403. The user should log in to https://twitter.com to unlock their account before the user token can be used.                                                                                |
|  327 | You have already retweeted this Tweet                                                            | Corresponds with HTTP 403. The user cannot retweet the same Tweet more than once.                                                                                |
|  354 | The text of your direct message is over the max character limit.                                 | Corresponds with HTTP 403. The message size exceeds the number of characters permitted in a Direct Message.                                                                                |
|  385 | You attempted to reply to a Tweet that is deleted or not visible to you.                         | Corresponds with HTTP 403. A reply can only be sent with reference to an existing public Tweet.                                                                                |
|  386 | The Tweet exceeds the number of allowed attachment types.                                        | Corresponds with HTTP 403. A Tweet is limited to a single attachment resource (media, Quote Tweet, etc.)                                                                                |
+------+--------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+


Most efficient way to change CSS between pages

Question: I'm looking to change certain parts of my design for my site through the CSS, my basic principle is that when you navigate to a certain page, it will kick in to effect, and change some CSS values.
Say for example you navigate to mysite.com/colour/red. It would change certain parts of the styling to red (like border colours, underlines, link colours etc) and it would remain in red until you then navigated to something like mysite.com/colour/green at which point, everything that had previously changed to red, now becomes green.
I have already written some code which runs a function when you navigate to one of these pages and sets a session variable using the Session Cache API so that I can set a temporary colour change for the site.
My question is, what is the best way of injecting the new lines of CSS into my site at this point? My initial train of thought is that I can extend the function I currently have to pull in an external CSS file with those specific colours already defined (ie if you go to mysite.com/colour/red, it will pull in red.css, with the border/underline already specified). Or alternatively, I have thought about using the html.tpl file to perform a check against the session parameter, and pull in a CSS file through there.
What would be the most efficient way of changing my stylesheet? Is there a function already in Drupal which would allow me to do something like this
NB. I am using the Alphorn Omega theme template
Comment: "Most efficient" depends on many factors, primarily on your definition of efficiency. And "best" depends on definition of value (see: http://xkcd.com/309/ ;) ). There can be about 3 ways to inject CSS, one or two to change theme and 3 more to get the effect with unchanging CSS...
Comment: I think in terms of 'Most efficient' I was considering how often it tries to check if it needs to alter the CSS and which would be the best in terms of load time. I was personally pushing more towards using the preprocessor function I already have to bring in a stylesheet relevant for that colour. Having never used it properly before, would/could LESS do this job?
Answer: I think the usual method of adding per-page CSS is in your template.php file using HOOK_preprocess_page(). A couple of examples:
alphorn_preprocess_page(&vars) {
  // Add CSS based on path (beware if you change your path structure!)
  // But as a bonus, this will add the CSS for any path under "/colour/red"
  if (strpos($_SERVER['REQUEST_URI'], 'colour/red') !== false) {
    drupal_add_css(drupal_get_path('theme','alphorn').'/css/red.css');
  }

  // Add CSS based on NID, with an out because this hook may be called on non-node pages
  // or pages that otherwise don't return anything useful for menu_get_object().
  @$node = menu_get_object();
  $red_nodes = array(1, 2, 3, 5, 8, 13);
  if(isset($node) && in_array($node->nid, $red_nodes)) {
    drupal_add_css(drupal_get_path('theme','alphorn').'/css/red.css');
    // If your stylesheet is really simple you could always inline it.
    drupal_add_css('body { background-color: #FF0000; }', 'inline');
  }

  // Then you need to plug your added CSS into your variables or nothing will happen.
  $vars['styles'] = drupal_get_css();
}


Learning Minor scales through 7 patterns (Guitar)

Question: I need a little guidance about learning the minor scales in 7 positions/patterns on a guitar. To begin with, I am reasonably comfortable with the major scales played in all 7 positions/patterns (covering the successive 7 modes?). Now I would like to learn the minor scales.
From the theory standpoint, I am given to understand that the 6th mode (i.e. 6th position of a major scale is the (first?) position of a minor scale? For example, referring to the circle of 5th diagram, I can see the 6th position of C major scale is the beginning of A Minor scale? But what I am struggling to understand is using my major scale pattern knowledge, how to co-relate the 7 positions for a particular minor scale? Am I asking a sensible question here?
Coming back to the C major and A Minor scale example, I know the 7 positions of the C major scale, so using my 7 position scale pattern diagram (which covers most of the guitar neck), I would like to know how the 7 positions can be used for Am scale? Is there a trick here?
The whole thing started off when I was trying to play a song in the key of Cm and was looking for a scale pattern to practice first.
By the way I am new to learning to play music with less than one year experience with guitar. I am guessing the way I have described my question above makes it obvious :-)

EDIT -
Thanks Tim and Uncle Bob. I think between your 2 responses I have figured out what I was looking for - correct me if I am wrong please, below is my current understanding:
When taking about G major scale and its enharmonic E minor scale as an example, both contain the same notes (in same order presumably?). As I have stated, I know how to play G major scale in 7 different positions on the fret-board in order (I learnt the scales from this video

).
Now, coming to the E minor scale, my understanding after reading your answer is that I can use the same 7 G major scale positions to play E minor scale with the only difference being that the start and the end of the E minor scale has to be with the note E in that pattern? And the same goes to other major-minor enharmonic scales too?
Is my above understanding correct?
Comment: Hi Steve. I don't understand what you mean about being "comfortable with the major scales played in all 7 positions/patterns (covering the successive 7 modes?)". If you mean that you've learned 7 ways of playing the major scale, then that has nothing to do with the modes; on the other hand, if you mean that you've learned the 7 modes of the major scale, then as you say, you've *already* learned the natural minor scale, because it can be seen as the 6th 'mode' of the major scale.
Comment: Is your problem that you don't know how to start a minor scale on any chosen root-
 as in, you want to play A minor, or C minor, or D minor, but you don't know how?
Comment: Hi Topo, yes, in this particular case, I want to know how to start a Cm scale in various positions of the fret board just like how i play C major scale at 7 different positions (patterns) up and down the neck Thanks.
Comment: Yes, you can use your knowledge of the major scales to play (natural) minor scales. C is enharmonic to Am natural (i.e. it has the same notes), D to Bm, Eb to Cm, and so on... (But have a look on e.g. Wikipedia to learn about the different minor scales: natural, harmonic and melodic.)
Comment: @Steve - so when you want to play the D major scale, or the B major scale, how do you currently do that?
Comment: Topo Morto - I learnt the 7 pattern technique (3 notes per string) from https://youtu.be/QLkGaUg63P4
Comment: Can you clarify position versus pattern I find this very confusing.  In classical guitar each fret marks a "position".  So playing with the index finger on the 5th fret is being in the 5th position.  There are more than 7 positions.
Answer:
I need a little guidance about learning the minor scales in 7 positions/patterns on a guitar. To begin with, I am reasonably comfortable with the major scales played in all 7 positions/patterns (covering the successive 7 modes?).

As per my comment, I wasn't quite sure what you meant there. Now I've watched the video, I think the video itself is where the confusion comes from!
Here, the video calls the notes A, B, C, D, E, F♯, G... "G major scale pattern 2". I think I'm agreeing with Tim's post here when I say that that's an unconventional thing to call those notes played in that order, starting on A. I would say he's playing A Dorian - the second mode of the G major scale, with the same notes as G major, but starting on A. That wouldn't itself usually be called playing a 'major scale' in a 'learning the scales' context, where there is a strong convention that you start (and end) on the root note.
If you don't agree that a scale should start on the root note, then I guess what the video says is fine. But generally the mental steps you need to take to play a particular scale (such as A major, or C major) is locate the root note (A, or C) first, then base your pattern on that.
However you learn your patterns, you need to be very aware of where your roots are. The whole point of a scale from a musical perspective is that it is defined by a set of intervals from the root; that's what gives a piece of music a certain flavour when you construct it from that scale.

From the theory standpoint, I am given to understand that the 6th mode (i.e. 6th position of a major scale is the (first?) position of a minor scale?

I wouldn't use the word 'position' how you use it there, but yes - you could call the 6th mode of the major scale the natural minor. Personally, as I've said in my answer to Flavor of the modes in melody, I don't like to think of the modes as coming from a major parent scale - I think of the diatonic scale (i.e. the note pattern, without any particular root) as the "parent" concept, and then of major/minor tonality and modal tonality as both being concepts derived from that.

Now I would like to learn the minor scales.

First can I just double check that you know how to play particular major scales first, by identifying the root on the fretboard, and playing the major scale pattern based on that root? For example, The way I would play an A major scale would be to:

find an A note on the fretboard
play the major pattern scale, starting with that A note as the root

tweaking one of the diagrams from the video, that's:

Note that we've started on A as the root (fret 5 on the low E string), and then played finger patterns that are the same as pattern 1 in the video - because pattern 1 in the video is the major scale pattern starting on the first string.
Another way to play it that's less of a stretch:

That's just another way to play the A major scale starting on the low E string. Note the roots circled in red.
Once you get to the point where if someone asked you to play "A major", or "B major", or "D-flat major", you could do it instantly, it should be just as clear what you have to do to play any natural minor scale - identifying the root on the fretboard, and playing the natural minor scale pattern based on that root. You can think of that minor pattern as being the "pattern 6" you were taught in that video, if that helps you; personally I prefer just to think of it as 1, 2, ♭3, 4, 5, ♭6, ♭7, 8, and then spot those intervals from my root (as suggested in Would it be a good idea to memorize relative interval positions on guitar?). It saves me from having to spend any more time learning scale shapes.
It might be that you've already started to think of things in the way suggested in that video, in which case my advice here might not make much sense to you. I can see that there are other sites on the internet that basically agree with what that video says, but I think it's confusing. If it wasn't, you wouldn't be here asking this question!

Now, coming to the E minor scale, my understanding after reading your answer is that I can use the same 7 G major scale positions to play E minor scale with the only difference being that the start and the end of the E minor scale has to be with the note E in that pattern?

If you agree that an E minor scale should start on E, then it doesn't make sense to think of what's shown in the video as "7 G major scale positions", because only one of the patterns shown in the video starts on G.
For what it's worth, I think a better way to describe the content of that video would be that it's teaching you 7 patterns of the diatonic scale - i.e. the diatonic scale starting at different points, each of which corresponds to one of the modern modes, the first of which (Ionian) is basically the same thing as the Major scale.
Comment: Good answer. I tend to think of a *scale* as starting and finishing on the root note (bottom and top). So your pattern showing an extra B is like so many other patterns, probably doesn't need it. I think they show the 'extra' notes 'cos they're within reach. But that then tends to beccome mode-like, and confusing to beginners. But absolutely, there never were '7 scale positions' of anything. 7 modes, yes! Why these contributors have free rein on the 'net, I'll never understand! Trouble is, it's on the net, therefore it's gospel... But at least *our site* has contributors who know about stuff!
Comment: @YourUncleBob - fair enough, so why erroneously call them scales? But I suppose our site wouldn't be so important if every other site got it right... But in any case, we still have 'avoid' notes that are in a certain key! So saying 'these are the notes that will fit' isn't especially helpful anyway! Why am I so dismissive of so many internet sites? I think I have an answer...
Comment: Thank you Topo Morto, for taking time to elaborate it. Really appreciated. The fact  is I have been practicing the pattern based approach from the video link I provided for the last 6 months (in fact literally every day for 1 hour). And yes, within each of the 7 patterns, for a particular major scale I also start with the root note for practicing that major scale as you have pointed out.
Comment: @Steve so if you play "pattern 4" on the video, you know that the root of the Major scale is played at fret 10 on the A string - i.e. it's the 5th note he plays?
Comment: @Tim you're right - I've edited the diagrams to end on the root too, as your answer rightly says. I don't really have a problem with the idea of starting a scale not on the root as long as there is some way of emphasising what the root is, otherwise your "Major" scale isn't defining major tonality at all...
Comment: @Tim I guess the teaching method and the associated diagrams are not so much about playing scales, but about memorizing which notes are "okay" when soloing over a song in a certain key. It's a shortcut for beginners which is quite mechanical, and it doesn't teach you much about keys and scales and modes, but it gets you playing along with songs quickly, which is probably why it's so popular.
Answer: Seems like you've learned to play all the major scale notes, in order (scale) but what you've actually done is learn the seven modes of the major scale. No big deal - just confusing to you. A major scale will always start - and finish - on the root note. otherwise it's just not the major scale.
Now, we move on to minor scales. A minor minefield - excuse the pun. You have, at the moment, only considered the natural minor. That's fine, as it contains ony the notes that are in the relative major. Thus, all your '7 positions' will help. Take key C major. from what you've said, the 6th mode, starting on note A, using all the C major scale notes, will give you A natural minor scale.
So far, so good. Now the fun starts. There are two other minor scales, which contain other notes than the natural minor scale notes. Not going into that now, but maybe that fact is messing things up. if so, another question is needed...
EDIT - in response to OP's edit - There are not 7 different scale patterns!! There is one pattern, which contains all the notes from a particular major scale and also its relative minor. All in the same order, but starting at different places. You may need to familiarise yourself with modes, which effectively this is. They are sets of notes basically from a major scale, where if one starts on the root of that key, one is playing the Ionian mode. (The major scale). Start on note no.6, and it's the Aeolian mode - (the natural minor).
Start on the 2nd note, it's the Dorian mode, etc. But you ask about minor scales. There are other minor scales, too - harmonic and melodic. Both of which use other notes than those from the relative major scale. Not for discussion here, but will further confuse when tackled!
I've just watched some of the video lesson. He really should be talking about modes, not patterns of a major scale, which is what they're not, really. I find the video not that helpful, and rather long-winded, but that's just me!
Comment: @Steve - no, certainly not wasted. Count it as a good start and move on and up.
Comment: @Steve what your *fingers* will have "learned" from following those videos is very useful - it's just some aspects of the explanation that seem incomplete (to me). Anyone who wants to get a good overview of music ends up learning about different ways to look at things though!
Comment: Thank you and @topo Morto. It's been very helpful discussion. I guess my 6 months' practice hasn't gone wasted, instead I believe it's just that I need to realign the theoretical understanding of this modes and patterns in my head.


Numerically Misleading Results

Question: Are there any calculations or results that have similar answers and when compared numerically look the same, but in actual fact after so much precision, the answers diverge from each other?
An example I could think of would be a fractional approximation for $\pi$ such as $\frac{245850922}{78256779}$. If one was unaware of $\pi$'s irrationality then they might think (through numerical "proof") that they were the same thing. Obviously this is a trivial and silly example so I am looking for examples that are more major and may even have been of a surprise to some.
Comment: Related and very interesting http://mathoverflow.net/questions/131528/how-closed-form-conjectures-are-made
Comment: You could search for "lies my calculator told me"!
Comment: This seems to fit in with [this question](http://math.stackexchange.com/questions/111440/examples-of-apparent-patterns-that-eventually-fail) from the "most votes" list.  There are some answers there that directly fit this question. [This answer](http://math.stackexchange.com/a/111499/35667) in particular is excellent.
Comment: [Thanks to Maesumi](http://apcentral.collegeboard.com/apc/members/courses/teachers_corner/11703.html).
Answer: Ramanujan gave the identity
$$e^{\pi \sqrt{163}} = 262537412640768743.99999999999925007...$$
Martin Gardner once claimed as a hoax that $e^{\pi \sqrt{163}}$ is an integer, which apparently confused a lot of people: when they tried to disprove the claim on their calculators, they found that $e^{\pi \sqrt{163}}$ was indeed an integer - but only because their calculators were not precise enough!
Comment: Strictly speaking, the value of $e^{\pi\sqrt{58}}$ is found in Ramanujan's Notebooks, but not $e^{\pi\sqrt{163}}$. However, in one section, he uses $d=19,43,67,163$ so he may have been aware of this near-integer property as well. Strange though that he didn't write it down.
Answer: You might enjoy the answers to this question over on MathOverflow that catalogs some examples of the phenomenon of "eventual counterxamples," particularly the Borwein integrals.

Numerically Misleading Results


Is Homicide Victims dataset repeated?

Question: I am studying an example where a Poisson model is applied to the Homicide Victims dataset. The dataset contains survey results of 1308 people who where asked about the number of homicide victims they knew. The dataset includes the response of a person (the number of homicide victims he/she knows) and his/her race. The response has minimum and maximum values of 0 and 6. The goal is to model the response using a Poisson model and assess the goodness of fit of the model.
I have two questions.

Is the dataset repeated? I understand that a repeated measure is a study where for each predictor variable there are repeated number of observations. In this case, I can redesign the dataset as a seven by two table (response and race) where each cell contains the number of people who know a specific number of homicide victims and have a specific race. It is important to identify if the data is repeated or not to make sure that the results of the Deviance and Pearson's Chi-Square tests are valid.
The results of the Deviance and Pearson Chi-Square tests are as follows:
Deviance Test: Deviance = 844.7073, df = 1306, p-value = 1 and
Pearson's Chi-Square Test: Chi-Square=2279.873, p-value = 0.
So, in this case I am not sure why the p-values are critically different.
Comment: What "Homicide Victims dataset"? Where is it from?  Can it be accessed anywhere?  Is there documentation for it?
Comment: Yes. Categorical Data Analysis - Chapter 13.4.3 Frequency of Knowing Homicide Victims Example - https://reneues.files.wordpress.com/2010/01/categorical-data-analysis-alan-agresti.pdf.
Answer: Agresti takes this data from the General Social Survey (GSS), and perhaps he treats it as a simple random sample(?) which is fine if he's simply using it as an illustration. However, the GSS is not a simple random sample; it's a multiple-stage cluster sample. You can find details here.
It is likely that respondents in the same cluster are not independent. If one respondent knows someone who was the victim of a homicide, it's likely that another respondent from the same cluster also knows someone who was the victim of a homicide, possibly the same victim.
I'm not sure that I follow your concern about repeated observations, but there is a problem here with using the chi-squared test as the standard test is not appropriate for data generated under a multi-stage cluster sample. P-values are likely to be too small. Several strategies exist for adjusting the chi-squared test. An early approach utilizes the Wald test. Rao and Scott introduce two additional approaches which are generally preferable. See here and here. All of these approaches are included in the survey package in R. See here.
Answer: I think the concern motivating this question is that the example shows up in the chapter on Other Mixture Models for Categorical Data.  That chapter follows a series of chapters on Models for Matched Pairs (10), Analyzing Repeated Categorical Response Data (11), and Random Effects... (12), which establishes a section dedicated to repeated measures data.  The dataset's existence within this section implies it should be that type somehow (prototypically, repeated measures or hierarchically nested data).  In contrast, however, the data do not appear to have that character.
I think what Agresti is doing is using these data to illustrate a different issue.  The simplest model for count data is a Poisson model.  There is a sense in which Poisson regression 'should' be the right model to use.  However, the Poisson distribution makes a very strong assumption that the conditional variance is always the same as the condition mean.  That assumption is typically violated in the real world.  If so, we can ask why and we can ask what we're supposed to do now.
One reason the variance can be 'too high' is that the data come from heterogeneous units (e.g., patients) with different attributes (e.g., age, sex, family history, etc.) that are relevant to the outcome but which are not included in the model.  These attributes could average out, in which case the mean can still be the same, but the data will still spread out further (i.e., the higher conditional variance).
There are various ways to handle such a situation.  One is to use a 'quasi-Poisson' likelihood with an ad-hoc adjustment.  Another is to use the negative binomial distribution instead of the Poisson, which allows the variance to be independent of the mean.  But another way is to have a latent normal distribution of units (i.e., random effects).  This can be done even though there is only one response value per unit.  Agresti uses this dataset to illustrate this approach and how it compares to the default Poisson and the negative binomial.  Thus, a GLiMM is appropriate (and these data make sense to show in this chapter) even though the data are neither repeated nor nested.
Answer: Repetition would be when you measure the response within a single same unit while varying other variables.
For instance, if you have a cyclist and you let them cycle 6 times some distance while giving them either 0, 1, 2, 3, 4, 5, or 6 candies. Then you have six different measurements but all of them with the same cyclist rather than with six different cyclists. For each cyclist you repeated the measurement, under different conditions (this contrasts to having a different cyclist for each different condition).
The difference that repetition makes is that you can model the differences between the six measurements because they were done by the same cyclist. Or with a different type of analysis (in a mixed/random-effects model), you could separate the noise into two parts, one due to the cyclist and one due to the measurement.

From your description of the homicide victims dataset it does not seem like you have a repeated measurement. You have values of predictor variables that are repeated but that is everytime with a different person out of the 1308 persons. There is no change of a predictor variable within the same person.
Copy of the table from your reference
<code>                 Race
           Black     White
Response
0            119      1070
1             16        60
2             12        14
3              7         4
4              3         0
5              2         0
6              0         1
</code>
However, in some sense, you do have some sort of repeated measures here. The observations of the number of responses 0, 1, 2, 3, 4, 5, 6 are done within the same race category populations.
It would, for instance, be a difference when you where performing the survey in different cities and in city A you observe the number of 0 response among white respondents, in city B you observe the number of 1 response among white respondents, in city C you observe the number of 2 response among white respondents, etc.

Is Homicide Victims dataset repeated?


best practice: what directory should the theme be located for a site install profile

Question: I am building a site install profile. Trying to wrap my head around the file structure.
I am creating a Drupal 7 install profile with a sub theme off of omega.
Is it better practice to put the theme in the
profile/themes

or
sites/all/themes

Answer: Normally, the theme would go in:
/profiles/YOURPROFILE/themes/YOURSUBTHEME

Also include the base theme at the same location:
/profiles/YOURPROFILE/themes/omega


How do you set up your JScript (NOT JScript.NET) development environment?

Question: In my environment, if I create a class in JScript syntax:
<code>class test{

}
</code>
and then save it to a file named "test.js" and run it with wscript, I get a Microsoft JScript "Syntax error" at line 1.
However, if I simply, say, write a function:
<code>  function getInput() {

   var wshell = WScript.CreateObject("WScript.Shell");
   wshell.Popup ("Do you want to continue?");

   return userInput
}

getInput()
</code>
and run it the same way, it works.
Hopefully, there is something fundamentally wrong with my class definition. If that is the case, I am excited to find out.
Answer: JScript is just Microsoft's implementation of JavaScript/ECMAScript. As such, it doesn't have classes, or any of the other things added to JScript.NET to make it kinda-sorta fit into .NET.
Ignore JScript.NET, and read up on the WSH version of JScript.


Why I got TypeError if calling staticmethod without class-body?

Question: Why it happens? is this "binding behavior"?
using staticmethod in class body
>>> class Test:

         @staticmethod
         def test(msg="asd"):
             print(msg)

>>> test = Test()
>>> test.test()
asd

but when I using it without, got error:
>>> @staticmethod
    def test(msg=""):
         print(msg)

>>> test
<staticmethod object at 0x10dde9be0>
>>> test()
Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<input>", line 1, in <module>
TypeError: 'staticmethod' object is not callable

Answer: Use a standalone function.
def test(msg=""):
    print(msg)

Comment: this is not explain why I got TypeError in my example)
Comment: Because your example isn't valid Python. In Python, you cannot use the decorator syntax for a `@staticmethod` when there is no class to which the method belongs.
Answer: A static method is a method that is bound to a class but does not require the class instance to function.
For example, you may have a class built around a file type to retrieve raw data from a source file and pass it to a lexer, your constructor could have you pass in the raw file however you may want another function to open the file, validate it and retrieve the data. In this case, you could use a static function within the class as the function is related to the class but doesn't require the class to function (in this case it would return the actual class).
A code example:

class PythonFile:

   def __init__(self, raw_data):

      self._raw_data = raw_data
      self._lexer = None

   @staticmethod
   def open(fp):
      with open(fp, "r") as rFile:
         data = rFile.read()
      # validate, etc...
      return PythonFile(data)

   def lex(self):
      self._lexer = PythonLex(self._raw_data)
      return self._lexer.get_master_block_array()

# etc, etc...

python_file = PythonFile.open("some\\path.py")
print(python_file.lex())

ItzTheDodo.


Laplace Transform of $(2\sinh(x))^2$

Question: I have to perform the Laplace Transform on the indicated function:
$$f(t)=(2\sinh(t))^2$$
I have to perform the given operation:

$$\mathcal{L}\{f(t)\}$$

However I am limited to this theorem $7.1.1$.
Theorem $7.1.1$

\begin{align}&a) \ \mathcal{L}\{1\}=\frac{1}s \\ &b)\mathcal{L}\{t^n\}=\frac{n!}{s^{n+1}} \\ &c)\mathcal{L}\{e^{at}\}=\frac{1}{s-a}\\&d)\mathcal{L}\{\sin(kt)\}=\frac{k}{s^2+k^2}\\&e)\mathcal{L}\{\cos(kt)\}=\frac{s}{s^2+k^s} \\&f)\mathcal{L}\{\sinh(kt)\}=\frac{k}{s^2-k^2}\\&g)\mathcal{L}\{\cosh(kt)\}=\frac{s}{s^2-k^2}\end{align}
  My question is how do this way I can do this way as well:

Definition 7.1.1

$$\displaystyle{\mathcal{L}\{f(t)\}=\int_\limits{0}^\infty e^{-st}f(t)dt}$$
  The only thing that is tripping me up is arriving at the answer using those theorems otherwise I can get the answer using the definition. Thank you in advance.
Answer: If you know $\sinh(x)=\frac{e^x-e^{-x}}{2}$, then $(2\sinh(x))^2=4\sinh^2(x)=(e^x-e^{-x})^2=e^{2x}-2+e^{-2x}$. Then use the fact that Laplace transform is linear so
$$
\mathcal{L}((2\sinh(x))^2)=\mathcal{L}(e^{2x})-2\mathcal{L}(1)+\mathcal{L}(e^{-2x}).
$$
Comment: Thanks +1. I found that useful.
Answer: Hint:
Use the fact that $$2\sinh(x) =e^x - e^{-x}$$
So, $$4\sinh^2(x) = e^{2x} -2 +e^{-2x}$$
Comment: Thanks +1. It really helped.
Comment: you're welcome!
Answer: $$\cosh (2t) =  \cosh^2 t + \sinh^2 t$$
$$\cosh (2t) =  1 + 2\sinh^2 t$$
Therefore:
$$\sinh^2 t = \frac 12 (\cosh (2t)-1)$$
$$\mathcal{L}(\sinh^2 t )= \frac 12 \mathcal{L}(\cosh (2t))-\dfrac 1{2s}$$
$$\mathcal{L}(\sinh^2 t )= \frac 12 \dfrac s{s^2-4}-\dfrac 1{2s}$$
$$\mathcal{L}(\sinh^2 t )= \dfrac 2{s(s^2-4)}$$

Laplace Transform of $(2\sinh(x))^2$


Display view nodes in lightbox?

Question: What would be the best way to show the nodes from a view in a lightbox, triggered by a single image?
The idea would be that a nice photo is shown on a frontpage. When users click on it, a view is opened in a lightbox/thickbox/colorbox/*box. This then shows all nodes in the view.
I currently manage to do this for only images with colorbox, but that's not sufficient as I would like to show captions etc.
I would like to use the full colorbox functionality, rather than just the image. I tried using an iframe, however this meant every node is shown with the full site theme (header, logo, footer etc) which is not what I want to do.
Answer: I managed in my project by using a custom page template and and an additional get parameter.
Template.php: (In active theme directory)
function phptemplate_preprocess_page(&$vars){
    if( isset($_GET['ajax']) && $_GET['ajax']=='true' ){
        $vars['template_files'][] = 'page-overajax'; # For Drupal 6
        $vars['theme_hook_suggestions'][] = 'page-overajax'; # For Drupal 7
    }
}

I then created a template file (page-overajax.tpl.php) in theme directory with following content:

   <?php print $content; ?>

After this (Clear all caches) you can use any path (page, view, node) with ?ajax=true to pass to your *box to load if it supports for AJAX content.
As using with fancybox:
$("a.overajax").fancybox({
    'width': 400,
    'height': 400,
    ajax: {
        type     : "GET",
        cache    : false,
        url      : "user/user-posts?ajax=true",
        success: function(data) {
              $.fancybox(data);
        }
    }
});

Comment: Could it be that this suggestion only works for Drupal 6? The template_files key seems deprecated in Drupal 7.
Comment: You are right :)
Answer: You can use Colorbox Node module:

Gives the user the ability to display ANY page inside a colorbox modal
without the header and footer.
Your link should look like this:
href="blogs/my-example?width=600&height=600"
Answer: For D7, I had to follow stricter naming conventions than in Shuaib Nawaz's answer. My code looks like this:
function my_theme_preprocess_page(&$variables, $hook){
    if( isset($_GET['ajax']) && $_GET['ajax']=='true' ){
        $variables['theme_hook_suggestions'][] = 'page__ajax';
        // then use page--ajax.tpl.php for page template file.
    }
}

Perhaps OP can add this to the comments on accepted answer, my score is too low.
Answer: Have you tried the Colorbox node module ?
I think that's exactly what you need ;)

Display view nodes in lightbox?


How to describe a test of differences between correlation of the same two variables across two groups?

Question: If I have two (Pearson) correlation coefficients between Variables A and B (for example .657 for males and .876 for females) and I want to test if there is a difference based on gender (as in this case), which of the following phrases should I use to describe this process?

Test for equality of the correlation coefficients
Test for the difference in the correlation coefficients

I want to use one of the above as a row heading in a table that describes the above results, so I am looking for the one that is more theoretically grounded in statistical terminology.
Comment: Using a table suggests you have made many tests of such equality.  This is an unusual thing to do, perhaps because it may be difficult to interpret the results and perhaps because differences in correlation do not appear to reveal much.  Suppose two variables do have different degrees of correlation for two subsets of the data.  What does that *mean*?
Comment: In my mind, if variable A correlates with B differently for males and for females (as shown by the test of equality), I can then say that the relationship between A and B is influenced by gender (or age or education etc.). Note I am not comparing males and females; I am comparing the relationship between A and B. Hence, all I am saying is that if you are a male, the relationship between A and B would be different for you, compared to if you are a female. (Something tells me that this borders on being meaningless!)
Comment: I wouldn't go so far as to say "meaningless," but it is indeed a subtle relationship.  One usually characterizes the overt relationships first, such as differences of means and regressions, before getting to this kind of comparison.  Its interpretation is rendered difficult by the need to characterize possible confounders and to investigate linearity and homoscedasticity of the relationships.
Answer: "Test for equality" is more theoretically correct because you test the (likelihood of) null hypothesis, and it states that the coefficients are equal in the population. But "Test for difference" will be more common way to put it, because it is the alternative hypothesis - the inequality - which a researcher and the reader usually "is after" or has a morbid interest in. Why don't you simply label the table "Correlation coefficients for females and males"?
Comment: My table has the following row headings: Demography (i.e. Gender), Pearson's 'r', r squared, p value, sample (n) and Equality of 'r'. The last label 'Equality of r' is what this question is about. Thanks a lot. (Am I missing any other vital information in this summary table?)
Answer: You should test for the difference in the correlation coefficients because if the test is positive, you reject the null hypothesis (equality of the two coefficients).
And if your test is negative, you conclude that you can not reject the null hypothesis, and therefore can not conclude that there is a difference, which does not mean that the two coefficients are equal (they most likely are not exactly the same) but it means that given the level of information in your data, you can not establish that they are different.
Given enough data points, you could have a significant difference between the correlation of variables A and B for males and females, even if the actual coefficient are very close (e.g. 0.40 and 0.41). In such a situation, you would state the statistically significant difference between the coefficients and you may add (based on your knowledge of the issue at hand) that such a small difference is likely to be of little consequence on the real life event under study (e.g. the difference may not be big enough to require that different drugs be developped for each gender).
Answer: Listen to @whuber and to me.
Don't do this.
It seems almost completely meaningless.
Comment: Why do you want to know the answer to this question? Suppose the correlation is stronger for men than for women. Then what?  Unless it's in a regression framework, I don't see how the answer can help you do anything
Comment: I confess to lacking the imagination to conceive of a realistic situation where these analyses are useful. But I would like to suggest that you focus on your study objective, Adhesh, rather than on trying to analyze your data solely in terms of correlation coefficients. I *do* have the imagination to envision datasets where these comparisons are not just meaningless, but are also misleading, and I suspect that may be Peter's concern too. You've been dancing around this issue for 43 questions now. What is it you really want to know about your data? Can you phrase this in non-statistical terms?
Comment: @whuber I like the way you have put it! (because it has helped me to rethink what I want to achieve with my data set). I am looking at the relationship between "product research" (A) and "product purchase" (B). Product means any consumer goods. A and B are composite scores (i.e. made up of responses to several questions). I want to see (1) if a relationship exists betwen A and B (which is bivarite in my case) and (2) if differences exist for certain demography (e.g. gender, age). i.e. do males do it differently than females. The second part is where "I am dancing..." because I don't know!
Comment: I think you have formulated a useful question with that last comment, Adhesh.  Why don't you consider starting (yet another :-) new thread where you pose it just like that, in a statistically neutral way (that is, without suggesting what analysis you think is needed) and perhaps offer an illustration of the kind of data you have, such as a dozen or so records randomly chosen from the database.  I am also still wondering what your clients would be doing with your discoveries: if you do find relationships, just what kinds of recommendations would that lead you to make?
Comment: Thanks and I am most grateful for your advice. Please help! How else do I find out if there is a difference, if any, in the relationship between A and B for males and females. I would add that the correlation for male and female on their own are statistically significant but this test of equality on the gender difference is not significant. I am totally confused now.


Cointegration structure

Question: I have two time series that I am investigating, acc and amb, the time frequency is daily data. They are both non stationary, as evidenced by the follows:
adf.test(df$acc)

    Augmented Dickey-Fuller Test

data:  df$acc
Dickey-Fuller = -2.7741, Lag order = 5, p-value = 0.2519
alternative hypothesis: stationary

> adf.test(df$amb)

    Augmented Dickey-Fuller Test

data:  df$amb
Dickey-Fuller = -1.9339, Lag order = 5, p-value = 0.6038
alternative hypothesis: stationary

I am looking to test for cointegration between the two time series but the problem I am running into is that the cointegrating vector seems to change in time.
1) First 200 points
Johansen-Procedure
Test type: maximal eigenvalue statistic (lambda max) , with linear trend
Eigenvalues (lambda):
[1] 0.0501585398 0.0003129906

Values of teststatistic and critical values of test:
          test 10pct  5pct  1pct
r <= 1 |  0.06  6.50  8.18 11.65
r = 0  | 10.19 12.91 14.90 19.19

Eigenvectors, normalised to first column:
(These are the cointegration relations)
        acc.l2    amb.l2
acc.l2  1.0000000  1.000000
amb.l2 -0.9610573 -2.237141

Weights W:
(This is the loading matrix)
       acc.l2       amb.l2
acc.d -0.03332428 -0.002576070
amb.d  0.03986111 -0.001591227

2) First 1000 points
Johansen-Procedure
Test type: maximal eigenvalue statistic (lambda max) , with linear trend
Eigenvalues (lambda):
[1] 0.019211132 0.001959403

Values of teststatistic and critical values of test:
          test 10pct  5pct  1pct
r <= 1 |  1.96  6.50  8.18 11.65
r = 0  | 19.36 12.91 14.90 19.19

Eigenvectors, normalised to first column:
(These are the cointegration relations)
        acc.l2   amb.l2
acc.l2  1.0000000  1.00000
amb.l2 -0.8611314 15.76683

Weights W:
(This is the loading matrix)
        acc.l2        amb.l2
acc.d -0.008993595 -0.0002419353
amb.d  0.027935684 -0.0002067523

3) Whole History
Johansen-Procedure
Test type: maximal eigenvalue statistic (lambda max) , with linear trend
Eigenvalues (lambda):
[1] 0.0144066813 0.0008146258

Values of teststatistic and critical values of test:
          test 10pct  5pct  1pct
r <= 1 |  1.16  6.50  8.18 11.65
r = 0  | 20.64 12.91 14.90 19.19

Eigenvectors, normalised to first column:
(These are the cointegration relations)
        acc.l2    amb.l2
acc.l2  1.0000000   1.00000
amb.l2 -0.8051537 -25.42806

Weights W:
(This is the loading matrix)
       acc.l2       amb.l2
acc.d -0.01003068 7.009487e-05
amb.d  0.02128464 6.980209e-05

You can see the marginal change the coefficient values, from -0.96 to -0.86 to -0.80.
My question is how to interpret this, what is the optimal look back period, what is the true relationship I should use for future prediction?
Answer: Two cointegrated time series share a common trend on the long run but there can exist large discrepancies between them on the short term.
The optimal look back period would be the very beginning of the data generating process at work in your phenomena. Unfortunately, you are limited to a finite data sample to estimate this potential cointegration relationship and nothing can guarantee that those data points were not sampled during a period with high or small discrepancies.
So I would definitely go for the largest data set available as it is the less likely to be mislead by a "one-time" perturbation.
NB: all of this is true provided that the data generating process remain the same during the whole time of observation. Now, you might want to consider applying a Chow test on your data in order to check for any structural break in your series.

Cointegration structure


Java, detect whether a String beyond Long type value boundary

Question: Given following Java codes:
String columnValue = "188237574385834583453453635";
columnValue =(Long.parseLong(columnValue)>Long.MAX_VALUE?"0":columnValue);

It throws java.lang.NumberFormatException since the input value is beyond Long's maximum value. However, it there an easy way to detect whether a number in a 'string' type get out of Long's maximum value with out using try catch solution?
Comment: No `long` value can be greater than `Long.MAX_VALUE`, by definition.
Comment: Extract the source code of `parseLong` and instead of throwing an exception, return a `boolean`. Though, throwing the exception here makes sense, in my opinion.
Answer: A lazy way can be to use BigInteger.
BigInteger a = new BigInteger("188237574385834583453453635");
BigInteger b = BigInteger.valueOf(Long.MAX_VALUE);

System.out.println("a > Long.MAX_VALUE is : " + (a.compareTo(b) > 0 ? "true" : "false"));

If performance is important, you will have to test more solutions.
@SotiriosDelimanolis idea is also a good one :

Extract the source code of parseLong and instead of throwing an
  exception, return a boolean.

Also there are many throw in the code, some are for the format, other are for the overflow, you will have to choose the right ones.
Comment: I really don't understad why this was downvoted, when it is the only good answer.
Answer: A really cheesy way:
columnValue.length() > ("" + Long.MAX_VALUE).length()

Of course this does NOT cover values greater than Long.MAX_VALUE but the same number of digits, only values with more digits.
Comment: Fortunately, 'Long.MAX_VALUE' is 9.22e18, which means that you will only have 7.7% of false positive result **on correctly formed string**. The good point is that you can't have false negative. So it can make a good pre-filter for parsing.
Answer: Not really.
The only naive partial solution is to compare the length of the String, but that would not work always.
Comment: Fortunately, 'Long.MAX_VALUE' is 9.22e18, which means that you will only have 7.7% of false positive result **on correctly formed string**. The good point is that you can't have false negative. So it can make a good pre-filter for parsing.
Answer: You can create a utility method that wraps the try/catch and returns a boolean, something like:
import java.util.*;
import java.lang.*;
import java.io.*;

class TestClass
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(TestClass.isLongString("188237574385834583453453635"));
    }

    public static boolean isLongString(final String longNumber)
    {
        boolean isLong = false;
        try
        {
            Long.parseLong(longNumber);
            isLong = true;
        }
        catch(Exception e)
        {
            // do nothing - return default false
        }

        return isLong;
    }
}

Comment: @OferLando, The problem here is that you will not know if a `false` result is caused by an overflow or a malformed string.
Comment: I find it regrettable that the `parseLong` function did not gives more informations when it throws exceptions (I looked to JDK 8u31 sources). In C# for example you get an OverflowException or a FormatException depending on the cause of the exception.
Comment: Whoever downvoted - it would be nice if you explained why you chose to do that.
Comment: Probably because the exception is still thrown and the OP doesn't want that.
Comment: It is not thrown - it is handled by the method itself, returning a boolean.
Comment: It is thrown and ignored.
Comment: True, but that wasn't the request - if you want to consider malformed string and other possible issues - it should be handled before trying to convert the string into a long.


Using MySQL with Entity Framework

Question: Can't find anything relevant about Entity Framework/MySQL on Google so I'm hoping someone knows about it.
Comment: frankly speaking, mysql support for LINQ is crap! I am banging my head on minor issues for last one week :| ...
Comment: did u use dblinq http://code.google.com/p/dblinq2007/?
Answer: It's been released - Get the MySQL connector for .Net v6.5 - this has support for
    [Entity Framework]
I was waiting for this the whole time, although the support is basic, works for most basic scenarios of db interaction. It also has basic Visual Studio integration.
UPDATE
http://dev.mysql.com/downloads/connector/net/
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
Comment: I thought I'd mention that the latest version is available here (current 6.2.2): http://www.mysql.com/downloads/connector/net
Comment: Does this support EF4 and VS2010? I installed the connector and tried to add a new connection in VS2010 but MySQL does not show up in the list of providers
Comment: I'm curious about MySQL, EF4 and VS2010.
Comment: It should if you have the latest connector. I just moved my product to .NET4 specifically because of MySQL Entity support. The tools and everything work okay, but the big issue is the underlying support it provides for actual querying. There's quite a few problems with lamba expressions that you don't run into with MSSQL
Comment: Ofcourse, there are new versions coming out. Now supporting EF5, version 6.7.4: http://dev.mysql.com/downloads/connector/net/#downloads Also, Since this version, the VS plugin with MySQL server and other tools included is bundled in one package: http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html
Comment: Thanks for the update, I was waiting for the same thing!
Comment: It took me quite a while to find this so I wanted to share in case anyone else gets an "Out of sync with server" error running the latest version(6.4.3), it is a known bug fixed in version 6.4.4+.  http://bugs.mysql.com/bug.php?id=61806
Comment: If you experience an issue with the DatabaseInitializer take a look at the following link http://brice-lambson.blogspot.com/2012/05/using-entity-framework-code-first-with.html.
Comment: Example connection string for Code-first:
Comment: Is using MYSQL with EF got any better or there are still issues?if SQL server is preferable can anyone pinpoint exactly why SQL server is preferable just because its the same vendor Microsoft?
Answer: Check out my post on this subject.
http://pattersonc.com/blog/index.php/2009/04/01/using-mysql-with-entity-framework-and-aspnet-mvc-–-part-i/
Comment: Link doesn't work
Comment: You can get to the articles with this link:  http://pattersonc.com/blog/2009/04/
Comment: I fixed the encoding of that link - users can now click right through rather than have to copy/paste or select/goto
Comment: Is using MYSQL with EF got any better or there are still issues?if SQL server is preferable can anyone pinpoint exactly why SQL server is preferable just because its the same vendor Microsoft?
Answer: MySQL is hosting a webinar about EF in a few days...
Look here: http://www.mysql.com/news-and-events/web-seminars/display-204.html
edit: That webinar is now at http://www.mysql.com/news-and-events/on-demand-webinars/display-od-204.html
Comment: Link is not working.
Answer: This isn't about MS and what they want.  They have created an *open system for others to plug-in 'providers' - postgres and sqlite have it - mysql is just laggin...  but, good news for those interested, i too was looking for this and found that the MySql Connector/Net 6.0 will have it...  you can check it out here:
http://www.upfromthesky.com/blog/post/2009/03/24/MySql-Supports-the-Entity-Framework.aspx
Comment: I wonder what "initial" means when they said "Initial Entity Framework support".
Answer: You would need a mapping provider for MySQL. That is an extra thing the Entity Framework needs to make the magic happen. This blog talks about other mapping providers besides the one Microsoft is supplying. I haven't found any mentionings of MySQL.
Comment: Yeah, you're right. I was hoping there's something ready right now.
Answer: Vintana,
Od course there's something ready now. http://www.devart.com/products.html - it's commercial although (you have a 30days trial IIRC). They make a living writing providers, so I guess it should be fast and stable. I know really big companies using their Oracle provider instead of Orace and MS ones.
Comment: Thank you for your response. @Vintana, you can find more information about dotConnect for MySQL and its advantages here http://www.devart.com/dotconnect/mysql/. To improve your work with Entity Framework entities we provide an advanced tool for visual model creation - Entity Developer http://www.devart.com/entitydeveloper/.
Answer: You might also look at https://www.devart.com/dotconnect/mysql/
DevArt's connector supports EF and MySQL.
Answer: Be careful using connector .net, Connector 6.6.5 have a bug, it is not working for inserting tinyint values as identity, for example:
create table person(
    Id tinyint unsigned primary key auto_increment,
    Name varchar(30)
);

if you try to insert an object like this:
Person p;
p = new Person();
p.Name = 'Oware'
context.Person.Add(p);
context.SaveChanges();

You will get a Null Reference Exception:
Referencia a objeto no establecida como instancia de un objeto.:
   en MySql.Data.Entity.ListFragment.WriteSql(StringBuilder sql)
   en MySql.Data.Entity.SelectStatement.WriteSql(StringBuilder sql)
   en MySql.Data.Entity.InsertStatement.WriteSql(StringBuilder sql)
   en MySql.Data.Entity.SqlFragment.ToString()
   en MySql.Data.Entity.InsertGenerator.GenerateSQL(DbCommandTree tree)
   en MySql.Data.MySqlClient.MySqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)
   en System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree)
   en System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree)
   en System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
   en System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary`2 identifierValues)
   en System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
   en System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   en System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
   en System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
   en System.Data.Entity.Internal.InternalContext.SaveChanges()
   en System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   en System.Data.Entity.DbContext.SaveChanges()

Until now I haven't found a solution, I had to change my tinyint identity to unsigned int identity, this solved the problem but this is not the right solution.
If you use an older version of Connector.net (I used 6.4.4) you won't have this problem.
If someone knows about the solution, please contact me.
Cheers!
Oware
Comment: The error is thrown because p is null.

You have to create a new empty instance of the object first.
I.e.
Person p = new Person();
not
Person p;

So:
`Person p = new Person(){Name = "Oware"};
context.Person.Add(p);
context.SaveChanges();`
Comment: sorry I forgot to add the new line, even if I add the new line, the error stills appearing
Comment: The bug is fixed in version 6.8.2.
http://bugs.mysql.com/bug.php?id=70888

Connector/Net 6.8.3 is released.
http://dev.mysql.com/downloads/connector/net/
Answer: I didn't see the link here, but there's a beta .NET Connector for MySql.  Click "Development Releases" to download 6.3.2 beta, which has EF4/VS2010 integration:
http://dev.mysql.com/downloads/connector/net/5.0.html#downloads
Answer: If you interested in running Entity Framework with MySql on mono/linux/macos, this might be helpful
https://iyalovoi.wordpress.com/2015/04/06/entity-framework-with-mysql-on-mac-os/
Comment: Is using MYSQL with EF got any better or there are still issues?if SQL server is preferable can anyone pinpoint exactly why SQL server is preferable just because its the same vendor Microsoft?
Comment: I am not sure how it is right now, but we had pretty bad experience due to lack of features and it being overall inconsistent. MS MSQL is definitely preferable, because Microsoft puts it's own stack first.

Using MySQL with Entity Framework


Protractor find item in repeat and click it

Question: I am trying to find a speaker by name in repeater. And the speaker is found click the edit button.
The test I got so far fails miserably :(. Anyone got a lead?
View:

  <button name="editbutton" title="edit" ng-click="$ctrl.onEdit(speaker)"></button>

Protractortest:
it('should remove Bill Gates', async function () {
    await browser.get(speakerLink); //url to page
    await browser.driver.sleep(200);

    let speakers = await element.all(by.repeater('speaker in $ctrl.speakers'));
    await speakers.isPresent();

    await speakers.then(function (speakers) {
        let description = element(by.model('speaker.name'));
        if (description.getText() == ('Bill Gates')) {
            await element(by.name('editbutton')).click();
        }
    });
    await browser.driver.sleep(5000);
});

Protractor error
Protractor fails with the error
    await element(by.name('editbutton')).click();
          ^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)    at Module._compile (module.js:588:28)
    at Object.Module._extensions..js (module.js:635:10)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Module.require (module.js:568:17)
    at require (internal/module.js:11:18)
    at C:\Users\ralf\AppData\Roaming\npm\node_modules\protractor\node_modules\jasmine\lib\jasmine.js:93:

More info
Running node v8.6.0
Using plain vanilla javascript (for the moment, planning on moving to typescript/webpack)
Comment: `Unexpected identifier` tells me you don't use an ES6-ready interpreter, or you don't have an async function. You do have the latter, so: what do you run your code with? What version of node?
Comment: @JeffHuijsmans Updated my question
Answer: This may not be the best solution but this is how I have implemented the same thing and it works just fine. I hope this helps.
  this.openCategory = function (category) {
element.all(by.repeater('page in section.pages')).then(function (rows) {
  rows.some(function (row) {
    row.getText().then(function (value) {
      if (value === category) {
        log.info('[PASS] - Category:' + ' ' + category + ' ' + 'matched the value:' + ' ' + value + ', ' + 'that is shown on UI.');
        row.click()
          .then(function (value) {
            log.info('[PASS] - Category:' + ' ' + category + ', ' + 'clicked.');
          });
      }
    });
  });
});


Set views exposed filter using url

Question: In a view an exposed filter of type taxonomy reference exists, the referenced taxonomy vocabulary contains about 15 terms, the functionality I'm trying to get is to allow user call view with a default value for filter, so if user enter the path sitename/view-name/term-name the view would be load with entities of term term1.
I used contextual filter for limiting entities to those having specific term-name but the problem is, if user selects another term name, rather than the one specified in contextual filter, the view returns no result (term reference in node accepts only one value).
So I wanted to know if there is a solution to set the exposed filter default value based on url?
Answer: Well after some research I could found the answer. Actually drupal itself do provide such functionality and there is no need to code or ...
When exposing a field as filter to user, in filter settings window a filter identifier can be set (this can't be empty and is filled with field name by default), this is shown in image below :

in above example the identifier is set as cat, in this situation the path sitename/view-address/?cat=term-1 will load the view with my exposed filter assigned as term-1 and corespond entities.

Set views exposed filter using url


NSManagedObject becomes null

Question: Im using a NSManagedObject as an attribute within my ViewController, declared like this:
@property(retain, nonatomic)NSManagedObject *person;

Im propagating the content of a fetch to a UITableView, when the user taps the contact he is looking for, this is what happens:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
       self.person = [contacts objectAtIndex:indexPath.row];

Contacts contains the result of the fetch, which is done like this:
NSArray *contactsArray;
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSManagedObjectContext *context = [(OAuthStarterKitAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

NSEntityDescription *entity = [NSEntityDescription
                               entityForName:@"Contacts" inManagedObjectContext:context];

[fetchRequest setEntity:entity];
testForTrue = [NSPredicate predicateWithFormat:@"SOME CONDITION"];

[fetchRequest setPredicate:testForTrue];
    [fetchRequest setFetchLimit:10];

contactsArray = [[NSArray alloc]initWithArray:[context executeFetchRequest:fetchRequest error:&error]];

When the user taps the contact, self.person has that value, but when I try to use that value in another method it's nil, and the address is 0x000000.
This only happens on iOS 5, on iOS 6 person has the value of the contact selected and I can use elsewhere.
Any ideas?
Thanks.
Answer: Instead of getting the NSManagedObject, which is always dependant of the life cycle of the context I just stored de NSManagedObjectID and then get the NSManagedObject by using the function objectWithID. And it worked!
Comment: Sometimes you must invent something more clever than simply storing of ID. For example try to create some records and try to send any fetch request on each `rowForIndexPath:` and you will see how it is slow even with ids

NSManagedObject becomes null


org.apache.flink.client.program.ProgramInvocationException: The program's entry point class could not be loaded due to a linkage failure

Question: I am trying to submit a basic flink job to my Apache Flink Web Dashboard (localhost:8081) . This is my pom-
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.flink</groupId>
    <artifactId>kafkaconsumer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <target.java.version>1.8</target.java.version>
    </properties>
    <dependencies>
     <dependency>
      <groupId>org.apache.flink</groupId>
      <artifactId>flink-clients</artifactId>
      <version>1.15.1</version>
      <scope>provided</scope>
    </dependency>
    </dependencies>

    <build>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.1.1</version>
        <executions>

          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <createDependencyReducedPom>false</createDependencyReducedPom>
              <artifactSet>
                <excludes>
                  <exclude>org.apache.flink:flink-shaded-force-shading</exclude>
                  <exclude>org.slf4j:*</exclude>
                  <exclude>org.apache.logging.log4j:*</exclude>
                </excludes>
              </artifactSet>
              <filters>
                <filter>

                  <artifact>*:*</artifact>
                  <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                  </excludes>
                </filter>
              </filters>
              <transformers>
                <transformer
                  implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                <transformer
                  implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass> com.flink.KafkaConsumer </mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
    </build>

    </project>

My jar file is getting successfully build. These are the contents of my jar -
META-INF/MANIFEST.MF
META-INF/
com/
com/flink/
com/flink/KafkaConsumer.class
com/flink/Main.class
META-INF/maven/
META-INF/maven/com.flink/
META-INF/maven/com.flink/kafkaconsumer/
META-INF/maven/com.flink/kafkaconsumer/pom.xml
META-INF/maven/com.flink/kafkaconsumer/pom.properties

On submitting my job jar file to Apache Flink Dashboard, i am getting server error with this-org.apache.flink.client.program.ProgramInvocationException: The program's entry point class 'com.flink.KafkaConsumer' could not be loaded due to a linkage failure.
Where am I going wrong? Please keep in mind that I am just starting with Flink and am learning.
Answer: Instead of creating a maven springboot project,I created a maven project with no archetypes.it worked.
Answer: I think there is a lack of dependencies in your pom.xml. I can see only flink-clients but you need at least flink-streaming-java read here and if you want to use Kafka you'll need a dependency for kafka connector.

If you want to use a data format (avro, orc, parquet...) you need a dependency. more here
If you use a connector (jdbc, kafka, nifi...) look here
Comment: I have added the dependencies,but I dont think they are necessary since I am not implementing any of their apis as of now. I added flink-core and flink-streaming-java. However I am still getting the same error-"linkage failure"
Comment: Some dependencies are mandatory like **flink-streaming-java** for executing core part of Flink. You probably should check the scope of your dependencies (**provided**, **test** ...) provided dependencies should be in flink/lib folder before starting your Flink server. Try to run an example jar (flink/examples) [like here](https://nightlies.apache.org/flink/flink-docs-release-1.15/docs/try-flink/local_installation/#submitting-a-flink-job)