Spring send message to Websocket Message Broker

Question: I want to send a message to websocket subscribers of a specific record - when an action takes place in one of my service class.
I'm trying to read the Spring Websocket documentation but it's kind of ambiguous to the point of how to get all these things working together.
Here are my setup files (this is extending jHipster btw):
WebsocketConfiguration.java
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/queue/", "/topic/", "/exchange/");
        config.setApplicationDestinationPrefixes("/app");
        config.setPathMatcher(new AntPathMatcher("."));
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }

WebsocketSecurity.java
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
    messages
        // message types other than MESSAGE and SUBSCRIBE
        .nullDestMatcher().authenticated()
        // matches any destination that starts with /rooms/
        .simpDestMatchers("/topic/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
         .simpDestMatchers("/topic/**").authenticated()
        // (i.e. cannot send messages directly to /topic/, /queue/)
        // (i.e. cannot subscribe to /topic/messages/* to get messages sent to
        // /topic/messages-user<id>)
         .simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll()
        // catch all
        .anyMessage().denyAll();
}

Controller class (attempt at implementing a simple broker I can test subscribing to from sockjs and recieving messages generated elsewhere in the application:
@MessageMapping("/ws")
@SendTo("/topic/sendactivity.{id}")
public void activity(@DestinationVariable string id, @Payload String message){
    log.debug("Sending command center: "+message);
}

@RequestMapping(value = "/updateactivity", method = RequestMethod.PUT)
public ResponseEntity<Membership> updateMembership(
        @RequestBody Membership membership) throws URISyntaxException {
    // ...
    String testString = "test";
    messagingTemplate.convertAndSend("/topic/commandcenter"+membership.getId().toString(), testString);
    // ...
}

When I put a breakpoint on the public void activity method, I don't get anything?
Comment: Could you share the sockJS client logs? There's no way to see which message was sent and what response it got in return. Could you also put `org.springframework.web.socket` in DEBUG and share the relevant logs as well?
Comment: @BrianClozel - I haven't even subscribed to the channel yet - would that cause it not to be active?! I thought after I ran `convertAndSend` I should hit the breakpoint in the `void activity` method?
Answer: Sending a message to "/topic/commandcenterID" using the messaging template will send that message to the message broker, which will dispatch that message to clients subscribed to that topic. So it won't flow through your activity method.
When using @MessageMapping annotated methods, you're declaring those as application destinations. So sending a message to "/app/ws" should map to that method. Note that in that case I doubt it'll work since the destination variable you're expecting as a method argument is missing from the path definition in the @MessageMapping annotation.
Also, the @SendTo annotation in fact tells Spring that the value returned by the method should be converted to a message and sent to the given destination.
It seems you're mixing things up here, and I think you should:

read carefully the flow of messages in Spring STOMP support
look at a few example apps like the websocket portfolio and websocket chat


When is a mySQL permission error not a permission error

Question: So I've been going sort-of crazy for the past few days.  I've got a mac, OSX 10.6.4, and I HAD mySQL running on it.  At some point after the 10.6.4 update, mySQL stopped working.  I got an error telling me that mySQL couldn't find the mysql.sock file.
I've uninstalled/reinstalled mySQL a couple of times and nothing is helping.  if I run the mysqld coommand in my bin directory I get a bunch of errors that lead me to believe there was a permission error on the data directory, but data is owned by mysql...so I'm lost.  I'm not really a DB guy, I just need one on my machine for connecting to wordpress and things like that.
This is everything out of local.err
101007 21:47:34 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql-5.5.6-rc-osx10.6-x86_64/data
error: Found option without preceding group in config file: /etc/my.cnf at line: 2
Fatal error in defaults handling. Program aborted
101007 21:47:34 mysqld_safe mysqld from pid file /usr/local/mysql-5.5.6-rc-osx10.6-x86_64/data/JoeC.local.pid ended
101007 21:48:20 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
101007 21:48:20 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/mysql/data/ is case insensitive
101007 21:48:20 [Note] Plugin 'FEDERATED' is disabled.
InnoDB: The InnoDB memory heap is disabled
InnoDB: Mutexes and rw_locks use GCC atomic builtins
InnoDB: Compressed tables use zlib 1.2.3
InnoDB: The first specified data file ./ibdata1 did not exist:
InnoDB: a new database to be created!
101007 21:48:20  InnoDB: Setting file ./ibdata1 size to 10 MB
InnoDB: Database physically writes the file full: wait...
101007 21:48:20  InnoDB: Log file ./ib_logfile0 did not exist: new to be created
InnoDB: Setting log file ./ib_logfile0 size to 5 MB
InnoDB: Database physically writes the file full: wait...
101007 21:48:20  InnoDB: Log file ./ib_logfile1 did not exist: new to be created
InnoDB: Setting log file ./ib_logfile1 size to 5 MB
InnoDB: Database physically writes the file full: wait...
InnoDB: Doublewrite buffer not found: creating new
InnoDB: Doublewrite buffer created
InnoDB: 127 rollback segment(s) active.
InnoDB: Creating foreign key constraint system tables
InnoDB: Foreign key constraint system tables created
101007 21:48:21 InnoDB 1.1.2 started; log sequence number 0
101007 21:48:21 [ERROR] Can't start server : Bind on unix socket: Permission denied
101007 21:48:21 [ERROR] Do you already have another mysqld server running on socket: /var/mysql/mysql.sock ?
101007 21:48:21 [ERROR] Aborting

101007 21:48:21  InnoDB: Starting shutdown...

help?
Answer: Check if the mysql process is currently running
ps -ef | grep mysqld

Does that give you any output?  If it is not the just the grep command itself then the process is still running.
Next check if mysql has any files open
lsof | grep mysql

Does that give you any output?  This is a list of files open by mysql.  It may explain why it is hanging around for.
Have you restarted your machine?  (You shouldn't need to - but you may have a process hanging around)
Answer: 1.) Either MySQL is running
or
2.) Your not running MySQL as a user with correct permissons
    try sudo first before the command.. so running it as root..
    My mac asks for a password - whereby it can run it as the correct user
Hope this helps :D


Indicating a "canonical" record in a one-to-many table

Question: Imagine we have a table of countries, and a table of cities.  A country can of course have many cities, but a city can only be in one country, thus a one-to-many relationship makes intuitive sense:
countries
| id | name    |
|  1 | Lorwick |
|  2 | Belmead |

cities
| id | country | name        |
|  1 |       1 | Marblecrest |
|  2 |       1 | Westacre    |
|  3 |       2 | Belcoast    |
|  4 |       1 | Rosemarsh   |
|  5 |       2 | Vertston    |

But in addition to our one-to-many relationship, we want to describe the one-to-one relationship of national capitals.  If it matters, assume that capitals may change fairly regularly, and for that matter cities appear and vanish at will, and that cities may switch countries.  Point is, this data is unstable.
I see a couple of options:

Add an int column capital to countries which cannot be null.  Pro: always exactly one city; Con: not associated with the city, nothing enforcing the city is in the country, or that it even exists.
Add a boolean column capital to cities, which if true indicates the city is the capital of the associated country.  Pro: directly associated with the city in question, no duplicate columns indicating hierarchy; Con: pretty sure this is poor normalization as there's nothing stopping there being zero, or more than one, "capital" for a given country.
Create an additional table capitals with columns country and city and a unique constraint on both columns (or at least on city).  Pro: feels cleaner, easy joining on either countries or cities; Con: still doesn't ensure city is in country, or that either exist.

What is the most normalized and/or best way to represent this relationship?  Is there any way to ensure each country has exactly one capital which does in fact exist and resides inside that country?  I imagine it's not possible, in which case, how can I best minimize issues for my client code?
I'm currently using SQLite, but I'm interested in generalized answers, regardless of the underlying database.
I did a little digging and found Indicating primary/default record in database but I don't think this really answers my question.

PS: It's not that bad if there's no capital (there may be no cities!), but it would be bad if there were multiple.
Answer: I think the requirement "each country has exactly one capital" conflicts with the requirement "cities appear and vanish at will". If a city can vanish, it follows that a capital city can vanish, too.
You can enforce the constraint "each country has [zero or] one capital which does in fact exist and resides inside that country" with a foreign key constraint on a table of capitals.
create table capitals (
  country_id integer primary key,
  city_id integer not null,
  foreign key (country_id, city_id) references cities (country_id, city_id)
);

In that table, the primary key constraint guarantees that there can be no more than one capital per country. The foreign key constraint guarantees that that the capital you choose exists in the country you choose. In the referenced table (the "cities" table), you also need a unique constraint on {city_id, country_id}; since {city_id} is unique in the "cities" table, {city_id, country_id} will necessarily be unique in that table, too, so that's not a problem.
The declarative "way" to guarantee a one-to-one relationship between countries and capitals (not a one-to-zero-or-one relationship) is to use an assertion. But I don't know of any current SQL dbms that supports CREATE ASSERTION. That forces us rely on one or more of these:

triggers and possibly deferred constraints,
application code, or
administrative procedures.

(Initially, you'd have to enter a row in the three tables "countries", "cities", and "captials" in a single transaction in order to satisfy all the constraints. I think you'll need deferred constraints for that, but I haven't had coffee yet today.)
Answer: For clarity and simplicity, I'd add the boolean IsCapital column to the cities table. Then add a trigger that sets all other cities (that share the updated record's country) IsCapital = false when IsCapital is set to true on a record. This will handle most of your concerns. The one case to ensure there is exactly one capital per country isn't really possible, you can ensure there is 0 or 1, but since the cities table has a FK constraint to countries, there is always going to be a point in time where inserted countries will have no cities that can be set as the capitol.
FWIW, I think logic should be left to the app, referential integrity to the database.
Comment: I just did a search for similar questions and found this answer
http://stackoverflow.com/a/638947/45767
(His answer reinforces why I think logic belongs in the app)
Answer: To make sure there is exactly one capital per country and the capital is not a city from a different country, do this:

Note how we use the identifying relationship to migrate the COUNTRY_ID to CITY's PK, so it can be migrated back to the CONTRY - this is what guarantees a capital must actually belong to the country it is the capital of.
The circular reference here prevents the insertion of new data, which is resolved using deferred foreign keys if the DBMS supports them. Otherwise, you can just leave COUNTRY.CAPITAL_NO NULL-able (and enforce its eventual non-NULL-ness at the application level).1

1 This assumes the DBMS has MATCH SIMPLE foreign keys (i.e. FK is ignored if any of its components are NULL). If the DBMS supports only MATCH PARTIAL or FULL (such as MS Access), you are out of luck, and would have to emulate the FK through non-declarative means (triggers or application code).


Finding script trying send spam via postfix

Question: I have had this problem before with crap wordpress sites on my server but it was always easy to find the source, a php script by looking at the spam header and see the php scripts name. But this time I got something different.
The spam isn't being sent actually, it's being dropped by postfix but it originates from localhost and I need to find where it comes from.
Dec  8 13:02:29 myserver postfix/smtpd[22018]: NOQUEUE: reject: RCPT from myserver.local[127.0.0.1]: 550 5.1.0 <email@example.com>: Sender address rejected: User unknown in virtual mailbox table; from=<email@example.com> to=<firstname.lastname@example.com> proto=ESMTP helo=<domainonmyserver.tld>

As you can see it tries to send under a phony account so it gets dropped. Before I fixed my postfix settings it was actually trying to send these out so I got a look at the spam itself and it didn't have a header in indicating a php script somewhere (that was a first, they always did before). Another strange thing is that it doesn't try to flood postfix with spam, instead it is sending them out one or two a minute.
Any idea how to track the source down would be appreciated. Thanks.
Answer: Auditd Logging
Assuming this is not occuring through a network socket (given your php header is not working), I would log all access to postfix itself.  Create auditd rules that log all access to the postfix binaries.
Get a list of all the postfix files
rpm -ql postfix | egrep "postfix|sendmail" | grep bin

