$content is only showing array text

Question: I have a theme, and for the life of me can't figure out why $content is rendering "array". I have switched to two other themes (framework and seven, and my new theme is based off of the framework theme that is working).
Here is an example of the theme code:
    <div <?php if ($left): ?>id="maincolright" <?php elseif ($right): ?>id="maincolleft" <?php else: ?>id="main" <?php endif; ?>class="nobg node-<?php print $node->nid; ?>">

    <?php if ($tabs): print '

'. $tabs .'
'; endif; ?>
    <?php if ($tabs2): print '
'. $tabs2 .'
'; endif; ?>
    <?php if ($tabs): print '
'; endif; ?>
    <?php if ($show_messages && $messages): print $messages; endif; ?>
    <?php print $help; ?>
    <?php print $content; ?>

So $content is there, and it should be fine, but on any pages I view, for instance, the page render, the edit page, or even my devel page, show only 'array'. See the screenshot:

Has anyone come across this?
Answer: print() is a command that doesn't work with arrays. print_r() will print out arrays for debugging but what you want is print render($content). Drupal uses large render arrays to output content, and they cannot be printed directly.
Comment: Hey Beth, thanks for the answer, I've never had to do that for Drupal 6, only 7. None of the themes I am using use render().
Comment: I would throw in a `print '' . print_r($content, TRUE) . '';` or something similar there in any case to see what is actually in the array.  That might shed some light onto what is going on.
Comment: Jimajamma is right. You can also install devel and use `dpm()` instad of `print_r()` if you want to browse arrays and objects.
Comment: Was a bit of user error on my part. Thanks to you both for pushing me to read into the array more. without TRUE and dpm() I wouldn't have discovered it. In my header, I did a module_invoke and when I copy and pasted some old code, I used $content = module_invoke(..); which overwrote $content. Thanks y'all.
Answer: some other people are saying the modules have a bug where you have to use underscore instead of dash in the div definitions; try tabs_wrapper for example
Comment: Drupal uses CSS classes like `.password-strength` and CSS IDs like `#user-admin-roles`. (See [user.css](https://api.drupal.org/api/drupal/modules!user!user.css/7).) That is not the issue.

$content is only showing array text


SNS -> Lambda: What happens when Lambda throttles

Question: I have a lambda function subscribed to an SNS topic. I wonder, what will happen when that lambda function is throttled?
Will SNS ensure that the message is delivered later?
Will the message got dropped on the floor after x retries?
Many thanks
Answer: In short, delivery will be re-tired three times, after which your message will be sent to the DLQ for your Lambda (if you have one).
You can read up about this in the lambda throttling documentation and event sources documentation.


OpenVPN as a service, client physically connected to network

Question: I've got OpenVPN running as a service on a client's computer, however oftentimes he will be in the office and able to physically connect to the network.  The issue I have with this, is that even when connected to our LAN, OpenVPN still connects.  This creates a latency issue of almost 5x the speed it would normally be if not going through VPN.
I looked at this post How to handle OpenVPN client as a service, when the laptop is physically on the network already? but am afraid either I'm not as knowledgeable as the poster here or we have a slightly different scenario.  Could anyone help me understand how I could get it to not connect through OpenVPN when physically connected to our network?
Thanks folks.
Comment: You don't mention whether you have a seperate subnet for OpenVPN connections - though this has been asked on the page you refer to...
Answer: From a network perspective it is best to solve this on the client: Check for the LAN ip and act accordingly (don't start OpenVPN; adapt routing; whatever). I don't know how to do that on Windows, though.
A workaround may be to change the IP addresses the client connects to. Probably it's just a few systems which the clients connects to. It may be possible to configure different IP addresses for the same host name depending on where the query comes from. So you could create a host name samba.vpn.example.org which points to e.g. 192.168.1.15. If you have a local DNS server you can configure it so that it gives e.g. 192.168.2.15 for that host name. Your OpenVPN gateway can make DNAT from .1.15 to .2.15. That does not affect bandwidth. If the client is local it does not try to connect via OpenVPN because the target is in the LAN network, not in the OpenVPN network. So OpenVPN would still (try to) establish the connection if physically connected but the OpenVPN connection would not be used and thus waste minimal bandwidth only.
A third option: Throw away the Windows client, keep Linux running in a VM, and route the company addresses (or a client-side mapping) through the VM. In the VM everything necessary can easily be done. The bandwidth loss should be quite small (if using virtio NICs).
Answer: Setup the network or VPN server such that the client fails to connect if it is on the internal network (e.g. setup a firewall to block packets to the VPN server and port from the internal network).


Qual a compatibilidade com os navegadores do uso da tag template?

Question: Referência: https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/template
Exemplo de uso:
Javascript:
window.onload = function() {
var contentHTML = document.getElementById("teste").content;
  var linha = document.importNode(contentHTML, true);
   document.getElementById("tabela").appendChild(linha);
}();

HTML:

<template id="teste">

Optional table caption.

 #	 First Name	 Last Name	 Username

 1	 Mark	 Otto	 @mdo

 2	 Jacob	 Thornton	 @fat

 3	 Larrya	 the Bird	 @twitter

</template>

Exemplo JSFiddle
Answer: Ivan, segundo o site Can I Use a tag template não é suportada pelo IE, Opera Mini e o Android 4.3.
mas para estes casos, você pode utilizar um Polyfill, como o implementado pelo jeffcarp.:
(function () {
  if ('content' in document.createElement('template')) {
    return false;
  }

  var templates = document.getElementsByTagName('template');
  var plateLen = templates.length;

  for (var x = 0; x < plateLen; ++x) {
    var template = templates[x];
    var content = template.childNodes;
    var fragment = document.createDocumentFragment();

    while (content[0]) {
      fragment.appendChild(content[0]);
    }

    template.content = fragment;
  }
})();

Comment: obrigado pela resposta.


Add remote method to GridView event

Question: I have an aspx web app that has multiple GridView's with similar methods. My thought was to create a "helper" class that has the reusable methods. My question is what is the best way to utilize those remote class methods?
the frontend doesn't accept the class.method like this:
<asp:GridView runat="server" ID="myGridView" ... OnSorting="myClass.reusableMethod"

Visual Studio didn't give me any compiling errors when I attached the handler on Page_Load, but I did get a runtime error saying the GridView tried to fire the event and it wasn't there.
if (!IsPostBack)
{
    myGridView.Sorting += myClass.reusableMethod;
}

The final way I am pretty sure will work, but seems counter-productive. Creating the method on the pages backend like normal but then having the only line being a call to the remote method
public void myGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    myClass.reusableMethod();
}

Answer: It can be done. First remove the OnSorting event from the GridView.
<asp:GridView ID="myGridView" runat="server" AllowSorting="true">

Then only bind the method outside the IsPostBack check.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //do not bind the event here
    }

    //but here
    myGridView.Sorting += myClass.reusableMethod;
}

Now you can use the Method
public static void reusableMethod(object sender, GridViewSortEventArgs e)
{
    GridView gv = sender as GridView;
}

Comment: doesn't !IsPostBack basically mean the first time hitting the page? Why would that not work? Or does the gridview lose the handler on a postback? Thus the code doesn't re-add the handler after a postback?
Comment: Yes it does. But since you are binding an event dynamically you need to do that on every page load or it is lost on PostBack. And if it is lost it will not trigger.
Comment: ok I wasn't aware it would lose assignment on postbacks. That makes sense now. Thank you!

Add remote method to GridView event


How do I simulate an unreachable host on windows?

Question: I have a windows 8 PC, I am testing a beta program for network socket error handling. One of the ones I am having problem simulating for it to test is host unreachable and network unreachable errors. How can I simulate these conditions to know if the program is handling them correctly.
Answer:
Try connecting to an IP address that isn't being used.
Unplug your network connection at the point you want to simulate a failure
Unplug the other end of the conversation from your switch (or disconnect your internet if it is remote).  This one tests what it does when your PC's connection is still up, which might be different from what it does when your network cable is disconnected.
Comment: Very simple idea, why didn't I think of that?
Answer: For network unreachable errors, you can use route delete and remove all your routes. You should be able to get lots of network unreachable errors then.
Answer: While one could go about unplugging wires or deleting routes in your routing table, the kind of error conditions using these techniques is fairly limited. Instead, you could use a network simulator that will allow you to configure a virtual network then test your application against that.
This approach gets you several things:

Test scenarios can be repeated easily.
Test scenarios can be tested automatically.
You can test many different (and difficult) network setups without having to invest in hundred or hundreds of thousands of dollars in networking equipment.
Because you don't rely on physical proximity to network hardware, you can test anywhere that you write code.

There are several open source alternatives such as Cloonix, CORE Network emulator and others.
Answer: you could also use the native firewall of Windows 8 to block the connection of your program.


Retrofit Error :500 Internal server error in Android

Question: Am Using retrofit for my connection with server,My app has signin page and signout page During Login i get the value from text box and send using POST request to the server It works fine,
   public void LoginUser(View v)

