How to declare nested object in php

Question: Hey it try to convert simple object from js to php and get errors.
This is the array of object:
    "signatures": [
{
        "id": 5,
        "flowID": 1,
        "fileID": 1,
        "type": "partner",
        "page": 1,
        "position": {
            "x": 444,
            "y": 111
        },
        "size": {
            "width": 555,
            "height": 321
        }
    }, {
        "id": 6,
        "flowID": 1,
        "fileID": 1,
        "type": "partner",
        "page": 1,
        "position": {
            "x": 444,
            "y": 111
        },
        "size": {
            "width": 555,
            "height": 321
        }
    }]

My converted php code:
class Signatures
{
  public $id;
  public $flowID;
  public $fileID;
  public $type;
  public $page;
  public $position;
  public $size;
}

$signature = new Signatures();
$signature->id = 5;
$signature->flowID = 1;
$signature->fileID = 1;
$signature->type = 'partner';
$signature->position->x = 50;
$signature->position->y = 50;
$signature->size->height = 200;
$signature->size->width = 200;

How to make to position and size nested in php?
I try to create new class but the problem that i cant create properties of "size" and "position".
Thanks its my first time on php.
Error:
Warning: Creating default object from empty value in /Users/baruchmashasha/Sites/index.php on line 25

Warning: Creating default object from empty value in /Users/baruchmashasha/Sites/index.php on line 27

Comment: Does this answer your question? [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php)
Comment: Use PHP syntax, not Javascript.
Comment: The `Signatures.$position` and `Signatures.$size` fields should be complex objects.
Comment: @Mr.Polywhirl I edited my post
Comment: Hey @PhilippMaurer thanks you but I have my answer.
Answer: You need to create complex classes for the position and size fields.
Generic concept classes
class Point {
    public $x; // int
    public $y; // int

    function __construct() {
        $this->x = 0;
        $this->y = 0;
    }

    public static function create($x, $y) {
        $instance = new self();
        $instance->x = $x;
        $instance->y = $y;
        return $instance;
    }
}

class Rectangle {
    public $width;  // int
    public $height; // int

    function __construct() {
        $this->width = 0;
        $this->height = 0;
    }

    public static function create($width, $height) {
        $instance = new self();
        $instance->width = $width;
        $instance->height = $height;
        return $instance;
    }
}

Data transfer objects
class Signature {
    public $id;       // int
    public $flowID;   // int
    public $fileID;   // int
    public $type;     // string
    public $page;     // int
    public $position; // Point
    public $size;     // Rectangle

    function __construct() {
        $this->id = 0;
        $this->flowID = 0;
        $this->fileID = 0;
        $this->type = NULL;
        $this->page = 0;
        $this->position = new Point();
        $this->size = new Rectangle();
    }
}

class SignatureHolder {
    public $signatures; // of Signature

    function __construct() {
        $this->signatures = array();
    }
}

Usage
$signatureHolder = new SignatureHolder();

$signature1 = new Signature();
$signature1->id = 5;
$signature1->flowID = 1;
$signature1->fileID = 1;
$signature1->type = 'partner';
$signature1->position = Point::create(444, 111);
$signature1->size = Rectangle::create(555, 321);
array_push($signatureHolder->signatures, $signature1);

$signature2 = new Signature();
$signature2->id = 6;
$signature2->flowID = 1;
$signature2->fileID = 1;
$signature2->type = 'partner';
$signature2->position = Point::create(444, 111); // or you can set x and y
$signature2->size = Rectangle::create(555, 321); // or you can set width and height
array_push($signatureHolder->signatures, $signature2);

echo '
' , var_dump($signatureHolder) , '
'

Output
object(SignatureHolder)#1 (1) {
  ["signatures"] => array(2) {
    [0] => object(Signature)#2 (7) {
      ["id"] => int(5)
      ["flowID"] => int(1)
      ["fileID"] => int(1)
      ["type"] => string(7) "partner"
      ["page"] => int(0)
      ["position"] => object(Point)#5 (2) {
        ["x"] => int(444)
        ["y"] => int(111)
      }
      ["size"] => object(Rectangle)#3 (2) {
        ["width"] => int(555)
        ["height"] => int(321)
      }
    }
    [1] => object(Signature)#4 (7) {
      ["id"] => int(6)
      ["flowID"] => int(1)
      ["fileID"] => int(1)
      ["type"] => string(7) "partner"
      ["page"] => int(0)
      ["position"] => object(Point)#8 (2) {
        ["x"] => int(444)
        ["y"] => int(111)
      }
      ["size"] => object(Rectangle)#6 (2) {
        ["width"] => int(555)
        ["height"] => int(321)
      }
    }
  }
}

Comment: @WebDeveloper I actually implemented the class constructors. I forgot about them for a second...
Comment: Hey What about array of objects its work the same? @Mr.Polywhirl
Comment: @WebDeveloper Wrapped the signatures in an array to represent your JSON.
Answer: While Mr Polywhirls answer isn't incorrect, there is a simpler, tiny bit dirtier option available:
$signature = new Signatures();
$signature->id = 5;
$signature->flowID = 1;
$signature->fileID = 1;
$signature->type = 'partner';
$signature->position = (object)['x' => 50, 'y' => 50];
$signature->size = (object)['height' => 200, 'width' => 200];

This isn't persé better/worse, just different. I'd say that this kind of solution is suitable for small solutions. If you have a significant class / workload, the solution by Mr Polywhirls is more neat.

How to declare nested object in php


Set the value of a hidden field in form block

Question: Using the code below in a block, I am displaying a form in a block on all pages for a content type called Goals. I want to use this block / form to update progress on the goal to a content type called Goal Progress, and connect the two through a key called goal_id - the nid of the Goal.
The challenge that I am having is setting the value for the goal_id field (Goal Progress content type). I suspect I need to use $form_state['values']['field_goal_id']['und']['0']['value'] = 'value'; to declare the value, but I can't figure out where that should be placed.
Been looking for a solution for a couple of hours now, so any suggestions are greatly appreciated.
<code><?php
  $node = menu_get_object();

  if (isset($node->nid)) {
    $nid = $node->nid;
  }

  module_load_include('inc', 'node', 'node.pages');
  $node_form = node_add('goal_progress');
  print drupal_render($node_form);
?>
</code>
Comment: where is the rest of your code? does this code render the whole node form? Is that your intention?
Comment: Yes, that is all the code used and it displays the entire form
Answer: OK, I have found a working solution. I added $form['field_goal_id']['und']['0']['value']['#value'] = $node->nid; to hook_form_alter in template.php, and the value is populating the field and the form is submitting successfully. Sweet!


How to disable monaco-decorations-style in vscode

Question: How to disable monaco-decorations-style in vscode.
It overwrite my custom theme.
Help me. thanks.
Answer: In user pref basis, there is explorer.decorations.colors in the settings.json:
// Controls if file decorations should use colors.
"explorer.decorations.colors": true

Setting this to false makes text in explorer pane uniform, regardless the SCM state.


$h\in H$ group $\rightarrow hH=Hh$?

Question: Probably this is pretty simple (or even trivial), but I'm stucked.
If $H\leq G$ is a subgroup, does it follow that $hH=Hh$, if $h\in H$ ? I can't prove or find a counter-example. If anyone could help me, I'd be grateful!
Answer: $$hH=\{hh' \mid h' \in H\}, \color{red}{H}h = \{h'h \mid h' \in H\}$$
Note that $hh' = \color{red}{hh'h^{-1}}\cdot h$, so $hH \subseteq Hh$.  A similar trick shows the reverse inclusion.
Answer: If $h\in H$, $hH=Hh$ because  both are equal to $H$.
Indeed, by definition of a subgroup, $hH\subset H$. Conversely, if $k\in H$, we can write
$\; k=h(h^{-1}k)\in hH$, so $H\subset hH$. Similarly, one checks $H=Hh$.
Answer: They are Always equal to $H$, then ir Always holds
Comment: You'd rather edit your answer rather than posting two answers.
Answer: If $H\leq G$ is a subgroup, then for any $h,h' \in H$ you have that $hh'\in H$.
Therefore $hH=H=Hh$. To see this, let's see the double inclusion:
An element of $hH$ is of the form $hg$ with $g\in H$. Since $H$ is a subgroup, then $hg \in H$.
The other way around, take $h' \in H$ you want to see that $h' \in hH$. Consider $h'=h(h^{-1} h') \in hH$

$h\in H$ group $\rightarrow hH=Hh$?


How is this bit mask merge derived to what author suggets?