then generate an audit.rules file (that will likely go in /etc/audit/audit.rules, but this varies from distro to distro) that looks something like
-w /usr/sbin/sendmail -p wra -k postfix_access
-w /usr/sbin/sendmail.postfix -p wra -k postfix_access

...etc
You may have to run this to update your rules:
augenrules

To send this output to syslog/splunk:
sed -i -e 's/^active.*/active = yes/g' /etc/audisp/plugins.d/syslog.conf

Then restart auditd.
This may give you more clues about what is calling postfix at the time the emails are being generated.
Answer: First, you should add mail.add_x_header option to your php.ini
mail.add_x_header = On

It will add a header to your emails, which will contain name of the script that called mail() function.
If that won't help, you can follow this tutorial to create a wrapper to sendmail, which will also log everything.
Comment: It is enabled, and it usually works too, but not this time as I said in the OP.


How to select a column corresponding to max value (SQL - impala)

Question: I checked history and there are some answers to similar problems but they seem to be too complicated.
I have table like this:
CUSTOMER_ID    SELLER_ID     MONTH     ITEMS_SOLD
1                A          201702      3
1                B          201702      2
2                X          201902      7
2                Y          201902      8

I would like to list columns (customer,seller and month) corresponding only to maximum items sold. The desired outcome would be:
CUSTOMER_ID    SELLER_ID     MONTH
1                A          201702
2                Y          201902

Answer: Use window functions:
select t.*  -- list whichever columns you really want
from (select t.*,
             row_number() over (partition by customer_id order by items_sold desc) as seqnum
      from t
     ) t
where seqnum = 1;

Note:  If multiple months have the same maximum for a customer, this arbitrarily chooses one of them.  If you want all of them, then use rank() instead of row_number().
Comment: Worked like a charm. You are a legend.


Powermock/Easymock tests take 10x as long when not on VPN

Question: I'll be as specific as I can with this...
Basically, the current unit tests for a large java project take around 19m30s to run when not on an OpenVPN network. When on the OpenVPN network, the tests take about 2m0s to run. Why is this?
From what I can tell, there are no external calls being made. One specific test takes 1m36s off VPN and then 1s when on VPN. Are the tests written inefficiently? Where should I start looking to improve the time it takes off the VPN? What could cause issues like this?
We are using Powermock and Easymock to do the unit tests. The specific test above uses an in-memory database.
Comment: You don't run tests "on a network". Where are the tests being run? What do you mean by "on" or "not on" the network? (And have you profiled the tests to see which ones are slow?)
Comment: are there host names involved that only resolve when connected to the OpenVPN?
Comment: @JochenBedersdorfer how would I find this out? what I mean is that I'm running the tests through maven on IntelliJ on my local machine without being connected to a VPN for work and the tests run slow. When I connect to the VPN and run the tests in IntelliJ, the tests run much faster.
Comment: it looks like you might be running into timeout issues, i.e. some services are not available when not connected to the VPN. Often these are DNS problems. I would start with any config file that the tests are using which might be host names and check those
Answer: First of all, make sure that no network calls are made. For example, if you use SOAP services the wsdl file could be retrieved implicitly. Use wireshark, fiddler or other software for network analysis.
Secondly, run JVM profiling and see where the most of the time being spent. Having this huge difference (1 minute vs 1 second)   should be easy to pinpoint the problem.
Answer: This has nothing to do with the mocking frameworks. However the test content can cause such thing. In general it is caused by code trying to do DNS resolution, even for localhost (InetAddress.getLocalHost().getHostAddress()).
Your best bet is to do a bunch of thread dumps during the test and look for network code like above.
The solution is usually to add a line in /etc/hosts to resolve quickly what your test is looking for. Or to fix the network but sometimes it's not that easy.
Answer: Thanks for everyones help. It turns out that theres a bug with Mac OS X that caused the tests to initialize much slower than on linux. When I went to do integration testing with timeouts on the connection services, everything worked much faster.


HTML meta viewport content working in chrome but being igored in firefox

Question: I have a web page that has this html meta tag
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
Whenever I make the browser responsive (select a mobile phone resolution), the change I make on this meta tag is reflected in chrome, but all the values are completely ignored in firefox regardless of the values are valid or not.
I have tried adding other attributes such as minimum-scale, maximum-scale,..etc. But no luck finding a workaround or a solution for this to reflect on Firefox.
Is there a reason that would make the browser ignore such tag or its attributes?
Comment: Not a fix but note that the [](https://html.spec.whatwg.org/dev/semantics.html#the-meta-element) tag does not use and does not need a closing slash and never has in any HTML specification.
Comment: What version of Firefox? How are you "setting the resolution" in Firefox? How are you testing if the meta tag has any effect?
Comment: - Firefox version : 91.12.0esr (64-bit).
- I'm setting the resolution by Inspect Element, then on the top right corner of the Inspect Element window I select the Responsive Design Mode. After that, I choose a specific mobile phone or I set the width x height resolution manually.
- I'm testing if the meta tag has any effect as I make the changes in both chrome and firefox in the same time, and I see the change reflected in chrome and not in firefox
Comment: Actually, after some searching. I found out that this is a configuration issue in Mozilla Firefox browser.
Setting 'dom.meta-viewport.enabled' this flag in about:config just solve the issue.
I'll post it as an answer.

Also, I'll be creating a new issue as it still occurs on apple devices.
Answer: 1- Open Mozilla Firefox
2- Go to about:config
3- Search for dom.meta-viewport.enabled
4- Change the flag value to true
5- It should work now.


Como acessar um ponteiro dentro de uma estrutura de ponteiro

Question: Eu sei que para acessar uma variável normal dentro de uma estrutura de ponteiro eu posso utilizar essa sintaxe:
struct teste {

    int valor;
    int *aponta;

};

struct teste testando, *testado;
testado = &testando;
testado -> valor = 10;

Porém, como acesso o ponteiro aponta que está contido na estrutura, utilizando o ponteiro testado?
Answer: Para fazer esse ponteiro apontar para algum lugar:
int teste2 = 123;
testado->aponta = &teste2;

Para alterar o valor do que é apontado:
*(testado->aponta) = 456;

E para ler o valor da variável:
*(testado->aponta)

Veja aqui um teste com o código completo:
#include <stdio.h>

struct teste {
    int valor;
    int *aponta;
};

int main() {

    struct teste testando, *testado;

    testado = &testando;
    testado->valor = 10;
    int teste2 = 123;
    testado->aponta = &teste2;
    *(testado->aponta) = 456;
    printf("%d %d", teste2, *(testado->aponta));
}

A saída é 456 456. Veja aqui funcionando no ideone.
Comment: @gato O parêntese serve para agrupar subexpressões. É o mesmo parêntese usado em `3 * (2 + 4)`. O operador unário `*` é o operador de dereferência e é usado para acessar o conteúdo de um ponteiro.
Comment: Isto seria um operador `*(ptrStruct->member)`? Se sim, qual seria o nome dele? Não entendi o motivo de ter que envolver em parentese `()`  seguido de um asterisco `*` a estrutura.
Comment: Valeu mesmo, eu não encontrei a resposta em outros locais, era quase meio obvio. É só colocar parenteses para respeitar a ordem de procedência e inserir o asterisco para pegar o valor de referencia;


How do I call an entity method in a TYPO3 fluid template?

Question: I have a template with a line like this:
<f:format.htmlentitiesDecode>
    {product.features}
</f:format.htmlentitiesDecode>

where "features" is an attribute of the "product" data model.
I would like to print the result if a method call on product instead. Something like:
<f:format.htmlentitiesDecode>
    {product.getStrippedFeatures}
</f:format.htmlentitiesDecode>

but that gives me empty content.
How can I call a method in the product model and print its output?
Answer: Just add the function in your product model like:
public function getStrippedFeatures()
{
    return your_stripping_method($this->features);
}

Fluid calls attributes with a prefixed get, so you only need this in the template:
{product.strippedFeatures}

Comment: Fluid also looks for the prefixes `is` and `has`.
Comment: Meh I was too late^^
Comment: Also noteworthy: If your method is called `isRoot` or `hasStrippedFeatures` then imho *unintuitively* you have to use `{root}` and `{strippedFeatures}` in fluid (I think `{isRoot}` and `{hasStrippedFeatures}` would have been the far better choice).
Comment: The part that fluid calls attributes with a "get" prefix did the trick - **thanks**! I thought about adding a viewhelper but its working now. ViewHelper: (http://stackoverflow.com/questions/24612883/how-to-access-a-method-and-pass-an-argument-within-the-template)
Comment: Early bird and worms. :)
Comment: Could be good to know that the Getter needs to be public in order for this to work


Parse JSON Multiple values into Rows

Question: Requirement: Parse JSON values into rows
JSON:
    {
      "uid":"2EDA9DC1D4",
      "m_lg_loc": "ml_0_49_2965_12990434_1450,ml_0_49_2965_12991888_1450,ml_0_49_2965_12997254_682,ml_0_49_2965_12997940_453",
      "codec": "PMMMU,G726-32,PMMMA,A729a,tel",
      "trv_dev": "1,10,2",
        "geoipp": {
        "area_code": 703,
        "location": [
          -77.2223,
          38.94990000014
        ]
      }
    }

Expected Output:
Need m_lg_loc multiple values into rows
ml_0_49_2965_12990434_1450
ml_0_49_2965_12991888_1450
ml_0_49_2965_12997254_682
ml_0_49_2965_12997940_453

Similarly for
codec
    PMMMU
    G726-32
    PMMMA
    A729a
    tel

location
-77.2223
38.94990000014

Tried:
select JSON_EXTRACT_PATH_TEXT($1, uid) as uid
      ,JSON_EXTRACT_PATH_TEXT($1, 'm_lg_loc') as m_lg_loc
 from /path/abc.json (FILE_FORMAT=>JSON_FORMAT)

Answer: You can do this all in one step using a LATERAL FLATTEN:
WITH x AS (
SELECT parse_json('{
      "uid":"2EDA9DC1D4",
      "m_lg_loc": "ml_0_49_2965_12990434_1450,ml_0_49_2965_12991888_1450,ml_0_49_2965_12997254_682,ml_0_49_2965_12997940_453",
      "codec": "PMMMU,G726-32,PMMMA,A729a,tel",
      "trv_dev": "1,10,2",
        "geoipp": {
        "area_code": 703,
        "location": [
          -77.2223,
          38.94990000014
        ]
      }
    }') as js)
SELECT js:uid::varchar, js:m_lg_loc::varchar, y.value::varchar
FROM x,
LATERAL FLATTEN(INPUT => split(x.js:m_lg_loc::varchar,',')) y;

Answer: You can use SPLIT_TO_TABLE to do what you want. Here's an example:
create temporary table foo(v variant);

insert into foo select parse_json('    {
      "uid":"2EDA9DC1D4",
      "m_lg_loc": "ml_0_49_2965_12990434_1450,ml_0_49_2965_12991888_1450,ml_0_49_2965_12997254_682,ml_0_49_2965_12997940_453",
      "codec": "PMMMU,G726-32,PMMMA,A729a,tel",
      "trv_dev": "1,10,2",
        "geoipp": {
        "area_code": 703,
        "location": [
          -77.2223,
          38.94990000014
        ]
      }
    }');

--Parse the property as a string.
select v:m_lg_loc::string from foo;
--Split to table
select * from foo, table(SPLIT_TO_TABLE(v:m_lg_loc::string, ','));
--Get and alias the column(s) you want
select "VALUE" as MY_COLUMN  from foo, table(SPLIT_TO_TABLE(v:m_lg_loc::string, ','));

Comment: Thanks, @Greg Pavlik, I see you inserted into a temporary table, Is it possible to get directly from stage s3 path ..Below one got me `SQL compilation error: ambiguous column name '$1'`

```select JSON_EXTRACT_PATH_TEXT($1, 'uid') as uid
       ,JSON_EXTRACT_PATH_TEXT($1, 'media_leg_locations') as media_leg_locations
       ,$1:media_leg_locations::string
FROM @stage/path
( FILE_FORMAT=>JSON_FORMAT)a
,table(SPLIT_TO_TABLE($1,'media_leg_locations'::string, ','));```
Comment: You have three parameters in your split_to_table function. You'll want to parse the JSON in $1 and assign an alias for it. Almost all the time Snowflake will let you use an aliased column name later in the SQL.

Parse JSON Multiple values into Rows


custom menu/sub-menu output

Question: what would i have to do to change the menu output structure for my theme?
this is the current structure:

                                //menu

Home

    Other Stuff

                            // sub-menu

Sub-Page 1

Sub-Page 1

what i would like to get is something like that:

Home

        Other Stuff  // the 'drop' class is for the styling of a menu item with child-items

            Sub-Page 1
            Sub-Page 2

Comment: did you get the solution? If yes then can you post the solution as an answer please..
Answer: Do you know of the nice menus module?  Nice menus will allow you to make dropdown menus without writing any code on your own.  You can also find instructions for customizing the Nice menus CSS here.
Nice menus has almost 60,000 installs as of this writing, indicating that it is likely to be supported well into the future compared to modules that aren't so popular.
Comment: mhh... not quite what i was looking for. i tried it out but i saw no option to configure the output markup to my needs. also i wanted to use my own menu css styles that i already have
Comment: What needs do you have that you weren't able to satisfy?
Comment: there's one thing that i don't need and one thing that i can't do with the plugin. i don't need the nice menu css styles because i want to use my own styles that fit into my layout and not the predefined stuff.
the thing i couldn't do (or at least i didn't find it) with the moduel is customizing the output markup so that i get the structure that i described above. and when i have the module and still have to modify my template files then i'm better off without the module because it doesn't add any useful functionality for me.
Comment: but in the meantime i have the solution for my problem (80% finished). as soon as i got it running 100% i will describe the steps i took to adjust the menu output structure to my needs.

custom menu/sub-menu output


Use getclicky to have most views nodes on home page

Question: I have installed the getclicky module and I can see the stats most views content.
How can I add that info in a view on my home page and list the top 10 nodes?
I cannot use the Statistics module.
Answer: I end up using google analytics reports. and added the top page view in my homepage.


How to write Firestore Rule to allow admin access

Question: I am trying to allow user to access their userID document and its sub collections or documents
at path:
/main-collection/{userid}
and I want that 'admin-userid' has reading permissions to all /main-collection documents and sub collections
/main-collection/{userid} as document
service cloud.firestore {
  match /databases/{database}/documents {

    match /main-collection/{userId} {
      allow read, write: if request.auth.uid == userId || request.auth.uid == 'admin-userid';

      match /{document=**} {
        allow read, write: if request.auth.uid == userId || request.auth.uid == 'admin-userid';
      }
    }
  }
}

Answer: If the user and the admin user need the same permissions to everything in the collection and the documents' subcollections:
match /main-collection/{userId} {
  allow read, write: if request.auth.uid == userId || request.auth.uid == 'admin-userid';
}

match /main-collection/{userId}/{document=**} {
  allow read, write: if request.auth.uid == userId || request.auth.uid == 'admin-userid';
}

Comment: so how you will get the variable {userId} here
Comment: Edited.  Try un-nesting the rules.


How to update mkdir in order to install express-generator without warnings?

Question: I was going to install express-generator on windows computer. I used this
npm install -g express-generator
command in cmd and it gave me this npm WARN deprecated firstname.lastname@example.com: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.) warning. Then I usednpm install mkdirp@1and successfully installed email@example.com version. CMD confirmed it showing me this message + firstname.lastname@example.com
updated 1 package and audited 1 package in 1.981s
found 0 vulnerabilities
But unfoutunately when I try to reinstall express-generator using npm install -g express-generator, cmd shows me the same warning. Exactly the same warning. How Can I update mkdirp?? Help Me..
Comment: In this case, you can't. Because the email@example.com is a dependency of express-generator package and when you install this package, npm will install all of it's dependencies automatically.
Answer: You can run the application generator with the npx command (available in Node.js 8.2.0).
$ npx express-generator