{RestAdapter adapter = new RestAdapter.Builder()
            .setEndpoint(ROOT_URL)
            .build();

    WashAPI api = adapter.create(WashAPI.class);

    api.LoginUser(

            Email.getText().toString(),
            Password.getText().toString(),

            //Creating an anonymous callback
            new Callback<Response>() {
                @Override
                public void success(Response result, Response response) {
                    //On success we will read the server's output using bufferedreader
                    //Creating a bufferedreader object
                    BufferedReader reader = null;

                    //An string to store output from the server
                    String output = "";

                    try {
                        //Initializing buffered reader
                        reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

                        //Reading the output in the string
                        output = reader.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

Interface for signin
public interface WashAPI {
@FormUrlEncoded
@POST("/xxx/yyy/signin")
public void LoginUser(
        @Field("email") String email,
        @Field("password") String password,

        Callback<Response> callback);

}

This works good
After login with my server API it returns me a token, At the time of signout i need to send the token so my session get experied.
code for signout
public void signout(View v)
{
    Log.d("insidetoken",t);
    RestAdapter adapter = new RestAdapter.Builder()
            .setEndpoint(ROOT_URL)
            .build();
    SignoutAPI api = adapter.create(SignoutAPI.class);
             api.signout(t,
                    new Callback<Response>() {
                        @Override
                        public void success(Response result, Response response) {

                            BufferedReader reader = null;
                            String output = "";
                            try {
                                reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                                output = reader.readLine();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

Interface for signout
public interface SignoutAPI {
@FormUrlEncoded
@POST("/xxx/yyy/zzz/signout")
public void signout(
       @Field("token") String token,
        Callback<Response> callback);

}
My code is same for both signin and sigout
but for signin it works and for signout it gives me RETROFIT ERROR : 500 INTERNAL SERVER ERROR
But Using POSTMAN It works fine
Comment: What is the question?
Comment: Why Internal server error occurs during my signout operation???
Comment: Because there is an error on the server
Comment: But it works good in POSTMAN for the same signout
Comment: So? The error is still there. I suggest you check the server logs
Comment: In Postman, why are you sending parameters as query parameters ?
Comment: Yes, @Eric B i use the same way for signin page aslo it works fine..
Comment: This is definitely a server issue, something you are doing in the login service and not doing in the logout one.
Comment: Thanx @Eric i just checkd the complete log it gives me

JWTException in JWTAuth.php line 295: A token is required---

token i send is not received by server so the server prompts me " token is required"
Comment: Great, i am posting my comment as answer.
Comment: I send the sameway for email and password for signin it works but for signout it doesnt work means that there is an error in android right
Answer: 500 INTERNAL SERVER ERROR means that there is problem in the server side you should have to check it using postman.
I am damn sure that there will be problem in the web service response not of your code at android side.
Comment: The problem in SERVER is, It requires TOKEN but there is no token

JWTException in JWTAuth.php line 295: A token is required
Answer: As mentioned in the comments too, it appears you are doing something in the login service that is not being done in the sign out service.
To fix this, make sure in you sign out service, you are checking for a POST parameter named token.
Comment: See this http://stackoverflow.com/questions/8100634/get-the-post-request-body-from-httpservletrequest
Answer: Maybe you are giving token in wrong way
In my way It was "Bearer TOKEN" -> for Authorization in Header
In my case I changed my parameters to that
fun setProfileAvatar(token: String,@Part image: MultipartBody.Part) : Single<Message> {
        return apiService.setProfileAvatar("Bearer ${token}",image)
    }

Answer: You can enable logging in retrofit to show you server-side errors and messages.
use this link to understand how to enable it.
https://stackoverflow.com/a/33256827/9474700


programmatically check if today is a market open trading day

Question: What might be the simplest way to check if today the U.S. stock exchanges are open for trading?
The prolonged way I am hoping to avoid is by creating routines to parse a feed with calendar info like https://business.nasdaq.com/trade/US-Options/Holiday-Trading-Hours.html
I prefer Ruby, but even a simple URL lookup with curl to yield a true/false, or time until next market open, would be great.
OPTIONAL
To be able to lookup any arbitrary date would be better, and solve this too.
I.e. Even something like curl google.com/search?q="Is the NYSE open on $(date +%Y-%m-%d)" from the shell.
Comment: Related (not identical) questions have been found here, but usually domain-specific (eg. Matlab, R, requiring libraries, fat API or infrastructure, etc.) or not adequately solved.
Comment: so given the answer (user crappy_hacker) currently given is it worth clarifying if will/will not be open at some point today? I don't know what happens in the case of the answer below when it is a trading day but outside of trading hours i.e. market closed but is a trading day. _if today the U.S. stock exchanges are open for trading_ implies only match required is trading should have occured that day.
Comment: Since your need is about "today" (and not historical dates), you can use the [NYSE page for market holidays](https://www.nyse.com/markets/hours-calendars). Parse the holdiays for the upcoming year at the beginning of every year. Save it to a file with readable format of your choice. And then retrieve that file and on top of that, exclude all weekends. Such is exactly what I do using Apps Script.
Answer: With Python, the easiest way I have found is using the pandas_market_calendars library, which tells you the market days.
import pandas_market_calendars as mcal
nyse = mcal.get_calendar('NYSE')
nyse.valid_days(start_date='2016-12-20', end_date='2017-01-10')

Substitute start_date, end_date for yourself and generate the follow range.
DatetimeIndex(['2016-12-20 00:00:00+00:00', '2016-12-21 00:00:00+00:00',
               '2016-12-22 00:00:00+00:00', '2016-12-23 00:00:00+00:00',
               '2016-12-27 00:00:00+00:00', '2016-12-28 00:00:00+00:00',
               '2016-12-29 00:00:00+00:00', '2016-12-30 00:00:00+00:00',
               '2017-01-03 00:00:00+00:00', '2017-01-04 00:00:00+00:00',
               '2017-01-05 00:00:00+00:00', '2017-01-06 00:00:00+00:00',
               '2017-01-09 00:00:00+00:00', '2017-01-10 00:00:00+00:00'],
              dtype='datetime64[ns, UTC]', freq='C')

Check that the date today is in there.
Answer: I'm using Tradier's API to do this in my shell scripts, then using jq to get the status for a particular day.
date="your date"
month=$(date -d $date +%-m)
year=$(date -d $date +%Y)
calendar=$(curl -H "Authorization: Bearer "$tradierApi"" -H "Accept: application/json" "https://production-api.tradier.com/v1/markets/calendar?month="$month"&year="$year)
marketStatus=$(echo $calendar | ./jq-linux64 '.calendar.days.day[] | select(.date == "'$date'") | .status')

Answer: As a previous answer mentioned, you can use pandas-market-calendars, and here's a simplified implementation based on the NYSE:
import pandas_market_calendars as mcal
from datetime import datetime

def market_is_open(date):
    result = mcal.get_calendar("NYSE").schedule(start_date=date, end_date=date)
    return result.empty == False

# check if market is open today
is_open = market_is_open(datetime.now().strftime("%Y-%m-%d"))

# check if market was open 2023-04-16 (False)
was_open = market_is_open('2023-04-16')

Answer: Until something more elegant and reliable turns up, I might use
curl -s "https://www.isthemarketopen.com/" |grep -c "** Stock market is closed"

which returns a 1 in today's case (Good Friday)--and I can directly use in conditional code--but has to be maintained and checked periodically how that URL's underlying HTML source may have changed.
Comment: Easter Monday morning, http://isthemarketopen.com is still publishing U.S. markets are closed due to Good Friday :( This breaks my code in the reverse case. Looking for alternatives for a quick single-line test.
Answer: MSN quotes include a property indicating if the stock listing's market is open or closed:
https://www.msn.com/en-us/money/stockdetails/nas-aapl/fi-a1mou2?symbol=AAPL&form=PRMFPS
Below is an example Python script to get the status using the Beautiful Soup parser.
If you're worried about them changing their css, I suppose a regex might be more reliable, etc.

from bs4 import BeautifulSoup

import requests

session = requests.session()

response = session.get('https://www.msn.com/en-us/money/stockdetails/nas-aapl/fi-a1mou2?symbol=AAPL&form=PRMFPS')

if response.status_code == 200:

    page = response.text

    soup = BeautifulSoup(page, "lxml")

    market = soup.find('span', attrs={'class': 'market-status-text'}).text

    if market == 'US Markets Closed':

       # do stuff

        print('closed')

    else:

        print('open')

        # do different stuff

Answer: I found a Google Calendar of the USA market holidays which is reasonably updated for the next several years.
As much as I hate to add a separate answer, this is a much better solution than the brittle URL page text-searcher before (which btw, two weeks later is still returning "** Stock market is closed Good Friday 4/19/19" instead of simply having "market is open today" somewhere).
First the code: (Ruby w/ embedded Bash)
$marketCal = %x'curl -s "https://firstname.lastname@example.com/events?key=[YOUR GOOGLE API KEY]&maxResults=1&timeMin=#{today=`date +%Y-%m-%d`.chomp}T00%3A00%3A01%2B00%3A00&timeMax=#{today}T23%3A59%3A59%2B00%3A00&"'

$isMarketOpenToday = $marketCal !~ /"status":/  # => true  when there exists event "id":, etc.

Since there are resource limits, you'll need to go and create your own free API key at
https://console.developers.google.com/apis/credentials?
The global variable $isMarketOpenToday yields true if there isn't a market holiday today, false otherwise.  Note that it doesn't consider day of the week, so on weekends it may still yield true.  So, just make that another simple test, if you need.  Eg. [[ $(date +%u) < 6 ]] && echo "Weekday, yay!"
A lot could be improved with programming standards; the goal here was simply to test the API with minimal lines of code easily checked from the CLI outside a script, however nasty.
Answer: PowerShell:
function isMarketOpen(){
    $url = "https://query2.finance.yahoo.com/v7/finance/quote?symbols=MSFT"
    try{
        $response = Invoke-RestMethod $url
        #return $response.quoteResponse.result[0]
        if($response.quoteResponse.result[0].marketState -eq 'CLOSED'){
            return $false
        }else{
            return $true
        }
    }catch{
        $_.exception | Write-Warning
        return $null
    }
}

isMarketOpen

Comment: Good, so the marketState of this JSON output on any ticker symbol.  I've yet to check if this will give "OPEN" on a trading day, but well before or after typical market hours.


Fresh Laravel install deletes server.php on artisan serve

Question: I'm a bit fresh to Laravel. I installed it via composer in the xampp/htdocs file. I installed the latest version 5.6.
The install works with no errors, and the file structure is as it should be.
When I run the php artisan serve command from inside the folder, it deletes the server.php file and therefore outputs the error:
This site can't be reached.
localhost refused to connect.
So I thought why not just add a new file inside and it will work... Well, trying to add new file shows that I do not have permissions to add files to this folder.
I tried a new install a few times, but the situation is always the same.
Has anybody else encountered this problem?
Comment: Take a look: http://sforsuresh.in/installing-laravel-5-wamp-xampp/
Comment: That is almost exactly what i did. but then when running php artisan serve, it deletes the server.php file and blocks permission...
Answer: So I realised it was some kind of server problem... well, removed the antivirus, chanhed my firewall settings and everithing works as it should.
Comment: It's not a server problem, it's just that the antivirus is deleting the file as it seems to be malicious file in antivirus. What works for me is to disable the antivirus,  rename/paste the file ```server.php```, again enable the antivirus and run the project, if it again shows the file as malicious, choose CREATE EXCEPTION for this file.
Happy Coding !!! :)
Answer: My advice to avoid this in the future is to start creating Laravel applications in a folder inside of your My Documents folder in Windows or using /home/{your-username}/projects directory in Unix environments.
What likely happened is xampp has certain permissions that don't play nice with what you need in Laravel.


Clarification of example of Clifford Algebra

Question: I just started studying Clifford algebras and I am puzzled by the following example.
Let $X$ be a Hilbert space with $\mathrm{dim}\ X = 1$. Let $\{e_1\}$ be the basis for $X$. Then the  Clifford algebra $\mathcal{C}(X)$ consists of all elements of the form $\alpha + \beta e_1$ where $\alpha,\beta \in \mathbb{R}$. Hence, $\mathrm{dim}\ \mathcal{C}(X) = 2$.
However, when I try taking $X = \mathbb{R}$ then $\mathrm{dim}\ X = 1$ and all elements of $\mathcal{C}(X)$ are of the form $\alpha + \beta e_1 \in \mathbb{R}$. But then $\mathrm{dim}\ \mathcal{C}(X) = 1$ ?
Comment: When you use a basis of the Hilbert space to compute the associated Clifford algebra, you are writing the latter as an algebra generated by the basis vectors with some constraints added. This basically means that $e_1$ is a *formal* element. That it used to be $1 \in\mathbb R = X$ does not mean that $1 + e_1 = 2$ in $\mathcal C(X)$.
Comment: Yes, when you write $\alpha$ you mean $\alpha \cdot 1$ with $1$ the identity of the Clifford algebra, while $e_1$ is an element such that $e_1^2 = -1$. I studied Clifford algebras on "Representations of compact Lie groups" of Bröcker and Dieck, maybe this reference can be helpful to you.
Comment: The product $\beta e_1$ should rather be seen as a tensor product $\beta\otimes e_1$. This means that they factors are considered to belong to different linear spaces, but any factor can be moved from one to the other: $(c\beta) \otimes e_1 = \beta \otimes (c e_1)$.
Answer: This is a bit tricky to answer without knowing your background, so I'll try to err on the side of a more accessible answer.
Basically, "$\mathbb R$ as a vector space" is a different thing from $\mathbb R$ (where numbers can be multiplied), and if you keep them separate you won't have this kind of issue. One choice, but not the only one, would be to distinguish them in notation by writing "$\mathbb R$ as a vector space" as "$\mathbb R^1$" (as discussed in Is $\mathbb{R}^1$ really the same as $\mathbb{R}$?). Let's say that when we have elements of "$\mathbb R$ as a vector space" (or $\mathbb{R}^1$), we write them in angle brackets so that $-2\langle-1\rangle=\langle2\rangle$ and $\langle-1\rangle+\langle2\rangle=\langle1\rangle$, but the product $\langle3\rangle\langle4\rangle$ is not defined since you can't just "multiply" vectors. There is also a natural inner product where $\langle2\rangle\cdot\langle3\rangle=6\ne\langle6\rangle$. With this ($\mathbb{R}^1$) as our Hilbert space $X$, elements of $\mathcal{C}(X)$ would be like $2+3\langle1\rangle\notin\mathbb R$.

It may be easier to understand the the $\mathcal{C}(X)$ example with $X$ being a one-dimensional vector space that is more clearly different from $\mathbb R$, like let $X$ be "the vector space of horizontal arrows, with addition given by attaching arrows tail-to-tip, and scalar multiplication given in the standard way where multiplication by $2$ doubles the length, multiplication by $-1$ flips the direction, etc." We can define $|\mathbf{v}|$ to be the length of $\mathbf v$. Then $X$ is a Hilbert space where $\mathbf v\cdot\mathbf w$ is given by $\mathbf v\cdot\mathbf w=\pm|\mathbf{v}||\mathbf{w}|$ with the minus sign when $\mathbf v$ and $\mathbf w$ point in opposite directions.
Any arrow of nonzero length could be a basis vector for $X$, say $e_1=``\to"$ (so that $-e_1=``\leftarrow"$, etc.). Then $\mathcal{C}(X)$ consists of all expressions of the form $\alpha +\beta e_1$, like $``3+2\to"=``3+\longrightarrow"$.
Comment: I think the problem was in taking $X = \mathbb{R}$ in the first place. I think the right thing to do here is to take $X = \mathbb{R}^1$ instead since there is a subtle difference between $\mathbb{R}^1$ and $\mathbb{R}$ as described here: https://math.stackexchange.com/questions/4124752/is-mathbbr1-really-the-same-as-mathbbr

According to this $\mathbb{R}$ as a vector space over $\mathbb{R}$ is in fact $\mathbb{R}^1$ and that should clear up this confusion then.
Comment: @MathCurious Yeah, that's what I was getting at with the "angle brackets" stuff at the beginning.
Comment: Thanks for your answer! Can we just look at $\alpha + \beta e_1$ as an ordered pair $(\alpha, \beta)$ w.r.t. basis $(1,e_1)$? Similar how we look at complex numbers $\alpha + \beta \mathbb{i}$ as ordered pair $(\alpha, \beta)$ w.r.t. basis $(1, \mathbb{i})$?
Comment: @Math Curious 001, yes it can, but doing it that way depends on the choice of basis vector $e_1$ in a way that the standard way of writing things in the Clifford Algebra does not.
Comment: So, when looking at $\mathcal{C}(\mathbb{R})$ just as a bare set, what exactly is that?
Comment: @MathCurious Depends on several set theory choices. If could certainly be the set of ordered pairs of reals. But as I mentioned in my answer, failing to distinguish the reals (what $\alpha$ and $\beta$ can be) from your one-dimensional vector space risks confusion. If $X$ is my one-dimensional vector space of arrows, then you could take $\mathcal{C}(X)$ to be $\left\{(\alpha,\mathbf v):\alpha\in\mathbb R,\mathbf v\in X\right\}$. Only if you choose a basis vector $e_1$ could you replace this with the set of pairs of reals.
Comment: Ok, I think if you just add a reference to https://math.stackexchange.com/questions/4124752/is-mathbbr1-really-the-same-as-mathbbr to the answer I can accept it.


selected columns must appear in GROUP BY clause error

Question: I am trying to write a SQL query to get the month end prices for a particular instrument.
Table (contains some other columns that can be ignored):

instrumentId
unitPrice
reportedAt

1
90.22
2018-10-28

1
80.55
2018-10-30

1
70.55
2018-09-15

1
70.56
2018-09-23

Expected result:

instrumentId
unitPrice
reportedAt

1
80.55
2018-10-30

1
70.56
2018-09-23

There will be multiple rows for the same instrumentId with different reportedAt from different months. The idea is for each month and year (e.g. Oct 2018), I am trying to get only the last price reportedAt for each month.
SELECT
    "instrumentId",
    "unitPrice",
    MAX("reportedAt") as reportedAt
FROM
    "InstrumentPrice"
WHERE
    "instrumentId" = 90
GROUP BY
    EXTRACT(MONTH FROM "reportedAt"),
    EXTRACT(YEAR FROM "reportedAt")
ORDER BY
    "reportedAt" DESC

However, this query keeps throwing an error saying the columns selected must appear in GROUP BY clause or be used in an aggregate function.
This will not work because if I group by unitPrice or reportedAt, I will not get the desired results (because they are all unique).
Comment: window functions will be better for this
Answer: The error in your query is caused by including the column unitPrice and instrumentId in the SELECT clause without including it in an aggregate function or in the GROUP BY clause.
In SQL, when you use GROUP BY, you should either:

Include the column in the GROUP BY clause.
Use an aggregate function (like MAX, MIN, SUM, etc.) on the column in the SELECT clause.

You can achieve this using window functions. You can use the ROW_NUMBER() window function to assign a row number to each row within each month and year partition based on the reportedAt column, and then filter for rows where the row number is 1 (indicating the last price reported for each month). Here's how you can do it:
SELECT
    "instrumentId",
    "unitPrice",
    "reportedAt"
FROM (
    SELECT
        "instrumentId",
        "unitPrice",
        "reportedAt",
        ROW_NUMBER() OVER (PARTITION BY "instrumentId", EXTRACT(MONTH FROM "reportedAt"), EXTRACT(YEAR FROM "reportedAt") ORDER BY "reportedAt" DESC) AS row_num
    FROM
        "InstrumentPrice"
    WHERE
        "instrumentId" = 90
) subquery
WHERE
    row_num = 1
ORDER BY
    "reportedAt" DESC;

In this query:

The inner subquery assigns a row number to each row within each month and year partition using the ROW_NUMBER() window function. The PARTITION BY clause partitions the data by instrumentId, month, and year, and orders the rows within each partition by reportedAt in descending order.
The outer query then selects rows where the row number is 1, which corresponds to the last price reported for each month and year combination.
Answer: group by is not the right tool for your job. Here it is using window function row_number().
with t as
(
 select
   instrumentId, unitPrice, reportedAt,
   row_number() over (
                      partition by date_trunc('month', reportedAt)
                      order by reportedAt desc
                     ) as rn
 from the_table
)
select instrumentId, unitPrice, reportedAt
from t where rn = 1;

Demo


Seach API Solr database service

Question: I have a Drupal 7 installation on Linux with Tomcat 6 and Apache Solr.
Drupal can connect to Apache Solr, but the search only works for the "database service" class, even though I used the same settings when I created the server with "Solr Service" class.
Is there any way to troubleshoot the Solr index directly from linux box or Tomcat?
Comment: i think i took schema and solrconfing from a different module called "apachesolr" which is not compatible with seach api
Answer: Does {Your drupal site}/admin/config/search/search_api show a "working" (Green tick/check mark) next to your server settings? If so press 'edit' and this should provide you with a connection link to your solr installation being served by tomcat.  The URL should be something like

http://{IP of server with Solr on}:8080/solr

If in a browser you do to http://{IP of server with Solr on}:8080/solr/admin you should see a solr web query page that will allow you to query the solr server directly.
This should help indicate if solr is indexing the drupal content or not.  On my localhost server a URL to return everything would be

127.0.0.1:8080/solr/select/?q=%3A&version=2.2&start=0&rows=10&indent=on

In the event you can't contact the tomcat server (And assuming your firewall is correctly configured, not all systems allow 8080 through by default) I found the article very helpful for installing and configuring Solr on Tomcat 6.

Seach API Solr database service


Semi-simple $\mathbb R[x]$-module structure on $\mathbb R^2$

Question: This might just be a trivial question:

Let $R=\mathbb{R}[x]$ and define an $R$-module structure on $\mathbb{R}^2$ with $x$ acting by $\begin{pmatrix}0&1\\-1&0\end{pmatrix}$. Is the module semi-simple?

So my thought is: since the matrix admits no eigenvalue in $\mathbb{R}$, we cannot find any non-trivial submodule, thus this is a simple module, thus semi-simple. Is this a correct understanding? What's the correct/better way to understand this?
Comment: @user26857 Oh yeah, in this special case it works. But for higher $\mathbb{R}$-dimensions it might cause confusion. I'll edit my post.
Comment: Yes, your argument is correct. A "better" way is to find a concrete module isomorphic with your module, and this is what I did in my answer.
Comment: @user26857 it think the argument is wrong. See my answer.
Comment: No, it's not! In the OP's question the vector space has dimension 2, so the proper non-zero submodules have dimension 1 as vector subspaces.
Answer: Let $A=\begin{pmatrix}0&1\\-1&0\end{pmatrix}$. The characteristic polynomial of $A$ is $x^2+1$, and thus the module is isomorphic to $\mathbb R[x]/(x^2+1)$ (since $x^2+1$ is irreducible over $\mathbb R$), hence it is simple.
Answer: The thought that the matrix not admitting an eigenvalue implies that the module is semi-simple is not correct if the $\mathbb{R}$-dimension of your module is greater than $2$. For example let $x$ operate on $\mathbb{R}^4$ by $$f_x = \begin{pmatrix} 0 & 1 & 1 & 0 \\ -1 & 0 & 0 & 1 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & -1 & 0 \end{pmatrix}.$$
The minimal polynomial of this matrix is its characteristic polynomial which is $(X^2+1)^2$. Hence $\mathbb{R}^4$ with the induced $\mathbb{R}[X]$-structure is isomorphic to the $\mathbb{R}[X]$-module $\mathbb{R}[X]/(X^2+1)^2$ which is indecomposable. However, $\mathbb{R}^2\times \{0_{\mathbb{R}^2}\}$ is a $\mathbb{R}[X]$-submodule, so $\mathbb{R}^4$ with this $\mathbb{R}[X]$-structure is not simple and hence not semi-simple, because indecomposable. The matrix also admits no eigenvalues in $\mathbb{R}$.
For the proof that your given module is semi-simple, see the other answer.


How to build a neighbor friendly soundproof booth?

Question: If you search the web for "vocal recording booth" you'll find build plans and diy guides by the dozen.
Thing is... I am not looking for a recording booth... I share a house with two families with kids that should sleep at night and adults working night shifts that need to sleep during the day.
What I am looking for is a "sound-proof" human sized box design to practice singing (and shouting) without worrying that I annoy my house mates.
My current idea is to get some cheap wood, add some rock-wool on the inside and some cloth to make it bearable. Put this together with a roof of the same design and put it in the cellar.
Would this be soundproof?
Comment: Possible duplicate of [Making a Soundproof Room](https://music.stackexchange.com/questions/9609/making-a-soundproof-room)
Comment: Or jump in the car, and drive somewhere secluded?
Comment: Believe me - I can hear my idiot neighbours shouting, through two layers of brick & insulation...
Comment: Funfact: The vocalist of my band _Arcsign_ does exactly that... His name is Tim :-)   Thing is, I want to use my microphone, amplification, etc and I would not want to have to set it up time and time again whenever I decide to practice ... and I would not want to leave it in the car.
Comment: Sound-proofing requires **mass**. Rockwool is nowhere near massive enough, by many factors. Brick walls are considerably better at it than wooden, but would you can still hear the neighbours' hifi through 2 layers with insulation between.
Comment: But the hifi is producing a lot of bass. My voice is quite low, but I suspect I can't compete with a medium sized bass speaker.
Comment: Not sure, I would suspect that a ceiling/floor is thicker than a wall. And rock-wool is pretty heavy. I think people actually use it for soundproofing on the cheap.
Comment: Why do you need amplification to practice singing?  Use headphones, just deafen yourself!
Comment: I am specifically trying to train singing "loud"... Metall stuff... PA in the rehearsal room is cranked up to just below feedback and it's still hard to get heard above the drums. And the drummer is actually not that loud.
Comment: A ceiling/floor may be thicker than a wall, but unless it's concrete, it will be nowhere near as good as brick at stopping sound. Rockwooll is a waste of time for proper soundproofing, on its own or in combination with just wood. You need mass..
Comment: A college/university/school local to you might have soundproof practice rooms (with PA systems etc.) available. Many will let you use them... sometimes for a price.
Comment: @ChristopheLynch we have a 120€/month practice room. I am looking for a solution at home.
Answer: In the end I bought a booth from a German company called Desone which I am very happy with. It wasn't cheap but it gives enough isolation that I can play baritone sax at 3am if I want. Outside (next to) the booth it sounds as if someone next door is listening to music a bit loudly. So my neighbours hear almost nothing. I also use it for recording as it is also quiet inside. It's pro-quality product. I'll give you an idea how it is constructed.
Basically it is a room within a room, with a double layer of fibreglass insulation. There is a heavy soundproof double door and each shell has a heavy double-glazed window. There is a ventilation duct between the two shells (I have the impression that most sound gets out through this). You can stay in there about 30 mins then you need to open the door and take a break.
The whole thing sits on rubber bumpers which isolate vibration going downwards. The two layers of fibreglass insulation are arranged so that seams always cross at right angles.
It took a couple of days (and a large van) to collect from Berlin, and about 3 or 4 days with two of us to build. Another day to clean everything top to bottom because of all the fibreglass. But now it's done, I love it - it has changed my life. I won't be moving in a hurry though.
It cost quite a bit but having built it and used it, I can see why. The components themselves are serious, and there is a lot of design. It was worth it.
Comment: Hi @danmcb, I really liked what you described from your comment and looks like you genuinely got rid of that. Is there a way let's say for anyone to make it themselves if one can't get company like Desone?
Comment: @ShashankBhatt yes, it is an excellent investment and I use it daily for practice and also recording. A DIY version is not exactly impossible but a big challenge. It is a room inside a room with a double isolation between the shells, but also with specialist door, window and passive ventilation system. When you take all that into account, with the fact that it can be dismantled and relocated reasonably easily, you start to see the value you are getting for the money. (I have in fact moved and it really was not too bad - easier than the original build as the fibreglass was already cut.)
Answer: "Soundproofing" is a bit of a misnomer in the sense that it is any attempt at noise reduction by definition. And, it is not realistically possible to completely soundproof a room (meaning to cancel 100% of sound entering into or escaping from a chamber,) at least not on any  pocket-friendly budget or with non-professional design and labor.
For example, Orfield Labs' anechoic chamber and Microsoft's 'quietest place on Earth' have a background noise measured in negative decibels. Each took years to design and a LOT of $$$ to ultimately realize... And, they are technically still around 99.99% soundproof, or something like this.
That said, there are a few things you can try if this is still an issue 3 years later... I'd start by searching the web for 'DIY Soundproofing' or 'soundproof closet,' instead of searching for any form of 'vocal booth;' which is going to assume that you are more concerned with keeping noise from entering the booth than you are of noise escaping the chamber (though the same result is achieved either way, arguably.)
Firstly, sound travels upward much more efficiently than downward; so, you are better off if you can get above your neighbors. Secondly, you want to try to reduce noise through absorption as much as possible (since you cannot increase distance from your neighbors...) If you go the route of soundproofing a closet, you will need to add a lot of absorbent material to the floors, walls, door(s), and ceiling. From there, you can, and should, build your 'human-sized box' inside this closet and add even more absorbent material to the inside and outside of that.
Finally, and unfortunately, you are not likely to find a very efficient or cost-effective solution to your problem...Unless you have a big budget, you are much better off to find a solution that is away from the property. It is simply not realistic to think that you can soundproof a room enough in order to avoid disturbing a sleeping child inside a house in which you are shouting... If you absolutely cannot find an off-property solution, then you are better-off building your soundproof closet in some sort of outbuilding like a shed or garage or bomb-shelter. :)


Screen Grab with PHP and/or Javascript?

Question: Just wondering if it's possible to screen grab a page you are viewing with a PHP script or javascript?  For example, load up a page in an iframe and then save that view as a JPEG?
I'm sure it's possible somehow, but are there any known implementations/libraries that help out?
Comment: there was a [similar question](http://stackoverflow.com/questions/181622/screencapture-from-the-browser-using-javascript)
Answer: Nope, sorry, it is impossible with Javascript and definitely impossible with a server-side language like PHP. (Edit: I mean it's impossible to take a screenshot of the user's view of the page.)
It depends on what you want to do this for, but you might want to find a script or program that runs server-side and renders the webpage there. But if you really want to take the screenshot of the user's view of the page, it's pretty much impossible.
Answer: There is a python tool called Webkit2png, hope it helps. But in PHP, i don't believe its possible
Answer: You can't do it in JS but you could do something similiar server side if you know the url of the page you want to convert to an image.
Tools like khtml2png could be called from php to render the page.
Answer: http://html2canvas.hertzen.com/ might do the trick.
Answer: Possible with the GD2 extension and some knowledge of the internals you are capturing - read here for an example.
Answer: Thanks for the help guys.  I did find this interesting resource:
http://www.zubrag.com/scripts/website-thumbnail-generator.php
It's not PHP specific by any means, just an example of running an EXE script that is called by PHP.  Needs a windows server I believe though.

Screen Grab with PHP and/or Javascript?


Expression evaluated client side or server side?

Question: I have the following Thymeleaf code snippet:
<select name="expiryYear">
    <option th:each="seq : ${#numbers.sequence(0,12)}"
            th:value="${ (new org.joda.time.DateTime()).getYear() + seq}"
            th:text="${ (new org.joda.time.DateTime()).getYear() + seq}"
            th:field="*{expiryYear}"></option>
</select>

What I need to know is the new org.joda.time.DateTime() will create object on server side or client side?
I need it to be on the server side so that the fields on the form are not affected by client settings.
Answer: DateTime is the standard implementation of an unmodifiable datetime class. It is Java implementation not javascript so it must be on the server-side.


Recommend reading on physiological basis of music perception.

Question: I am looking for a general description of what happens when people listen to music.
Essentially, I'm looking for which areas of the brain are more active, what substances are secreted, what effect they have, and why we get pleasure from hearing music.
Comment: I don't know how much research has been done on the neuroendocrine aspect of music perception, but this is definitely an interesting question.
Comment: http://www.archive.org/details/onsensationsofto00helmrich -
"On the sensations of tone as a physiological basis for the theory of music" (1895) is first attempt of such research, but too old and incomplete.
Answer: This is by far one of my favorite music texts on that subject precisely:
http://en.wikipedia.org/wiki/This_Is_Your_Brain_On_Music
Comment: No problem!  You can click the green "check mark" next to this answer to accept it if it answers your question (it looks like you have not accepted answers to your other questions as well)


Finding the radius of convergence of this power series involving logarithms

Question: As the title says, I'm looking for the radius of convergence of this power series: $$\sum\limits_{k=3}^\infty (\log k)^{k/2}x^k$$ where "$\log$" denotes the natural logarithm.
I suspect I need to use the ratio test (since we have not proved any other methods in class); dividing the absolute values of successive terms, I get $$|x|\frac{(\log(k+1))^{\frac{k+1}{2}}}{(\log k)^{k/2}}$$
Now there is probably a specific step I need to take towards simplifying this before I take the limit as $k \rightarrow \infty$, but I'm just not seeing it.
Please only hints, not full solutions, in your answers
Comment: You may want to try the root test instead.
Comment: Sorry, should have mentioned - we have not proved the root test, so I think it's best if I don't use it.
Answer: Well, $${\log(k+1)^{\frac{k+1}2}\over\log k^{\frac k2}}>{\log(k+1)^{\frac{k+1}2}\over\log(k+1)^{\frac k2}}$$.
I think that will get you the answer you're looking for.
Comment: Hah, tonight is not my night. So since the limit of the right hand side is $\infty$ as $k \rightarrow \infty$, so is the left side, and therefore the series never converges?
Comment: Only converges for $x=0$.
Comment: Right, thanks for your help
Comment: Your quite welcome.


Adobe AIR HTML Application with Window Shadow

Question: I have been building a HTML based AIR application that uses a transparent window (doesn't use the system chrome). I want the window to have a drop-shadow effect which using a combination of JavaScript and CSS3 I make the shadow change depending on window focus. And when the window is maximised the shadow will be removed completely.
The application looks like the following (wireframe diagram):

The red area is the  container itself. The blue box is the application content area (a simple
) and the black border with green shadow is a container
 that is positioned absolute on the page. This black container is the application itself in my design.
As you can see the black border (around the blue box) has a subtle green shadow in the outer edges of the  page.
The problem is that because the  is the application in AIR it means that the application can never touch the edge of the screen due to the fact that AIR is treating the  as the application edge rather than the container
 for the black border.
Any ideas on how to get around this? The only thing I could think of was some crazy JavaScript that could offset the application somehow.... Anyone else had this problem?
Comment: Maybe I don't understand the question, but why would the javascript be "crazy"? If the application is absolutely positionned, can't you git it a position that is a few pixel off (possibly negative), and take that into account whenever the window is moved / re-drawned?
Comment: Want to show an example of what you mean?
Answer: I probably don't understand the question correctly, or maybe I am missing a limitation of AIR, but I don't see why the solution you think of would be hard.
When the application window is moved with a drag-and-drop, simply leaving the window where it is dropped without checking "screen" bounds will work. If you do want to check the bounds, simply allow the user to be off-bounds by the width of the border.
When the application window is maximized, you can offset the application container with negative values equal to the border width, and give to the application (rather than its container) the width and height of the screen.
As I can't test what I say as an AIR application at the moment, I illustrate it below with some code that you can test in jsfiddle. I used jquery to simplify the code. Is this what you mean?
HTML:

        Maximize

CSS:
#appContainer {
    background-color: black;
    width: 106px;
    height: 106px;
    position: absolute;
}

#app {
    background-color: blue;
    width: 100px;
    height: 100px;
    margin: 3px;
}

Javascript:
$("#maximize").click(function(){
    var $app = $("#app");
    var $appContainer = $app.parent();
    var borderWidth = parseInt($app.css('margin'));
    $appContainer.offset({top: -borderWidth, left: -borderWidth});
    $app.width($(document).width());
    $app.height($(document).height());
});


Posicionar 2 botões lado a lado de um input

Question: Preciso fazer um botão assim pro meu site mas não estou conseguindo?

Como fazer isso em html e css e bootstrap?
Até tentei fazendo assim, mas não funciona.

     <input type="button" class="btn btn-secondary" value="+">
     <input class="form-control" type="number" name="quantidade" onchange="preencheTotalProduto()" min="0" max="<?= $tamanho['estoque'];?>" value="0">
     <input type="button" class="btn btn-secondary" value="-">

Comment: o seu problema é com o layout, ou é com relação a clicar no + ou no - e mudar o valor do input?
Answer: Cara funciona sim basicamente é só tirar o border-radius do input no meio, para isso use a classe nativa rounded-0. No input vc tb pode colocar as classes btn-default border para ficar mais próximo do seu desenho, eu tb defini um width na mão para ficar com a largura de 4 caracteres, 4ch. Documentação https://getbootstrap.com/docs/4.3/utilities/borders/#border-radius

<link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />

                <input type="button" class="btn btn-default border" value="+">
                <input style="width: 4ch" class="form-control rounded-0" type="number" name="quantidade" onchange="preencheTotalProduto()" min="0" max="<?= $tamanho['estoque'];?>" value="0">
                <input type="button" class="btn btn-default border" value="-">

Comment: As duas soluções deram muito certo. Obrigado.
Comment: @Bruno demoro Brunão, se vc quer ver um esquema interessante para controlar esses números no input, isso pode te interessar https://pt.stackoverflow.com/questions/336061/estilizar-um-input-type-number-para-trocar-as-setas tem umas coisas bem legais lá
Answer: Voce pode usar o segunte modo, com css e js que controla tudo, e para que nao apareçam os botoes encima e abaixo se usam o input de tipo text

$('.btn-number').click(function(e){
    e.preventDefault();

    fieldName = $(this).attr('data-field');
    type      = $(this).attr('data-type');
    var input = $("input[name='"+fieldName+"']");
    var currentVal = parseInt(input.val());
    if (!isNaN(currentVal)) {
        if(type == 'minus') {

            if(currentVal > input.attr('min')) {
                input.val(currentVal - 1).change();
            }
            if(parseInt(input.val()) == input.attr('min')) {
                $(this).attr('disabled', true);
            }

        } else if(type == 'plus') {

            if(currentVal < input.attr('max')) {
                input.val(currentVal + 1).change();
            }
            if(parseInt(input.val()) == input.attr('max')) {
                $(this).attr('disabled', true);
            }

        }
    } else {
        input.val(0);
    }
});
$('.input-number').focusin(function(){
   $(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {

    minValue =  parseInt($(this).attr('min'));
    maxValue =  parseInt($(this).attr('max'));
    valueCurrent = parseInt($(this).val());

    name = $(this).attr('name');
    if(valueCurrent >= minValue) {
        $(".btn-number[data-type='minus'][data-field='"+name+"']").removeAttr('disabled')
    } else {
        alert('O numero minimo foi alcançado');
        $(this).val($(this).data('oldValue'));
    }
    if(valueCurrent <= maxValue) {
        $(".btn-number[data-type='plus'][data-field='"+name+"']").removeAttr('disabled')
    } else {
        alert('O maximo numero foi alcançado');
        $(this).val($(this).data('oldValue'));
    }

});
$(".input-number").keydown(function (e) {
        //permite: backspace, delete, tab, escape, enter e .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        //verifica que seja um numero
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });

    .center{
      width: 150px;
        margin: 40px auto;

      }

    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

              <button type="button" class="btn btn-default btn-number" disabled="disabled" data-type="minus" data-field="quantidade">

              </button>

          <input type="text" name="quantidade" class="form-control input-number" value="1" min="1" max="10">

              <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quantidade">

              </button>

Substitui o input do meu codigo com o seu :
 <input type="text" class="form-control input-number" name="quantidade" onchange="preencheTotalProduto()" min="0" max="<?= $tamanho['estoque'];?>" value="0">


Count rows with model::count laravel

Question: I am trying to count the records in the table, but it's showing me nothing in the response, I am working on an API, can anybody help please ?
public function devicesCount()
{
    $x = Device::count();
    if ($x) {
        return ['devices' => $x];
    } else {
        return ['message' => 'ranii karrezt ydyyyyyyk'];
    }
}

Comment: Are you sure you're entering that method? if you add `dd($x);` before `if ($x) {`, does it show anything?
Comment: Is the route defined correctly? How are you querying this API?
Comment: the route is defined correctly . i am querying it with postman
Comment: If you go to the terminal and run `php artisan r:l`, does your route appear there? Just in case, run the command `php artisan route:clear` This will clear the cached routes.
Comment: did not work and there is no error
Comment: Does the route show in your route list?
Comment: yes it's showen
Answer: use $x = Device::all()->count(); in place of $x = Device::count();
or use Laravel Aggregates like
$count = DB::table('devices')->count();

Comment: This will cause performance issues if the `devices` table is large. It's not scalable
Comment: okay you can use Laravel Aggregate $count = DB::table('devices')->count();
Comment: both didn't solve the problem
Comment: can i see the error ?
Comment: there is no error it's sending a 200 response with no value or message
Comment: now it's still loading with no response
Comment: have you filled the table ?
Comment: yes i filled the table
Comment: let me see your code
Comment: Route::get('/devices/count',[DeviceController::class , 'devicesCount']);

Count rows with model::count laravel


How do I override a default view template from another module?

Question: Drupal provides hook_theme(). But is there a hook_theme_alter()? I'm looking for something like hook_menu_link_alter(), which overrides hook menu entries, but for the theme. I want to modify a view hook theme entry so I can specify where to look for one of my custom templates. I am not interested in specifying it through the Views interface, since it look for the theme template inside the theme folder, and I want my template in a feature module.
I found hook_theme_registry_alter() and _theme_process_registry(). You can answer which one is the best to use and why.
Which of these keys should I modify in order to make the view pickup the template from the module?
If I put views-data-export-xml-header--richard-feeds-nokia-movies--views-data-export-1 in the feature, the View defaults to pick up views-data-export-xml-header.tpl.php. If I put that template in the theme layer, the view picks it up (even with the registry alter hook in place).
Answer: Your feature should implement hook_theme_registry_alter(). The use case you describe is exactly what that hook is for. The example code linked on the API page should get you started. The basic idea is to target the entry that corresponds to the entry that views_theme() is inserting into the registry, and change the template to match the one in your feature.
Comment: @kiamlaluno UPDATE: Pairing `hook_theme_registry_alter()` with a `_theme_process_registry($registry, 'phptemplate', 'theme_engine', 'mymodulename', $path);` like suggested [here](http://hddigitalworks.com/zh-hans/provide-theme-templates-from-a-module) did the trick. [This issue queue](http://drupal.org/node/939462#comment-3758480) has some interesting information as well. Might want to add that information to the answer. Thanks!
Comment: jhedstrom is right: the equivalent of `hook_menu_link_alter()` for `hook_theme()` is `hook_theme_registry_alter()`; `_theme_process_registry()` is a private function that should never be used from third-party modules.
Comment: It sounds logical, but it actually did not work. Refer to http://drupal.org/node/939462#comment-3758480.
Answer: This is the code I use to declare a view template stored in the template folder of a custom module.
/**
 * Implements hook_theme_registry_alter().
 */
function custom_module_theme_registry_alter(&$theme_registry) {
  $extension   = '.tpl.php';
  $module_path = drupal_get_path('module', 'custom_module');
  $files       = file_scan_directory($module_path . '/templates', '/' . preg_quote($extension) . '$/');

  foreach ($files as $file) {
    $template = drupal_basename($file->filename, $extension);
    $theme    = str_replace('-', '_', $template);
    list($base_theme, $specific) = explode('__', $theme, 2);

    // Don't override base theme.
    if (!empty($specific) && isset($theme_registry[$base_theme])) {
      $theme_info = array(
        'template'   => $template,
        'path'       => drupal_dirname($file->uri),
        'variables'  => $theme_registry[$base_theme]['variables'],
        'base hook'  => $base_theme,
        // Other available value: theme_engine.
        'type'       => 'module',
        'theme path' => $module_path,
      );

      $theme_registry[$theme] = $theme_info;
    }
  }
}

You should be easily able to fork it override an existing theme instead of adding a new one.
Hope it helps someone.


When I add a context filter, my view is wrapped in a div

Question: I created a view block to display a button (join / leave) above my groups. When I add a context filter to my view, it is wrapped in a div without "class" and "id".
1) I added to my view the following context filter:
(Group content User) User: User ID
2) When the filter value is NOT available: Provide a default value: User ID of the logged in user
Here is the result :

       Rejoindre le groupe

If I delete the context filter, the div envelope would disappear, but that's not the view I want:

 Quitter le groupe

 Quitter le groupe

I encounter this problem with other block view, it's really weird. An idea ?
Answer: Check the twig template (by turning on twig debugging) that is generating the div for your contextual filter. Then alter it with an ID or Class tag.
Let me know if you need help turning on twig debugging.
Find the twig template that is generating that div, copy it and rename it with one of the FILE NAME SUGGESTIONS. The add the following code to the div.

Comment: I'm guessing you want the"Rejoindre le groupe" button to be on the same line as the other two buttons. This guide will show you how to turn on twig debugging for your local host [link] (https://www.chapterthree.com/blog/drupal-8-theming-setting-up-theme-debugging). Once you have access to the twig template, simply find the template that is generating that part of your site, it should look like this:  find that file and update the template via the twig markup language.
Comment: I activated the twig mode in service. You can look at my page again. What must I do now ? I want to delete the div or add a class
Comment: I updated my question with a screenshot
Comment: Looks good. you need to go higher in the document structure and find the twig template that is generating that div. I think it's the template for  on that page. It will say


For which values of the real parameter the following...

Question: How should I solve this exercise:
For which values of real parameter $a$ the following equality is true:
$$\lim_{x\to 0}{1-\cos{ax}\over x^2}=\lim_{x\to \pi}{\sin{x}\over \pi-x}$$
Comment: $\sin(x)=\sin(\pi-x)$ could help
Comment: Try changing variables and bound in the rhs. Think also about Taylor for the lhs.
Comment: That gives you that the RHS equals $1$. Evaluate the LHS by using L'Hôpital twice. Equating both gives a simple condition for $a$.
Comment: I've tried but I haven't seen anything
Answer: As pointed out by Claude Leibovici. Rewrite
$$
\lim_{x\to \pi}{\sin{x}\over \pi-x}=\lim_{\pi-x\to 0}{\sin{(\pi-x)}\over \pi-x}=1.\tag1
$$
As pointed out by  Your Ad Here, you will get
$$
\begin{align}
\lim_{x\to 0}{1-\cos{ax}\over x^2}&\stackrel{\text{l'Hospital}}=\lim_{x\to 0}{a\sin{ax}\over 2x}\\
&\stackrel{\text{l'Hospital}}=\lim_{x\to 0}{a^2\cos{ax}\over 2}\\
&=\frac{a^2}2.\tag2
\end{align}
$$
$(1)$ and $(2)$ yield $\ \Large a=\large\pm\sqrt{2}$.


Calculate the angle x

Question: In the figure, AB is diameter, PM = MH and PN = NB.
If PEB arc = 108 °, calculate "x"

Drawing to obtain the right triangle in P: $\Delta APB $.  $\hat{A}$ as $\hat{B}$  are angles inscribed on the circumference, they are equal to half the arc you see. Therefore,  $\hat{A} = 54^o$ , $\hat{B} = 36^o$ and  note also that $\overline {MN}$ t is  average base $\Delta HPB $.
If $\hat{B} = 36^o$. $\hat{H} = 90^o$ then  $H\hat{P}B = 54^o$

In the right triangle, the middle base is parallel to the base of the original triangle. Therefore, the triangle $\Delta PMN$ is $\hat{M}$ rectangle is $P \hat{N} M = 36^o$ and In addition $R \hat{Q}N$ and $O \hat{Q}M$ are opposed by the vertex. From this, it is easy to conclude that $\Delta OMQ$ $\simeq$ $\Delta NRQ$
Therefore,  in the triangle $\Delta OMQ$ we obtain that $ x + 90^o + 36^o = 180^o \Rightarrow x = 54^o $
how to demonstrate the similarity of $\Delta OMQ$ $ and \Delta NRQ$ ?
Comment: show  that $ \angle AOH = \angle ARP$ so $\angle MRN =\angle 180-AOH$ this shows that $OMRN$ is a cyclic quadrilateral and we are done
Comment: There are two errors in your text. $\measuredangle PMN$ is equal to $90^0$ and not $36^0$, However, $\measuredangle PNM$ is equal to $36^0$. Furthermore, $\measuredangle RQN$ and $\measuredangle OQN$ are adjacent angles and not opposite angles. But, $\measuredangle RQN$ and $\measuredangle MQO$ are opposite angles.
Comment: Thank´s ..I've already corrected
Comment: $OR\parallel AP\to x=54°$
Comment: I need an algebraic demonstration and not just an affirmation
Answer:
The sketch shown in $\mathrm{Fig.\space 1}$ is an extended version of the diagrams you have included in your problem statement. We denote the sought angle $\measuredangle RQN$ as $\alpha$.  Let $F$ be the center of the semicircle $BPA$ and $\measuredangle NRO=\phi$.
As you have mentioned in your incomplete answer, $\measuredangle PAB$ and $\measuredangle ABP$ can be easily determined as $54^o $ and $36^o$ respectively, because $\measuredangle PFB =108^o$. It is also given that $M$ and $N$ are the midpoints of the segments $PH$ and $PB$ respectively. Therefore $MN$ is parallel to $AB$, which makes $\measuredangle MNR = 36^o$.
To solve this seemingly difficult problem we have to bring Ceva's theorem in to play. That is why we have extended the line $NM$ to intersect $PA$ at $D$. This makes $D$ the midpoint of $PA$. As you see below, solving of the problem now becomes as easy as eating a piece of cake. Consider the triangle $PAN$, in which three cevians $ND$, $PO$, and $AR$ are concurrent at $M$. Applying Ceva's theorem to $\triangle PAN$, we obtain,
$$\frac{PD}{DA}\frac{AO}{ON}\frac{NR}{RP}=1. \tag{1}$$
Since $PD=DA$, equation (1) can be simplified to get,
$$\frac{AO}{ON}=\frac{RP}{NR}. \tag{2}$$
Equation (2) implies that $PA$ is parallel to $RO$. Therefore, we have $\phi = \measuredangle NRO = \measuredangle BPA = 90^o$. Using triangle $RQN$, we obtain,
$$\alpha = \measuredangle RQN =180^o-\measuredangle QNR\space\space –\space\phi =180^o – 36^o – 90^o = 54^o.$$

Calculate the angle x


check if firebase record exist and return bool

Question: Trying to check firebase record and perform subsequent logics,
Future<bool> isAlreadyThere(selectedPropertyId) async {
 final FirebaseUser user = await FirebaseAuth.instance.currentUser();

 var myMapQuery = Firestore.instance
    .collection("props")
    .where('xxx', isEqualTo: xxxid)
    .where('yyy', isEqualTo: user.uid);
 var querySnapshot=  await myMapQuery.getDocuments();
 var totalEquals= querySnapshot.documents.length;
 return totalEquals > 0;
}

and in the onTap() of widget ,
bool isThere=isAlreadyThere(suggestion.documentID) as bool;
 if (isThere) {//do stuff here}

errors,
type 'Future' is not a subtype of type 'bool' in type cast
I know its the casting , but tried removing and some other ways as well , wont work.
Comment: You have to await the Future, right, just like you are with getDocuments()?  It doesn't instantly produce a value.
Comment: You forgot to handle the `Future`. Use `await` or `.then()`.
Comment: cant use async modifier on widget , let me try .then()
Comment: There is no widget in the code you shared. But if the call to `isAlreadyThere` is in your `build` method, you'll need to either use a `FutureBuilder` or use `setState()` to get the state from the database to the render method.
Answer: await is missing in where the query
Future<bool> isAlreadyThere(selectedPropertyId) async {
 final FirebaseUser user = await FirebaseAuth.instance.currentUser();

 var myMapQuery = (await Firestore.instance
    .collection("props")
    .where('xxx', isEqualTo: xxxid)
    .where('yyy', isEqualTo: user.uid));
   var querySnapshot=  await myMapQuery.getDocuments();
   var totalEquals= querySnapshot.documents.length;
   return totalEquals > 0;
}

Use method like
isAlreadyThere(suggestion.documentID).then((value) {
     if (value) {//do stuff here}
    });


How to get the "typeof" of a custom user control

Question: I have a custom user control DatePicker.cs. Inside of another piece of code I have a collection of controls where I am checking the type of the control and doing some logic based on the type. My problem is the following:
typeof(DatePicker)

Evalutes to:
{Name = "DatePicker" FullName = "cusitecore.cedarsc.UserControls.DatePicker"}

But when I run the debugger and look at the type of the control that is on my web form it is:
{Name = "cedarsc_usercontrols_datepicker_ascx" FullName = "ASP.cedarsc_usercontrols_datepicker_ascx"}

These two things aren't equal so the correct logic isn't getting evaluated. I've tried using Type.GetType("ASP.cedarsc_usercontrols_datepicker_ascx") but this returns null.
EDIT
Here's what I'm trying to do:
private readonly Dictionary<Type, ControlType?> _controlTypes = new Dictionary<Type, ControlType?>
    {
        {typeof(CheckBox), ControlType.CheckBox},
        {typeof(CheckBoxList), ControlType.CheckBoxList},
        {typeof(DropDownList), ControlType.DropDownList},
        {typeof(HiddenField), ControlType.HiddenField},
        {typeof(ListBox), ControlType.ListBox},
        {typeof(RadioButton), ControlType.RadioButton},
        {typeof(RadioButtonList), ControlType.RadioButtonList},
        {typeof(TextBox), ControlType.TextBox},
        {typeof(Label), ControlType.Label},
        {typeof(DatePicker), ControlType.DatePicker},
        {typeof(CustomSelect), ControlType.CustomSelect}
    };

private void PopulateFields(Control control)
{
    ControlType? controlType;
    _controlTypes.TryGetValue(control.GetType(), out controlType);

    // recurse over the children
    if (control.Controls.Count > 0 && controlType == null) // don't want to recurse into children of controls we are reading values of
    {
        foreach(Control childControl in control.Controls)
        {
            PopulateFields(childControl);
        }
    }

    if (controlType != null)
    {
        switch (controlType)
        {
            case ControlType.CheckBox:
            case ControlType.RadioButton:
                CheckBox checkBox = control as CheckBox;
                    if (checkBox != null)
                        _fields.AddFieldValue(checkBox.ID, checkBox.Checked ? "Checked" : "Not Checked");
                    break;
            case ControlType.CheckBoxList:
            case ControlType.ListBox:
            case ControlType.RadioButtonList:
                ListControl listControl = control as ListControl;
                if (listControl != null)
                    _fields.AddFieldValue(listControl.ID, String.Join(", ", listControl.Items.Cast<ListItem>().Where(item => item.Selected).Select(item => item.Value).ToArray()));
                break;
            case ControlType.DropDownList:
                DropDownList dropDownList = control as DropDownList;
                if (dropDownList != null)
                    _fields.AddFieldValue(dropDownList.ID, dropDownList.SelectedValue);
                break;
            case ControlType.HiddenField:
                HiddenField hiddenField = control as HiddenField;
                if (hiddenField != null)
                    _fields.AddFieldValue(hiddenField.ID, hiddenField.Value);
                break;
            case ControlType.TextBox:
                TextBox textBox = control as TextBox;
                if (textBox != null)
                    _fields.AddFieldValue(textBox.ID, textBox.Text);
                break;
            case ControlType.DatePicker:
                DatePicker datePicker = control as DatePicker;
                if (datePicker != null)
                    _fields.AddFieldValue(datePicker.ID, datePicker.Text);
                break;
            case ControlType.CustomSelect:
                CustomSelect customSelect = control as CustomSelect;
                if(customSelect != null)
                    _fields.AddFieldValue(customSelect.ID, customSelect.SelectedValue);
                break;
            case ControlType.Label:
                Label label = control as Label;
                if(label != null)
                    _fields.AddFieldLabel(label.AssociatedControlID, label.Text);
                break;
            default:
                throw new Exception("Unhandled Control");
        }
    }
}

Comment: ASP.NET creates it's own type inherited from the user control. Use the `is` keyword for comparisons and try `control.GetType().BaseType` for extraction.
Comment: Can you provide some more context?  What do your code look like that is trying to perform the comparison between the two types?
Comment: @Jaroslav this is the answer. Slap that down at the bottom so we can give you credit :)
Answer: ASP.NET creates it's own type inherited from user controls.
For comparisons use the is operator.
For extractions use control.GetType().BaseType.
Comment: The only problem with this seems to be that calling .BaseType on a native control returns "WebControl". So for instance for a control which is a TextBox, control.GetType().BaseType is "WebControl". Any thoughts?
Comment: Based on naming conventions, classname should not contain `_`. So if the type `EndsWith("_ascx")`, you can be pretty sure it is a user control and extract the name as explained in my answer.
Answer: Your post doesn't quite go into how you are intending to use this, but I never had any problems with typeof() being used in my events.  For example, I would have the following if-statement in an event dealing with hovering:
if (sender.GetType() == typeof(Transparent_Panel))

where Transparent_Panel was a custom user control.  I never did any special under-the-hood work with Tansparent_Panel to make this work.
Answer: You could try using the keyword is. It's not quite the same thing but if all you are trying to do is determine if an object is of a certain type (or extends/implements a class/interface) then that should do the trick.
Of course depending on your code this may not help.
Comment: I just had this problem today and (myControl is TypeICareAbout) worked. The "is" keyword checks to see if the variable can be cast to the desired type without throwing an error. See: http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.80).aspx
Answer: ASP.NET 2.0 and later will compile the UserControl to the Temporary ASP.NET Files directory on-demand, so the type you are inspecting when you look at the type of the control in the debugger is being automatically generated by the ASP.NET compilation engine. The good news is that this type inherits from the DatePicker type, so the following code should work to test whether a given UserControl is actually a DatePicker:
typeof(DatePicker).IsAssignableFrom(userControl.GetType().BaseType)

Alternatively, you could always create an instance of the DatePicker UserControl at runtime and check for type equivalence via:
LoadControl(typeof(DatePicker)).GetType() == userControl.GetType()

Sources: Compilation and Deployment in ASP.NET 2.0


Computing $E[1/X]$ for binomial $X$

Question: Let $X$ be a binomial distributed with parameters $n$ and $p=1/k$. Then we have $E[X]=n/k$. But what is $E[\dfrac{1}{X}\mid X>0]$? Is there a nice closed formula getting the exact value or approximation?
Comment: Related: http://math.stackexchange.com/questions/154060/sum-with-binomial-coefficients-sum-k-1m-frac1km-choose-k
Answer: I don't know a closed formula for this, but you could simply calculate it as $E[\frac{1}{X}|X>0]=\sum\limits_{i=1}^n i^{-1}\frac{B(i;n,p)}{1-B(0;n,p)}$
Answer: I know this is old but I wanted to save others time. There is no known closed form solution, but bounds can be placed. (You've already seen that it can be found numerically)
Jensen's inequality provides a lower bound.
$$E[1/X]\ge E[X]$$
I never found an upper bound but Wikipedia does offer a citation for establishing the rough order of an upper bound:
$$E[1/(1+X)] \approx O(1/np)+o(1/n)$$
https://en.wikipedia.org/wiki/Inverse_distribution#Reciprocal_of_binomial_distribution
https://en.wikipedia.org/wiki/Jensen%27s_inequality

Computing $E[1/X]$ for binomial $X$


How to change the label of username field on all forms/pages that it occurs?

Question: The following snippet changes the label of the username field on the user registration form from 'username' to 'nick-name' (when inserted into the template.php of the theme:
function my_theme_form_user_register_form_alter(&$form, &$form_state, $form_id) {

    $form['account']['name']['#title'] = t('nick-name');

}

To be consistent I'd like to change the label everywhere that it occurs in the system, such as the user settings form... how do I do that!
Answer: Add the following code at the bottom of the settings.php file:
 $conf['locale_custom_strings_en'][''] = array(
   'username'      => 'nick-name',
 );

As alternative, you can use the String Overrides module.

Provides a quick and easy way to replace any text on the site.
Features

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
Comment: Altering the files of a third-party theme/module, or any Drupal core files is never a good idea. It is the beginning of the maintaining nightmare, as all times the theme/module is updated, you need to edit the new revision of the files to introduce again the changes you put. You could alter a form within a custom module, but in this case there is already a module that can be used.
Comment: Both great answers! Thank you. I'm guessing that placing something in the settings.php is more efficient but the module is easier for clients to maintain.... Either way far better than changing theme templates that may get overwritten on updates.


How can I fit in a linear model with specifiy level of a factor in R?

Question: Stfmodel1<-lm(SATISFACTION~AGE+SEVERITY+ANXIETY+SURG,data=Stf)
SURG is a factor variable with levels "Yes" and "No"
This is my code and I want to fit in a linear model with SURG = yes and SURG = NO separately, could anyone tell me how can I do that?
Answer: This was probably more appropriate as a Stack Overflow question but I write the solution for you here. You can achieve what you want by the following codes:
Stfmodel1 <- lm(SATISFACTION~AGE+SEVERITY+ANXIETY, data=subset(Stf, SURG=="Yes"))
Stfmodel2 <- lm(SATISFACTION~AGE+SEVERITY+ANXIETY, data=subset(Stf, SURG=="No"))

Comment: Thank you so much!
Comment: Would you accept the answer by clicking the tick sign on the left?


View to show 2 different fields that have multiple values next to each other

Question: I have a content type that has 2 fields on it:

image (multiple values)
image description (multiple values)

I have 6 images and 6 descriptions. I want to use a view to show each image with each description. I have tried playing around with the "Display all values in the same row" settings but just can't get this to work. It displays the same image repeatedly (6 times) and then the descriptions are all correct, then repeats the next image 6 times again.
I am tearing my hair out here, how do I get a view to simply out output:
Image 1, Description 1
Image 2, Description 2
and so on?
I have included an image of current output plus the way the fields were set up on the node. I have set them up this way as I need to import a lot of them.
Comment: A small suggestion, it might better and easier to achieve this functionality using either Field Collection or Paragraph modules.
Answer: As commented there might be better data models. But in case you can't change the data model it's probably the easiest solution to switch the View to display content in a view mode and display the field deltas in a node template:
node--content-type--view-mode.html.twig
{% for key, item in content.field_image if key|first != '#' %}

  {{ item }}

  {{ content.field_description[key] }}

{% endfor %}

Answer: As already suggested the most sensible way would be to use the Alt text field for each Field value. You can still import the images with matching textual descriptions into a Single field with multiple images (each image with its own description).
But there is fix you can use if you want to keep the structure - "manually" add all the relevant information to display in Views results.
Multiple value Fields have delta info that records the order/placement of each value.
As you know in Views these types of Fields have Multiple field settings where you can Display all values in the same row.
This is what you want to do here, but only display one value at a time. First add the File field showing the first image only, then add Description field showing the first description only, then add File field again showing the second image, then add the Description field again showing the second description only and so on until you've shown all of them:
First image and Description:

File: Display 1 value(s) starting from 0 (first item is 0)
Description: Display 1 value(s) starting from 0 (first item is 0)

Second image and Description:

File: Display 1 value(s) starting from 1 (first item is 0)
Description: Display 1 value(s) starting from 1 (first item is 0)

Third image and Description:

File: Display 1 value(s) starting from 2 (first item is 0)
Description: Display 1 value(s) starting from 2 (first item is 0)

etc...
Comment: Yes, I did exactly this, and went through them all one by one. The reason I didn't use Field Collection, which to me is the most obvious, is because I build sites around feeds importer so I can upload all data through this. Field collections requires a second importer which is a pain.


How do I add a class to elements preceding a clicked class?

Question: I have the following HTML in which I am building up star-based voting. I want it to where if the user clicks on the fourth star all the stars up to and including the one they clicked have the new class that would show the stars "lit up" such that they have the CSS class called jquery-ratings-full?

Comment: look at `.prev()` or `.prevAll()` in jQuery
Comment: Or use Pure CSS: http://kubyshkin.ru/posts/star-rating-input-pure-css.html
Answer: You can select previous siblings with .prevAll and following siblings with .nextAll:
$('.jquery-ratings-star').click(function() {
    $(this)
      .prevAll().addBack().addClass('jquery-ratings-full').end().end()
      .nextAll().removeClass('jquery-ratings-full');
});

Comment: @Terry: Better in terms of what? There are so many ways to do a thing ;)
Comment: Wouldn't it be better if you remove class for everything, i.e. `$(this).siblings().addBack().removeCLass('...').end()` and then add classes to the previous elements? :)
Answer: .prevAll() - selects all the previous siblings
.addBack() - adds the this element to the selection, so you also fill the clicked star.
You can first remove the fill from all stars, but this is not necessary if the user can't change it's vote (rate again).
$('.jquery-ratings-star').click(function(){
   $('.jquery-ratings-star').removeClass('jquery-ratings-full');
   $(this).prevAll().addBack().addClass('jquery-ratings-full');
});

Working demo: http://jsfiddle.net/P8wrM/2/
Answer: I haven't double checked, but something like this ought to do the trick.
var stars = $(#starRating).children('img');

stars.click(function(e){
  var clickedIndex = $(e.target).index();

  // If you want user to be able to click a different star,
  // after they've already clicked one, do this first

  stars.removeClass('selected')

  // Apply selected class to every star at or below the clicked index

  stars.each(function(){
    if ($(this).index() <= clickedIndex){
      $(this).addClass('selected');
    }
  });

  // Set a callback function to track or process rankings, if needed

  optionalCallback(clickedIndex);
});

Comment: Really? I really like my code comments in all caps.. because my code is never in caps so it helps my eyes see the comments even if they're deep in the code...

Didn't realize that was a faux pas... :\
Comment: FYI, `stars` is already a jQuery object, so you can replace `$(stars)` with `stars` (there is no point to pass it to jQuery *again*, or would you do `$($('#foo'))`?) The outer `.each` loop is completely unnecessary, just do `stars.click(...)`. The inner `.each ` loop can be simplified to `stars.slice(0, clickedIndex + 1).addClass('selected');`.
Comment: My comments ARE screaming in pain, because I wrote them so hard!!
Comment: Ok, I yield. Comments and downvotes have forced me to update my answer. Hopefully its not quite so disappointing to everybody now...


Conditions for Central Limit Theorem for dependent sequences

Question: Cumbersome technical assumptions (e.g., mixing properties) are used in the literature to prove Central Limit Theorems for dependent sequences. I sketched a proof that does not require any of these technical assumptions. Can you help me figure out what is wrong with this proof? The proof is at: http://www.statlect.com/central_limit_theorem_for_correlated_sequences.htm. Thanks in advance to all those who will be so generous and patient to read it.
Comment: One thing that is not explicitly stated is that $V$ needs to be finite, so you would have to impose some sort of conditions on the covariance structure.  This is usually what those "technical conditions" are doing, making sure that the variance doesn't get "too big"
Comment: @user4422, hand-waving is good, but I did not see any proof. All the technical details usually come up, after you start to write rigorous proof. As the text stands now it is just an idea or strategy of proof, not a proof. The 2 things which stand out is the first claim that omiting some elements changes nothing, another thing is the claim that the remaining sequence is iid, it is not and assymptotic closeness to iid does not immediately allows application of CLT for iid variables.
Comment: OK. Right, we must ensure that V stays finite. Is there any counter-example where V goes to infinity for a stationary ergodic process?
Comment: The link does not seem to work properly any more. Equations are not displayed so it is not possible to follow the proof. Would it be possible to post the proof here instead of a separate website?
Answer: Additional conditions are needed. (A near-proof of this fact is that many incredibly smart individuals have been thinking deeply about these issues for over 100 years. It is highly unlikely that something like this would have escaped all of them.)
First of all, note that the formula for $V$ that you give is part of the conclusion of the associated central limit theorem. See, for example, Theorem 7.6 on pages 416–417 of R. Durrett, Probability: Theory and Examples, 3rd. ed., which based on your link, you appear to have access to.
At any rate, here is a simple counterexample to your claim.

Let $X_0$ equal $+1$ with probability $1/2$ and $-1$ with probability $1/2$. Define $X_n = (-1)^n X_0$. Then $\{X_n\}$ is a stationary ergodic process with mean 0 and variance 1, but the Central Limit Theorem fails.

The properties of stationarity and ergodicity should be pretty easy to see as we can construct this process by defining a function over the states of a two-state Markov chain with stationary probability measure $\pi(x) = 1/2$ for $x \in \{0,1\}$.
Observe that this process yields a sequence of the form $-X_0, X_0, -X_0, \ldots$ and so

Even without appealing to any notions about ergodicity, it is easy to see that $\newcommand{\e}{\mathbb{E}}\bar{X}_n \to \e X_0 = 0$ almost surely, and,
$\newcommand{\Var}{\mathbb{V}\mathrm{ar}}\Var(S_n) = 0$ if $n$ is even and $1$ if $n$ is odd.

This already is enough to conclude that there is no way that any rescaling of $S_n$ can make it converge in distribution to a normal random variable. In fact, for every function $f$ such that $f(n) \to \infty$, $S_n / f(n) \to 0$ almost surely no matter how slowly $f$ diverges.
Note also that this example should make it clear that the formula for $V$ is a conclusion of the theorem. Indeed, for the example above,
$$
V_n = 1 + 2 \sum_{i = 1}^n \e X_0 X_i = \left\{
\begin{array}{rl}
-1, & n \text{ odd}, \\
1, & n \text{ even},
\end{array}
\right.
$$
which, of course, (a) makes no sense as a variance, (b) does not have a limit, and (c) is not asymptotically equivalent to $\Var(S_n)$. (NB: I use a slightly different form for $V_n$ than you do where mine matches that given in Durrett.)
Comment: First of all thanks for your long and careful answer, I really appreciate that. As for the example, it is very interesting, but I am struggling to understand why the process is ergodic: the notion of ergodicity I have in mind, coupled with stationarity, implies strong mixing, i.e. asymptotic independence of the terms of the sequence, which in this example seem perfectly dependent.
Comment: Sorry, I was wrong again. Mixing is stronger. Then it might be ergodic even if it's not mixing.
Comment: OK. Now I understood why it is ergodic. Trivially all shift invariant subsets have either probability zero or one.


Composite relation of R

Question: I'm new to relations in discrete mathematics and I am having a hard time understanding how to do this exercise.
Let $R$ be a binary relation on the set of integers such that $(a,b) \in R$ if and only if $b-a=1$. What is the composite relation $R \circ R$?
Comment: What have you tried? See [How to ask a good question](https://math.meta.stackexchange.com/questions/9959).
Comment: See [Composition](https://en.wikipedia.org/wiki/Composition_of_relations#Definition): $(a,c) \in R \circ R \text {  iff  } (\exists b \ (a,b) \in R \text { and } (b,c) \in R)$.
Answer: The composite relation $R \circ R$ consists of those pairs $(a,c)$ such that there is a $b$ where $(a,b)$ and $(b,c)$ are both members of $R$.  Suppose I give you a number $a$.  How many pairs $(a,b) \in R?$
Comment: To me it seems logical that there is as many pairs of $(a,b) \in R$ that there is elements in R
Comment: That is correct, but I was asking for a specific $a$. how many pairs are in $R$
Comment: Since $R$ is an infinite set I would think there would be an infinite number of pairs
Comment: I was trying to suggest you think about how many pairs there were with a given first element, leading to the solution Hagen von Eitzen gave.
Answer: By definition, $a\mathrel{(R\circ R)}b$ iff there exists $c$ with $a\mathrel R c$ and $c\mathrel R b$, The latter means $c-a=1$ and $b-c=1$, hence $b-a=2$. We conclude that $a\mathrel{(R\circ R)} b$ iff $b-a=2$ - at least provided that in our underlying set, we always have $a+1$ in int whenever $a$ and $a+2$ are in it!

Composite relation of R


Cocomplete concrete category, morphism of sheaves on a space is an isomorphism iff every induced map on stalks is an isomorphism

Question: Reading Hartshorne, I had this question:
Suppose $F$ and $G$ are $C$-valued sheaves on a space $X$, where $C$ is a cocomplete concrete category. Is it the case that $\phi:F→G$ is an isomorphism iff each induced map from $\phi$ on stalks is an isomorphism?
Hartshorne's proof assumes $C(A,B)^x=C(A,B)\cap Set(A,B)^x$, where $C(A,B)^x$ denotes the isomorphisms from $A$ to $B$.
What if we don't even assume $C$ is concrete?
Thank you!
Comment: This question and the [other one](https://math.stackexchange.com/questions/222896/a-property-of-a-sheaf-in-an-arbitrary-category) are different: the current question is asking about joint conservativity of the stalk functors, while the other one is asking about joint faithfulness. Also, of course, Hartshorne's assumption just means that the forgetful functor from $C$ to $Set$ is conservative. While faithfulness and conservativity are related, they are in general distinct concepts.
Comment: That is strange, that Hartshorne writes that $C(A,B)^\times=C(A,B)\cap\operatorname{Set}(A,B)^\times$, since there are many cocomplete concrete categories for which this is not true. (The standard example is when $C$ is itself the category of topological spaces and continuous maps; then this says that a homeomorphism is the same thing as a continuous bijection, which is incorrect.) But $C(A,B)^\times\subseteq C(A,B)\cap\operatorname{Set}(A,B)^\times$ would be correct.
Comment: There is a proof at https://math.stackexchange.com/questions/222896/a-property-of-a-sheaf-in-an-arbitrary-category (thanks to Alex Kruckman's answer for linking this). If I understand your question correctly, it is (other than the confusion from trying to understand Hartshorne's assumption) a duplicate of that question, so see if that helps you.
Comment: Hartshorne does not write this, nor does he talk about cocomplete concrete categories in general. He's simply presuming that isomorphisms are precisely the bijective morphisms. Your observation that $C(A,B)^x \subset C(A,B)\cap Set(A,B)^x$, but not necessarily the other way around, is the motivation for my question.
Comment: @GeoffreyTrang :  Yes, you're right, thanks for clearing up my confusion.
Answer: In analogy with topos theory, we could say that the category $\text{Sh}(X;\mathcal{C})$ has enough points if your condition holds: For all $\mathcal{C}$-valued sheaves $F$ and $G$ on $X$, a map of sheaves $\varphi\colon F\to G$ is an isomorphism if and only if for all points $x\in X$, the induced map on stalks $\varphi_x\colon F_x\to G_x$ is an isomorphism.
The question of when a category of $\mathcal{C}$-valued sheaves on a space $X$ has enough points seems to be delicate. See Zhen Lin's answer here: A property of a sheaf in an arbitrary category, and see the nLab for information on the notion of a topos having enough points. Hopefully someone who knows more about this topic than I do can provide more information.
Comment: +1, this is good information. As someone who previously wrote a wrong answer to this question I agree with your final sentence. For others who are curious about a non-example of the mentioned property, there is an example of a topos with no points [here](https://sinhp.github.io/scribbling/22-11-2017-a-topos-without-points) which
is fairly readable.
Comment: Depending on what $\mathcal C$ is, $\operatorname{Sh}(X;\mathcal C)$ may not be a topos at all. The linked nLab article is only about toposes (although the terminology 'enough points' is probably good terminology in any case).
Comment: Thank you, Alex!
Comment: Toby, I know nothing about topoi. If $C$ is cocomplete and concrete, is $Sh(X,C)$ a topos?
Comment: @TobyBartels Good point, thanks for pointing it out! I've edited. catagoricalimperative: If $X$ is the one-point space, then $\text{Sh}(X,\mathcal{C})$ is isomorphic to $\mathcal{C}$. So in general, $\text{Sh}(X,\mathcal{C})$ is not a topos unless $\mathcal{C}$ is.
Comment: @categoricalimperative :  A topos can be thought of as (among other things) a category of the form $\operatorname{Sh}(X,\operatorname{Set})$ for some $X$.  The most famous example is $\operatorname{Set}$ itself (which is $\operatorname{Sh}(X,\operatorname{Set})$ when $X$ is a one-point space).  More generally, $\operatorname{Sh}(X,C)$ is a topos whenever $C$ is (and Alex gave a converse to this).  This concept began with Grothendieck's work on algebraic geometry, but it's not central to algebraic geometry the way categories of schemes are, and it's taken on a life of its own far beyond AG.