Question: From the following Sean Anderson's page:
http://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
He says that result of [ (a & ~mask) | (b & mask) ]
can be written as [ a ^ ((a ^ b) & mask); ]
From the problem statement, it is intuitive to do  [ (a & ~mask) | (b & mask) ]. But how do I derive the later expression from the first one? Any clues?
Answer: Intuitively, & bits means "take these bits", and ^ bits means "flip these bits".
The original expression, (a & ~mask) | (b & mask), means "take bits from b selected by the mask, and take the rest of the bits from a".
Let's start with (b & mask) — the bits of b selected by the mask.
a ^ (b & mask) would flip some bits of that — namely, the 1-bits of a.  Which is almost correct.  However, we don't actually want to flip the 1-bits of a that were selected by the mask.  To correct those bits in the positions where both a and mask are 1, we flip them again: a ^ ((a ^ b) & mask).
Comment: thanks for the explanation. As I see it, `a ^ ((a ^ b) & mask)` will be same as `a ^ (a ^ (b & mask))`.
Comment: No, `a ^ (a ^ (b & mask))` is the same as `(a ^ a) ^ (b & mask)`, which is `0 ^ (b & mask)`, or just `(b & mask)`.


setup saga middleware with redux-starter-kit's configureStore()

Question: I am working on the application which is purely redux-saga, but as the application is growing, the number of files is also growing. To solve this issue I am trying to setup redux-starter-kit to my current application.
Here is my store configuration file index.js
import { configureStore, getDefaultMiddleware } from 'redux-starter-kit'
import rootReducer from '../reducers'

export const store = configureStore({
  reducer: rootReducer,
  middleware: [...getDefaultMiddleware()]
})

old set up for just redux-saga without redux-starter-kit
// import createSagaMiddleware from 'redux-saga'
// import { initSagas } from '../initSagas'
// import rootReducer from '../reducers'
// import { loadState, saveState } from './browserStorage'

// function configureStore () {
//   const sagaMiddleware = createSagaMiddleware()
//   const persistedState = loadState()
//   const createdStore = createStore(
//     rootReducer,
//     persistedState,
//     applyMiddleware(sagaMiddleware)
//   )
//   initSagas(sagaMiddleware)
//   return createdStore
// }

// export const store = configureStore()

// store.subscribe(() => {
//   saveState(store.getState())
// })

the problem:
when I set up the redux-starter-kit the old sagas are not working.
Long story short:
How can I set up my existing redux-saga application with redux-starter-kit, without disturbing the current saga files?
Thank you in advance.
Answer: redux-starter-kit does not include sagaMiddleware by default [1]. You'll need to add it to the middleware list and initialize the sagas yourself.
In your case I believe this should work:
import createSagaMiddleware from 'redux-saga'
import { configureStore, getDefaultMiddleware } from 'redux-starter-kit'
import rootReducer from '../reducers'
import { initSagas } from '../initSagas'

const sagaMiddleware = createSagaMiddleware();
export const store = configureStore({
  reducer: rootReducer,
  middleware: [...getDefaultMiddleware(), sagaMiddleware]
})
initSagas(sagaMiddleware);

[1] https://redux-starter-kit.js.org/api/getdefaultmiddleware
Comment: Thank you @azundo for the quick solution. That worked.


Accessing IP restricted URI from Azure function (powershell)