Answer: it's caused by generally access copyright;
you can avoid the access to modify directory by :
$ sudo npm install -g firstname.lastname@example.com
or the latest version to install:
Comment: nicolas alien -technology - zone 51
Answer: Run all this in window terminal CMD or powershell
Step-1 update the mkdirp.

$ npm install mkdirp@1* in CMD

Step-2 Install express globlly.

$ npm i -g express-generator* in CMD

 Now its works
Answer: Try this command(from the official website):
npm install express --save

Comment: The question is about express-generator not express itself
Answer: Use the application generator tool, express-generator, to quickly create an application skeleton.
You can run the application generator with the npx command (available in Node.js 8.2.0).
$ npx express-generator


div/input in middle of paragraph

Question: I am trying to align a div containing an input in the middle of a paragraph. Seeing as a div cannot be contained by a paragraph in a valid way, I need to make all three elements align inline-block.
The first paragraph is relatively small, the div is around 350px, the last paragraph is really long. Its that last paragraph that gives my a problem as it won't automatically word-wrap when the text reaches the end of the page - instead the entire paragraph wraps to a new line.

Blah Blah Blah Text Goes Here:

<input name="blah" value="123456yg323456y23456yr345yr3456tr3454345">

blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah

The output I am getting looks like this:
Blah Blah Blah Text Goes Here: <-------------div input goes here ------------->

blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah

I am looking for output that looks like this:
Blah Blah Blah Text Goes Here: <-------------div input goes here -------------> blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah

Removing the input from the div is not an option.
How can I properly get the desired output in a responsive manner?
Answer: Try display: inline

Blah Blah Blah Text Goes Here:

<input name="blah" value="123456yg323456y23456yr345yr3456tr3454345">

blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah

Comment: Ha that set me off in the right direction, thank you, seeing as I need a width on the div its inline, inline-block, inline.

div/input in middle of paragraph


Google Earth Engine - concatenate 'year' to iterate over a function

Question: I wanted to iterate a function taking year as an argument to get my desired Landsat collections per year. I'm concatenating argument 'yr' and iterating using .map function.
An _.concat is not a function error appears.
Any help is appreciated! Thanks!
-Nands
var per_year = function(yr){
    var start = '-01-01';
    var end = '-12-31';

    var collect = ee.ImageCollection("LANDSAT/LE07/C01/T1_RT_TOA")
     .filter(ee.String(yr).concat(start), ee.String(yr).concat(end));

    return (collect);
}

var years = ee.Array(ee.List.sequence(2006, 2012));
print (years);

var year_list = years.map(per_year(years));

Answer: You will need to map over an ee.List object that has all of the years, call the Landsat image collection in the function, and cast the results to an image collection.
var landsat = ee.ImageCollection("LANDSAT/LE07/C01/T1_RT_TOA")
var years = ee.List.sequence(2013,2017)

var yearlyCollections = years.map(function(i){
    i = ee.Number(i)
    var date = ee.Date.fromYMD(i,1,1)
    return landsat.filterDate(date, date.advance(1,'year')
})

print(yearlyCollections)

The result should be a ee.List object with the same number of image collection as years.


Estimating the distribution of a very large population of known size and unknown variance

Question: I would like to estimate the distribution of a very large population of known size but unknown mean and variance. I cannot assume anything about the shape of the underlying distribution (although I am relatively certain that it is not normal). However, I am certain that the values in the population are non-negative, non-zero integers. I believe that the distribution is naturally lumped in some way discretely rather than being continuously distributed over the entire range. I cannot sample the entire population but I would like to estimate the probability density function. I would also like some level of assurance of the correctness of the estimated distribution. What is the best way to go about this?
Comment: Are you saying you cannot draw a sample that includes every element in the population, or that you cannot draw a sample such that every element in the population has equal probability of making it into the sample?
Comment: @fgregg: I CAN draw a sample such that every element in the population has equal probability of making it into the sample but it would prohibitively expensive computationally to draw a sample that includes every element in the population.
Comment: If you'll present us with a histogram of a reasonably large sample of the population, someone will probably have suggestions as to good candidate distributions against which you can test it, and how best to do so.
Answer: Since the empirical distribution function of the sample should converge to the true population distribution function as the sample size approaches the population size, it seems to me that best estimate of the population pdf is the empirical pdf of the largest sample you an afford to draw.
Depending upon what the sample pdf looks like, you could consider summarizing the distribution with some functional form, particularly if you have some ideas about what generated the population.


Calculate $\sum_{n=0}^\infty n ( \frac{4}{5})^{n+1}$

Question: Exercise Calculate $\displaystyle\sum_{n=0}^\infty n \Big( \frac{4}{5}\Big)^{n+1}$
This is what I have so far
$$\displaystyle\sum_{n=0}^\infty n \Big( \frac{4}{5} \Big)^{n+1} = \displaystyle\sum_{n=0}^\infty n \Big( \frac{4}{5} \Big)^n \cdot \Big( \frac{4}{5} \Big)^1 = \frac{4}{5} \displaystyle\sum_{n=0}^\infty n \Big( \frac{4}{5} \Big)^n$$
I know that the series converges to $16$ but I can't quite finish this. This series is so close to being geometric if it weren't for that pesky $n$ attached to it. You could argue that the constants here are $n$ but this $n$ is always changing, so it's not quite what we want. Any advice?
Comment: Your tags suggest you are studying power series, particularly Taylor/Maclaurin series. The sum $\sum_{n=1}^\infty nx^{n-1}$ has a nice closed form for $-1 < x < 1$ (think differentiation/integration).
Comment: Not quite, but close. Try bringing $\frac{4^2}{5^2}$ out the front instead (and note that the first term of the summation is $0$ and can be ignored).
Comment: Do you mean to imply that I should consider $\displaystyle\sum_{n=1}^\infty (n-1) \Big( \frac{4}{5} \Big)^n = \displaystyle\sum_{n=1}^\infty (n-1) \Big( \frac{4}{5} \Big)^{n-1} \cdot \Big( \frac{4}{5} \Big)^1 =\frac{4}{5} \displaystyle\sum_{n=1}^\infty (n-1) \Big( \frac{4}{5} \Big)^{n-1}$ ?
Comment: Also: https://math.stackexchange.com/q/647587/42969, https://math.stackexchange.com/q/30732/42969, https://math.stackexchange.com/q/333192/42969
Answer: So , $$\sum_{n\geq0}n\left(\frac{4}{5}\right)^{n+1}=1\left(\frac{4}{5}\right)^2+2\left(\frac{4}{5}\right)^3+3\left(\frac{4}{5}\right)^4+.......\infty$$
Now , $$S=1\left(\frac{4}{5}\right)^2+2\left(\frac{4}{5}\right)^3+3\left(\frac{4}{5}\right)^4+..........\infty\tag{1}$$ $$\frac{5S}{4}=1\left(\frac{4}{5}\right)^1+2\left(\frac{4}{5}\right)^2+3\left(\frac{4}{5}\right)^3+.......\infty\tag2$$
Substract equation $(1)$ from $(2)$ . $$\frac{5S}{4}-S=\frac{4}{5}+(2-1)\left(\frac{4}{5}\right)^2+(3-2)\left(\frac{4}{5}\right)^3+..........\infty$$ $$\frac{S}{4}=\frac{4}{5}+\left(\frac{4}{5}\right)^2+\left(\frac{4}{5}\right)^3+.........\infty$$
This is nothing but Infinite GP , where $|r|<1$ as $r=\frac{4}{5}$ [note : sum of infinite GP is $\frac{a}{1-r}$]
So you get $$\frac{S}{4}=\frac{\frac{4}{5}}{1-\frac{4}{5}}\implies S=16$$
Answer: Expanding the suggestions given in the comment,
By the power series expansion we have that,
$$\frac{1}{1-x}=\sum_{k\ge 0}x^{k} , |x|<1$$
Differentiation on both sides,
$$\frac{1}{(1-x)^{2}}=\sum_{k\ge 0}kx^{k-1}$$
$$\frac{1}{(1-x)^{2}}=\frac{1}{x}\sum_{k\ge 0}kx^{k}$$
Multiply by $x^{2}$ on both sides,
$$\frac{x^2}{(1-x)^2}=\sum_{k\ge 0}kx^{k+1}$$
Now according to required question, $x=\frac{4}{5}$.
So answer will be,
$$\frac{(4/5)^2}{(1-4/5)^2}=\sum_{k\ge 0}k \left(\frac{4}{5}\right)^{k+1}$$
$$\frac{(4/5)^2}{(1-4/5)^2}=\frac{4^2}{1}=16$$
Answer: An straight solution was given by @Pi..Mechanic;
Another one is what @TheoBendit try to guide you to that:
$$ (\sum x^n)' = \sum (x^n)' = \sum nx^{(n-1)} $$
Now you can find why @TheoBendit encourage you to:
"Try bringing $\frac{4^2}{5^2}$ out the front instead"


Classification (regression) with rolling window for time series-type data

Question: This is rather a conceptual question, than technical. I am interested in performing a rolling (sliding) window analysis, where I aim to predict a label ('0' or '1') of the next value of my time-series. For example, consider the time-series data and the array of labels:
(I work with Python and sklearn)
ts  = array([11, 15,  3, 18,  6, 10,  9, 25,  7, 15])
lab = array([ 0,  0,  0,  1,  1,  0,  0,  1,  0,  1])

What I am doing is trying to learn a function 'F', which maps the input features (extracted from the window from the 'ts' array) to the binary labels 'lab': F(feat(ts)) -> lab. Conceptually, this problem is equivalent to the labeling of windows of size-k conditioned on the next timestamp.
F(ts[i:i+3]) -> lab[i+3]

Practically: Consider a window of size 3, then we get:
F([11,15, 3]) -> y = 1
F([15, 3,18]) -> y = 1
F([ 3,18, 6]) -> y = 0
F([18, 6,10]) -> y = 0
F([ 6,10, 9]) -> y = 1
F([10, 9,25]) -> y = 0
F([ 9,25, 7]) -> y = 1

(the very last value is unused). The real time-series is much longer.
QUESTION: For training, testing and cross-validation, may I (pretend and) use my instances as i.i.d? What I mean is: can I randomly divide  the instances to training, validation and test sets?
Of course they are not i.i.d., but when I naively tried to process my data and to learn a classifier (simple logistic regression), it surprisingly worked very well and I got quite reasonable results for the classification metrics.
EDIT
I'm reading the paper A Note on the Validity of Cross-Validation for Evaluating Time Series Prediction of and authors clearly state, that:
"....and CV can and should be used without modification, as in the independent case.."
Answer: How you divide your data set into training/test depends on the data you have available and how your model will be used. Ideally you wouldn't randomly separate the time-points, since as you say, they are not independent if there is any temporal signal at all.
If you have multiple time-series then I'd divide the time-series themselves into training and test in whatever fashion you want.
If your training data is a single time-series and you intend to predict future values of this time-series then I'd segment it accordingly. I.e. use the first 60% of the samples as your training data and the remaining 40% as your test. Of course, these sets aren't independent but given the nature of your data this is unavoidable.
If you have a single time-series for training but the actual time-series that you want to predict future values for is entirely separate then I'd still follow the procedure from the above paragraph, but bear in mind that any estimates of model fit you derive are very likely to be inaccurate.
As an aside, I would be tempted to use a Recurrent Neural Network approach to a problem like this. This would allow you to model the temporal aspect elegantly - something like an an LSTM can maintain a memory of previous values without having to explicitly specify a window size. Of course, if you wish to use a window approach then you could in theory use any classification algorithm you want.
EDIT
That technical paper looks to have covered the issue in far more depth than my answer so I'd follow their recommendations instead. The main difference from your use case is that they are dealing with standard forecasting the next sample, rather than classification
Comment: thanks for your thoughts and mentioning LSTM. I develop a new method for feature extraction using the rolling window and I would definitely benchmark it agains the LSTM. I can't agree more, that data in time-series are dependent, but sometimes it might be skipped and pretended as iid.
Comment: good point (about the difference). Each row in their embedded matrix is indeed \epsilon, and thus it is reasonable to assume that rows are iid. I'm trying to understand how I can use their result in my case.


Reference for R VGLM function

Question: Could someone please either explain to me what the VGLM function in R does or point me towards comprehensive documention? Currently, the only documentation I can find does not explain what a Vector GLM is, such as seen here. A worked through example would be fine.
Comment: How about the references mentioned in the documentation page you link to?  The Yee/Wild paper seems like it explains it fully and has a non-proportional odds model example.  The Yee/Hastie paper specifically references this library and has several examples, and there is code for at least one in the appendix. Plus the documentation page you link to also has several examples.  What more are you looking for?
Answer: In addition to the references in the documentation of the VGAM R package, there is now even a book "Vector Generalized Linear and Additive Models: With an Implementation in R (Springer Series in Statistics)" by the same authos as the R package.  See https://www.amazon.com/Vector-Generalized-Linear-Additive-Models/dp/1493941984/ref=sr_1_1?ie=UTF8&qid=1534868939&sr=8-1&keywords=vector+generalized+linear+models&dpID=41INcDCkR9L&preST=_SY291_BO1,204,203,200_QL40_&dpSrc=srch
Comment: I have got the book but I could not find a way to use cluster-robust standard errors with vglm yet.
If you are familiar with vglm, I would appreciate you having a look at this question: https://stats.stackexchange.com/questions/521181/cluster-robust-standard-errors-after-vglm

Reference for R VGLM function


Git - how to diff changes *introduced* in a branch after multiple merges to and from master?

Question: Here's the scenario. When a member of my team starts to work on a feature we branch off master to create a feature branch. We then merge master into feature often (at least every few days) to keep it up to date. When the feature is complete, we do a code review and make any changes necessary, and then merge feature into master. The code review process is: merge master into feature to be sure it's up to date, then diff master feature to see the whole set of feature code changes which can be reviewed nicely.
The above works well, but requires the whole code review process to be done before merging feature to master. Unfortunately the project schedule sometimes demands that we merge feature to master as soon as it's implemented so that the test team can begin testing it, and we must do code review after its been merged to master. This pre-review merge to master sometimes happens multiple times as pieces of the feature get finished.
Here is an example timeline of events:

Branch feature off from master.
Make changes on feature.
Merge master into feature to bring it up to date.
Make more changes on feature.
Merge feature to master so it can be tested.
Make more changes on feature.
Merge master into feature to bring it up to date.
Merge feature into master so it can be tested.
feature is now ready for code review.

My question is: how can feature be reviewed? Specifically, how can I isolate a line-by-line "diff" of all code changes that were introduced on feature (but now also exist in master) without seeing changes that were introduced elsewhere (but now also exist in feature)? Multiple merges have occurred between master and feature in both directions.
Is this possible?
Answer:
Unfortunately the project schedule sometimes demands that we merge feature to master as soon as it's implemented so that the test team can begin testing it,

Can't you git checkout -b test-feature-as-of-x master; git merge feature and your testing team can bang on test-feature-as-of-x without polluting the master history with code that's going to get rejected?
Anyhoo, to find the oldest merge base from an upstream,
oldest-base() {
        ( git rev-list --first-parent $1; git rev-list --first-parent $2 ) \
        | awk 'seen[$1]++ { print;exit }'
}

and then oldest-base feature master to find the original master commit feature was branched from. To see all the changes in feature without the master stuff getting in the way you can
git checkout -b review `oldest-base feature master`
git cherry-pick -n --first-parent --no-merges ..feature

and that will bring in only the feature first-parent commits, stripping out all the merges from master.
Comment: If you're collecting horribly long first-parent histories a more-efficient oldest-base finder would be `git rev-list --first-parent --parents $1 $2 | awk '++seen[$2] == 2 { print $2; exit }'` might save you a few tenths of a second here and there.
Comment: Yes, merging un-reviewed code to master is very risky and not ideal, but it's not going to get rejected. The devs must do some initial testing before saying the feature is complete, and the test team tests many features at once so sadly individual branch testing isn't feasible. Hopefully we can convince management to get out of this "fast paced" mode of operation soon, and go back to conducting code reviews before merging to master. Thanks for your help!
Answer: The moment you merge feature into master, there's not much you can do to separate the changes from one branch or the other. If you do not merge feature into master, the way to do it is:
git diff master...feature # notice 3 dots

I said: If you do not merge feature into master. Merges of master into feature are OK and the diff works.


Why console.log(window) works but JSON.stringify(window) doesn't work, and how can I beat that?

Question: If I type in console:
 console.log(window)

I get all the objects in window with expand buttons.
But if I try the same with:
JSON.stringify(window)

I get in Firefox:
Error: Permission denied to access property 'toJSON'

And in chrome:
TypeError: Converting circular structure to JSON

Is this the only case where this happen? And given that console.log() and JSON.stringify() work differently, can I access and still stringify objects that console.log() manages to display?
Comment: `var x = {}; x.x = x; JSON.stringify(x)`
Comment: Only a subset of possible JavaScript objects can be serialized as JSON. DOM nodes are not native JavaScript objects.
Comment: @SLaks console.log(x) works but you can expand x in x too many times to try to see if it ends.
Answer: That's because window has circular references (for instance, in most cases window.self refers to window) and then it cannot be converted to JSON, otherwise it would turn into an infinite loop.
This may happen on any object, not only on window:
var foo = {
    bar: 'bar'
};
JSON.stringify(foo);    // works fine

var foo = {
    bar: foo
};
JSON.stringify(foo);    // circular reference -> crashes

Comment: That's because Chrome has added a feature to avoid circular references in JSON objects during their stringifing process.
Comment: `var foo = { bar: foo }; JSON.stringify(foo);` does not crash for me in Chrome.


problem with sending a float number in a stream in vivado_hls

Question: I am trying to do a simple image processing filter where the pixel values will be divided by half to reduce the intensity and I am trying to develop the hardware for the same. hence I am using vivado hls to generate the IP. As explained here https://forums.xilinx.com/t5/High-Level-Synthesis-HLS/Float-numbers-with-hls-stream/m-p/942747 to send floating numbers in a hls stream , an union needs to be used and I did the same. However, the results don't seem to be matching for the red and green components of the image whereas it is matching for the blue component of the image. It is a very simple algorithm where a pixel value will be divided by half.
I have been trying to resolve it but I am not able to see where the problem is. I have attached all the files below, can someone can help me resolve it??
////header file
#include "ap_fixed.h"
#include "hls_stream.h"

typedef union {
    unsigned int i;
    float r;
    float g;
    float b;
} conv;

typedef hls::stream <unsigned int> Stream_t;

void ftest(Stream_t& Sin,Stream_t& Sout);

////testbench
#include "stream_check_h.hpp"

int main()
{
Mat img_rev = imread("C:/Users/20181217/Desktop/images/imgs/output_fwd_v3.png");//(256x512)
Mat final_img(img_rev.rows,img_rev.cols,CV_8UC3);
Mat ref_img(img_rev.rows,img_rev.cols,CV_8UC3);

    Stream_t S1,S2;
    int err_r = 0;
    int err_g = 0;
    int err_b = 0;

    for(int i=0;i<256;i++)
    {
        for(int j=0;j<512;j++)
        {
        conv c;
        c.r = (float)img_rev.at<Vec3b>(i,j)[0];
        c.g = (float)img_rev.at<Vec3b>(i,j)[1];
        c.b = (float)img_rev.at<Vec3b>(i,j)[2];
        S1 << c.i;
    }
    }

        ftest(S1,S2);
    conv c;
    for(int i=0;i<256;i++)
        {
            for(int j=0;j<512;j++)
            {
                S2 >> c.i;
                final_img.at<Vec3b>(i,j)[0]=(unsigned char)c.r;
                final_img.at<Vec3b>(i,j)[1]=(unsigned char)c.g;
                final_img.at<Vec3b>(i,j)[2]=(unsigned char)c.b;

                ref_img.at<Vec3b>(i,j)[0] = (unsigned char)(((float)img_rev.at<Vec3b>(i,j)[0])/2.0);
                ref_img.at<Vec3b>(i,j)[1] = (unsigned char)(((float)img_rev.at<Vec3b>(i,j)[1])/2.0);
                ref_img.at<Vec3b>(i,j)[2] = (unsigned char)(((float)img_rev.at<Vec3b>(i,j)[2])/2.0);
            }
        }
    Mat diff;
    cout<<diff;

    diff= abs(final_img-ref_img);
    for(int i=0;i<256;i++)
            {
                for(int j=0;j<512;j++)
                {
                    if((int)diff.at<Vec3b>(i,j)[0] > 0)
                        {
                        err_r++;
                        cout<<"expected value: "<<(int)ref_img.at<Vec3b>(i,j)[0]<<", final_value: "<<(int)final_img.at<Vec3b>(i,j)[0]<<", actual value:"<<(int)img_rev.at<Vec3b>(i,j)[0]<<endl;
                        }
                    if((int)diff.at<Vec3b>(i,j)[1] > 0)
                        err_g++;
                    if((int)diff.at<Vec3b>(i,j)[2] > 0)
                        err_b++;

                }
            }
cout<<"number of errors: "<<err_r<<", "<<err_g<<", "<<err_b;
    return 0;
}

////core
#include "stream_check_h.hpp"

void ftest(Stream_t& Sin,Stream_t& Sout)
{
    conv cin,cout;

    for(int i=0;i<256;i++)
    {
        for(int j=0;j<512;j++)
        {
            Sin >> cin.i;
            cout.r = cin.r/2.0 ;
            cout.g = cin.g/2.0 ;
            cout.b = cin.b/2.0 ;
            Sout << cout.i;
        }

    }

}

when I debugged, it showed that the blue components of the pixels are matching. for one red pixel  it showed me the following:
expected value: 22, final_value: 14, actual value:45

and the total errors for red, green, and blue are:
number of errors: 126773, 131072, 0

I am not able to see why it is going wrong for red and green. I posted here hoping a fresh set of eyes would help my problem.
Thanks in advance
Answer: I'm assuming you're using a 32bit-wide stream with 3 RGB pixels 8bit unsigned (CV_8U3). I believe the problem with the union type in your case is the overlapping of its three members (not just like the one float value in the example you cite). This means that by doing the division, you're actually doing it over the whole 32bit data you're receiving.
I possible workaround I quickly cam up with would be to cast the unsigned int you're getting from the stream into an ap_uint<32> type, then chop it in the R, G, B chunks (with the range() method) and divide. Finally, assemble back the result and stream it back.
unsigned int packet;
Sin >> packet;
ap_uint<32> packet_uint32 = *((ap_uint<32>*)&packet); // casting (not elegant, but works)
ap_int<8> b = packet_uint32.range(7, 0);
ap_int<8> g = packet_uint32.range(15, 8);
ap_int<8> r = packet_uint32.range(23, 16); // In case they are in the wrong bit range/order, just flip the r, g, b assignements
b /= 2;
g /= 2;
r /= 2;
packet_uint32.range(7, 0) = b;
packet_uint32.range(15, 8) = g;
packet_uint32.range(23, 16) = r;
packet = packet_uint32.to_int();
Sout << packet;

NOTE: I've reused the same variables in the code above: HLS shouldn't complain about it and come out with a good RTL anyway. In case it shouldn't, just create new ones.
Comment: Hi, thank you for your reply, The solution you suggested is for a 8 bit unsignigned int, I want to send the r,g and b values in terms of floating point.
Comment: You will anyway transfer 3x8bits, which can be manipulated as unsigned ints (or chars actually). Once in the accelerator, they can be "interpreted" as floats. However, there's no standard for representing 8bit floating points numbers. If you really need to represent real values, cast them to the HLS ap_fixed type (set its bitwidth to 8).
Comment: What I mean is: floats are just a way to interpret/see/process a bunch of bits (being 32 or 64 (or 16 half if the compiler supports it, as Vivado HLS does)). In this case, and in the code you propose, the transfering packets doesn't require to be float, but to be interpreted as floats once in the accelerator.

If you have tried my solution, does it work now?


Interpretation of the results of ordinal regression

Question: My ordinal DV is estimation of danger (10-point Likert scale, 1 - least dangerous, 10 - most dangerous). One binary IV is gender (male, female). The other binary IV is type of image (fast, slow).
Following instructions on this web page, I conducted the ordinal regression to get the main effects and gender*image interaction in SPSS (I cannot use R or other programming software):

Danger = Rating of how dangerous they see each type of image
Gender 1 = Men
Gender 2 = Women
Image 1 = Fast
Image 2 = Slow
My interpretation of the table: Men (Gender 1) were less likely (the value is negative) than women to give a high rating of danger. Those exposed to image 1 were more likely to give a high rating of danger than those exposed to image 2. There is a significant interaction between gender and image, such as men who were exposed to Image 1, were less likely (the value is negative) to give a high rating of danger than men who were exposed to Image 2, and than women who were exposed to Image 1 and Image 2.
This is as far as I got. Could anyone confirm that that is correct?
It seems pretty incomplete and nonsensical (especially the interaction bit).
I'm also meant to do (according to the instructions that I found) some calculations (by hand!) and some odds ratios (within each level of the factors or something) but I do not understand any of it and I would have to input some codes into SYNTAX in SPSS which I have no clue about. I would never be able to do that.
Comment: It sounds like this question might be arising from instructions for an academic course assignment. If so, please replace one of your tags with the `self-study` tag and read the [policy](https://stats.stackexchange.com/tags/self-study/info) for handling such questions on this site. This [web page on ordinal regression with SPSS](https://stats.oarc.ucla.edu/spss/dae/ordinal-logistic-regression/) might be helpful.
Comment: A link to the instructions that you're trying to follow and what extra calculations you need would help. Please provide that information by editing the question, as comments are easy to overlook and can be deleted. Note that the interpretation of an interaction in an ordinal model isn't that much different from that in a binary logistic regression. It's the _difference_ in log-odds from what you would predict based on the predictor variables individually, with the log-odds being those for being in a higher level.
Comment: @EdM no no, it's not an academic course assignment! The instructions I'm using is just some pdf on how to do ordinal regression. It's the only resource showing interaction but as I have said there is usage of the SYNTAX. Thank you for the link; I have seen this page already, it is very confusing. It uses some matrix language. And they don't show how to do interaction in ordinal regression at all.
Comment: @EdM Thank you for your response. Yes I do not know how to do log-odds. I could only interpret the Parameter Estimates table but I'm not even sure if my interpretation above is correct or not. I was hoping someone could look at the output I have included and confirmed? I'm using this website: https://www.restore.ac.uk/srme/www/fac/soc/wie/research-new/srme/modules/mod5/7/index.html I managed until the middle of the page but then they start calculating stuff and use excel and syntax which I could not follow.
Answer: Start by thinking about how you would do this in a standard ordinary least squares model with a continuous outcome. Say that your software reported an Intercept of 5 and coefficients of -1.689 for Gender = 1, 2.506 for Image = 1, and  -1.925 for the [Gender = 1] * [Image = 1] interaction.
With the "dummy coding" evidently used here, the Intercept is the expected outcome at the reference levels of categorical independent variables. SPSS chooses the highest level of each as the reference by default. So the Intercept value of 5 is the expected outcome for Gender = 2 and Image = 2.
The coefficient of -1.689 for Gender = 1 is the difference from that intercept value when Gender = 1  and you still have Image = 2. The predicted value for Gender = 1 and Image = 2 is thus 5 - 1.689 = 3.311.
The coefficient of 2.506 for Image = 1 is the difference from the intercept value when Image = 1  and you still are at the reference level of Gender = 2. The predicted value for Image = 1 and Gender = 2 is thus 5 + 2.506 = 7.506.
The [Gender = 1] * [Image = 1] interaction coefficient of -1.925 is the extra difference from what you would otherwise predict from those two individual coefficients. That is, to get the prediction for [Gender = 1] and [Image = 1] in ordinary least squares, you start with the Intercept and add both the individual coefficients and the interaction coefficient. For this hypothetical example, you get an estimate of 5 - 1.689 + 2.506 - 1.925 = 3.892.
In the ordinal regression model the primary interest is in the regression coefficients themselves.* Instead of each coefficient representing a change in linear outcome associated with a change in a predictor, it represents the change in log-odds of being in a higher outcome category. Note that my hypothetical example used the same coefficients as your ordinal regression model. So your understanding:

Men (Gender 1) were less likely (the value is negative) than women to give a high rating of danger. Those exposed to image 1 were more likely to give a high rating of danger than those exposed to image 2.

is partly correct and needs to be modified to:

Men (Gender 1) were less likely (the value is negative) than women to give Image 2 a high rating of danger. Women (Gender 2) exposed to image 1 were more likely to give a high rating of danger than women exposed to image 2.

That's because, with the interaction, the coefficient for Gender (not really a "main effect" when there's an interaction) is the difference between men and women when viewing the reference Image, Image 2. The coefficient for Image (again, not really a "main effect") is the difference between Image 1 and Image 2 when viewed by the reference Gender, women. That's not specific to ordinal regression. When there's an interaction between predictors and predictors are coded this way (called dummy of treatment coding), then all single-predictor coefficients are presented for differences when their interacting predictors are at reference levels.
Interaction coefficients can be harder to express in words. One way to describe the negative interaction coefficient could be:

Men exposed to Image 1 were less likely to give it a high rating of danger than you would expect based on their reaction to Image 2 and women's reaction to Image 1.

That complexity of explaining an interaction coefficient is a reason to show illustrative examples at combinations of predictor values instead. With only 4 combinations that's pretty easy. Relative to the reference of women seeing Image 2, men seeing image 2 had a difference of - 1.689 in the log-odds of a higher danger rating, women seeing Image 1 had 2.506 higher log-odds of a higher danger rating, and men seeing Image 1 had a difference of -1.689 + 2.506 - 1.925 = -1.106 in log odds.
Exponentiating those log-odds differences give you corresponding odds ratios of higher danger ratings.
Calculations up to that point are pretty simple; you just think in terms of changes of log-odds (or odds ratios) instead of changes in linear outcomes. But you should combine such estimates with estimates of the error, which require taking the coefficient covariance matrix into account. There presumably are ways to do that in SPSS, but I don't use it and software-specific questions are off-topic on this site.
This answer goes into more detail about interactions in general and for generalized linear models like ordinal regression in particular. The UCLA OARC web page on ordinal regression in SPSS provides more information specific to ordinal regression and its implementation in SPSS. The SPSS syntax for calculating probabilities of specific outcome ratings given combinations of predictors does seem awkward, but the approach of starting with the probability for the highest outcome level and working downward from there with the level-specific intercepts and the level-independent regression coeffcients can be implemented by hand for point estimates.

*Although there is a relationship between the reported "Threshold" values and a set of intercepts, "In general, these are not used in the interpretation of the results" according to the UCLA OARC web page on ordinal regression in SPSS. In the SPSS output, the "Threshold" values are the negatives of corresponding intercepts for each level.
Comment: Looks like we had comments crossing in time. Look at the paragraph I added under the portion of the answer that you didn't understand.
Comment: I will have a close look at your logodds explanation. I have now been told ordinal regression is far too complex to interpret and that I could "try categorising the DV into 2 or 3 groups and using logistic regression instead" = can I categorise my ordinal DV that way?
Comment: @lisaarthur "The table above shows the main effect of gender and the main effect of image and an interaction between the two. No?" With an interaction there is NO single "main effect" of gender "without the image" whether you are doing regular, logistic, or ordinal regression. The effect of `gender` depends on the `image` that is presented, and vice versa. I wrote very carefully how each of those "main effects" needs to be interpreted given the interaction, with this dummy coding of the IV. There is no more difficulty interpreting log-odds in ordinal than in binary logistic regression.
Comment: @lisaarthur I added a paragraph to explain. This is a common misunderstanding with interaction terms. With the usual treatment/dummy coding of categorical predictors, a "main" coefficient for a predictor involved in an interaction is for a situation _when the predictors interacting with it are at reference levels_. So the `Image` coefficient in your table is for the situation with the reference `Gender`, women in this case.
Comment: My biggest query is in regards to what you said before: "Men (Gender 1) were less likely (the value is negative) than women to give Image 2 a high rating of danger. Women (Gender 2) exposed to image 1 were more likely to give a high rating of danger than women exposed to image 2" = I get the first sentence about men but not the "Women (Gender 2) exposed to image 1 were more likely to give a high rating of danger than women exposed to image 2" = Where did you get this from? Which line? I cannot see information on which image women rated as more dangerous.
Comment: So sorry but I still don't get it. We have [Gender = 1]*[Image = 1] which was -1.925, [Gender=1]*[Image = 2] which was 0, [Gender = 2]*[Image = 1] which was 0, and [Gender = 2]*[Image = 2] which was 0. How did you get the following results from that: 1) Men (Gender 1) were less likely (the value is negative) than women to give Image 2 a high rating of danger.
2) Women (Gender 2) exposed to image 1 were more likely to give a high rating of danger than women exposed to image 2.
Comment: I think stamement 1) should be: Men (Gender 1) were less likely (the value is negative) than women to give Image 1 (and not Image 2 as you said) a high rating of danger. This is because there is: [Gender = 1]*[Image = 1] and it's negative. It talks about Gender 1 which is men and Image 1.
Comment: Your other statement I do not understand at all. I cannot see it in the table at all: Women (Gender 2) exposed to image 1 were more likely to give a high rating of danger than women exposed to image 2.
Comment: @lisaarthur I think that you are mis-interpreting the 0 coefficients. The reported 0 coefficients are for the baseline situations against which the other coefficients are compared. In SPSS the _highest_ level of a categorical predictor is taken as the default baseline. You will note that all of the coefficients with 0 values have either or both of `Gender = 2` or `Image =2`. To get predictions for a particular situation you _add_ all of the coefficients involved--each represents a _difference from_ a corresponding baseline. For those baseline-related coefficients, you thus add 0.
Comment: @lisaarthur It would help if you review the way that treatment/dummy coding represents categorical predictors. [This page](https://stats.oarc.ucla.edu/spss/library/spss-libraryunderstanding-and-interpreting-parameter-estimates-in-regression-and-anova/) has a section on categorical by categorical interactions in SPSS, like yours.


why do some use ν=n instead of ν=n-1 in the t distribution

Question: I have always accepted that ν=n-1, but then I come across multiple authors showing a derivation of the t distribution by marginalizing out the variance from the normal-inverse-gamma distribution, or by marginalizing out the inverse variance (precision) from the normal-gamma distribution.
The results of deriving the t distribution from the normal-inverse-gamma distribution require the use of ν=n and not ν=n-1.
For example in the book "Bayesian Data Analysis: Third edition" on page 69, it derives $p(μ|μ_0,σ_0)=t(μ|μ=μ_n,σ=σ_n^2/κ_n,ν=ν_n)$ where
$$ μ_n={κ_0\over κ_0+n}μ_0+{n\over κ_0+n}\bar y $$
$$ κ_n=κ_0+n $$
$$ ν_n=ν_0+ν $$
$$ ν_nσ_n=ν_0σ_0^2+(n-1)s^2+{κ_0n\over κ_0+n}(\bar y-μ_0)^2 $$
Since the least informative prior has $κ_0=ν_0=0$ therefore $ν_n=ν_0+n=n$.  For example when using a normal gamma distribution to derive the t distribution, the prior on the precision is $Γ(α=ν_0/2,β=ν_0σ_0^2/2)$ [1] where clearly the least informative prior is obtained in the limit as $ν_0$ approaches 0.  Yet on page 66 ν=n-1 is derived, and seems to be correct.
Even if $ν_n=ν_0+n$ is correct there is no way to obtain $ν=n-1$ without $ν_0=-1$, which I can not make sense of, with a gamma or inverse gamma distribution.
I clearly must have some fundamental misunderstanding. What is it?
I thought that perhaps $σ_n$ would cancel out the different value of ν, but no, instead I get two different results depending on which derivation of the t distribution I use.
How do I get the same results from the two different derivations of the t distribution?
Answer: The difference is in the prior distributions.

The book starts with
$$p(\mu,\sigma) \propto \sigma^{-2} \phantom{\cdot \sigma^{-1} e^{- \frac{(\mu-\mu_0)^2}{2\sigma^2}}}$$
From which the t-distribution with $n-1$ degrees of freedom is derived as the marginal posterior distribution.

The second derivation uses*
$$p(\mu,\sigma) \propto \sigma^{-2} \cdot \sigma^{-1} e^{- \frac{(\mu-\mu_0)^2}{2\sigma^2}}$$
From which the t-distribution with $n$ degrees of freedom is derived as the marginal posterior distribution.

So the difference is in the prior distribution. The former is uniform in $\mu$. With the latter this is not the case and you get a multiplication of this $\sigma^{-2}$ with a term for the distribution of $\mu$ conditional on $\sigma$. This changes the power from $\sigma^{-2}$ into $\sigma^{-3}$ and that changes the end result when you integrate out the $\sigma$.

*I have simplified it with $\nu_0 =0$ such that the difference between the two situations is more clear. But, the second case is more general and with $\nu_0\neq 0$ the equation is more complex. $$p(\mu,\sigma) \propto \sigma^{-2} \sigma^{-\nu_0} \exp \left( - \frac{1}{2\sigma^2} [\nu_0 \sigma_0^2 + \kappa_0(\mu_0-\mu)^2] \right)$$ But this complexity is not needed to see the difference why you get $n-1$ versus $n$.
Comment: I am not sure what you are trying out here? The $\nu_0$ is the degrees of freedom of the inverse chi-squared distribution that is the prior for $\sigma$. This value should be a positive integer.
Comment: alright, maybe this time I will say things sufficiently and correctly: $p(σ^2;ν_0,σ_0^2)\propto (σ^2)^{-(1+ν_0/2)}e^{\frac{-ν_0σ_0^2}{2σ^2}}$ and $p(μ|σ^2)\propto (σ^2)^{-1/2}e^{\frac{-κ_0}{2σ^2}(μ-μ_0)^2}$ so when $ν_0=-1$ and $ν_0σ_0^2=κ_0=0$ then $p(μ,σ^2)\propto p(σ^2;ν_0,σ_0^2)\cdot p(μ|σ^2)\propto \sigma^-1\cdot\sigma^-1$, because $(σ^2)^{-(1+ν_0/2)}=σ^{-1}$ when $ν_0=-1$ and $ν_0σ_0^2=κ_0=0$.
Comment: what I am trying to do is bridge the gap between the two "different" priors, and get a point of view that makes sense, even if it requires negative parameters for the inverse gamma distribution, which ordinarily would be undefined or result in complex values, but when ν_0=-1 and $ν_0σ^2_0=0$, and use $IG(\alpha=\nu_0/2,\beta=\nu_0\sigma_0^2/2)=IG(\alpha=-1/2,\beta=0)$ everything does end up working.
Comment: for reference $I_{\chi^2}(ν_0,σ^2_0)=IG(\alpha=\nu_0/2,\beta=\nu_0\sigma_0^2/2)$
Comment: sigh... now I see $σ^-1σ^-1$ ... I ment $σ^{-1}σ^{-1}$.  (In the fight against sleep, I always lose, every time)
Comment: ν_0 should be positive...  It is like saying if you have n samples then you have n-1 degrees of freedom, so if you have one sample then you have zero degrees of freedom and if you have no data then you have -1 degrees of freedom, which both sound like non-sense, but the math works out, and eliminates the difference between the two priors.


AngularJS Pagination - Get Current Page and Pass to Controller

Question: I am implementing server-side sorting and pagination, and I need to pass the current page that the user is on so that if they sort and are on a page different than the first page (ex. sort by "least votes" on page 5 does not show the resorted results from page 1 on page 5 but shows the resorted results that should be on page 5). Basically, I need in place sorting but can't figure out how to get the current page.
Server side paging is working without issue, and I believe I am missing something simple here.
HTML (please note that I am using this custom directive: https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination)

{{article.articlevotes}}

{{article.articletitle}}
{{article.articlecategoryid}}
{{article.articletitle}}

<dir-pagination-controls on-page-change="pageChanged(newPageNumber)"></dir-pagination-controls>

Controller
$scope.articles = [];
$scope.totalArticles = 0;
$scope.articlesPerPage = 10; // this should match however many results your API puts on one page
$scope.currentPage = 1;

   // sort options
$scope.sortoptions = [
{
    label: 'Most Votes',
    value: 'articlevotes desc',
},
{
    label: 'Least Votes',
    value: 'articlevotes asc',
}
];

var sortBy = $scope.sortoptions[0].value;
var currPage = $scope.currentPage; // Get current page
console.log(currPage);

// Initial page load
getResultsPage(1, sortBy);

$scope.update = function (articleSortOrder) {
    // get value of sort and log it
    console.log(articleSortOrder.value);
    sortBy = articleSortOrder.value;

    // log current page and pass as parameter
    console.log(currPage);
    getResultsPage(currPage, sortBy); // need to make dynamic so it gets current page
}

$scope.pageChanged = function (newPage) {
    getResultsPage(newPage, sortBy);
};

function getResultsPage(pageNumber, sortorder) {

    // currently skipping by page number * articles per page
    pfcArticles.query({ $skip: (pageNumber - 1) * $scope.articlesPerPage, $top: $scope.articlesPerPage, $orderby: sortorder, $inlinecount: 'allpages' }, function (data) {
        $scope.articles = data.results;
        $scope.totalArticles = data.count; // Can change to hard number to reduce total items instead of LimitTo
    });
}

Comment: If I console log the $scope.currentPage, it is only returning the number 1. I have tried the code listed in some paging plunks, and the plunker returns the page numbers correctly but mine doesn't.
Comment: I don't see the `dir-paginate` and `dir-pagination-controls` directives in your view code. Could you update the question to show them?
Comment: Added, it appears that the currentPage is not being passed. I spun up an example of the default angularUI pagination but appeared to have the same issue.
Answer: The problem is that you are assigning:
var currPage = $scope.currentPage;

So currPage is set to 1 as your controller is instantiated, and is then never changed. So when you reference currPage later in the controller, it remains 1.
You should instead directly reference the $scope.currentPage value, which will get updated by the pagination directive.
So try changing the "update" method to this:
$scope.update = function (articleSortOrder) {
    sortBy = articleSortOrder.value;
    getResultsPage($scope.currentPage, sortBy);
}

This should pass the correct current page value to your service.
Comment: I've been trying that as it should work... and that is where things are weird. It doesn't pass. Maybe its related to calling my controllers as part of app.js instead of in the page? the pageChanged function works with the newPage variable representing the correct page number.
Comment: Just found the issue. I have a controller overlap because a div got deleted that closed that div. Count this as coding while tired! Thanks @Michael Bromley


Angles and secants in an ellipse

Question: Can I express $\gamma$ as an analytic function of $a,b,c$, and $\alpha$?

So far, I have computing $p_1$ from $a,b,\alpha$, then solved numerically for $p_2$ by intersecting the ellipse with a circle with radius $c$, then solved analytically for $\gamma$ using $\alpha, a,b$ and $p_2$. I am looking for a better way that, ideally, does not require a numerical solver in the middle.
Comment: Which tools did you draw your diagram with?
Comment: powerpoint. why?
Comment: That's impressive. I wasn't aware something as accessible as PowerPoint could do this. I've been looking for a good drawing tool for making some notes with.
Comment: That's impressive. I wasn't aware something as accessible as PowerPoint could do this. I've been looking for a good drawing tool for making some notes with.
Comment: Are you interested in Groebner bases solver solutions?  I have used it on things like this.  Basically you feed it a set of algebraic equations and it finds the simultaneous equations in to a lower triangular of equations that are the result.  You walk your way up the ladder one parameter at a time until you have the final solution.  There is a problem that angles have to be interpreted algebraically; say s=cos(\alpha), t=sin(\theta) , and the answer is arcsin(t).   If you want I will do that as an answer (to keep in practice) ; but I am sure it wouldn't get credit as homework solution :)
Answer: The intersection of circle and ellipse generates quartic equation. The quartic equation is solvable in algebraic functions, so the answer to your question is yes, there is an analytic solution. however the resulting formula is so big, that a Brent or even Newton method would work way faster.
To illustrate what we are talking about. Here is the answer to one of the coordinate of an equivalent problem of
$$
\begin{cases}
a x^2+bxy+cy^2=1,\\
(x-1)^2+y^2=1
\end{cases}
$$
$$
x=\frac{b^2+2 c^2-2 a c}{2 \left(a^2-2 c a+b^2+c^2\right)}-\frac{1}{2} \sqrt{\frac{\left(b^2+2 c^2-2 a c\right)^2}{\left(a^2-2 c
   a+b^2+c^2\right)^2}+\frac{\sqrt[3]{128 c^6-384 c^5+384 a c^4+384 c^4-288 b^2 c^3-768 a c^3-128 c^3+384 a^2 c^2+432 b^2 c^2+384 a
   c^2-384 a^2 c-288 a b^2 c-144 b^2 c+108 b^4+128 a^3+144 a b^2+\sqrt{11664 b^8-6912 c^3 b^6+10368 c^2 b^6+31104 a b^6-62208 a c
   b^6+10368 c b^6-6912 b^6+27648 a c^4 b^4-6912 c^4 b^4+27648 a^3 b^4-55296 a c^3 b^4+13824 c^3 b^4-6912 a^2 b^4+55296 a^2 c^2
   b^4+13824 a c^2 b^4-6912 c^2 b^4-55296 a^2 c b^4+13824 a c b^4}}}{3 \sqrt[3]{2} \left(a^2-2 c a+b^2+c^2\right)}+\frac{4
   \sqrt[3]{2} \left(4 c^4-8 c^3+8 a c^2+4 c^2-6 b^2 c-8 a c+4 a^2+3 b^2\right)}{3 \left(a^2-2 c a+b^2+c^2\right) \sqrt[3]{128
   c^6-384 c^5+384 a c^4+384 c^4-288 b^2 c^3-768 a c^3-128 c^3+384 a^2 c^2+432 b^2 c^2+384 a c^2-384 a^2 c-288 a b^2 c-144 b^2 c+108
   b^4+128 a^3+144 a b^2+\sqrt{11664 b^8-6912 c^3 b^6+10368 c^2 b^6+31104 a b^6-62208 a c b^6+10368 c b^6-6912 b^6+27648 a c^4
   b^4-6912 c^4 b^4+27648 a^3 b^4-55296 a c^3 b^4+13824 c^3 b^4-6912 a^2 b^4+55296 a^2 c^2 b^4+13824 a c^2 b^4-6912 c^2 b^4-55296
   a^2 c b^4+13824 a c b^4}}}+\frac{4 \left(-2 c^2-c+a\right)}{3 \left(a^2-2 c a+b^2+c^2\right)}}-\frac{1}{2} \sqrt{\frac{2
   \left(b^2+2 c^2-2 a c\right)^2}{\left(a^2-2 c a+b^2+c^2\right)^2}-\frac{\sqrt[3]{128 c^6-384 c^5+384 a c^4+384 c^4-288 b^2
   c^3-768 a c^3-128 c^3+384 a^2 c^2+432 b^2 c^2+384 a c^2-384 a^2 c-288 a b^2 c-144 b^2 c+108 b^4+128 a^3+144 a b^2+\sqrt{11664
   b^8-6912 c^3 b^6+10368 c^2 b^6+31104 a b^6-62208 a c b^6+10368 c b^6-6912 b^6+27648 a c^4 b^4-6912 c^4 b^4+27648 a^3 b^4-55296 a
   c^3 b^4+13824 c^3 b^4-6912 a^2 b^4+55296 a^2 c^2 b^4+13824 a c^2 b^4-6912 c^2 b^4-55296 a^2 c b^4+13824 a c b^4}}}{3 \sqrt[3]{2}
   \left(a^2-2 c a+b^2+c^2\right)}-\frac{4 \sqrt[3]{2} \left(4 c^4-8 c^3+8 a c^2+4 c^2-6 b^2 c-8 a c+4 a^2+3 b^2\right)}{3
   \left(a^2-2 c a+b^2+c^2\right) \sqrt[3]{128 c^6-384 c^5+384 a c^4+384 c^4-288 b^2 c^3-768 a c^3-128 c^3+384 a^2 c^2+432 b^2
   c^2+384 a c^2-384 a^2 c-288 a b^2 c-144 b^2 c+108 b^4+128 a^3+144 a b^2+\sqrt{11664 b^8-6912 c^3 b^6+10368 c^2 b^6+31104 a
   b^6-62208 a c b^6+10368 c b^6-6912 b^6+27648 a c^4 b^4-6912 c^4 b^4+27648 a^3 b^4-55296 a c^3 b^4+13824 c^3 b^4-6912 a^2
   b^4+55296 a^2 c^2 b^4+13824 a c^2 b^4-6912 c^2 b^4-55296 a^2 c b^4+13824 a c b^4}}}-\frac{\frac{8 \left(b^2+2 c^2-2 a
   c\right)^3}{\left(a^2-2 c a+b^2+c^2\right)^3}+\frac{16 \left(-2 c^2-c+a\right) \left(b^2+2 c^2-2 a c\right)}{\left(a^2-2 c
   a+b^2+c^2\right)^2}+\frac{32 c}{a^2-2 c a+b^2+c^2}}{4 \sqrt{\frac{\left(b^2+2 c^2-2 a c\right)^2}{\left(a^2-2 c
   a+b^2+c^2\right)^2}+\frac{\sqrt[3]{128 c^6-384 c^5+384 a c^4+384 c^4-288 b^2 c^3-768 a c^3-128 c^3+384 a^2 c^2+432 b^2 c^2+384 a
   c^2-384 a^2 c-288 a b^2 c-144 b^2 c+108 b^4+128 a^3+144 a b^2+\sqrt{11664 b^8-6912 c^3 b^6+10368 c^2 b^6+31104 a b^6-62208 a c
   b^6+10368 c b^6-6912 b^6+27648 a c^4 b^4-6912 c^4 b^4+27648 a^3 b^4-55296 a c^3 b^4+13824 c^3 b^4-6912 a^2 b^4+55296 a^2 c^2
   b^4+13824 a c^2 b^4-6912 c^2 b^4-55296 a^2 c b^4+13824 a c b^4}}}{3 \sqrt[3]{2} \left(a^2-2 c a+b^2+c^2\right)}+\frac{4
   \sqrt[3]{2} \left(4 c^4-8 c^3+8 a c^2+4 c^2-6 b^2 c-8 a c+4 a^2+3 b^2\right)}{3 \left(a^2-2 c a+b^2+c^2\right) \sqrt[3]{128
   c^6-384 c^5+384 a c^4+384 c^4-288 b^2 c^3-768 a c^3-128 c^3+384 a^2 c^2+432 b^2 c^2+384 a c^2-384 a^2 c-288 a b^2 c-144 b^2 c+108
   b^4+128 a^3+144 a b^2+\sqrt{11664 b^8-6912 c^3 b^6+10368 c^2 b^6+31104 a b^6-62208 a c b^6+10368 c b^6-6912 b^6+27648 a c^4
   b^4-6912 c^4 b^4+27648 a^3 b^4-55296 a c^3 b^4+13824 c^3 b^4-6912 a^2 b^4+55296 a^2 c^2 b^4+13824 a c^2 b^4-6912 c^2 b^4-55296
   a^2 c b^4+13824 a c b^4}}}+\frac{4 \left(-2 c^2-c+a\right)}{3 \left(a^2-2 c a+b^2+c^2\right)}}}+\frac{8 \left(-2
   c^2-c+a\right)}{3 \left(a^2-2 c a+b^2+c^2\right)}}
$$

Angles and secants in an ellipse


fractional ideals are discrete in $K_\infty$

Question: Let $K$ be a numbe field, $S_\infty$ the set of infinite places of $K$ and $S$ a finite set of places of $K$ containing $S_\infty$. Define a fractional ideal $I$ over the ring of integer $\mathfrak{o}_K$ of $K$ by $$I=\prod_{v\in S-S_\infty} P_v^{k_v}$$
where $k_v$ are some integers and $P_v$ the prime of $K_v$. How to show that $I$ is a discrete in $K_\infty:=\prod_{v\in S_\infty}K_v$? I want to use the fact that $K$ is discrete in the adele $A_K$ of $K$, so $I$ is discrete in $A_K$, but what I want is regard $I\subseteq K$ as a subset in $K_\infty$, not in $A_K$.
Answer: Let $n=[K:\Bbb{Q}]$ and $\sigma_1,\ldots,\sigma_n$ be the embeddings $K\to \Bbb{C}$.
$O_K$  is discrete in $\Bbb{C}^n$ because for $a,b\in O_K$, if
$\sup_j |\sigma_j(a-b)|< 1/[K:\Bbb{Q}]! $ then the coefficients of the polynomial $\prod_{j=1}^n (x-\sigma_j(a-b))\in \Bbb{Z}[x]$ all are $< 1$ so
$\prod_{j=1}^n (x-\sigma_j(a-b))=x^n$ and hence $a=b$.
This implies that any fractional ideal is discrete in $K_\infty\subset \Bbb{C}^n$ as well.


How to fix springs noise on guitar with whammy bar?

Question: I've bought cheap used electric guitar with nice reviews.
As I played entire mounth I didn't encounter this problem. But yesterday the problem appeared when I use whammy bar (vibrato bar). It seems to me the noise is coming from the point where the springs are hanged onto the metal plate (which is screwed into the wood).

The best explanation of the problem would be to watch short 20 sec video.
What I did to fix the problem:

put a lubricanton the joints. Didn't resolve the problem
put some plastic cloth (some kind of buble wrap, but with much more finer bubles and generally more dense). Didn't resolve the problem as well

The guitar is currently not usable at all. I use whammy bar very often.
Any help is welcome.

UPDATE:
  I've fixed the issue with rubbery/plastic tubings (bought in garden store) as was suggested by Tim. Though I don't find these tubings as an ideal solution. 3 months have passed and it still works. Maybe tube material is squishing over time, hence strings' tension drops, which requires one more strings tuning per month, but it is still better than nothing
Comment: The metal sheet where the springs connect to is commonly called the "claw". The other end, where the springs connect to the bridge, is the "block". Knowing these terms might make your problem more searchable.
Answer: I'd be inclined to find a bit of plastic tubing - for aquarium use, or similar, that fits over the claws that hold the springs. Take springs off, add tubing, cut to length, replace springs. Ought to last a long time. Heat shrink would also do, but is much thinner.
Comment: Heat shrink tubing is what I use for both guitars and for Key clicking on woodwinds. There are thicker types available than tubing made for  electrical work, although outside of repair suppliers I'm not sure where you would get it (probably internet).  You can put small pieces on the spring hooks. The other option is a product called plasti-dip, which is a rubber coating for tool handles. You paint it on and it hardens into a flexible plastic coating.
Comment: Thank you for the answer, tomorrow I'm buying that foam, and respond whether it helped or not.
Comment: I just realized that plastic tubings will greatly shifts the springs up, which will cause the strings to detune a lot. When I'm done I'll reply
Comment: Depends on the wall thickness, but all is adjustable with the two long screws, which will be slackened slightly to reinstate the existing spring tension.
Comment: Though I don't find these tubings as an ideal solution. 3 months have passed and it still works. Maybe tube material is squishing over time, hence strings' tension drops, which requires one more strings tuning per month, but it is still better than nothing
Comment: Glad it's a partial solution. Most of us tune up each time we play, rather than each month!
Answer: I agree with Tim's plastic tubing suggestion, and would add that many tremolo players routinely keep small blocks of packing foam (see photo) jammed behind and in-between the trem springs.
Comment: unfortunatell it didn't resolved the issue. The noise was maybe slightly less hearable, but still it was enough to be annoying
Answer: I had the same issue with a Wilkinson strat trem and thought it was a ground issue. I put a thin sheet of foam from the packing the came in a fender pickup box under the springs in the cavity and the noise was gone. I am not sure why the springs caused the scratchy noise...something mechanical? ... but the foam cured the problem.


$(1-2^{1-s})\zeta(s)$ is an entire function

Question:
Show that $(1-2^{1-s})\zeta(s)$ is an entire function, which is represented by the series $$(1-2^{1-s})\zeta(s)=1-\dfrac{1}{2^s}+\dfrac{1}{3^s}-\dfrac{1}{4^s}+\cdots$$ for $\Re{s}>1$.

From the definition that $$\zeta(s)=\sum_{n=1}^\infty\dfrac{1}{n^s},$$ I want to multiply by $(1-2^{1-s})$. But it doesn't seem that the term $1-\dfrac{1}{2^s}+\ldots$ will come out.
Comment: @Mike Yes, sure.
Answer: Laurent series of $\zeta(s)$ about $1$ is
$$\zeta(s) = \dfrac1{s-1} + \sum_{k=0}^{\infty}\dfrac{(-1)^k}{k!} \gamma_k (s-1)^k$$
Hence,
$$\eta(s) = \dfrac{1-2^{1-s}}{s-1} + \sum_{k=0}^{\infty}\dfrac{(-1)^k}{k!} \gamma_k (s-1)^k(1-2^{1-s})$$
This makes sense everywhere except at $s=1$. At $s=1$, we have
$$\lim_{s \to 1} \eta(s) = \lim_{s \to 1} \dfrac{1-2^{1-s}}{s-1} = \ln(2)$$
This shows the function is entire.

For the series representation, see AaronS's answer.
Comment: http://www.youtube.com/watch?v=JYsKDaQIX54
Comment: @PedroTamaroff :). There are some nice people on M.SE as well.
Answer: It seems that I am late to the party, but here is a conceptually clear proof that might be beneficial:

$ \zeta $ is meromorphic on $ \mathbb{C} $ with a pole of order $ 1 $ (a.k.a. a simple pole) at $ 1 $. (This happens to be the only non-trivial fact that we need, and we shall take it for granted.)
The mapping $ s \longmapsto 1 - 2^{1 - s} = 1 - e^{(1 - s) \ln(2)} $ is obviously entire.
The mapping $ \eta: s \longmapsto (1 - 2^{1 - s}) \zeta(s) $ is thus meromorphic on $ \mathbb{C} $ with either (i) a simple pole at $ 1 $ or (ii) a pole of order $ 0 $ (a.k.a. a removable singularity) at $ 1 $.
If (i) were the case, then $ \displaystyle \lim_{s \to 1^{+}} |\eta(s)| = \infty $.
Fortunately, this is not the case because $ \displaystyle \lim_{s \to 1^{+}} \eta(s) = \ln(2) $.
Therefore, Case (ii) holds.
Conclusion: $ \eta $ can be extended to an entire function whose value at $ 1 $ is $ \ln(2) $. The validity of the series representation has already been proven by Aaron.

Note: In order to show that $ \displaystyle \lim_{s \to 1^{+}} \eta(s) = \lim_{s \to 1^{+}} (1 - 2^{1 - s}) \zeta(s) = \ln(2) $, we can employ the following formula (a college-level proof of which may be found here):
$$
\forall s \in \mathbb{R}_{> 1}: \quad
  \zeta(s)