Question: I'd like to know given a Powershell function such as:
<code>$url = "http://AnIPrestrictedURL"
[xml]$xml = (new-object System.Net.WebClient).DownloadString($url)
</code>
with $url being an IP restricted url what are my options (if any) to be able to make this work? Is VPN an option or some other method? Would Express route (obv cost not being a factor) or point to site VPN work for this??
EDIT: To make this clearer? I have control of the IPRestrictedUrl server so in theory I could allow access to this via VPN / express route presumably without the IP restriction?? this is the point of the question?
Perhaps I should have said "how can I use an Azure Function with a service I do not want to be publicly accessible" If it matters the end service is SOLR
Comment: Yes. Azure can provide you with Outbound IP addresses, see my answer [here](http://stackoverflow.com/a/43656397/1171619). I'm not exactly sure if they are fixed in stone or might change over time.
Comment: Aren't you able to whitelist Azure IPs in that service?
Comment: @Mikhail - Do you mean in the ""http://AnIPrestrictedURL" service? I have an on premise URL that I need the Azure function to be able to talk to but that on premis URL is IP restricted and the Azure function won't have a static IP presumably
Comment: Thanks @Mikhail I did see that but assumed that they weren't fixed, I'd much rather not rely on that without documentation as the idea would be this would replace some fairly low level batch processes that are meant to keep going without much / any investigation long term.
Answer: While the list of Outbound IPs is provided for Azure Web App (and is stable), the equivalent does not exist for Azure Function Apps. The reason is that they get scaled out very dynamically, and can end up running across many scale units, each with a different set of Outbound IPs.
So generally, you cannot make assumptions on Outbound IPs when using Azure Functions.
Comment: If you're willing to use a dedicated app service plan instead of the consumption plan, then you could try using hybrid connections. Basically you would run the hybrid connection manager on a server that has access to your SOLR server. https://learn.microsoft.com/en-us/azure/biztalk-services/integration-hybrid-connection-overview
Comment: Thanks @David Ebbo that answers in terms of IP / being able to rely on it. Do you know re: express route / point to site VPN?
Comment: Not really expert on that part. Maybe ask new question focusing on that?
Comment: I thought that was the focus of or rather I tried that to be the focus of the question?
Comment: Thanks @PaulBatum I think that looks like what I want, but I can't see a documented reference to Azure functions - mark it as the answer and will mark it thanks :)


Confidence Intervals for ratio of risk ratios

Question: How can you compute the confidence intervals for a ratio of risk ratios? For example:
RRa = 0.52 (95% CI 0.25 to 1.08)
RRb = 0.68 (95% CI 0.52 to 0.89)
If I take the natural logarithm of each RR (RRa = -0.65, RRb = -0.39), then my ratio is 0.39/0.65 = 0.6
But I don't have confidence intervals for this number (0.6)...
Assume I don't have the raw data used to develop the original risk ratios
Answer: Shortly before he died, John Pezzullo wrote an Excel spreadsheet that calculates the ratio and confidence interval (and p value) for a comparison of either 1 two ratios and their confidence intervals or 2 two means and their confidence intervals.
The Excel spreadsheet (with one tab for means and another for ratios) is here.
With an explanation here.
For the example in the question, using the Ratios tab in the Excel spreadsheet for 0.52 (95% CI 0.25 to 1.08) compared to 0.68 (95% CI 0.52 to 0.89) we get 0.76 (0.35-1.67) for A/B and 1.31 (0.60-2.85) for B/A, with p = 0.50.
Comment: Thanks. Any formulas and citations behind the John Pezzullo's spreadsheet?


Get json value from byte using rust

Question: I need to get the name from a base64 value, I tried like following but I didn't able to parse it and get the name property, any idea how can I do it ?
extern crate base64;
use serde_json::Value;
fn main() {

    let v = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ";

    let bytes = base64::decode(v).unwrap();
    println!("{:?}", bytes);

    let v: Value = serde_json::from_slice(bytes);

}

The value represnt json like
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1df0f644a139f8d526a44af8abf78e8e
At the end I need to print "name": "John Doe"
this is the decoded value
Answer: Masklinn explains why you have an error, and you should read his answer.
But IMO the simplest and safest solution is to use serde's derive to decode into the desired structure:
use serde::Deserialize;

/// a struct into which to decode the thing
#[derive(Deserialize)]
struct Thing {
    name: String,
    // add the other fields if you need them
}

fn main() {
    let v = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ";
    let bytes = base64::decode(v).unwrap(); // you should handle errors
    let thing: Thing = serde_json::from_slice(&bytes).unwrap();
    let name = thing.name;
    dbg!(name);
}

Answer: Denys has provided for the usual way to use serde, and you should definitely apply their solution if that's an option (if the document is not dynamic).
However:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1df0f644a139f8d526a44af8abf78e8e

Have you considered at least following the indications of the compiler? The Rust compiler is both pretty expressive and very strict, if you give up at every compilation error without even trying to understand what's happening, you'll have a very hard time.
If you try to compile your snippet, the first thing it tells you is
error[E0308]: mismatched types
  --> src/main.rs:12:43
   |
12 |     let v: Value = serde_json::from_slice(bytes);
   |                                           ^^^^^
   |                                           |
   |                                           expected `&[u8]`, found struct `Vec`
   |                                           help: consider borrowing here: `&bytes`
   |
   = note: expected reference `&[u8]`
                 found struct `Vec<u8>`

and while it doesn't always work out perfectly, the compiler's suggestion is spot-on: base64 has to allocate space for the return value so it yields a Vec, but serde_json doesn't really care where the data comes from so it takes a slice. Just referencing (applying the & operator) the vec allows rustc to coerce it to a slice.
The second suggestion is:
error[E0308]: mismatched types
  --> src/main.rs:12:20
   |
12 |     let v: Value = serde_json::from_slice(bytes);
   |            -----   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Value`, found enum `Result`
   |            |
   |            expected due to this
   |
   = note: expected enum `Value`
              found enum `Result<_, serde_json::Error>`

which doesn't provide a solution but a simple unwrap would do for testing. However you really want to read up on Rust error handling as Result is very much the normal way to signal fallibility / errors, and thus like compiler errors you will also encounter it a lot.
Anyway that yields a proper serde_json::value::Value, which you can manipulate the normal way e.g.
v.get("name").and_then(Value::as_str));

will return an Option<&str> of value None if the key is missing or not mapping to a string, and Some(s) if the key is present and mapping to a string: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5025d399644694b4b651c4ff1b9125a1
Comment: @DenysSéguret Oh wow sorry I don't know why I thought you were callled Daniel. Fixed. And agreed your solution is the much better one, hence why I called it the usual way to use serde (and upvoted it). I just wanted to provide the "bare" fix for the issue demonstrated.
Comment: But yes, you're right. I largely prefer the safety of derive based deserialization but I should have explained the error and how to use the Value too. Good point.

Get json value from byte using rust


How to print a taxonomy term's field value alongside a Views grouping header?

Question: In Drupal 8.4.4 I have a "Living Things" taxonomy vocabulary. One field on the terms in the vocabulary is "Most Common Name", with machine name field_most_common_name. On my "Animalia" term its value would be "Animal".
In Views, I have a "Taxon Media" view which lists media related to the taxonomy term. I display it in a block on the taxonomy term's pages themselves (not on nodes). In the view I group media by another field, "Primary Taxon", which is a reference to the term. It prints on the page as the grouping heading (e.g. "Animalia").
How can I print the value of my "Most Common Name" field next to that title? i.e. "Animalia Animal".
I have made a template, views-view-grouping--taxon-media.html.twig, cloned from the one in the Classy template, tested that works, then added the 4th line and tried a few other things such as content.field_most_common_name, but cannot get the field's value to display:

    {{ title }}
    {{ field_most_common_name }}

{{ content }}

Comment: You should create that title in your view (grouping). So instead of providing your template and the template variables, better provide details of your view settings.
Comment: Thank you again @MarioSteinitz ! Your hint got me there. I will delete the "dump" part of my question, which is irrelevant, and accept my answer tomorrow when I'm allowed to.
Answer: Thanks to Mario's helpful hint in the first comment, I was able to do this in the View and not in the twig template:

In the FIELDS section of the View, add "Most Common Name" as a field.
Select "Exclude from display", because I only want it in the title, not the results themselves.
(3. Select "Link to the Taxonomy term", because I want it to be a link.)
Next to "FIELDS", under the "Add" drop-down menu, choose "Rearrange".
Drag "(field_primary_taxon: Taxonomy term) Taxonomy term: Most Common Name" above "Media: Primary Taxon" > Apply
Click "Media: Primary Taxon [hidden]" field
Check "Override the output of this field with custom text"
REWRITE RESULTS > and copy the required tokens from the "REPLACEMENT PATTERNS" list, and paste into the "Text" area. I also inserted brackets outside of those tokens, so my Text area looks like this:
{{ field_primary_taxon }}
(
{{ field_most_common_name }}
)
Apply > Save > Clear all caches if necessary > Refresh the page.
Title now in my example is "Animalia (Animal)". "Animalia" and "Animal" are links to the taxonomy page.


How to manipulate the output after selecting and ordering TOP RESULT

Question: USE DNWorld
GO

SELECT TOP (100) WITH TIES PvPExp
FROM PvPRanking
ORDER BY PVPExp DESC

UPDATE PVPRanking
SET PVPLevel = 26
WHERE TOP(1) = 1

ERROR:

Msg 156, Level 15, State 1, Server NS544979, Procedure , Line 0
  Incorrect syntax near the keyword 'TOP'.
  [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near the keyword 'TOP'. (156)

I have successfully selected and ordered the PvPExp in the query.
I want to set PVPLEVEL = 26 for the #1 Top result. That isn't working.
Then from that I want to set The #2-#5 Top result a certain value.
So on and so forth. Please help
Answer: With RANK() window function:
WITH cte AS (
  SELECT *, RANK() OVER (ORDER BY PVPExp DESC) AS rn
  FROM PvPRanking
)
UPDATE cte
SET PVPLevel = CASE rn
  WHEN 1 THEN 26
  ELSE ?
END
WHERE rn <= 5

Replace ? with the value that you want to set to #2-#5 Top rows.
If you want to set different values for them also:
.............................
SET PVPLevel = CASE rn
  WHEN 1 THEN 26
  WHEN 2 THEN ?
  WHEN 3 THEN ?
  WHEN 4 THEN ?
  WHEN 5 THEN ?
END
.............................

Comment: thanks finally resolved it!

WITH cte AS (
  SELECT *, RANK() OVER (ORDER BY PVPExp DESC) AS rn
  FROM PvPRanking
)
UPDATE cte
SET PVPLevel = CASE
  WHEN rn = 1 THEN 26
  WHEN rn BETWEEN 2 AND 10 THEN 25
  ELSE 17
END
WHERE rn <= 100
Comment: I do have one question if you're still around. Would there be a way to shorten this?

Example

Set PVPLEVEL =  Case rn

When rn between 2 and 10 then 5

Meaning 2-10 get assigned 5
Comment: Check the syntax for this case: `Case When rn = 1 then 26 when rn between 2 and 10 then 5 end`
Comment: But if there is a where clause like: `where rn<=10` then you only need `else`: `Case When rn = 1 then 26 else 5 end`
Comment: Well I'm going to be expanding this list to TOP results at the moment.

I understand the first solution you presented but the syntax didn't work out.

 [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '='. (102)
Comment: Check this demo: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=c511c8a7f02d0f94b6e3d789e73e428e All the queries are syntactically correct.
Answer: You can use row_number() with a CTE. ie:
with rankings (PvpExp, rowNo) as
(
   SELECT PvPExp, row_number() over (order by PvpExp desc)
   FROM PvPRanking
)
UPDATE PVPRanking
   SET PVPLevel = case
                  when r.rowNo = 1 then 26
                  when r.rowNo > 1 and r.rowNo < 6 then xx
                  -- other settings
                  end
from PVPRanking pr
inner join rankings r on pr.PVPExp = r.PVPExp;

What you need might be Rank(), DenseRank() ... instead of row_number() based on your real needs.
Comment: Thank you so much for the help. It wasn't the answer that I needed but it helped me understand where I should start and what I should do.


Single-signon: Login to two site at once?

Question: I need to check if sure is logged in

user login to account.domain.com

system creates session for account.domain.com
(at this point i want the user to also login to support.domain.com)

How does support.domain.com check if the user is logged into to account.domain?
Answer:   session_set_cookie_params(0, "/", ".domain.com");

note that leading dot. This functions should be called BEFORE session_start();
Answer: If you change your session cookie domain to .domain.com, then the same session will be accessible on both subdomains.
Session wont work with www


How to selectively import and export content between 2 Drupal websites?

Question: How to merge simple core content into from site a to site b. Content is created using core functionality and modules.
Let's say I have 2 Drupal 7 sites, both have same configuration and modules.
Site A has:

3 content types
3 taxonomies
3 articles

Site B has:

1 content types
1 taxonomies
1 articles

How do I append content of site B to site A?
I want the content from site A to be appended to site B. If I do backup migrate, the content of site A will be overwritten.
I've noticed that backup migrate can have manual selection of what to export, but it will overwrite destination right?
What is the best procedure for this?
Answer: You could always write a couple of migration classes with the Migrate module, and hook up Site B as the datasource (the module would live in Site A).
You can do this by adding Site B's database credentials to the settings.php as another configuration, then calling on that in your script.
Here is an example of what a Migration class might look like:
class YourMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $query = Database::getConnection('connection_name', 'connection_key');
    // other query arguments to execute
  }
}

Where the Database::getConnection arguments are the names of the items in your $databases array in settings.php. With a working script, you can then write other scripts (or a cron job) to periodically run the migrate job.
Others will say to use Feeds, but I've always been a big Migrate fan (not Drupal2Drupal migrate module, the main Migrate module itself).

I've noticed that backup migrate can have manual selection of what to
  export, but it will overwrite destination right?

Pretty much. Site A would get wiped out. It also isn't as simple as moving MySQL data around, unless every data model in Site B is identical or exists in Site A even then its a fairly large technical challenge not to screw anything up. I would not do anything with SQL at this level - it needs to go through the API.
Comment: Thanks but....I'm not a developer...so this is way out of my league...isn't there a module or a simple way to to this in phpmyadmin or backup migrate?
Comment: A database sync would overwrite everything. You'd still be looking at custom MySQL scripts and it is way more complicated to do at that level because then you have to account for all the tables etc - there is more going on behind the scenes when Drupal creates a node. Dozens of tables can be involved depending on various factors, also all the revision tables too.
Comment: Feeds sounds like the only option for you then. https://www.drupal.org/project/feeds
Answer: No code solution:
Use Feeds to import the data. But first, you'll need to create a CSV of your data. You can use Views Data Export.
Now that you have a CSV, simply import using feeds.


Why doesn't skip_on_empty work when migrating from a text field?

Question: I'm trying to migrate Drupal 7 users to Drupal 8.  In Drupal 7, there's an additional text field representing the user's group.  In Drupal 8, it's a taxonomy vocabulary.  So I'm using the following pipeline:
  field_user_group:
    -
      plugin: skip_on_empty
      method: process
      source: field_directorate
    -
      plugin: extract
      index:
        - 0
        - value
    -
      plugin: entity_generate
      value_key: name
      bundle_key: vid
      bundle: groups
      entity_type: taxonomy_term
      ignore_case: true

field_directorate is the source field in D7, and field_user_group is the target in D8.
Records without that value set should be caught by the skip_on_empty plugin, and left blank, but that plugin seems to be failing (letting the process continue to the next plugin in the pipeline) as I'm getting errors from the extract plugin saying:

Array index missing, extraction failed.

According to the documentation,

The skip_on_empty process plugin checks to see if the current input value is empty (empty string, NULL, FALSE, 0, '0', or an empty array). If so, the further processing of the property or the entire row (depending on the chosen method) is skipped and will not be migrated.

How is the processing even getting to extract if skip_on_empty is supposed to skip values with an empty array?
It works fine for records with the value set.
Comment: I'm still wondering why `skip_on_empty` doesn't work, but I was able to work around this by dropping that plugin entirely, and going directly to [extract](https://api.drupal.org/api/drupal/core%21modules%21migrate%21src%21Plugin%21migrate%21process%21Extract.php/class/Extract).  You can specify a `default` parameter that gets used if there are missing keys.  I set it to the empty string '', and then there were no more failures.
Answer: I now believe this to be caused by Get process plugin sets multiple for empty array.


son vs. rumba clave and bass line

Question: The answer to Latin jazz: anticipated chord change on last beat provided by Ulf Åkerstedt raises another question: I have written a son bass line, and I realize I have a rumba clave on the drum set. Is this something legal, or is there a specific bass line pattern for the rumba clave?
Comment: In my book anything is legal as long as you feel that it sounds and/or feels good. However it would be really interesting if someone knowledgable in latin music would elaborate on this. :-)
Comment: That is very kind of you. However I'm thinking there actually might be 'rules' for latin that I don't know of. For example, when arranging jazz there are situations where you want to avoid having one instrument or section starting a note on a down beat if another instrument or section started a note on the preceding syncope (I believe due to the risk of it sounding like sloppy playing, rather than two different rhythmical note values, if the syncope is very delayed).
Comment: @UlfÅkerstedt: if you posted this as an answer rather than as a comment, I would be able to accept it.
Answer: A lot of salsa tunes use rumba clave instead of son and the bass tumbao is used the same in both. However, it doesn't match quite as well because the last beat on the three-side of the rumba clave occurs on the 'and' of 4, whereas the bass tumbao usually plays the anticipated note on the 4. Of course, the bass can emphasise the 4+ as well if desired.
I agree with @Ulf that anything is legal, since this is music! But if you want to sound more authentic then it's worth getting the rhythms right I think. As I said in another answer, the Salsa Guidebook by Rebeca Mauleon is a fantastic resource and well worth buying if you're interested in playing latin music.
Comment: I was offered Rebeca Mauleon's book for my birthday by my brother who was following this thread. Well I guess I have some homework to do now...
Answer: There's actually some disagreement on that actually... People do it all the time... play clave in "afro-Cuban" or any & every "Latin" "style", usually if they're that vague about it... everything just starts sounding "Latinish".
I used to play in Caribbean bands all the time and there's a big difference in how those drummers & percussionists differentiate styles from one another as compared to the Jazz guys. I have definite memories of them saying there is no clave in Cuban music... of course you have to realize that they are differentiating between African "bell patterns" & Brazilian clave (the instrument... wooden stick form). While related and similar... the patterns don't fit exactly the same (or are even in the same time signature)... and you don't use the same instrument. (But what the heck do I know... I'm a guitarist)
http://en.wikipedia.org/wiki/Clave_(rhythm)

Cuban folkloric musicians do not use the 3-2/2-3 system. Many Cuban performers of popular music do not use it either. The great Cuban conga player and band leader Mongo Santamaria said: "Don't tell me about 3-2 or 2-3! In Cuba we just play. We feel it; we don't talk about such things."[44] "In Cuba we don't think about [clave]. We know that we're in clave. Because we know that we have to be in clave to be a musician."[45] According to Cuban pianist Sonny Bravo, the late Charlie Palmieri would insist: "There's no such thing as 3-2 or 2-3, there's only one clave!"[46] The contemporary Cuban bassist, composer and arranger Alain Pérez flatly states: "In Cuba we do not use that 2-3, 3-2 formula . . . 2-3, 3-2 [is] not used in Cuba. That is how people learn Cuban music outside Cuba."[47]

Oddly... it's obviously inherent somewhere in the music (well... not in Boleros apparently, and some other "folkloric" styles...), but it's obviously in Songo...
The Clave and the Backbeat
It took me awhile to remember the name of the groove/style this is called, but it's Songo... That's a great site by Kevin Moore called timba.com... it is a veritable encyclopedia of the history of Cuban music since the 40's, it's divided into 3 parts, the roots of Timba I, II, and III, the only reason I mention this is because sub-navigation on the site is on the right of the page, I found it confusing at first, but he's got the complete development of Cuban grooves notated in a really neat "contextual" way.
They start in the 40's and trace every example of the evolution of Cuban music with a basic notation and links to music examples as well as a complete tracing of the evolution of "Drum Set" in Cuban music beginning with Changuito.

Changuito's contributions to Cuban music can't be overestimated. He was one of the first Cuban drumset players to combine aspects of jazz and funk drumming with traditional Cuban comparsa, batá and timbal rhythms. He used the drum kit both melodically and polyphonically and was a master at spicing up slower rhythms with double-time variations. In addition to his performances and recordings, he's also been the musical padrino to generation after generation of students at Havana's Escuela Nacional de los Artes (la ENA), teaching timba giants such as Tomasito Cruz, Alexis "Pututi I" Arce and many others.

I can't find the page link right now... I was reading this a few months ago and there was a mention of tumbao figures up to 4 measures in length (I'll look for the source, I think there may have been an example)
My previous comment earlier...

"So while you find it in "North American" Afro-Cuban Jazz (they talk all about that on the Wiki page)... I can't recall ever hearing it in a traditional Cuban music setting... Bell? Oh Ya! lots of that... just a simple quarter-note cowbell pattern rocks & I've heard more complex bell patterns as well... but 3-2/2-3 clave with actual "claves", nope; now a college jazz combo playing that way? of course... every time (see Latinish), but actual traditional Cuban players? You know... it's been such a long time, dredging my memory I remember a drummer playing it on a jam block on a kick drum pedal... It always seemed to come in somewhere in the mix, it was rare someone got dedicated to that singular role."

Is kind of an outsider's view of the topic... but reducing a Cuban drum groove to just the clave itself doesn't really represent the bigger picture of what's going on.
As a funny somewhat related story... a friend of mine spent a month studying in Brazil at a couple different Samba "schools"; I remember his comment that they didn't even think of any of the rhythm's starting on "1", or that there was even anything called "1" in music... 4/4 what??? cut what time??? I guess my point is that trying to identify these things from a reference point of "Western" or "European" concepts of time signature really cloud the issue and can lead to fundamental misunderstandings concerning the nature of another culture's music.
Oh... see how you like just a quarter note guagua rhythm, something has to be "on the beat" if you want something else to sound "off the beat". (Kind of like trying to add "altered notes" to a tri-tone sub... it's already altered... if you alter it again... it just ends up diatonic in the end.)

The most basic songo bell pattern is an embellishment of the Matanzas-style cáscara pattern for guaguancó, traditionally played on a guagua (hollowed piece of bamboo).[4] In both patterns the right hand (lower notes) plays the four main beats, while the left hand plays offbeats. The right hand is typically played on a closed hi-hat, woodblock, or cowbell. The left hand is typically played on the snare rim, snare, cowbell(s), or toms The left hand portion of the pattern is expressed in a wide variety of melodic motifs, and timbres. [See: "Songo Patterns on Drum Kit" (Changuito)].

On the pages describing the grooves on the Timba site you'll see it notated in context…
Comment: I think that it all comes down to how authentically afro-cuban he wants the music to sound. If the answer is 'quite a lot' then getting the clave and other patterns right is important. Just about all percussion patterns in cuban music fit around the clave, as does the piano montuno. The bass tumbao in its simplest version is a 1-bar rhythm that is the same across both bars of the clave, but any additional embellishments will fit the clave. Other instruments and vocals also should also base their phrasing around the clave.
Comment: I kind of interpreted his questioning of "is this legal" to be exactly that... what goes with what? in a traditional sense. For example, he's basically asking what a traditional Rhumba bassline is as his last question... I would think we need to point out the different meanings of Rumba/Rhumba, Afro-Cuban Vs. Folkloric Cuban Vs. African  Vs. Ballroom Vs. Flamenco... some are son based, some aren't; just as pointing out the various different uses of the word "clave" (instrument Vs. pattern)... in other words, even though we are talking about the same thing; I might refer to it as a bell pattern
Comment: I agree 100% with you that there are lots of other fun variations that borrow from Cuban, Brazilian and African traditions. But his question about 'legal' to me implied that he wanted to get it right from an authenticity point of view. He specifically asked about how a rumba clave fits with a tumbao bass line so I think he's aware of the differences. My other point was just that if you're playing Cuban music, the chances are that the music is 'in clave', either son or rumba, and being aware of the relationship between the clave and the other instruments is very important.
Comment: I agree that Cuban musicians don't talk about clave, but that's because they've all grown up just feeling it. It's definitely there though and even if no one is actually playing the pattern, all of the other instruments are aware of it. There's even a word, cruzado,  that means playing against the clave (either accidentally or deliberately)
Comment: Oh, I agree, I was just trying to point out the little I know about specific distinctions of where the "clave" (I was some what referencing the link... i.e. the same heritage extending back to african bell patterns)and how the clave is played and what type of instrument it would be played with. For instance would you want to play a stylisticaly different Brazillian Clave pattern (with wooden claves vs bell/bells) for a traditional Cuban sound or for that matter if you were trying to play in an African style? Functionally all three are respectively playing the same role in the groove.
Comment: Or rather I was trying to suggest he try some form of traditional afro-Cuban bell pattern/sound if he's going for a Cuban feel/groove with his son bassline... Actually I'd like to know what drum groove he's using with his son bassline (did I miss that?); although I just went and read the question again and I see his actual question is about what bassline he should use with the Rhumba clave. I guess I answered backwards, it does seem easier to just change the drum pattern to match your son bassline and then write a new bassline inspired by the Rhumba clave as a separate project... it's a twofer
Comment: But thinking functionally of what's going on, he's really asking in essence... How does the delineation of the subdivisions in stylistically unique yet related grooves vary from style to style? Well, for one thing you have different collections of percussion instruments to use... but in some way shape or form you somehow have to be defining those subdivisions (similar?: funk guitar? high hats/ride?)... There is even a "son clave pattern" on that page. Or similarly I would play a more traditional Cuban guitar pattern with a son bass line not a samba finger style pattern... he needs a montuno.
Comment: ... (I might use it cont...) Just to try and draw a useful distinction... he seems to be interested in learning the various different styles and how the parts fit together. I don't always think of it as a level of "authenticism" but rather from the point of view of what to do if you're playing a 4 hour afro-cuban gig and you don't want to play the exact same specific things song after song... for instance, it's a lot cooler (and more fun to listen to) if you can differentiate between African, Cuban, and Brazillian styles from song to song... instead of a vague mish-mash of styles constantly.
Comment: @tinyd (see above as well... ) and in re-reading my earlier post... each of those three countries have whole sub-sets of differing styles in and of themselves. It's also nice to switch specific instruments from tune to tune as well (even though I'm a guitarist, I would generally have a shaker, tambourine, brake drum, scratcher (trinidadian)... cowbell with my foot while playing guitar even, and sometimes even "clave"). Now I was just the guitarist so imagine what the percussionists were bringing along... I've seen guys play a saw! It's great fun; I'm just trying to help him out with some ideas
Comment: I'm sorry I realize I was being a bit dense in that sense... I finally thought back to the first time I played it reversed... a montuno that is; your right that 2 vs 3 pulse is still inherently in the music, and you do have to change with it. I remember a lot of people I played with all did it the same way... and then one night I did a gig with a guy who sequenced his backing track with the other one (2-3 vs. 3-2)(or vice versa... I don't remember) I'm sick tonight but I'll update my answer better (or more completely) (I can certainly be guilty of going off on a tangent occasionally)@tinyd...
Comment: @tinyd finally got around to updating this... (I remembered Songo a couple days after we spoke, but I've been busy). I think it's a bit broader explanation of what I was trying to express...

son vs. rumba clave and bass line


Programmatically loaded taxonomy form ajax errors

Question: I load a taxonomy term in the edit form via the following code:
<code>module_load_include ( 'inc', 'taxonomy', 'taxonomy.admin' );
$vocabulary = taxonomy_term_load ( $tid );
$form = drupal_get_form ( 'taxonomy_form_term', $vocabulary );
</code>
The vocabulary has a custom text field with unlimited values, so this appears on the form, but when I click the "add another item" button, I get:

Call to undefined function, taxonomy_form_term_validate() in [truncated path].../form.inc" on line 1513.

I appreciate any guidance I can get in solving this.
Comment: Where do make the ajax? It can be the case that you are not bootstrapping the necessary files in the ajax.
Comment: Potney, this is just the "add another item" button that appears under a field that's set to have unlimited values.
Answer: This function worked for me:
Please try to use form_load_include() and drupal_build_form() instead of drupal_get_form() to generate form
<code>  $form_id = 'taxonomy_form_term';
  $vocabulary = taxonomy_vocabulary_load($tid);

  $form_state = array();
  $form_state['build_info']['args'] = array($vocabulary);

  // use form_load_include() and drupal_build_form() instead of drupal_get_form()
  form_load_include($form_state, 'inc', 'taxonomy', 'taxonomy.admin');

  $form = drupal_build_form($form_id, $form_state);
</code>
Comment: Shouldn't it be `$term = taxonomy_term_load($tid); $form_state['build_info']['args'] = array($term);`?


Beta regression using categorical variables

Question: I have been asked to do beta-regression for my data. The independent variable is categorical (there are three treatments A, B and C). The dependent variable is the proportion of time an animal is sleeping. I used the following equation:model1 <- gamlss(CI_frac ~ factor(Treatment), data =df,family=BEINF) for the model. How do I do pairwise comparisons between Treatment A, B, and C?
Comment: I would suggest using contrasts for this purpose, which gamlss provides.
Answer: You can do this with the multcomp package, even though the standard linfct = mcp(...) functionality for specifying the contrast matrix does not work. However, it is possible to set up the desired contrast matrix by hand.
See the following discussion for a worked example for gam objects from mgcv. The analogous strategy can also be used for gamlss objects:
Correcting for multiple pairwise comparisons with GAM objects {mgcv} in R
Comment: Would the package emmen work ?
Comment: If you mean `emmeans`: According to its NEWS page, `emmeans` provides support for `gamlss` objects: https://cran.r-project.org/web/packages/emmeans/news/news.html
Comment: Is it okay to use emmeans package if your data is not normal or has hetegenous variance?
Comment: I think `emmeans` leverages (asymptotic) normality of the parameter estimates, not of the actual observations. So provided that you have specified an appropriate model that can capture the non-normality and heteroscedasticity, this holds for many models.


Determine critical points of $f(x,y) = x^2-3xy+y^2$ using hessian

Question: Let $f(x,y) = x^2-3xy+y^2$. Determine whether the point $(0,0)$ is a local maxima, local minima, or a saddle point using the eigenvalues of the Hessian of $f$ at the point $(0,0)$ or the eigenvalues of the associated symmetric matrix of $f$ .
This is start of my calculation:
The Hessian is a 2x2 matrix and looks like this:
$$
\text{Hess}(f) = \begin{bmatrix}
\frac{\partial^2 f}{\partial x^2} & \frac{\partial^2 f}{\partial x \partial y} \\
\frac{\partial^2 f}{\partial y \partial x} & \frac{\partial^2 f}{\partial y^2}
\end{bmatrix}
$$
Now, calculate the second derivatives of $f$:
$$
\frac{\partial^2 f}{\partial x^2} = 2
$$
$$
\frac{\partial^2 f}{\partial y^2} = 2
$$
$$
\frac{\partial^2 f}{\partial x \partial y} = \frac{\partial^2 f}{\partial y \partial x} = -3
$$
So the Hessian of $f$ is:
$$
\text{Hess}(f) = \begin{bmatrix}
2 & -3 \\
-3 & 2
\end{bmatrix}
$$
Now we need to calculate the eigenvalues of this matrix. The eigenvalues can be calculated by solving the determinant equation:
$$
\text{det}(\text{Hess}(f) - \lambda E) = 0
$$
where $\lambda$ is the eigenvalue we are looking for and $E$ is the identity matrix. For our Hessian matrix we get:
$$
\text{det}\left(\begin{bmatrix}
2-\lambda & -3 \\
-3 & 2-\lambda
\end{bmatrix}\right) = 0
$$
How to continue?
Comment: What about the determinant of $\begin{bmatrix}2-\lambda & -3\\ -3 & 2-\lambda\end{bmatrix}$?
Comment: Perhaps worth noting  when converted to polar coordinates one finds directly that $(0,0$ is a saddle node.
Answer: Well, continuing from where you stopped,
\begin{align*}
\det \begin{pmatrix} 2 - \lambda & -3 \\ -3 & 2 - \lambda \end{pmatrix} &= 0 \\
(2-\lambda)(2-\lambda) - (-3)(-3) &= 0 \\
\lambda^2 - 4\lambda + 4 - 9 &= 0 \\
(\lambda - 5)(\lambda+1) &= 0.
\end{align*}
So the eigenvalues are $\lambda = 5, -1$.
What does this tell you about what type of stationary point $(0,0)$ is?

 The eigenvalues have different signs, so $f$ increases in some directions around $(0,0)$ and decreases in others. Thus $(0,0)$ is a saddle point.

You can actually deduce the signs of the eigenvalues in the $2 \times 2$ case straight from the Hessian $H$. If the eigenvalues are $\lambda_1$ and $\lambda_2$, then here $\det H = \lambda_1 \lambda_2 = -5$ so the eigenvalues must have opposite signs.
Comment: One typo for 5 and -1
Comment: @Tim Thank you!
Answer: Take the determinant of your Hessian, set the result equal to zero and then solve for $\lambda$. In this case, you you get
$$
\begin{vmatrix}
2-\lambda & -3 \\
-3 & 2-\lambda
\end{vmatrix}
= (2-\lambda)^2 - (-3)(-3) = 0
$$
The above is quadratic in $\lambda$ meaning you will get two values for $\lambda$ which may, or may not, be unique. These are your eigenvalues.
To determine if the point is a minima, or maxima, you need to look at the eigenvalues you just found. What are the conditions on the eigenvalues that would allow you to make this calssification?
Answer: For dimension less than 3, to check local maxima, local minima, or a saddle point, it is not a must to calculate the eigenvalues of the hessian.
You can compute $\operatorname{det}(H)$ and $f_{xx}$ to determine the result. In your case, $\operatorname{det}(H)<0$ , which implies $(0,0)$ is a saddle point.
For more details, you may check Second partial derivative test and Sylvester's criterion
Answer: $f(x,y) = x^2 - 3xy + y^2$ is either a paraboliod or a hypebolic paraboliod.  If it is a paraboloid, $(0,0)$ will be a minimum.  If it is a hyperbolic paraboloid $(0,0)$ is a saddle point.
Consider $x^2 - 3xy + y^2 = 0$
Plugging into the quadratic formula
$(x - \frac {3\pm \sqrt {5}}{2}y)(x + \frac {3\pm \sqrt {5}}{2}y) = 0$
or $f(x,y) = (x - \frac {3\pm \sqrt {5}}{2}y)(x + \frac {3\pm \sqrt {5}}{2}y)$
We are dealing with a hyperbolic paraboloid.  $(0,0)$ will be a saddle point.
If you really want to do calculus...
If $f_{xx} f_{yy} > (f_{xy})^2$ we have a saddle point, while $f_{xx} f_{yy} < (f_{xy})^2$ is a maximum or a minimum.
If $\det\pmatrix {f_{xx}& f_{xy}\\f_{xy} & f_{yy}} < 0$ then we have a saddle point.
If the eigenvalues of $\pmatrix {f_{xx}& f_{xy}\\f_{xy} & f_{yy}}$ are one positive and one negative we have a saddle point.
Or, we could take the original function.
$f(x,y) = \begin{bmatrix}x&y\end{bmatrix}\begin{bmatrix}1&-\frac 32\\-\frac 32& 1\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}$
Diagonalize that matrix, and the same implications of the eigenvalues holds.


Mathematical flop count of column based back substitution function ( Julia )

Question: I am new to Linear Algebra and learning about triangular systems implemented in Julia lang. I have a col_bs() function I will show here that I need to do a mathematical flop count of. It doesn't have to be super technical this is for learning purposes. I tried to break the function down into it's inner i loop and outer j loop. In between is a count of each FLOP , which I assume is useless since the constants are usually dropped anyway.
I also know the answer should be N^2 since its a reversed version of the forward substitution algorithm which is N^2 flops. I tried my best to derive this N^2 count but when I tried I ended up with a weird Nj count. I will try to provide all work I have done! Thank you to anyone who helps.
function col_bs(U, b)

n = length(b)
x = copy(b)

for j = n:-1:2
    if U[j,j] == 0
        error("Error: Matrix U is singular.")
    end
        x[j] = x[j]/U[j,j]

        for i=1:j-1
        x[i] = x[i] - x[j] * U[i , j ]
        end
end

x[1] = x[1]/U[1,1]

return x
end

1: To start 2 flops for the addition and multiplication x[i] - x[j] * U[i , j ]

The $i$ loop does: $$ \sum_{i=1}^{j-1} 2$$

2: 1 flop for the division $$ x[j]  / = U[j,j] $$
3: Inside the for $j$ loop in total does: $$ 1 + \sum_{i=1}^{j-1} 2$$
4:The $j$ loop itself does:$$\sum_{j=2}^n ( 1 + \sum_{i=1}^{j-1} 2)) $$
5: Then one final flop for $$  x[1] = x[1]/U[1,1].$$

6: Finally we have
$$\\ 1 + (\sum_{j=2}^n ( 1 + \sum_{i=1}^{j-1} 2))) .$$

Which we can now break down.

If we distribute and simplify
$$\\ 1 + (\sum_{j=2}^n + \sum_{j=2}^n \sum_{i=1}^{j-1} 2) .$$

We can look at only the significant variables and ignore constants,

$$\\
  \\ 1 + (n + n(j-1))
  \\ n + nj - n
  \\ nj
$$

Which then means that if we ignore constants the highest possibility of flops for this formula would be $n$ ( which may be a hint to whats wrong with my function since it should be $n^2$ just like the rest of our triangular systems I believe)
Answer: Reduce your code to this form:
for j = n:-1:2
   ...
   for i = 1:j-1
      ... do k FLOPs
   end
end

The inner loop takes k*(j-1) flops. The cost of the outer loop is thus

Since you know that j <= n, you know that this sum is less than (n-1)^2 which is enough for big O.
In fact, however, you should also be able to figure out that


Implementar comunicação por voz e vídeo chamada no android?

Question: Queria saber o que começar a estudar para implementar funcionalidades como vídeo chamada e chamada por voz no android. Quais bibliotecas estudar e tals.
Me dêem um norte.
:)
Comment: Protocolo Voip.
Comment: https://tools.ietf.org/html/rfc6405
Answer: Só para esclarecer o comentário do @mauhumor, VOIP não é um protocolo, VOIP é uma tecnologia IP que define a capacidade de transmissão de VOZ sobre IP, geralmente usamos como transporte de dados o protocolo UDP, este protocolo não é confiável, ou seja ele não possui nenhum mecanismo de controle e retransmissão de dados, isso quer dizer que se um determinado pacote se perder ele não será retransmitido e realmente ele é a melhor escolha, quando falamos em transmissões em tempo real e que algumas perdas de dados não afetam tanto a comunicação ele é a escolha óbvia, pois ele não vai adicionar latência durante uma transmissão tentando retransmitir pacotes como é feito no protocolo TCP.
Pois Bem agora que você sabe qual protocolo usar para comunicação stream, existem alguns protocolos de sinalização de chamadas por voz, essa sinalização nada mais é do que uma conversa entre o ponto A e o ponto B que define quando uma ligação foi recebida do ponto A para fazer o ponto B tocar, se o ponto A e B ainda estão em uma chamada ativa, se um dos pontos desligou para poder encerrar os sockets, etc, etc, etc... O protocolo de sinalização mais atual e mais utilizado hoje em dia é o SIP mas você também pode encontrar o H323 e o IAX ou seja é só a sinalização de controle sobre o curso da chamada. O transporte da mídia em sí será feito em outro protocolo que ficará responsável pela transmissão da mídia (voz ou video), hoje em dia é muito comum o protocolo RTP - (Real-time Transport Protocol).
Essa explicação acima define uma excelente arquitetura para transmissão de voz ou vídeo, e isso com certeza é implementado em transmissões de grande escala (whats, skype, etc). Agora se você quer apenas aprender o básico, fazer de brincadeira uma transmissão de voz sobre IP do seu computador ou Smartphone para outra pessoa, você pode abrir seu microfone, capturar a voz, enviar os pacotes de VOZ dentro de um socket UDP, do outro lado sua outra aplicação vai receber os pacotes UDPs e dar play no áudio recebido para poder escutar, pronto você está fazendo uma transmissão de áudio em tempo real sobre IP.
Isso é o básico do básico, se quiser ir a fundo nisso você tem que comer com farinha, sockets, DSP, compactação de dados (diminuir os dados enviados para economizar banda), arquitetura IP.
Como você deve estar percebendo o assunto é amplo de mais para entrar em todos os campos citados acima, espero que pelo menos ajude a você entender e saber por qual caminho seguir.
PS: eu não conheço nenhuma biblioteca pronta para fazer isso em android, se você pensar friamente é preciso de algum servidor ou algum método que reúna e atualize a informação dos ips dos clients, é claro você precisa conhecer em qual IP o cliente Y está para poder chamá-lo.
Comment: Era exatamente isso que eu queria, muito obrigado.


java.util.date's value changed itself

Question: when I startup tomcat , open a Jsp page with
new java.util.date()
at the beginning , date is correct ,like it
date : Fri Mar 29 19:06:07 GMT 2013
soon it changed to another value without timezone .
date : Fri Mar 29 11:06:07 GMT 2013
My server is linux centos6.4 , tomcat version is 7 ,jdk1.6 ,and server clock config is:

I modified my tomcat catalina.sh , add user zone :
JAVA_OPTS="$JAVA_OPTS $LOGGING_MANAGER -Duser.timezone=GMT+08"
I doubt maybe my application has some bug , but what bugs can make date changes. I spent hours in this question and not resolved. any help will be greately appreciate.
Comment: the default timezone can be changed in java code.  make sure you don't have any code setting the default timezone.
Answer: Java's Calendar classes have ways of managing time zones.
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
String monthString = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);

There's also the DateFormat class to help you get a complete date string out of the calendar.

java.util.date‘s value changed itself


Bubble sizes are being rendered too small in MPAndroidChart

Question: Hi I´m working with  BubbleChart on MPAndroidChart .My X values are pretty big and so my bubbles size are very small,in order to see the bubbles is necessary to zoom a lot on the chart.I set big size for the bubbles but they keep small. Thats my code.
BubbleChart bubbleChart=(BubbleChart) findViewById(R.id.bubbleChart);
    ArrayList<BubbleEntry> entries = new ArrayList<>();

    entries.add(new BubbleEntry(323,1f,10f));
    entries.add(new BubbleEntry(981,5f, 10f));
    entries.add(new BubbleEntry(1300,3f ,10f));

    XAxis xAxis = bubbleChart.getXAxis();
    xAxis.setAxisMinimum(0);
    xAxis.setAxisMaximum(1440);

    YAxis yAxis = bubbleChart.getAxisLeft();

    yAxis.setAxisMinimum(0);
    yAxis.setAxisMaximum(8);

    YAxis yAxis2=bubbleChart.getAxisRight();
    yAxis2.setAxisMinimum(0);
    yAxis2.setAxisMaximum(8);

    BubbleDataSet bubbleDataSet = new BubbleDataSet(entries, "");
    bubbleDataSet.setColor(Color.RED,180);

    BubbleData data= new BubbleData(bubbleDataSet);
    bubbleChart.setData(data);

Screenshot:
bubblechart
Comment: did you find a better solution?
Answer: This kind of problem can be solved by pre-processing your data and multiplying by a scalar. So instead of what you have above you can try multiplying the y-values or z-values by a scalar (we've chosen 100f):
public static float SCALAR = 100f;

ArrayList<BubbleEntry> entries = new ArrayList<>();
entries.add(new BubbleEntry(323, 10 * SCALAR, 10 * SCALAR));
entries.add(new BubbleEntry(981, 5 * SCALAR, 10 * SCALAR));
entries.add(new BubbleEntry(1300, 3 * SCALAR, 10 * SCALAR));

If you have labels on the y-values or on the y-axis you would then write a custom IAxisValueFormatter or IValueFormatter to return the original y-value:
public class MyValueFormatter implements IValueFormatter {

    String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        return Float.toString(value / SCALAR);
    }
}


How to dynamically add new instance (of say a text-field or a checkbox) in Wordpress widgets?

Question: I am creating a Wordpress widget. I want users to enter their phone numbers. By default, the widget should show only one textbox and a link below it that says "Add New". When the user clicks the link, a the second text-box should appear below the first one with a small (X) beside it, that will be used to remove it.
This functionality is there in the post editing screen in Wordpress. Users can dynamically "Add new category" there. Can this me implemented inside Widgets?
Answer: Sure. Start with this HTML at the bottom of your widget:

Add New

        <input type="text" id="p_number" size="20" name="p_number" value="" placeholder="Input Number" />

Now a little jQuery:
$(function() {
        var nmbrsDiv = $('#numbers');
        var i = $('#numbers p').size() + 1;

        $('#addNew').live('click', function() {
                $('
<input type="text" id="p_number_' + i +'" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Number" /> Remove
').appendTo(nmbrsDiv);
                i++;
                return false;
        });

        $('#remNew').live('click', function() {
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});

Comment: Thanks for the reply. I implemented what you told. But the console gives the error: scntDiv is not defined. I gave the id of the div in which the widget lies. But it does nothing and no error is displayed.


nmap port 3128 shows open but no squid running

Question: Im trying to lock down an Ubuntu server and ran nmap -T4 against
my server.  Everything looks right except that it shows port 3128
open but I dont run a squid server or anything else I know of on
that port.
<code>PORT     STATE SERVICE
80/tcp   open  http
3128/tcp open  squid-http
</code>
So I have 2 questions:

When I run netstat -tlnp I get nothing that shows port 3128.  When I telnet
to that port from another machine on my local lan it responds!?  What is
running and why cant I find it?
I have iptables setup to bare minimum, but I cant seem to close port 3128
from telnet in question 1?

Can anyone tell me whats going on with port 3128?
Is it something to do with the linksys router thats responding
and not the computer itself?  Ive googled this and havent been able to
find an answer.
Thanks in advance
Comment: try sending an HTTP request from your telnet connection (e.g. type `HEAD / HTTP/1.0` and press return twice) and see if there is any answer... if there is an actual squid or something similar, it might identify itself in the response headers. at the same time, I'd run a tcpdump on port 3128 on your server to see if it is actually receiving any packets form that connection.
Comment: 1) If you disconnect the Ubuntu server from the network altogether, do you still get a response? 2) The LinkSys router suggests that your question is off-topic for Server Fault and probably belongs on [su].
Answer: Try

fuser -n tcp 3128

Which will give you the Process ID's associated with the port, then you can use, for example

ps waux | grep "[pid]"

to get the associated process.  (There are probably more elegant ways to do the second step, but it works for me !)
Comment: The second command could simply be `ps -fp [pid]`.
Answer: After trying your suggestions Ive come to the conclusion that the router is
answering my telnet, not the box.
Tried sending the HEAD and it just came back with 'Connection closed by foreign host.'
Ran 'fuser' command above, showed nothing.
Disconnected the network cable and tried telnet again and it still answers,
so I have to assume its the router.
As a sidenote, if it is the router, Im wondering if that's a security concern
or not...Ill have to look into that.
Thanks everyone!
Comment: if you have port 3128 open on your router and you don't know why, I would recommend you to investigate the issue. home routers generally don't have this port open. and these days, you can get malware even on home routers... so double check, just to be sure.
Comment: Thank you, yes I agree.  I see quite a few router hack attempts in my log files.  Im going to try to setup DD-WRT on my router.  Unfortunately linksys no longer supports my rev number.  I see no reason for that port to be open after going through my entire linksys GUI, so Im going to assume its been somehow hacked.


How to change core search result snippet?

Question: I want to change core search result snippet. I tried with preprocessor theme_preprocess_search_result(&$vars) but in $vars['result']['node'] there coming basic fields values and rendered content array. In my node, content is with paragraph bundles and field collections. I want to display one of my bundle value in search snippet.
$vars['result']['node'] values coming in array key 'rendered'
stdClass Object
(
    [vid] => 1039
    [uid] => 1
    [title] => What are the cut off times for funds transfers to an external bank?
    [log] =>
    [status] => 1
    [comment] => 0
    [promote] => 1
    [sticky] => 0
    [nid] => 235
    [type] => support
    [language] => und
    [created] => 1444988988
    [changed] => 1446531922
    [tnid] => 0
    [translate] => 0
    [revision_timestamp] => 1446531922
    [revision_uid] => 1
    [field_support_type_ref] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [tid] => 16
                            [taxonomy_term] => stdClass Object
                                (
                                    [tid] => 16
                                    [vid] => 4
                                    [name] => Internet Banking
                                    [description] =>
                                    [format] => filtered_html
                                    [weight] => 0
                                    [vocabulary_machine_name] => support_type
                                )

                        )

                )

        )

    [field_paragraph] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 1102
                            [revision_id] => 7916
                        )

                )

        )

    [name] => orangedigital
    [picture] => 0
    [data] => b:0;
    [workbench_access] => Array
        (
            [28] => 28
        )

    [entity_view_prepared] => 1
    [rendered] =>
Type:
Internet Banking
Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.

)

Comment: may this help you https://www.drupal.org/node/287345
Answer: You could build your own search result .tpl file inside your theme and take control over what displayed and the markup by creating a file named like search-results--[searchType].tpl.php After that you have to clear the cache in order to be recognized in theme registry
In your case you could limit the number of words displayed or divide based on empty line which mean a pragraph.
Take a look at D7 theme suggestions


Create list with custom text jetpack compose

Question: I'm trying to create a list with customized text views, like the image bellow.

I tried to do that with a lazy column, but it does not work properly.
The problem is that row does not grow with the content created, I don't know how compose redraw that view behind de hood but it isn't working to me.
<code>@Composable
fun NumberList(viewModel: HomeViewModel) {
    val gameList = viewModel.numberList //The list of numbers

    LazyColumn(
        modifier = Modifier.padding(top = 24.dp),
        content = {
            item {
                gameList.forEach {
                    MegaCard(item = it)
                }
            }
        })
}

@Composable
fun MegaCard(item: String) {
    val itemList = item.split("-")
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
            .padding(horizontal = 16.dp, vertical = 4.dp)
    ) {
        Row(modifier = Modifier.padding(3.dp)) {
            itemList.forEach { number ->
                GameCircle(number)
            }
        }
    }
}

@Composable
fun GameCircle(number: String) {
    val megaColor = colorResource(id = R.color.mega_green)
    Text(
        modifier = Modifier
            .padding(16.dp)
            .drawBehind {
                drawCircle(
                    color = megaColor,
                    radius = this.size.maxDimension
                )
            },
        text = number,
        style = MaterialTheme.typography.body2,
        color = Color.White,
        fontSize = 18.sp
    )
}
</code>
The final result is something like this bellow:
Comment: "The problem is that row does not grow with the content created" -- could you please explain in greater detail what you mean?
Answer: As more game numbers are added, I assume you want each row to grow vertically. If that's the case, the problem is that the total circle size exceeds the available space. You can use a FlowRow for this:
<code>@Composable
fun MegaCard(item: String) {
   val itemList = item.split("-")
   Card(
       modifier = Modifier
         .fillMaxWidth()
         .wrapContentHeight()
         .padding(horizontal = 16.dp, vertical = 4.dp)
   ) {
     FlowRow(modifier = Modifier.padding(3.dp)) {
         itemList.forEach { number ->
             GameCircle(number)
         }
     }
  }
}
</code>
You'll need to add the flow layout Gradle dependency:
<code>implementation 'com.google.accompanist:accompanist-flowlayout:0.25.1'
</code>
Also, unless you intend to treat them as one entity, I recommend not adding every row into a single item. The docs go into more detail on the pitfalls of doing so. Here's the final result using FlowRow.
Comment: Hi Jason, thank you! It works like a charm. I never heard about FlowRow before.


Convert byte[] returned by a 3rd party software to zip file

Question: Was going through stackoverflow article Convert to Zip file, but my issue is a bit different. I do not have the PDF file. I get the array of bytes array after HTML is converted to PDF via a 3rd party software called HiQPDF and I want to convert the same array to zip file. My code for converting the byte array to zip is
private void  DownloadZipFile(HttpContext aHttpContext, byte[] pdfBuffer)
    {
        try
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    archive.CreateEntry(NomineeName + ".pdf", CompressionLevel.Fastest);
                }

                //return the ZIP byte stream as base 64 string
                memoryStream.Seek(0, SeekOrigin.Begin);
                byte[] zipArchive = memoryStream.ToArray();

                aHttpContext.Response.ContentType = "application/zip";

                aHttpContext.Response.AddHeader("content-disposition", String.Format("{0}; filename={1}; size={2}",
                                                  "attachment", "\"" + this.NomineeName + ".zip\"", zipArchive.Length));

                aHttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);

                aHttpContext.Response.BinaryWrite(zipArchive);

                aHttpContext.Response.End();

            }
        }
        catch (Exception exception)
        {
            new LogDetails { Exception = exception }.AddLog();

            this.ShowErrorMessage(aHttpContext);
        }

    }

This codes downloads the zip file but I know I am missing something somewhere as a result of which I cannot open the pdf after extracting it.

pdfBuffer in the parameter is the byte array returned by the HiQPDF.

Thanks for the help. I know I am duplicating the question but I need to know where I am wrong. I searched plenty of articles and blogs but still I couldn't find where my mistake is.
Answer: With a little R&D I found out that I was not writing the data into the newly created entry in zip file thus I missed couple of lines of code:
using (BinaryWriter writer = new BinaryWriter(readmeEntry.Open()))
 {
    writer.Write(pdfBuffer);
 }

Adding these lines of code after
archive.CreateEntry(NomineeName + ".pdf", CompressionLevel.Fastest);

fixed my problem.


Different hiera hierarchy per dynamic environment

Question: Is it possible to define a separate hiera.yaml for a given environment? Currently I am using dynamic environments. Each one has its own hiera data directory, per my hiera.yaml file.
<code>:yaml:
   :datadir: /var/lib/hiera/%{environment}
</code>
One drawback though is all of these environments are subject to the same hierarchy. I don't think this would work very well with many teams on a shared Puppet master.
So what is the best option, a dedicated Puppet master for each team that has a set of servers to maintain?
Answer: I think I just found it.
My guess is you can make this dynamic in the same way as environments, something like
<code>hiera_config = $confdir/environments/$environment/hiera.yaml
</code>


Alguém explica essa mensagem do git, depois de um pull para o develop?

Question: Tenho o braço develop na minha maquina local. No develop remote existem uns 10 programadores fazendo push todos os dias.
Por isso faço sempre um pull antes de fazer o merge do meu develop com o a feature123 que estou trabalhando e prestes a enviar para o braço feature123 remoto.
Fazendo o pull do develop remoto tive a seguinte mensagem:
$ git pull origin develop
Enter passphrase for key '/c/Users/.../.ssh/id_rsa':
remote: Counting objects: 193, done.
remote: Compressing objects: 100% (193/193), done.
remote: Total 193 (delta 149), reused 0 (delta 0)
Receiving objects: 100% (193/193), 30.63 KiB | 0 bytes/s, done.
Resolving deltas: 100% (149/149), completed with 48 local objects.
From bitbucket.org:.../....-source
 * branch                develop    -> FETCH_HEAD
   21......64........c8  develop    -> origin/develop
Auto-merging postback.php
CONFLICT (content): Merge conflict in postback.php
Auto-merging includes/db_manager.php
Auto-merging checkout-site.php
Automatic merge failed; fix conflicts and then commit the result.

Que diz que houve alguns merges automaticos e um que não foi possivel fazer automaticamente no caso no arquivo postback.php.
Em seguida pedi um status:
$ git status
On branch develop
Your branch and 'origin/develop' have diverged,
and have 131 and 74 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)
You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)

Changes to be committed:
...
modified:   admin/details.php
...
both modified:   postback.php

O fato é que o que eu tenho no meu develop é exatament o que eu tinha desde o último pull ( que foi ontem a noite ). Não trabalhei no develop.
A primeira coisa que não entenedo é pq não foi possivel fazer um merge automático, já que foi feito nos outros arquivos e em nenhum deles houve mudança no branch em questão - no caso develop.
A segunda coisa que não entendo é pq foi considerado both modified:   postback.php modificado nos dois lados se eu não trabalhei com ele no develop local.
Eu tenho outro braço que se chama feature123 e nesse braço eu modifiquei o arquivo postback.php. Mas não foi em develop.
Alguem pode explicar pq o git mostrou essa mensagem?
Comment: Você não está na branch `feature123` e tentando fazer `pull` da `develop`?
Comment: nao, estou na branch develop
Comment: E o arquivo `postback.php` que **você modificou** foi commitado? Perceba que eu não disse enviado para o servidor, quero saber se ele foi commitado localmente.
Comment: Isso aconteceu algumas vezes, não consegui descobrir o motivo pra resolver de um forma 'correta', mas como sempre deixo sincronizado, resolvi apagando o (os) arquivo(s) local que aparecia(m) como modificado(s) (mesmo sem modificar), fazia um pull, depois commit, e depois push funcionava de novo, mas vira e mexe isso acontece, e as vezes não funciona, nesses casos preciso clonar de novo, vai ser muito útil uma resposta, pois isso deve ser problema por mau uso.
Comment: LINQ, o postback.php foi modificado e comitado no meu branch feature123.  Agora estou no branch develop. Nao tem motivo para ter modificação ou commit aqui.
Comment: @AnthraxisBR  pois é.. eu tenho que entender de onde está vindo esse mau uso.. Se de minha parte, ou do software que estou utilizando ou algum outro bug em algum outro lugar.
Answer: Existe algumas provabilidades vou citar em ordem de relevância:

Alguém comitou o merge errado entre as branchs
Sua branch local se chama feature123 mas está apontando na develop
O arquivo checkout-site.php foi alterado comitado e o git não consegui entender sozinho as alterações(simples assim, isso pode acontecer);

Soluções:

Quero q minha develop fique igual como está no repositório:

git fetch all
git reset --hard origin/develop
git pull

Não alterei o arquivo checkout-site.php quero que somente ele fique igual ao repositório:

git fetch all
git checkout-site.php
git pull

3 Quero resolver o conflito afinal de contas quero entender o que aconteceu no arquivo:

Entra no arquivo e procura as alterações de merge que o git criou automaticamente conforme o exemplo abaixo:

<<<<<<>>>>>> iss53:index.html

Depois de localizar o código fazer as alterações, conforme a documentação de merge do git
Você deverá fazer o commit das alterações e subir no servidor

git commit -m "Merge das alterações"
git push
Comment: Essa ultima opção acontece comigo direto, inclusive o Netbeans alerta erro no código por causa disso, a opção 2 resolveu meu problema.
Comment: @AnthraxisBR pois é comigo acontece as vezes também , rs
Comment: @Diogo, depois de analisar aqui acho que é o segundo caso. Como eu vejo qual branch o meu local esta apontando?
Comment: @zwitterion git branch -vv