= s \left(
    \frac{1}{s - 1} -
    \underbrace{\int_{1}^{\infty} \frac{\{ t \}}{t^{s + 1}} \mathrm{d}{t}}
    _{\text{Bounded above by $ 1 $}}
    \right),
$$
where $ \{ \cdot \}: \mathbb{R} \to [0,1) $ is the fractional-part function. No more is needed than a simple application of l'Hôpital's Rule to establish that
$$
\lim_{s \to 1^{+}} \frac{1 - 2^{1 - s}}{s - 1} = \ln(2).
$$
Answer: For the series representation:
\begin{align}
\zeta(s) &= 1+\frac{1}{2^s}+\frac{1}{3^s}+\frac{1}{4^s}+ \cdots \\
2^{1-s}\zeta(s) = \frac{2}{2^s}\zeta(s) &= 2(\frac{1}{2^s}+\frac{1}{4^s}+\frac{1}{6^s}+\frac{1}{8^s}+ \cdots)
\end{align}
Subtract the two and the even terms will be negated:
$$(1-2^{1-s})\zeta(s) = 1-\frac{1}{2^s}+\frac{1}{3^s}-\frac{1}{4^s}+ \cdots$$
Comment: You're right with the series representation. Can you also show that the function is entire?


What is the default database location of an android app for an unrooted device?? Is it same as for rooted one?

Question: I have quite a specific question.
First let me explain what I am trying to do and then the problem.
Basically what I am trying to do is to store an existing .db database file in assets folder and then after installation I want to copy the .db file from assets to the default database location in Android. Something similar to this page answer [link]How to use an existing database with an Android application.
Problem For unrooted device I cannot access /data/data/<<package name folder>> . In this case where is the database file gets stored. In other term I want to copy a file from assets to applications default location for database which is DB_PATH = "/data/data/" + context.getPackageName() + "/databases/" in case of a rooted device. Would it be the same for the unrooted device.
Comment: yes but u wont able to read anything unless you r rooted
Answer: Yeah, For both the cases it will be same path. /data/data/<application_package_name>/databases
Now, on un-rooted device you can not access /data/ directory of device's internal storage. That's why you can not seen the database file.
If you want to get the file you can copy database file from internal storage  /data/data/<application_package_name>/databases to external storage (sdcard) then using ddms or adb pull get the database file.
Also just try command adb pull /data/data/<application_package_name>/databases/<database_file_name> from your system to get the database file.
But by default all the android application store database on internal storage path /data/data/<application_package_name>/databases. And its applicable for all devices rooted or un-rooted.
Comment: This answer is not correct anymore. For years I have been using this   directory for copying databases in and out of the app, today for some reason databases were stored in /data/user/0//databases This directory can be retrieved by context.getDatabasePath(String name) as posted below by cja.
Comment: I agree I cannot see the directory in an unrooted device but can I perform operation assuming the directory `/data/data//databases` exists. I want to copy a file from **assets** folder to the databases folder. Can I copy assuming the same directory path for rooted as well as unrooted device.
Comment: Yes, you can not seen the file, but you can access the database file within your application and perform any operation on it. As file already physically present there.
Comment: is there any app that can fetch db file from this location?
Comment: Worth noting that within Android Studio, the "Device File Explorer" can be used to retrieve the database from the device; however, it is still located within /data/data//databases.
Answer: According to Android docs at http://developer.android.com/reference/android/content/Context.html#getDatabasePath(java.lang.String) you should use context.getDatabasePath.
Works for me:
File dbFile = context.getDatabasePath(name_of_database_file);

Answer: By Default Android Stores its SQLite Database to this below link, where you can access your .db file by using shell from command prompt to get owner access using chmod for read or write permission.
String DATABASE_PATH = "/data/data/" + PACKAGE_NAME + "/databases/" + DATABASE_NAME;

Where:
String DATABASE_NAME = "your_dbname";
String PACKAGE_NAME = "com.example.your_app_name";

For more details you can check the following link. Click here


Unhandled rejection error: StatusCodeError: 401 (Unauthorized: Access is denied due to invalid credentials)

Question: This page shows JSON inside plain empty html/body tags. For example:

    **JSON DATA ***

I can access that page fine doing it normally within a browser. But, when I send a request it says that my credentials are invalid (The response error is pretty much in the title).
And here is the code
import dotenv = require('dotenv');
dotenv.config({ path: '../logins.env' });
import rp = require('request-promise');
const jsonUrl = `http://availability.emodal.com/ImportAvailability/GetContainerInfoList?sgrdModel=%7B%22searchtext%22:%22%22,%22page%22:1,%22pageSize%22:280,%22sortBy%22:%221%22,%22sortDirection%22:%22asc%22,%22sortColumns%22:%22%22%7D`;

const authOpts = {
  uri: jsonUrl,
  auth: {
    user: process.env.EMODAL_id,
    pass: process.env.EMODAL_pw,
    sendImmediately: false
  },
  method: 'get'
}

rp(authOpts)
.then(resp => {
  console.log(resp);
}).catch(err => { throw Error(err)});

I tried changing everything around. Like adding headers, or putting json: true, or changing sendImmediately to true. Nothing works. What am I not understanding or what am I doing wrong?
Here is an image showing the error in terminal:

Thank you
Comment: `Here is an image showing the error in terminal` - copy/paste the text would've been *quicker* and easier to work with
Answer: From my understanding, the issue is: the page of the URL can be displayed successfully after login, but the URL itself cannot be fetched directly by program.
The cause of this issue is: auth option of request-promise (inherited from module request) works by adding Authorization header in HTTP request (document). This is called Basic access authentication and may not be supported by many servers. Unfortunately, in current web world, Basic access authentication is not popular any more (it's not secure), and it is very likely that emodal.com does not support it. Actually, I find a cookie in www.emodal.com named ASP.NET_SessionId which indicates the site is using SessionId cookie to authenticate user.
To fix the problem, I think the program need to login and save the SessionId cookie after login successfully. Then, fetch the URL resource by adding the SessionId cookie in the HTTP request header.