How to get meta attribute in javascript

Question: I have a span element like this:

And I want to get the attribute of meta-embed, which is "TESTLINK".
I've tried document.getElementById(), but it doesn't work, do you know how i can do it?
Comment: It really should be `data-` and not `meta-` so you can use dataset and be valid
Comment: `.getAttribute()`.
Comment: Possible duplicate of [Get value of a Custom Attribute using Javascript or Jquery](https://stackoverflow.com/questions/12226311/get-value-of-a-custom-attribute-using-javascript-or-jquery)
Answer: There is no id for this span element so you can use querySelectorAll with a class name and use  .getAttribute to get the attribute you want from.

const res = [...document.querySelectorAll(".player-overlay")].map(el =>

  el.getAttribute("meta-embed")
)

console.log(res)

Comment: And what if  i have class="player-overlay radius4 show ep-2-2 and class="player-overlay radius4 show ep-2-3" etc and i want get the meta attribute of everyone ?
Comment: i updated my code for an example of group of span update your question please

How to get meta attribute in javascript


Functions in Haskell - Understanding

Question: I have the following code which gives out [2,4,6] :
j :: [Int]
j = ((\f x -> map x) (\y -> y + 3) (\z -> 2*z)) [1,2,3]

Why? It seems that just the "z-function" is being used, what happens to the "y-function"?
And how does map work in this particular case?
Answer: Let's compute:
((\f x -> map x) (\y -> y + 3) (\z -> 2*z)) [1,2,3]
                 ^^^ f ^^^^^^^ ^^^ x ^^^^^
=
(map x) [1,2,3]
   where f = \y -> y +3
         x = \z -> 2*z
=
[x 1,x 2,x 3]
   where f = \y -> y +3
         x = \z -> 2*z
=
[2*1,2*2,2*3]
   where f = \y -> y +3
         x = \z -> 2*z
=
[2,4,6]
   where f = \y -> y +3
         x = \z -> 2*z

As we can see, f was taken as an argument, but was never used after that. Consequently \y -> y+3 never affected the final result.
The function map x is the function that applies function x to each element of a list. Note that, above, (map x) [1,2,3] is the same as map x [1,2,3]. Indeed, each function application g x1 x2 x3 x4 can be equivalently written as (((g x1) x2) x3) x4 by left-associating the applications.
Comment: Thank you for that really good explanation!

Functions in Haskell - Understanding


How does the 10th frame count towards a 'closed' game in bowling

Question: At my club we were discussing what a 'closed' game is.
A closed game is when you hae no open frames. The thing we couldn't agree on was the 10th frame.
Lets assume we have 9 strikes.
What if I throw a spare in the 10th and finally 9 pins. Is this considered a 'closed' game?
Or do I allways have to end with a strike/spare
Comment: I'm familiar with this as a "Clean Game" but I understood that it sometimes refers as a "Closed Game"
Comment: Is "closed game" is a concepy you and you friends invented?
Comment: I have heared more people talk about it. Until now nobody was able to give me an exact answer on the 10th frame.
Answer: The Definition to Closed Game, Also Known As: Patch or Clean game, is:

(1) A game with no open frames. This comes from the pursuit of the
  fictional USBC award patch for no open frames.
(2) An award given out by the USBC for individual and team
  accomplishments. Starting with the 2009-2010 season, the patches have
  been replaced by magnets.

According to Wikipedia:

A "Clean Game" is a game with strikes or spares in every frame (not
  counting bonus balls).

or

A single game of bowling where the player has a mark (spare or strike)
  in all ten frames.

So according to this definitions the case you describe is in deed a "Closed Game" since you didn't left any open frames. the last 9-pins throw was part of the bonus shoot which isn't included in "Close Game" definition.
Here is a very similar post that present the same question with a little bit different scenario.


On-Prem AD to Azure AD Sync with existing users in both

Question: I have an on-prem active directory domain called xyzcorp.com.  I also have an Azure AD domain called xyzcorp.com. The two are not synchronized at the moment. What I want to be able to do is enable directory synchronization between on-prem and Azure AD.  This brings me to the issue at hand.
I have a user called email@example.com that's present in both directories. That same user is a Global admin/Azure Owner.  What will happen if I attempt to synchronize my on-prem directory over to Azure?  Will I lose access to Azure AD?  In general what's the best practice for dealing with two disjointed domains how can I combine them making the on-prem as the authoritative source?
Many thanks.
Answer: Azure AD Connect won't synchronize an on premises user account to an Azure AD user account that is a Global Admin.
Azure AD Connect will not synchronize an on premises user account to Azure AD where the isCriticalSystemObject attribute of the on premises user account is set to True.
When you synchronize your on premises objects to Azure AD the on premises objects become the source of authority for the synchronized objects in Azure AD.
If you've got everything configured correctly, Azure AD Connect will match your on premises objects to your existing Azure AD objects.


BCP queryout file to FTP server

Question: I am querying a set of tables and generating XML from it. I can then use xp_cmdshell to create a file on the disk and this works well.
<code>EXEC xp_cmdshell 'bcp "SELECT MyXML FROM ##Orders" queryout "C:\Temp\OrderFile.xml" -T -c -t,' </code>
Instead of saving to the local disk, how can I amend this to save to a location on an FTP server instead?
Comment: Presumably you've tried to use the share name eg `"\\servername\sharename\filename.xml"` - what problems did you encounter?
Comment: I am not sure how to pass credentials for the FTP. I am using Trusted Connection for SQL
Comment: Also, I tried that, but I get this error: ```Error = [Microsoft][ODBC Driver 11 for SQL Server]Unable to open BCP host data-file``` I even tried mapping the location as a network drive, so that I can put ```Y:\filename.xml``` in the script. The mapped drive works fine from Windows Explorer, but produces the same error in the script
Comment: `EXEC xp_cmdshell` executes any command, right? So just google for any example how to upload a file to FTP from commandline and do that.
Answer: I had the same error (Unable to open BCP host data-file) on my local machine. For me, it turned out that the file path was too long. When the destination path was shorter, it started working.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33213689)

BCP queryout file to FTP server


spinner selection defines choices for another spinner

Question: I have a question about spinners, and cannot find anything online about how to do it.
I have a spinner in my app, with region selections i.e. Southwest, Southeast.
I want the spinner to selections available of the second spinner to be dependent on the selection made in the first one. i.e. When the user selects Southwest the choices on the second spinner would be Lake Charles, Iowa, Lake Arthur etc. And when the user selects southeast, the choices of the second spinner would be Gretna, New Orleans, Luling etc.
how do I go about doing that?
examples would be greatly appreciated!
Thank you!
Answer: Try this Code..
I hope it will helpful to you...
<code>public class MainActivity extends Activity {

Spinner sp1,sp2;
ArrayAdapter<String> adp1,adp2;
List<String> l1,l2;
int pos;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    l1=new ArrayList<String>();

    l1.add("A");
    l1.add("B");

    sp1= (Spinner) findViewById(R.id.spinner1);
    sp2= (Spinner) findViewById(R.id.spinner2);

    adp1=new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,l1);
    adp1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    sp1.setAdapter(adp1);

    sp1.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            pos=arg2;
            add();

        }

        private void add() {
            // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), ""+pos, Toast.LENGTH_SHORT).show();

            switch(pos)
            {
            case 0:
                l2= new ArrayList<String>();
                l2.add("A 1");
                l2.add("A 2");

                adp2=new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_dropdown_item_1line,l2);
                adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                sp2.setAdapter(adp2);

                select();

                break;
            case 1:
                l2= new ArrayList<String>();
                l2.add("B 1");
                l2.add("B 2");

                adp2=new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_dropdown_item_1line,l2);
                adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                sp2.setAdapter(adp2);

                select();

                break;
            }

        }

        private void select() {
            // TODO Auto-generated method stub

            sp2.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getBaseContext(), "Test "+arg2, Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub

                }
            });

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });
    }

}
</code>
Comment: This is it! Thank you! I just need to make a few changes to match my data, add another spinner, then have that open a new activity!
Answer: Well essentially you would catch the first spinners selection event.  Upon this you would change the contents of the list availabe for the second spinner.  You might also have to call invalidateView() in order for the change to take effect. So there are really three parts
1) Catch the selection in a onClick handler.
2) modify the data for the second spinner, and reset spinner2 data to the adjusted data after filtering.
3) Invalidate the second spinner if needed, and possibly invalidateView on the containingView so it all shows up.
So break it down to these three steps and let us know if you have questions about any of them.
Comment: I forgot to mention how new I am to this. This is my first app and the only experience I have with any kind of coding is basic HTML lol
Comment: actually, I think I found something  http://www.mkyong.com/android/android-spinner-drop-down-list-example/


If 2d is only length and width, but not depth then can something really exist in 2d?

Question: 2d is length and width, not depth. So if I have an object in 2d (0 depth), then it would be non-existent, right? Paper, graphite, etc. have depth even if it is extremely small. Here is my own theory on the 2cnd dimension:The first thing that comes to my mind would be light, but it is made up of waves which have length width and depth. But I thought for a while and realized that color has no depth, but physically exist in our world. Color being how much light is reflected from an object (or how much of one or more types of light waves are absorbed by an object) then, is 2d. So another question I have is, would 2d be measured by length and width, or something like temperature and frequency?
EDIT

I would ask anybody leaving comments to bear in mind that the OP is a potential physicist, at some time in the future and would probably appreciate encouragement. Thanks........ Count_to_10

END EDIT
Comment: you are just saying that true 2D objects does not exist in our 3D world. But what if there exist a 2D world? People living there would have a hard time understanding your question, just like you wouldn't be able to 'visualize' 8D. Beside, even though no 'object' is 2D in our world, the concept is still useful to describe 3D objects. For example, how many dimension does a surface of  your table have?
Comment: Well, I do believe that 2d exists in "our world", but I don't think it is measured by length and width.
Comment: The first thing that comes to mind would be light, but it is made up of waves which have length width and depth. But I thought for a while and realized that color has no depth, but physically exist in our world. Color being how much light is reflected from an object (or how much of one or more types of light waves are absorbed by an object) then, is 2d.
Comment: What I would do, is write out your ideas on paper first, read  through the paper slowly and look where people might not understand what you are saying and then, rather than post your ideas in one go, ask questions about every part of it here, one at a time,  to make sure you are right in your assumptions.  There is plenty of time to get things checked, if you just go ahead and post your ideas, unless you have your facts right, people will not pay much attention to it, no matter how sensible and right it seems to you.
Comment: Ok, I am sure you know about the atoms and the bits that go to make them up, like the electron. As far as we know, the electron might be 2 D, or 4 D or 0 D, (no dimensions at all) and that's because we can't measure it with the instruments we have. If you read this link http://www.pantone.com/how-do-we-see-color you might see how complicated it is to figure out how **exactly** we see color, especially when it's detected by an electron, which might have no dimensions at all. It's really, really complicated, if you read this you will see for yourself https://en.m.wikipedia.org/wiki/Electron
Comment: - thanks, I will definitely give it a look.
Comment: Since the question appears to have been migrated from `physics` to `math` for some odd reason... Please first define `really exist` and `measured by`. Does Euclidian geometry `really exist`? Is the 2d surface of a sphere `measured by` width and length? Do non-measurable sets `really exist`?
Comment: @EmanuelVanRijn Have you heard **fractional dimension**?
Comment: No, I have only heard of the four dimensions, but if you have a website or someway to explain it then I can definitely try to understand it better. (I will also do some research to try to learn more.)
Answer:
(...)
  'I do not mean to ask you to accept anything without reasonable ground for
  it. You will soon admit as much as I need from you. You know of course that a
  mathematical line, a line of thickness nil, has no real existence. They taught you that? Neither has a mathematical plane. These things are mere abstractions.'
  'That is all right,' said the Psychologist.
  'Nor, having only length, breadth, and thickness, can a cube have a real
  existence.'
  'There I object,' said Filby. 'Of course a solid body may exist. All real
  things-'
  'So most people think. But wait a moment. Can an
  instantaneous cube exist?'
  'Don't follow you,' said Filby.
  'Can a cube that does not last for any time at all, have a real existence?'
  Filby became pensive. 'Clearly,' the Time Traveller proceeded, 'any real
  body must have extension in four directions: it must have Length, Breadth,
  Thickness, and - Duration. '
  (...)

H. G. Wells, The Time Machine (1895)
Comment: The line I best remember from that book was "its simple, even a pork butcher could understand it".
Answer: When you actually research if there are such things as 2D objects, you find that there are many objects that are accepted to be 2D, such as electron gas clouds used in electronics. On the other hand, the orientation of a 2D object is not permanently defined.This means that you would be able to render an object invisible simply by changing the direction of observation. As this is not possible(even these electron clouds could be observed from all angles, even more so with proper equipment), there is, in my opinion, no such thing as a 2D object that has been discovered as of yet.
Comment: It is better not to include email addresses in the post. If you really want to you can put such information into your "About me" (this is not a recommendation to do it, but that's the correct place for this type of information).


Need to remove a vertical line in my header. Not sure how it's there

Question: I have just made some links for the header on my site, however, after the second link there is a vertical grey line (the same as the divider between the header and the navbar)
I have tried to reorder the links and I have tried using different columns on bootstrap however only col-6 correctly aligns my links whereas any others such as col and col-4 don't give me this vertical line issue.

.header-area {
  position: relative;
  z-index: 10;
  width: 100%;
  -webkit-transition-duration: 500ms;
  -o-transition-duration: 500ms;
  transition-duration: 500ms;
  background-color: #1c66de;
}

.header-area .top-header-area {
  position: relative;
  z-index: 10;
  width: 100%;
  height: 50px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

@media only screen and (min-width: 768px) and (max-width: 991px) {
  .header-area .top-header-area {
    z-index: 1;
  }
}

@media only screen and (max-width: 767px) {
  .header-area .top-header-area {
    z-index: 1;
  }
}

.header-area .top-header-area .top-header-content {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.header-area .top-header-area .top-header-content a {
  color: #ffffff;
  font-size: 14px;
  font-weight: 400;
  line-height: 50px;
  display: inline-block;
}

             Status
             Support
             Billing

             Login / Register

I expect no line to be after the "support" link
http://prntscr.com/p8fzk9
Comment: I do not see a line!
Comment: @MadeInDreams check the screenshot and look closely. I can assure you there is a line
Comment: is that why your offsetting by 1 pixel?
Comment: href="~" ?? what is that for?
Comment: Let me know if it was that
Comment: @MadeInDreams it wasn't the '~', that was put there by mistake and wouldn't effect it regardless
Comment: where are the other class your using like fa but it's not in the css
Comment: The problem is not reproduced here. The line does not show up so it's impossible to help. I also copied everything to local dev and the problem does not show up. The result does not even match the image. Add what's needed or reproduce it in a fiddle or similar. Also specify the version of bootstrap (which could be affecting the result for me.)
Answer: Added a class x for text decoration and the link underline was gone - if that's what you mean.
                <!DOCTYPE html>

                    <title>Untitled</title>

                                             Status

                                             Support

                                             Billing

                                             Login / Register


Parsing JSON in Java and data manipulation

Question: I'm super new to Java and am trying to parse JSON and manipulate the data into a final data structure as shown below.
I have this model:
public class StoreInfo {
    private String storeName;
    private String storeCode;
    private List<StoreLocations> locations = new ArrayList<>();
}

Here is the JSON response I get from calling Redis:
redisResult = "[{
   storeName: 'Walmart',
   storeCode: '0001',
   locations: [ [Object] ]
 },
 {
   displayName: 'Wegmans',
   storeCode: '0002',
   locations: [ [Object] ]
 }]"

When I call Redis, I use the keyName groceryStores and the fieldName 1.
I want to have a resulting data structure that looks like this:
groceryStores: { 1 : [
  {
    storeName: 'Walmart',
    storeCode: '0001',
    locations: [ [Object] ]
  },
  {
    displayName: 'Wegmans',
    storeCode: '0002',
    locations: [ [Object] ]
  }]

I'm having lots of trouble using Jackson to parse the initial JSON string into the type StoreInfo. When I try the following, I get an exception from Jackson:
StoreInfo[] storeInfoArray = objectMapper.readValue(redisResult, StoreInfo[].class);

I don't understand how I would create an array of StoreInfo objects.
Then, to use the key and field in order to create my final data structure.

I'm super new to Java and I have figured out how to do the latter part in Javascript, but how to do it in Java?
// Assuming the JSON response has been parsed

function addResponse (response, key, field, data) {
    response[key] = {}
    response[key][field] = data
  return response
}

Answer: Easiest Option is create a wrapper class for StoreInfo i.e.
class StoreInfoDTO {
   List<StoreInfo> storeInfoList;
   //getter and setters

}

Now use ObjectMapper as:
StoreInfo[] storeInfoArray = objectMapper.readValue(redisResult,
StoreInfoDTO.class).getStoreInfoList();

Part2, setting the Value in response :
class ResponseDTO {
       @JsonProperty("groceryStores")
       Map<Integer, List<StoreInfo>> props;
      //getter and setters
 }

Now to use it :
    ResponseDTO responseDTO = new ResponseDTO();
    GrosseryStores grosseryStores = new GrosseryStores();
    ArrayList<StoreInfo> storeInfos = new ArrayList<StoreInfo>();
    storeInfos.add(new StoreInfo("SN1","1234"));
    ArrayList<StoreInfo> storeInfos1 = new ArrayList<StoreInfo>();
    storeInfos1.add(new StoreInfo("SN2","1236"));
    Map<Integer, List<StoreInfo>> map = new HashMap<>();
    map.put(1,storeInfos);
    map.put(2,storeInfos1);
    responseDTO.setProps(map);

Comment: Thank you for the response! The first part makes sense to me. However, for part 2, I need an implementation that allows me to set any key or field, not just `groceryStores` and `1`. I will be calling my cache with many different types of stores, and want to combine the responses into one large hash. I suppose I can do this similarly to how I've done the JS example, by passing the values for key and field into a function and setting them that way
Comment: Hey..based on your comment I have updated the response object.Now you should be able to use dynamic keys. Initially , I assumed you are looking for "1" as key.


Why is ESLint complaining about @inheritdoc tag?

Question: ESLint is complaining about a missing JSDoc return declaration even though I placed there an @inheritdoc tag:

This is the relevant part of the interface I am inheriting from:
export interface L2BlockSource {
  /**
   * Gets the sync status of the L2 block source.
   * @returns The sync status of the L2 block source.
   */
  getSyncStatus(): SyncStatus;
}

Anyone have any idea what's wrong?
Thank you
Answer: I think ESlint is not showing the actual problem. Try removing the logic from the parent class method leaving only an empty return.


Pick random numbers from different ranges, what is the probability each is greatest?

Question: Suppose the random variables $X_1, X_2, \ldots, X_n$ are independent distributed uniformly with different bounds: $X_i \sim U(0, x_i)$. What is the probability of "$X_i$ is the greatest number" for each $i$?
We can assume $x_1=1$ and $x_1 \ge x_2 \ge \cdots \ge x_n$. I'm more interested in the inverse problem of how to pick the parameters $x_i$ given the probabilities for "$X_i$ is the greatest number" but working out the relationship between the bounds and the probabilities seems like a necessary intermediate step.
I have solved this for $n=2$ and $n=3$ with geometric methods but I don't see any way to generalize.
Answer: Try conditioning:
\begin{align}
\Pr( X_k \geq X_j \forall j \neq k) &= \frac{1}{x_k} \int_0^{x_k} \Pr( X_k \geq X_j \forall j \neq k | X_k = x)x \mathrm{d} x
\end{align}
I think you will have to split the integral into different parts 0 to $x_1$, $x_1$ to $x_2$, etc.
Comment: The important part now is that the probability under the integral is about lots of *independent* events, so it can be easily numerically calculated as a product. If you need a closed formula, then, as stated, you will have to do it in intervals between the $x_i$
Comment: Thank you! By breaking the integral into intervals I was able to find a simple recurrence relation that makes computations very easy.


Half step mordent in Sibelius

Question: Is there a way I can do the mordent that is shown in the pictures below in Sibelius? When I try to just put a sharp sign below the mordent, it doesn't play it correctly.
Answer: There is an Ornament Playback Plugin for Sibelius. You can select options for inverted and chromatic ornaments. Information about this plugin, including how to find it, can be found at this webpage.
UPDATE: the picture below shows where the Ornament Playback Plugin can be found in the Play tab of the ribbon (this is in the latest version, Sibelius 7):

The picture below shows the dialog box for the Ornament Playback Plugin, with the options that can be set:

The OP is absolutely right with his comments below. This plugin seems to have a bug. When you select Chromatic in General Options, the direction of the mordent is reversed: an upper mordent is played when Lower is selected; a lower mordent is played when Upper is selected. When the chromatic option is not selected the mordents play as expected. This is particularly annoying as the plugin adds the correct symbol for these chromatic mordents (although admittedly it doesn't add the accidental) even though the playback is wrong. So, for chromatic mordents, it is best to add the symbol manually, especially as you have to add the accidental anyway!
Comment: I had to select an upper mordent to get the affect of a lower mordent. This is strange.

Half step mordent in Sibelius


CentOS 7 sending e-mail crons while sendmail is not installed

Question: Background
I have configured my crontab to send me emails that way
firstname.lastname@example.com
...

And I am receiving the e-mail in email@example.com's inbox through the company SMTP server without having to configure anyting. (They do not require authentication if you send an e-mail from the company's network a company e-mail address).
The server is linked to our Windows active directory through Kerberos and Samba, if this is of any help to diagnose the issue.
The issue
I want to edit the e-mail settings because I need to authenticate to the SMTP to be able to send the cron e-mails on non-company e-mails.
What I've tried already
After a quick look on google, I've found this question. Problem: Sendmail is not installed on the server and there is nothing related to e-mail configuration in /etc/sysconfig/crond.
What else can I do to figure out what is used to send e-mails from crond and how to configure it ?
Comment: The source code of the message may have `Received` headers pointing the name of the mail transfer agent. Have you looked into it?
Comment: maybe postfix ? have you an `/etc/postfix` directory ?
Comment: I do have postfix installed, does crond falls back to postfix if sendmail is not installed ?
Comment: @NoahBoegli, both `sendmail` and `postfix` are MTA so they can deliver mail. If you set `postfix` not to listen it can be used to deliver locally and forward the mail.
Comment: I hadn't thought of looking in here. It says postifx. Thanks to all of you for helping me figuring this out!
Answer: The solution
Looking into the headers of the e-mail, there was a small line mentionning postfix.
Furthermore, I could have directly thought of looking for postfix when I found out that sendmail was not installed.
Conclusion: Next time I'll double check e-mail headers before posting.
Comment: This is a typical RTFM (read the fine mail) solution. +1


How to Write Browser Tests on Custom Theme?

Question: I'm writing front end tests for a custom webform. These tests work fine when testing on the webform page of the form.
$this->drupalGet('/webform/custom_form');
$this->assertResponse(200);

However, testing the form using a custom theme and the page that the form is displayed on, does not work and the assertion fails returning a 404 response.
<?php

namespace Drupal\Tests\test_module\Kernel;

use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\webform\Functional\Element\WebformElementBrowserTestBase;

class WebformValidationTest extends WebformElementBrowserTestBase {

  public static $modules = [
    'webform',
    'test_module',
  ];

  public static $testWebforms = ['custom_form'];

  protected $defaultTheme = 'custom_theme';

  /**
   * Test custom_form page from site with custom_theme theme install.
   *
   * @throws \Exception
   */
  public function testThemeFormPage() {
    $this->drupalGet('/page-that-displays-form');
    $this->assertResponse(200);
  }
}

I have also tried creating a submodule that imports the full config and installs all dependent modules from the site. This also did not work.
Is writing front end tests for specific nodes something that is possible with Drupal Browser Tests? If not, how does one write tests for webforms (validation, fields, display, etc)?
Thanks.
Answer: I Would recommend reading
https://www.previousnext.com.au/blog/introducing-drupal-testing-traits-drupal-extension-testing-existing-sites
in this article it explains using https://gitlab.com/weitzman/drupal-test-traits
in this way you can do...
use weitzman\DrupalTestTraits\ExistingSiteBase;

/**
 * Test webform on theme
 */
class WebformValidationTest extends ExistingSiteBase
{
    public function testThemeFormPage()
    {
        $this->drupalGet('/page-that-displays-form');
        // Assert stuff here.
    }
}

Answer: It is possible to get a custom theme to load during a test.
Checkout the webform_bootstrap_test_theme included in the core Webform module. Make sure to includes all the needed blocks.
You can use the WebformNodeBrowserTestTrait to create a webform node during a test.
Still, it is worth checking out DrupalTestTraits.


Firebase i18n rewrite language-override cookie is ignored

Question: I localized an Angular App with the standard Angular localize package. That works perfect and I host my app on firebase. I read the firebase article on how to configure i18n rewrites and implemented it in my firebase.json(https://firebase.google.com/docs/hosting/i18n-rewrites).
The french version is loaded when .../fr, russian one for .../ru depending on the language preference of the user's browser and as a default .../en for English. The rewrite also works as expected.
I also want to enable the user to save their preference and that should be possible by setting
document.cookie = "firebase-language-override=fr"
However, it seems like the cookie is completely ignored and firebase still serves whatever the user's preference is.
Any experience or suggestion what I can do about it? Are there other ways to change the firebase rewrite behavior?
Answer: The problem is most likely related to cache control. When the client loads the page for the first time, it is cached for an hour (by default) and even if you change the cookie, requesting the same page will give you cached result back (the result that is based on initial conditions - user language settings or cookie override).
You can test this by disabling cache in dev tools Network tab.
To solve the problem, try updating cache-control for default routes in your firebase.json:
{
  "headers": [
      {
        "source": "/",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-store"
          }
        ]
      }
    ]
 }

Comment: Thank you so much, this was exactly what I was missing!


Passing WPARAM into DragQueryFile not compatible?

Question: I'm kinda confused. When a file is dragged onto a window with WS_EX_ACCEPTFILES flagged it places a PostMessage into the WndProc function, which sets UINT message to WM_DROPFILES and, according to
https://msdn.microsoft.com/en-us/library/windows/desktop/bb774303(v=vs.85).aspx
the WPARAM = (WPARAM) (HDROP) hDrop; So am I wrong to assume that I can use the WPARAM to initialize the HDROP or just pass it into the DragQueryFile ??
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_CREATE:
    return 0;

case WM_DROPFILES:
    TCHAR* FilePath;
    HDROP hDrop = wParam; //wParam cannot be used to ini. an entity of type HDROP
    //HDROP hdrop = (HDROP)wParam; initialization of hDrop is skipped by case label
    DragQueryFile(wParam, 0, FilePath, 0); //wParam not compatible
    return 0;

case WM_DESTROY:
    PostQuitMessage(0);
    return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}

Every kind of help is appreciated.
Comment: Why `c++` tag here? This is pure C.
Comment: @i486: If it's being passed through a C++ compiler, it is C++. I'm not even convinced C would give that error.
Comment: @BoundaryImposition C++ compilers work as C compilers for `.c` source files or have option for this. Win32 API is in C and in the example above there is nothing C++.
Comment: @i486: GCC if running in C mode is a C compiler, not a C++ compiler. You simply cannot tell from the small snippet of code above whether the OP is writing C or C++, period. The fact that they chose the [tag:c++] tag is firm evidence that it is C++, way more so than your "this is pure C" assertion unsupported by any evidence of any kind.
Comment: @BoundaryImposition The sample in the question is in C, Win32 API is based on C, not C++. At least everything in the possible ansfer of the question will be in C. Then - why talking about C++?
Comment: @i486: It's like you're not listening at all. And I'm sure it's deliberately ironic that the currently highest scored answer involves namespcaes and C++11 features, neither of which are valid in C. Try to engage your brain before writing a comment.
Comment: @BoundaryImposition "currently highest scored answer" with score "1" and total of 2 answers... You have "ultimate" argument. Maybe it is good to engage your brain before your next comment. PS: It is interesting why YOUR answer does not use namespaces and C++ features?
Answer: You need to cast wparam to HDROP and then iterate over dropped file paths supplying buffer.
case WM_DROPFILES:
{
    auto const drop_handle{reinterpret_cast< ::HDROP >(wParam)};
    auto const dropped_files_count
    {
        ::DragQueryFileW(drop_handle, 0xFFFFFFFF, nullptr, 0)
    };
    ::std::vector< wchar_t > buffer;
    for(::UINT dropped_file_index{0}; dropped_files_count != dropped_file_index; ++dropped_file_index)
    {
        auto const file_path_symbols_count_excluding_terminating_null
        {
            ::DragQueryFileW(drop_handle, dropped_file_index, nullptr, 0)
        };
        if(0 < file_path_symbols_count_excluding_terminating_null)
        {
            auto const buffer_size{file_path_symbols_count_excluding_terminating_null + 1};
            buffer.resize(buffer_size);
            auto const copied_symbols_count_excluding_terminating_null
            {
                ::DragQueryFileW(drop_handle, dropped_file_index, buffer.data(), buffer_size)
            };
            if(copied_symbols_count_excluding_terminating_null == file_path_symbols_count_excluding_terminating_null)
            {
                buffer.back() = L'\0'; // just in case....
                // buffer now contains file path...
            }
        }
    }
    break;
}

However note that even though handling WM_DROPFILES should work, the preferred way to handle drag-and drop is to implement IDropTarget interface and register it as drop target handler for your application.
Answer: You're nearly there. You had the right answer, but you commented it out, due to a different error relating to your use of case labels. Instead of going backwards with your HDROP and WPARAM, you should just have fixed that different error ;)
The cast is correct, but you need to scope your case "body" (because, in fact, a case has no body, or scope of its own), and that's what the error's telling you:
case WM_DROPFILES: {
    TCHAR FilePath[MAX_PATH];
    HDROP hdrop = (HDROP)wParam;
    DragQueryFile(hdrop, 0, FilePath, 0);
    return 0;
 }

Here I've added { and } to introduce a block scope.
Comment: Shouldn't that be `hdrop` as the argument to `DragQueryFile`? The arguments for `lpszFile` and `cch` are also incorrect. You are supposed to either pass a preallocated buffer and its size or pass `NULL` for `lpszFile` to get required buffer size.
Comment: but `TCHAR` doesn't make sense since windows 2000.
Answer: add VTT answered.
you can replace ::std::vector< wchar_t > buffer; with std::wstring buffer
code
case WM_DROPFILES:
{
    auto const drop_handle{ reinterpret_cast<::HDROP>(wParam) };
    auto const dropped_files_count
    {
        ::DragQueryFileW(drop_handle, 0xFFFFFFFF, nullptr, 0)
    };
    ::std::wstring buffer;
    for (::UINT dropped_file_index{ 0 }; dropped_files_count != dropped_file_index; ++dropped_file_index)
    {
        auto const file_path_symbols_count_excluding_terminating_null
        {
            ::DragQueryFileW(drop_handle, dropped_file_index, nullptr, 0)
        };
        if (0 < file_path_symbols_count_excluding_terminating_null)
        {
            auto const buffer_size{ file_path_symbols_count_excluding_terminating_null + 1 };
            buffer.resize(buffer_size);
            auto const copied_symbols_count_excluding_terminating_null
            {
                ::DragQueryFileW(drop_handle, dropped_file_index, &buffer[0], buffer_size)
            };
            if (copied_symbols_count_excluding_terminating_null == file_path_symbols_count_excluding_terminating_null)
            {
                buffer.back() = L'\0'; // just in case....
                // buffer now contains file path...
                MessageBox(0, buffer.c_str(), buffer.c_str(), MB_OK);
            }
        }
    }
    break;
}


Slow internet connection issue in android

Question: I'm creating an application in Android in which checks the Internet connectivity. I want to display a toast message when the Internet connection is very slow. Or when the server does not respond to a request. In this case I want to put a toast like Connection is slow !!!. Here in my code I have found the whether the internet is connected or not, but don't know how to toast the message of internet slow...
<code>public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}
</code>
Answer:
For WiFi link speed check WifiInfo.getLinkSpeed()
For Mobile Data Link you can only check TelefonyManager.getNetworkType() to determine the current Mobile Data Link type. You should then aproximate to actual speed by link type (i.e. for GPRS up to 128 kbps, for EDGE up to 236.8 kpbs, for 3G up to 2 Mbps, for HDSPA up to 7.2 Mbps). Take into consideration that this is only an aproximation. Your could be conneting using HDSPA but your carrier limiting the top speed to 2 Mbps.

Now , you have to get speed and put condition whether below 100kbps , "low internet connection"


use GenericAPIView for different seriailizers based on different condition

Question: Due to the use of different serializers based on certain condition, i preferred to use APIView and override get function. I was content with APIView but now that i need pagination feature, I am having trouble to make it happen. That is why i want to switch to GenericAPIView but due to the use of multiple serializer I have no idea how can i do it.
class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS

    def get(self, request, format=None):
        """
        Return a list of all devices of this user.
        """
        reply = {}
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.dev_items().filter(owner=request.user)
            reply['data'].extend(ItemSerializer(items, many=True).data)

        except:
            reply['data'] = []
        return Response(reply, status.HTTP_200_OK)

UPDATE
Another way i tried is
class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS

    def get(self, request, format=None):
        """
        Return a list of all items with product of this user.
        """
        reply = {}
        print ('request', request.META.get('REMOTE_ADDR'))
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.dev_items().filter(owner=request.user)
            page = self.paginate_queryset(items)
            print ('page', page) # i always get None even when pass url as api/items?page=1
            if page is not None:
                reply['data'].extend(ItemSerializer(page, many=True).data)
            reply['data'].extend(ItemSerializer(items, many=True).data)

        except:
            reply['data'] = []
        return Response(reply, status.HTTP_200_OK)

    @property
    def paginator(self):
        """
        The paginator instance associated with the view, or `None`.
        """
        if not hasattr(self, '_paginator'):
            print (hasattr(self, '_paginator'))
            if self.pagination_class is None:
                self._paginator = None
            else:
                self._paginator = self.pagination_class()
        return self._paginator

    def paginate_queryset(self, queryset):
        """
        Return a single page of results, or `None` if pagination is disabled.
        """
        print ('queryset', queryset)
        if self.paginator is None:
            return None
        return self.paginator.paginate_queryset(queryset, self.request, view=self)

    def get_paginated_response(self, data):
        """
        Return a paginated style `Response` object for the given output data.
        """
        assert self.paginator is not None
        return self.paginator.get_paginated_response(data)

No any way is working. Where have i done mistake?
Comment: Possible duplicate of [http://stackoverflow.com/questions/29071312/pagination-in-django-rest-framework-using-api-view](http://stackoverflow.com/questions/29071312/pagination-in-django-rest-framework-using-api-view).
Comment: @hybor Thanks for your reply. In my case there is use of two serializer so I do not have any idea on dealing this.
Comment: I tried that page = self.paginate_queryset(items)
            print ('page', page)
            if page is not None:
                reply['data'].extend(ItemSerializer(page, many=True).data)
            reply['data'].extend(ItemSerializer(items, many=True).data) but i get page as None all the time even when passing url as ?page=1
Answer: Do you really need two serializers ?
I think it may be a better choice to use a single Serializer with a custom to_representation:
class ItemSerializer(ModelSerializer):
   # Your fields

   def to_representation(self, instance):
       data = super(ItemSerializer, self).to_representation(instance)
       request = self.context.get('request')
       if request and instance.is_owned_by(request.user):
           return self.owner_to_representation(data, instance) # TO IMPLEMENT
       return data

Then, you can use a generic view. Your code is cleaner, simpler and you do not have to worry about the pagination:
class ItemList(generics.ListAPIView):
    serializer_class = ItemSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get_queryset(self):
        return BaseItem.objects.owned_items()| BaseItem.objects.dev_items()

Answer: This is as simple as importing your paginator, and calling it manually in the APIView.
class PollView(views.APIView):
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication,)
paginator = CustomPagination()

def get(self, request):
    queryset = Poll.objects.all()
    context = self.paginator.paginate_queryset(queryset, request)
    serializer = PollSerializer(context, many=True)
    return self.paginator.get_paginated_response(serializer.data)

NOTE: Custom class is not necessary, you can simply import from rest_framework.pagination at the top of your script. I created a CustomPagination class, inheriting from PageNumberPagination, so that I could set the page_size query, as per docs - http://www.django-rest-framework.org/api-guide/pagination/


Conditional LEFT JOIN clause SQL Server where conditionality in second table

Question: I have a view (v_Flat_DemogTDComps) which contains the following fields (among others)
PatientID     Integer
[Start date]  DateTime
SystemicStart DateTime

I also have a table (Operation) with:
PatientID                Integer
[Operation/Reason Date]  DateTime
[Surgical]               Boolean
[Operation/Reason Name]  String

I want to LEFT JOIN v_Flat_DemogTDComps ON Operation where:

PatientID = PatientID AND
(
If [Surgical] = 1 THEN [Operation/Reason Date] = SystemicStart OR
 If [Surgical] = 0 THEN [Operation/Reason Date] = [Start Date]
)

Ultimately, I want to SELECT everything in v_Flat_DemogTDComps along with [Operation/Reason Name]
I've tried using this solution and thought about creating two Views of Operation (one where Surgical=1 and one where Surgical=0): Case statement in Join Clause
However this only seems to work where the conditional part is in the first table. There is nothing in v_Flat_DemogTDComps which can determine whether I should use one View of Operation over another.
How do I JOIN when the conditional clause is in the second table?
Answer: Use Or and And operator to simulate If else. Try this.
ON v_Flat_DemogTDComps.PatientID = Operation.PatientID
AND ( ( [Surgical] = 1
        AND [Operation/Reason Date] = SystemicStart )
        OR ( [Surgical] = 0
            AND [Operation/Reason Date] = [Start Date] ) )

Comment: I've tried this as well but it only returns values where Surgical = 0 and the rest are null.
Comment: @Matthew can you sample data and desired output.
Comment: Silly mistake - SystemicStart had actual times recorded whereas the other three DateTime fields simply had 00:00:00.000. Your solution worked after using CONVERT() on the relevant fields.


Is the projection from $\mathbb R^n$ locally isometric to the flat torus?

Question: I'm reading a problem asking to introduce a Riemannian metric on $T^n$ in such a way that the projection $\pi(x_1,...,x_n)=(\exp(ix_1),...,\exp(ix_n))$ from $\mathbb R^n$ to $T^n$ is a local isometry. Does the flat metric apply here?
By definition, flat torus is defined as the product of n copies of the Riemannian manifold $S^1$ with its metric induced by $\mathbb R$.
Comment: Maybe you ought to clarify what the projection $\pi$ you refer to is?
Comment: I editted my question @T_M
Comment: isn't the flat metric exactly defined via this property? related to this: https://math.stackexchange.com/questions/450110/metric-of-the-flat-torus?rq=1
Comment: I'm reading DoCarmo's book and the definition there is different @Balou
Comment: maybe you should state then how "the flat metric" is defined in DoCarmo
Comment: @Balou I added the definition in my question
Comment: ok, then it is less obvious then if you defined it via $T^n = R^n / Z^n$ and the inherited metric...
Answer: Yes; both of these spaces are "flat" in the sense that the curvature of the Riemannian metric is identically zero.
Comment: Why does DoCarmo following this question want to prove that the torus with the metric introduced is isometric to the flat torus? Is it not redundant?
Comment: I imagine it's just building familiarity with the rigorous definitions. Just because you know it's true, it certainly doesn't mean that its a pointless exercise
Answer: Notice that the natural projection written above maps a point of $R^n$ to a point in $T^n$. This may seem odd at first but notice how the coordinate curves of $R^n$ get mapped to $T^n$. Because $e^{ix}$ is a point in a complex circle, the projection essentially wraps each axis of $R^n$ into a circle of the torus. This maps coordinate curves into coordinate curves. Since the projection is evidently the cartesian product of a number of complex circles (which are the same as $S^1$) you can introduce the product metric the same as if you were working with real numbers exclusively. Since you can take the vectors to be coordinate curves locally, the product metric is a local isometry.


Generalized linear models (GLMs)

Question: Let's say, I want to establish a relation between the distribution of $Y$ and $p$ covariates. I denote the covariates with $x_1,x_2,...,x_p$. Then, I denote the linear predictor with $\eta$ , where $\eta = \beta_0 + \beta_1 x_1 + ~... ~+\beta_p x_p$ .
Thus, $E \left[Y|X \right]=\mu$, which is connected with the linear predictor by the response function $h$, where $\mu=h(\eta)$. Finally, I call $g$ the inverse of $h$, where $g= h^{-1}$. It must be noted that $\eta=g(\mu)$, and $g$ is called the link function.
Why does the link function $g$ make the model linear? The question seems a bit trivial, but is the answer that $\eta=g(\mu)$ is just a definition, in the sense that the linear predictor is linear because $g$ is a linear function?
Comment: It's called linear because the cheeky statisticians apply the link function on the left side of the equation, so viewed from that angle, the right side (linear predictor) remains a polynomial. However, when considering the effect of parameter changes on the expectation value of the response, a GLM is not linear.
Answer: Some clarifications:
$\bullet$ The linear predictor
$$\eta_i =\sum_{j=1}^p\beta_jx_{ij}\tag 1\label 1$$
is linear in the parameters.
$\bullet$ $g(\cdot), $ aka the link function that links $\eta_i$ to $\mu_i$ by $\eta_i=g(\mu_i), $ i.e., $\mu_i\mapsto \mathbf x_i^\top\boldsymbol\beta$, is monotonic and differentiable.
So, $g\left(\mathbb E[Y]\right) $ is linear in the parameters. This is the basis of GLM.

Generalized linear models (GLMs)


Troubling calculation for a wreath product of groups.

Question: Let $G$ be a group, $H$ a transformation group acting on a set $S$, and suppose $G$ acts on another set $T$. Let $G\wr H$ denote the wreath product of $G$ and $H$. So the composition for $(f_1,h_1),(f_2,h_2)\in G\wr H$, (where $f$ is a map of $S\to G$), is defined as
$$
(f_1,h_1)(f_2,h_2)=(f_1(h_1f_2),h_1h_2).
$$
Also, if $G^S$ denotes the set of maps, it is a group if we define $(f_1f_2)(s)=f_1(s)f_2(s)$. And for $h\in H$ and $f\in G^S$, define $hf$ by $(hf)(s)=f(h^{-1}s)$, which is an action of $H$ on $G^S$. I wanted to check that for $(t,s)\in T\times S$, the rule $(f,h)(t,s)=(f(s)t,hs)$ gives an action of $G\wr H$ on $T\times S$.
I calculate
$$
\begin{align*}
[(f_1,h_1)(f_2,h_2)](t,s) &= (f_1(h_1f_2),h_1h_2)(t,s)\\
&= ((f_1(h_1f_2))(s)t,(h_1h_2)(s))\\
&= ((f_1(s)(h_1f_2)(s))t,h_1h_2s).
\end{align*}
$$
But
$$
\begin{align*}
(f_1,h_1)[(f_2,h_2)(t,s)] &= (f_1,h_1)(f_2(s)t,h_2s)\\
&= (f_1(h_2(s))f_2(s)t,h_1h_2s)\\
\end{align*}
$$
which is puzzling since I'm getting different $h_i$ in the first entry, when they should be equal, to satisfy one of the properties of being a group action. Have I applied something incorrectly here?
Comment: I think, maybe you should regard the side you take the functions. I mean that sometimes we write $xf$ and sometimes we take $f(x)$. Actions may lead to different results.
Comment: Right, but do you see an error in my calculations?
Comment: I write your action like $(t,s)^{(f,h)}$=$(t^{f(s)},s^h)$ wherein $(t,s)\in T× S$ so, $((t,s)^{(f_1,h_1)})^{(f_2,h_2)}$=$((t^{f_1(s)},s^{h_1}))^{(f_2,h_2)}$=$(t^{f_1(s)f_2(s^{h_1}),s^{h_1h_2}})$. I think this notation makes clear what you are looking for. Hope it help.
Comment: The wreath product symbol is typset with `\wr`, rather than with `\int`.
Answer: This is exercise 1.12.11 out of Jacobsons Basic Algebra 1 right? I believe that this question has a mistake in the phrasing. Given you notation, one should define the action of $G\wr H$ on $T\times S$ by
$$
(f, h)(t, s):= (f(hs)t, hs).
$$
Doing this, you avoid the problems you were experiencing in the calculation.
Comment: Use `\wr` for the wreath product symbol. `\int` produces the wrong symbol (mirror image and the shading is all wrong), and bad spacing,
Comment: It's not the question (posed by hmIII) that "has a mistake in phrasing". The error (a typo, or perhas not) is in Exercise 1.12.11 in Jacobson's Basic Algebra I.
Comment: Thanks.  This was driving me crazy.


Webform/YAML Form component email mapping

Question: In Drupal 7, Webform module have the ability to map different emails against webform component's options so that the webform notification could be sent to different emails depending on a user selection.

In Drupal 8, Webform was ported and its email submission settings pretty basic so I decided to use YAML Form. However, YAML Form email handler have the ability to either have a custom emails separated by comma or a value from the component.

Is there a way to have component email mapping functionality?
Answer: The feature has been added to the latest dev release of Webform-8.x-5.x.
@see Issue #2854021 by jrockowitz: Send email based on element options selection
Answer: Currently the functionality is not inbuilt to web forms UI but it can still be done with a custom module.
Following the webform recpie on handlers you can create a custom email handler like so:
Folder/File structure:

ModuleName

src

Plugin
WebformHandler

MODULENAMEWebformHandler.php

MODULENAME.info.yml

Content example for MODULENAMEWebformHandler.php
<code>namespace Drupal\MODULENAME\Plugin\WebformHandler;
use Drupal\Core\Url;
use Drupal\webform\Plugin\WebformHandler\EmailWebformHandler;

/**
* Emails a webform submission.
*
* @WebformHandler(
*   id = "test_email",
*   label = @Translation("New Email"),
*   category = @Translation("Notification"),
*   description = @Translation("Send email depending on dropdown value"),
*   cardinality = \Drupal\webform\WebformHandlerInterface::CARDINALITY_UNLIMITED,
*   results = \Drupal\webform\WebformHandlerInterface::RESULTS_PROCESSED,
* )
*/
class MODULENAMEWebformHandler extends EmailWebformHandler {

  public function sendMessage(array $message) {

    $form_data = $message['webform_submission']->getData('dropdown_id');

    switch($form_data) {

     case 'APAC':
       $recipient = 'email@example.com';
     break;

     case 'US':
       $recipient = 'email@example.com';
     break;

     default:
       $recipient = 'email@example.com';
     break;

    }
    $message['to_mail'] = $recipient;

    parent::sendMessage($message);
  }
}
</code>


MATLAB image transformation

Question: The following code descripes the affine transformation of an image, I,
T = [sx, 0, 0;...
      0, sy, 0;...
      0, 0, 1];
tform = maketform('affine', T);
[J,cdata,rdata] = imtransform(I,tform);

After obtaining the transformed image, J, I want to find the appropriate pixel value of I(5,5) on image J.
What should I do?

My code is
function test()
    sx = 0.5; sy = 1;
    theta = pi/4;
    Ts = [sx, 0, 0;...
    0, sy, 0;...
    0, 0, 1];
    Tr = [cos(theta) -sin(theta) 0;...
          sin(theta) cos(theta), 0; ...
          0, 0, 1];
    T = Ts*Tr;

    I = imread('image_0002.jpg');
    tform = maketform('affine', T);
    [J,xdata,ydata] = imtransform(I,tform);
    h = ydata(2) - ydata(1);
    w = xdata(2) - xdata(1);

    %%
    gridOx = meshgrid(1:50:size(I,2), 1:50:size(I,1));
    gridOy = meshgrid(1:50:size(I,1), 1:50:size(I,2))';
    go = [gridOy(:), gridOx(:), ones(length(gridOx(:)),1)];

    for i=1:size(go,1)
        I = makept(I, go(i,1), go(i,2));
    end
    imshow(I);

    %%
    gt = T*go';

    TL = T*[1,1,1]';
    BL = T*[size(I,1), 1, 1]';
    TR = T*[1, size(I,2), 1]';
    BR = T*[size(I,1), size(I,2), 1]';
    minr = min([TL(1), TR(1), BL(1), BR(1)]);
    minc = min([TL(2), TR(2), BL(2), BR(2)]);

    %%
    gt = int32(round(gt));
    r = gt(1,:) - minr+1;
    c = gt(2,:) - minc+1;

    figure,hold on;
    for i=1:length(r)
        J = makept(J, r(i), c(i));
        plot(gt(1, i), gt(2, i));
    end
    figure, imshow(J);

    close all;
end

function I = makept(I, r, c)
    mr = max(r-2,1);
    mc = max(c-2,1);
    maxr = min(r+2,size(I,1));
    maxc = min(c+2,size(I,2));

    I(mr:maxr, mc:maxc,:) = 0;
    I(mr:maxr, mc:maxc,1) = 255;
end

Answer: You transform the pixel coordinates just like you transformed the image.
appropriatePixel = J(T*[5;5;1]);

EDIT
The code you posted was already quite close. Always remember that with images, the origin for images is in the top left and that the order of image dimensions is columns-rows, unlike with matrices. You took this into account in some places, but not everywhere.
The code below should fix the problem. gt = T*go was changed to use the transpose of T, and minc and minr were swapped.
function airplane()
       close all
       sx = 0.5; sy = 1;
       theta = pi/4;
       Ts = [sx, 0, 0;...
       0, sy, 0;...
       0, 0, 1];
       Tr = [cos(theta) -sin(theta) 0;...
           sin(theta) cos(theta), 0; ...
           0, 0, 1];
       T = Ts*Tr;

       I = imread('airplane2.png');
       tform = maketform('affine', T);
       [J,xdata,ydata] = imtransform(I,tform);

        %%
       gridOx = meshgrid(1:50:size(I,2), 1:50:size(I,1));
       gridOy = meshgrid(1:50:size(I,1), 1:50:size(I,2))';
       go = [gridOx(:), gridOy(:), ones(length(gridOx(:)),1)];

       figure; imshow(I); hold on;
       scatter(go(:,1), go(:,2), 25, 'rs', 'filled');

       %%
       gt = T'*go';

       TL = T*[1,1,1]';
       BL = T*[size(I,1), 1, 1]';
       TR = T*[1, size(I,2), 1]';
       BR = T*[size(I,1), size(I,2), 1]';
       minc = min([TL(1), TR(1), BL(1), BR(1)]);
       minr = min([TL(2), TR(2), BL(2), BR(2)]);

       %%
       gt = int32(round(gt));
       r = gt(1,:) - minr+1;
       c = gt(2,:) - minc+1;

       figure; imshow(J);hold on;
       scatter(c, r, 25, 'rs', 'filled');

end

Result:
Comment: Right. Based on the example I was thinking of (positive) scaling transforms only. Well in that case, first do this transform on all four corners of the image, take the minimum x and y and subtract that from the above, and add one, so that the origin is back at 1,1.
Comment: no.. if I transform a pixel coordinate the transform pixels may be [-5.5, -20].
Comment: What `sx` and `sy` are you testing with?
Comment: Thank you very much.. I found another way to solve this problem.. I added the answer... We need to scale it as well..
Comment: When the transformed image is big matlab rescales it.. so we need to multiply by a scaling factor... as NPtImage(:,1) = NPt(:,1) - xdata(1) + 1;
              NPtImage(:,2) = NPt(:,2) - ydata(1) + 1;      we need to do it at this point...        gt = int32(round(gt));
       r = gt(1,:) - minr+1;
       c = gt(2,:) - minc+1;.. anyway thank you very much for your answer and effort.... really thank you..
              NPtImage(:,1) = NPtImage(:,1)*scalex;
              NPtImage(:,2) = NPtImage(:,2)*scaley;
Comment: for more http://blogs.mathworks.com/steve/2006/02/14/spatial-transformations-maketform-tformfwd-and-tforminv/
Answer: I found another way.. use 'tformfwd'.. we need to apply a scaling as well as explained in http://blogs.mathworks.com/steve/2006/02/14/spatial-transformations-maketform-tformfwd-and-tforminv/
         function [new_im, grn, gcn] = transformImage(I, gr, gc, TM)
              [new_im xdata ydata] = imtransform(I, TM);
              w = xdata(2)-xdata(1) +1;
              h = ydata(2)-ydata(1)+1;
              scalex = size(new_im,2)/w;
              scaley = size(new_im,1)/h;

              % cartesian coordinates
              go = [gc(:), gr(:)];

              %% cartesian coordinates
              NPt = tformfwd(TM, go);

              % convert to image coordinates
              NPtImage(:,1) = NPt(:,1) - xdata(1) + 1;
              NPtImage(:,2) = NPt(:,2) - ydata(1) + 1;
              NPtImage(:,1) = NPtImage(:,1)*scalex;
              NPtImage(:,2) = NPtImage(:,2)*scaley;
              NPtImage = round(NPtImage);

              grn = NPtImage(:,2);
              gcn = NPtImage(:,1);
              grn = reshape(grn, size(gr,1), size(gr,2));
              gcn = reshape(gcn, size(gc,1), size(gc,2));

              showimgs = false;
              if showimgs
                  I = uint8(I);
                  new_im = uint8(new_im);

                  figure, imshow(I), hold on;
                  for i=1:size(go,1)
                      plot(go(i,1), go(i,2), 'r*');
                  end

                  figure, imshow(new_im, 'XData', xdata, 'YData', ydata);
                  hold on
                  axis on
                  for i=1:size(go,1)
                      plot(NPt(i,1), NPt(i,2), 'r*')
                  end

                  tmpim = new_im;
                  for i=1:size(NPtImage,1)
                      tmpim = makept(tmpim, NPtImage(i,2), NPtImage(i,1), 'b');
                  end
                  figure, imshow(tmpim);
              end

              end

              function I = makept(I, r, c, color)
              mr = max(r-2,1);
              mc = max(c-2,1);
              maxr = min(r+2,size(I,1));
              maxc = min(c+2,size(I,2));

              I(mr:maxr, mc:maxc,:) = 0;

              if strcmp(color, 'r')
                  I(mr:maxr, mc:maxc,1) = 255;
              else
                  I(mr:maxr, mc:maxc,3) = 255;
              end
              end

MATLAB image transformation


General Graph Cycle Detection (Confirm my Answer please)

Question: The problem:
An undirected graph is unicyclic if it contains exactly one cycle. Describe an O( |V| + |E| ) algorithm for determining whether or not a given graph, G is unicyclic.
My solution:
int i = 0
Run a modified DFS on G, where we increment i everytime we decide not to visit a vertex because it has already been visited.
After DFS is done, if i==1, graph is unicyclic.
I thought this solution would work but am wondering if there is a counter example that would prove it false. If anyone could clarify that would be great, Thanks.
Comment: "where we increment i everytime we decide not to visit a vertex because it has already been visited." what do you mean by this line?
Answer: "Increment i everytime we decide not to visit a vertex because
it has already been visited."

I am quite unclear about what you are trying to do here.
Rather then this, how about this:
Perform DFS and count number of back edges.
A back edge is an edge that is from a node to itself (selfloop) or one of its
ancestor in the tree produced by DFS.

If number of back edges ==1 then unicycle else not.
To count number of back edges, follow this algorithm.

To detect a back edge, we can keep track of vertices currently in recursion stack of
function for DFS traversal. If we reach a vertex that is already in the recursion stack,
then there is a cycle in the tree. The edge that connects current vertex to the
vertex in the recursion stack is back edge

Comment: I meant that I would modify the portion of the DFS code to be if vertex v is unexplored then label e as a discovered edge, recursively call DFS(G,v) ELSE i++ (increment i because we decided not to visit an already visited node)
Answer: Does your graph consists of a single connected component?
In this case just count vertices and edges and check |V| - |E| = 0
Otherwise count the number of connected components O(|V| + |E|),
and check |V| - |E| = number of connected components - 1.
Remark: having more than one connected component is a counterexample to your algorithm.
Comment: Oh that is clever, but would it not be check |V| - |E| = 0, since a graph containing 2 vertices and 1 edge is not a cyclce and 2-1=1. Also, would my algorithm would work if I restarted the modified DFS in each component?
Comment: @user2931097 thanks for the remark, I've just edited


ASP.NET Core Web API controller to extract http header on each request

Question: I'm trying to extract http header prior to executing any controller action and have it stored in a property on a controller.
The controllers inherit from ControllerBase which doesn't have OnActionExecuting to override.
I can't seem to find an elegant way of doing it other than having something like MyCustomBaseController that implements ControllerBase, have all of my controllers implement MyCustomBaseController and then do action filter on MyCustomBaseController that would extract headers and save it to some custom property on it.
Sounds clumsy.
Is there any more elegant way?
Comment: Is the real question how to bind to a header? Have you checked the [FromHeader](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromheaderattribute?view=aspnetcore-7.0) attribute?
Comment: [FromHeader](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromheaderattribute?view=aspnetcore-7.0) can be used with properties too and possibly inherited, based on the `System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)` attribute
Comment: No, I'm saying use normal parameter binding, like you would with query or form parameters. `MyAction(int id,[FromHeader] string myHeader)` or `MyAction(MyDTO dto)`. `AttributeTargets.Property` suggests you can apply the attribute to a *model* property
Comment: Why are you asking about a *controller property* specifically? Controller properties are never used to bind to request data. You'll find over 300 SO questions and answers about FromHeader though
Comment: @PanagiotisKanavos no, its a rest api. probably old habit of having, for example, `Controller.User` as a property. But you absolutely have a point: there is no reason for having header value as a property and if there is ever a need for communicating between different parts of the pipeline (which is rare), we have `httpContext.Items` for that.
Comment: did you try `middleware`?
Comment: @RomanMarusyk no. is there a way to write header value to controller property from middleware or the best it can do is writing to `httpContext.Items`?
Comment: @PanagiotisKanavos no, the real question is if there is a way to have header value in custom controllers property before any of the actions is being executed.
Comment: @dzg that's your assumed solution to accessing the header value. There's no reason or benefit to binding to properties instead of parameters. Each request is server by a different controller instance, so a *property* can't be used to "communicate" between actions or with views. Unless you use a static property (a bad idea and a security risk), property contents aren't persisted
Comment: @PanagiotisKanavos so if i understand correctly, what you're suggesting is reading header directly from `httpContext` within an action where i need the value? (or bind it to parameter, same thing)
Comment: @PanagiotisKanavos yeah, that make sense. i believe you're right that i went into a dead-end for no practical reason. please post it as answer so i can accept it.
Comment: Did you have some other stack in mind, like Razor Pages? The "PageModel" architecture can cause a "bit" of confusion
Answer: You can bind header contents to action parameters or model properties using the FromHeader attribute.
Request data isn't bound using controller properties in MVC or Web API, the way it's done in Razor Pages. Data can only be bound to action parameters. You can find the available binding sources in the Binding Source Parameter inference section of the Web API overview docs.
In a controller-based aplication (MVC, Web API), a new controller instance is created to server each request. Request data is provided to the action itself, not the controller.


Finding a basis for the columnspace of a matrix

Question:
Find a linearly independent set of vectors that spans the same subspace of $R^4$ as that spanned by the vectors -
  $$
\begin{bmatrix}
2 \\
-4 \\
-1 \\
-2 \\
\end{bmatrix}
,
\begin{bmatrix}
7 \\
-2 \\
7 \\
2 \\
\end{bmatrix}
,
\begin{bmatrix}
1 \\
2 \\
3 \\
2 \\
\end{bmatrix}
,
\begin{bmatrix}
3 \\
-2 \\
2 \\
0 \\
\end{bmatrix}
$$

So I start by reducing the matrix of these vectors to echelon form -
$$
\begin{bmatrix}
1 & -7 & -3 & -2 \\
0 & 21 & 7 &  7 \\
0 & -30 & -10 & -10 \\
0 & -12 & -4 & -4 \\
\end{bmatrix}
$$
$$
\begin{bmatrix}
1 & -7 & -3 & -2 \\
0 & 3 & 1 &  1 \\
0 & -3 & -1 & -1 \\
0 & -3 & -1 & -1 \\
\end{bmatrix}
$$
$$
\begin{bmatrix}
1 & -7 & -3 & -2 \\
0 & 3 & 1 &  1 \\
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
\end{bmatrix}
$$
Then I get $x_2 = -\frac{1}{3}x_3 - \frac{1}{3}x_4$ and $x_1 = \frac{2}{3}x_3 - \frac{1}{3}x_4$
So this gives me the linearly independent vectors below that span the same subspaces as the original vectors -
$$
\begin{bmatrix}
1 \\
0 \\
\frac {2}{3} \\
-\frac {1}{3}\\
\end{bmatrix}
,
\begin{bmatrix}
0 \\
1 \\
-\frac {1}{3} \\
-\frac {1}{3} \\
\end{bmatrix}$$
But when I enter this answer I am told it is incorrect...anyone able to see where Im going wrong?
Comment: Try writing the first of your four vectors as a linear combination of the two you derived. It is impossible.
Comment: @Brian_CS: (Edit, too late; deleted old comment and fixed it) What you are doing is finding a basis for the nullspace. What you are supposed to be doing is finding a basis for the columnspace. The columnspace does not equal the nullspace, and elementary row operations do not respect the columnspace.
Comment: @Samuel Reid: isn't it obvious that row 3 and 4 and linear combinations of row 2? just thought Id save myself writing in another matrix.
Comment: @AlexBecker: can you see where I am going wrong though, I can't pinpoint where I am making a mistake.
Comment: I am certified as blind as a bat.
Answer: Start with a matrix whose columns are the vectors you have.
Then reduce this matrix to row-echelon form.
A basis for the columnspace of the original matrix is given by the columns in the original matrix that correspond to the pivots in the row-echelon form.
What you are doing does not really make sense because elementary row operations do not preserve the column space, but you are looking for a basis of the column space. In the end, what you are finding is a basis for the nullspace of the matrix, but what you are looking for is a basis for the columnspace.
Now, the nullspace and the rowspace are orthogonal to each other (in fact, orthogonal complements), so you could use your two vectors to find a basis for the column space, but it's too much extra work.
So: starting with the matrix of vectors you have,
$$\begin{align*}
\left(\begin{array}{rrrr}
2 & 7 & 1 & 3\\
-4 & -2 & 2 & -2\\
-1 & 7 & 3 & 2\\
-2 & 2 & 2 & 0
\end{array}\right) &\to
\left(\begin{array}{rrrr}
-1 & 7 & 3 & 2\\
-4 & -2 & 2 & -2\\
2 & 7 & 1 & 3\\
-2 & 2 & 2 & 0
\end{array}\right) \to
\left(\begin{array}{rrrr}
-1 & 7 & 3 & 2\\
0 & -30 & -10 & -10\\
0 & 21 & 7 & 7\\
0 & -12 & -4 & -4
\end{array}\right)\\
&\to \left(\begin{array}{rrrr}
-1 & 7 & 3 & 2\\
0 & 3 & 1 & 1\\
0 & 3 & 1 & 1\\
0 & 3 & 1 & 1
\end{array}\right) \to
\left(\begin{array}{rrrr}
\color{red}{-1} & 7 & 3 & 2\\
0 & \color{red}3 & 1 & 1\\
0 & 0 & 0 & 0\\
0 & 0 & 0 & 0
\end{array}\right)
\end{align*}$$
(Same thing you had)
Now, since the pivots of the row echelon form are in columns 1 and 2 (marked in red), that means that columns 1 and 2 of the original matrix are independent and span the column space. That is, you can take
$$\left(\begin{array}{r}
2 \\-4\\-1\\-2\end{array}\right)\quad\text{and}\quad
\left(\begin{array}{r}
7\\-2 \\ 7 \\ 2
\end{array}\right).$$
It should be easy to see that the two vectors are linearly independent. Also,
$$\left(\begin{array}{r}
1\\2\\3\\2\end{array}\right) = -\frac{2}{3}\left(\begin{array}{r}
2\\-4\\-1\\-2\end{array}\right) + \frac{1}{3}\left(\begin{array}{r}7\\-2\\7\\2\end{array}\right)$$
and
$$\left(\begin{array}{r}
3\\-2\\2\\0\end{array}\right) = \frac{1}{3}\left(\begin{array}{r}
2\\-4\\-1\\-2\end{array}\right) + \frac{1}{3}\left(\begin{array}{r}7\\-2\\7\\2\end{array}\right)$$
so the first two columns span the same space as all four.
The reason this works is that any linear combination between the columns is respected by elementary row operations (equivalently: elementary row operations do not change the nullspace).  Since the columns that contain the pivots are necessarily a basis for the columnspace of the row-echelon form, the corresponding columns in the original form a basis. In fact, you can find the expressions I found above to show the other two columns are linear combinations by looking in the reduced-row echelon form instead of the original matrix; this is often easier.
This method extracts a subset of your original set that is a basis for the span of the set; that is, it gives you a way to pare your set down to a basis. If all you need is to find a basis, you can also begin by putting the vectors as the rows of a matrix and then performing elementary row operations until you get a matrix in row-echelon form. The (transpose of the) rows that contain the pivots in the row-echelon form give you a basis for the span of the original vectors. The reason this works is that elementary row operations don't change the row space, and the rows that contain the pivots are clearly a basis for the row space of the row-echelon form of the matrix. But you would not look for the nullspace in any case.
Comment: Excellent answer, cheers mate.


Increasing/decreasing audio on a video element, triggered via jQuery Waypoints

Question: I have a page with a series of (HTML 5) videos whose audio needs to fade in or out depending on your position on the page (and it may be different for each video). I'm using jQuery Waypoints with the InView plugin to detect when an element is in the viewport. I'm not sure how to do it consistently, so that you don't cause unexpected behavior when you trip a waypoint while the volume is still decreasing or increasing.
var waypoint = new Waypoint.Inview({
  element: $('#element')[0],
  enter: function() {
    $('#element')[0].volume = 0;
    $('#ielement')[0].play();
    incVol($('#element')[0]);
  },
  entered: function() {},
  exit: function() {},
  exited: function() {
    decVol($('#element')[0]);
  }
});

function incVol(e) {
  setTimeout(function() {
    if ((e.volume + .05) < 1) {
      e.volume += .05;
      incVol(e);
    } else {
      e.vol = 1;
    }
  }, 100)
}

function decVol(e) {
  setTimeout(function() {
    if ((e.volume - .05) > 0) {
      e.volume -= .05;
      decVol(e);
    } else {
      e.volume = 0;
      e.pause();
    }
  }, 100)
}

This is an inconsistent attempt, if you trigger 'enter' while 'decVol' is still running you lose volume completely and have to trigger an 'exit', wait, and then trigger 'enter' again.
I've also tried something with jQuery's animate on volume. But that doesn't seem consistent either.
var waypoint = new Waypoint.Inview({
  element: $('#element')[0],
  enter: function() {
    $('#element')[0].volume = 0;
    $('#element')[0].play();
    $('#element').animate({
      volume: 1
    }, 1000);
  },
  entered: function() {},
  exit: function() {},
  exited: function() {
    $('#element').animate({
      volume: 0
    }, 1000, function() {
      $('#element')[0].pause();
    });
  }
});

If I scroll up and down too fast, especially if I have multiple waypoints of this type in the page, then the queue of events becomes extensive and I  have fade ins/outs happening far after the events have triggered (though, I prefer this implementation for the moment).
Any suggestions on how to achieve what I want a little better?
Answer: Prefacing the animate() function with stop() is the answer.
Something like:
$('#element').stop(true, false).animate({
  volume: 1
}, 1000);


Bijection between $\mathbb{P}^{1}(\mathbb{C})$ and the unit sphere

Question: I have the following complex analysis problem that I am completely lost on.

Let $(z_{1},z_{2})$ be a non-zero vector in $\mathbb{C}^{2}$ and define $F:\mathbb{C}^{2}\to\mathbb{R}^{3}$ by $$F(z_{1},z_{2})=\left(\frac{z_{1}\bar{z}_{2}+\bar{z}_{1}z_{2}}{z_{1}\bar{z}_{1}+\bar{z}_{2}z_{2}},\frac{z_{1}\bar{z}_{2}-\bar{z}_{1}z_{2}}{i(z_{1}\bar{z}_{1}+\bar{z}_{2}z_{2})},\frac{z_{1}\bar{z}_{1}-\bar{z}_{2}z_{2}}{z_{1}\bar{z}_{1}+\bar{z}_{2}z_{2}}\right).$$ Show that:
(1) $F$ defines a bijection between $\mathbb{P}^{1}(\mathbb{C})$ and the unit sphere in $\mathbb{R}^{3}$;
(2) if $S$ denotes stereographic projection from $\mathbb{C}_{\infty}-\{(0,0,1)\}$ to $\mathbb{C}$ and $[z_{1}:z_{2}]\neq[1:0]$, then $S(F([z_{1}:z_{2}]))=\frac{z_{1}}{z_{2}}$.

As mentioned above, I really have no idea of where to begin. Any suggestions and comments are appreciated!
Comment: No, I think $z_{1}$ and $z_{2}$ are supposed to be two non-zero vectors in $\mathbb{C}^{2}$.
Comment: Ahhh, okay, I see your point. Sorry, I was confused over notation for some reason. I'll edit the question.
Comment: And I assume that $[z_1:z_2]$ means basically the same thing as $(z_1,z_2)$. You're applying $F$ to both.
Comment: I believe so, yes.
Comment: On second thought, $[z_1:z_2]$ is the same as $[kz_1:kz_2]$, unlike vectors. I think $[]$ denotes an element of the projective space, while $()$ denotes an element of the ordinary vector space.
Comment: That's part of where I was confused. I think you're right on the distinction between the two.
Comment: The domain of $F$ is not actually $\mathbb C^2$, because $F(0,0)$ is undefined. (The denominator is simply the squared magnitude of the vector.)
Answer: As for (1), you first need to show that the domain and range are correct. The function $F$, as defined, has domain $\mathbb C^2$, not $\mathbb{PC}$. But it suffices to show that $F(z_1,z_2) = F(kz_1,kz_2)$ for any $k\neq0$ . Then $F$ applied to an element of $\mathbb{PC}$ can be defined as $F$ applied to any representative in $\mathbb C^2$, because all representatives have the same value of $F$. (Remember the definition of a function: any input must have exactly one output.)
The codomain (a superset of the range) given is $\mathbb R^3$. (Check that all components of $F$ are actually Real numbers.) You need to show that the function maps to the unit sphere; $\lVert F(z_1,z_2)\rVert = 1$ .
A bijection is an injection and a surjection. $F$ being an injection means that it's one-to-one, that different inputs cannot give the same output. $F$ being a surjection, also called "onto", means that the range is the entire unit sphere, not just a part of it. Another way to think of bijectivity is that $F^{-1}$ is uniquely defined everywhere on the unit sphere.

(2) is slightly confusing. I haven't seen a definition of $\mathbb C_\infty$ , but the fact that $S$ is applied to the output of $F$ implies that $\mathbb C_\infty$ is simply the unit sphere in $\mathbb R^3$. (I think this is bad notation, similar to saying that $\mathbb R^2 = \mathbb C$.)
Stereographic projection is invertible, so (2) is equivalent to $F(z_1,z_2) = S^{-1}(\frac{z_1}{z_2})$. I'm familiar with the Real version of stereographic projection as
$$(x,y,z) = S^{-1}(X,Y) = \left(\frac{2X}{X^2+Y^2+1}, \frac{2Y}{X^2+Y^2+1}, \frac{X^2+Y^2-1}{X^2+Y^2+1}\right)$$
(Is there a specific definition that you have to work with?)
Compare this with the given components of $F$, which can be rewritten as
$$F(z_1,z_2) = \left(\frac{2\,\text{Re}(z_1\overline z_2)}{|z_1|^2+|z_2|^2}, \frac{2\,\text{Im}(z_1\overline z_2)}{|z_1|^2+|z_2|^2}, \frac{|z_1|^2-|z_2|^2}{|z_1|^2+|z_2|^2}\right)$$
or, noting that $\frac{z_1}{z_2} = \frac{z_1\overline z_2}{|z_2|^2}$ if $z_2 \neq 0$ ,
$$F(z_1,z_2) = \left(\frac{2\,\text{Re}(z_1/z_2)}{|z_1/z_2|^2+1}, \frac{2\,\text{Im}(z_1/z_2)}{|z_1/z_2|^2+1}, \frac{|z_1/z_2|^2-1}{|z_1/z_2|^2+1}\right)$$
I think you can see the connection, if $z_1/z_2 = X+iY$.


OData Support in ASP.net core

Question: Is oData supported now in ASP.netcore now that version 1 has been released?
I have searched, but I could not find anything that says one way or the other.
Answer: Edit: now available at https://www.nuget.org/packages/Microsoft.OData.Core/
It's in the road map, OData Lib has released 7.0.0 which is a breaking change release, OData/WebAPI will release 6.0.0 based on this, after the release, we will consider to support ASP.NET Core. Relative issue: https://github.com/OData/WebApi/issues/772
Comment: Also, some pre-release code: https://www.nuget.org/packages/Microsoft.AspNetCore.OData/
Comment: @FanOuyang What is available is just the OData library, not the webapi integration?
Comment: the link is not update/clear about where you are with this? Can you shed a light
Comment: According to the issue mentioned in the post, the development of OData for asp.net core hasn't been finished yet. Any alternatives ?
Comment: This lib appears to have .NetCore support: https://gitlab.com/djanosik/moon-odata
Comment: @ChrisW This package is not officially supported by Microsoft. It's an individual attempt to port OData to ASP.NET Core, and it hasn't been updated since 2016.
Answer: Now at the beginning of December 2017, an official prerelease of OData for ASP.NET Core is available at this MyGet feed: https://www.myget.org/F/webapinetcore/
The releases are currently from nightly builds.
For more information, see this comment on a GitHub issue: https://github.com/OData/WebApi/issues/772#issuecomment-348670747
Still no ETA for beta or stable releases.

EDIT: This issue is better to follow to track progress:
https://github.com/OData/WebApi/issues/939
EDIT 2: Beta1 was released December 22. If used with Swashbuckle, this is a great tip: https://github.com/OData/WebApi/issues/1177#issuecomment-358659774
Answer: According to the blog OData team at Microsoft
https://blogs.msdn.microsoft.com/odatateam/2018/07/03/asp-net-core-odata-now-available/
There is a a release of OData for ASP.NET Core at :
https://www.nuget.org/packages/Microsoft.AspNetCore.OData
Regards

OData Support in ASP.net core


laravel Maatwebsite\Excel 3.1 locked cell

Question: referring from official documentation laravel excel implementing styles can refer from PhpSpreadSheet and i succeed try to make a row bold.
then how can we protect some columns from being edited ?
I've tried use \PhpOffice\PhpSpreadsheet\Style\Protection and implementing lock but seem doesn't work
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class someExport implements FromArray, WithHeadings, ShouldAutoSize, WithStyles
{
    public function styles(Worksheet $sheet)
    {
        return [
            // Style the first row as bold text and disable Column A for edited
            1 => ['font' => ['bold' => true]],
            'A' => [
                'protection' => [
                    'locked' => true,
                ],
            ],

        ];
    }

    /**
     * function headings()
     * function array()
     * some source array
     */
}

Comment: Hello have you tried looking at https://github.com/SpartnerNL/Laravel-Excel/issues/1349 ?
Answer: full implementation from PhpSpreadSheet Setting security on a spreadsheet look like this
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class someExport implements FromArray, WithHeadings, ShouldAutoSize, WithStyles
{
    public function styles(Worksheet $sheet)
    {
        // Make sure you enable worksheet protection if you need any of the worksheet or cell protection features!
        $sheet->getParent()->getActiveSheet()->getProtection()->setSheet(true);

        // lock all cells then unlock the cell
        $sheet->getParent()->getActiveSheet()
            ->getStyle('T2:T10')
            ->getProtection()
            ->setLocked(Protection::PROTECTION_UNPROTECTED);

        // styling first row
        $sheet->getStyle(1)->getFont()->setBold(true);
    }

    /**
     * function headings()
     * function array()
     * some source array
     */
}

Comment: Isn't there a way of just locking specific cell instead of locking the entire sheet and then unlocking the specific cells you want? I searched the entire web and de library source code for it and couldn't find it. It doesn't make sense to me.
Comment: @ThallesPortilho I just found it on the documentation and direct implement it


Topic Models: Latent Dirichlet Allocations

Question: I am trying to figure out the details of LDA and have been stuck for a while now. While reading the paper by Blei, I came across this -

Latent Dirichlet allocation (LDA) is a generative probabilistic model of a corpus. The basic idea is that documents are represented as random mixtures over latent topics, where each topic is characterized by a distribution over words.
  LDA assumes the following generative process for each document w in a corpus D:

Choose N ∼ Poisson(ξ)
Choose θ ∼ Dir(α)
For each of the N words wn:

Choose a topic zn ∼ Multinomial(θ).
Choose a word wn from p(wn |zn,β), a multinomial probability conditioned on the topic zn.

When they mention Choose θ ∼ Dir(α), they mean that the probabilities come from a Dirichlet distribution and in case of an observation (or any number of obs), we update the α and the probabilities change accordingly. And when they say Choose N ∼ Poisson(ξ), they mean the number of words in each document can be sampled from a Poisson distribution, that is if I have the number of words in each document they will follow a Poisson distribution. So this part I get (or correct me if I have gotten the details wrong).
Gaps in my understanding:

I want to understand what the authors mean when they say choose a topic zn ~ Multinomial(θ). From my understanding of the multinomial distribution parameterized by θ, you get the probability of a particular distribution of events (ex: picking a ball from a bag with replacement n times). So how do we choose a topic for each word using a multinomial distribution?
From what I understand each document is randomly assigned topic probabilities and each topic is assigned word probabilities and is updated later on. My question is how are these probabilities updated?
Comment: I can't tell what confuses you about the inference referenced in your second question, but if you clarify I'd be happy to try and update my answer. Cheers!
Comment: Actually, that's a useful example: The variational method in the paper defines a function to minimize (KL divergence), which turns out to be equivalent to maximizing log-likelihood. ("The
overall procedure can thus be viewed as coordinate ascent in L," says the paper.) Does that help?
Comment: @SeanEaster thanks for the answer. my confusion is around how the parameters - the topic proportions across documents, distribution of words over topics get updated. I read a little on Gibbs sampling but couldn't make much out of it. This is the part that has me confused. To give an example in gradient descent we have a loss function and learning parameter to adjust the weights. How is that taking place here?
Answer: To the first question, your confusion seems due to the use of the term "multinomial" in the paper. Somewhat confusingly, "multinomial" is used for the multinomial and categorical distributions. (The two are analogous to binomial and Bernoulli.)
So what the authors mean is that each word in the document is assumed to have a single topic sampled according to $\theta_d$. (We then sample a word from the topic's corresponding distribution.) The document has a mean distribution over possible topics; each word is assumed assigned to a single, unknown topic.
As written, your second question is rather broad: Section 5 of the paper covers inference in depth.
Answer: I have been trying to implement a LDA program in python. So, far I have had little luck. I have found this youtube video rather informative and easy to understand.
I am a programmer and I do not really understand weird mathematical notations, but here is what I collected.

ndk = number of times in document, topic t was observed
vkwdn = number of times in topic k, wdn was observed
Assign topics randomly to each word in each document
Count the number of times a word was used in a topic from all docs
Count the number of times a document has a word of a particular topic
Normalize the vectors in 4 and 5 for each topic
Multiply M1[document][topic] with M2[topic][word] for each topic
You should get a probability vector, having the probability for each topic
Sample randomly using the vector as weights
Assign it to the topic of that word in that document
Go to step 4 unless everything has converged


jQuery AJAX response type

Question: I'm trying to make a working example of jQuery 1.9.1 AJAX + icanhaz/mustache. This is my template:

and this is my JavaScript:
$(document).ready( function() {
    $("#user-btn").click(function() {
        $.ajax({
            type: "GET",
            url: "../php/client/json.php",
            data: {
                type: "users"
            }
        }).done(function( response ) {
            var element = $('#dialog-message');
            element.html("
");
            element.append(ich.user(response));
            element.append("
");
        });
});

The AJAX response from this address looks something like:
{"users":[{"username":"jd","fullname":"John Doe"},{"username":"jl","fullname":"John Lennon"}]};

With the following code, icanhaz cannot render anything for me. I spent some time with javascript console and found out that the typeof response is string and I expected object. Icanhaz also expects object - that's why it didn't manage to render the correct response.
Am I doing something wrong or am I just a poor newbie who didn't know that jquery.ajax returns string responses always? If so, how should I handle them?
Answer: If you are getting a string returned from your AJAX call, you need to add dataType: "json". This will make jQuery parse the response as JSON, if possible.
$(document).ready( function() {
    $("#user-btn").click(function() {
        $.ajax({
            type: "GET",
            url: "../php/client/json.php",
            data: {
                type: "users"
            },
            dataType: "json"
        }).done(function( response ) {
            ...
        });
});

Are you sure your ich.user method expects an array of users and not just a single user object?
Comment: yep, I'm sure, because I'm iterating through them (see [another question](http://stackoverflow.com/questions/15650487/icanhaz-mustache-loop-iterate-through-elements-js-error/15652623)).
Comment: OK... glad it is correct. Just thought I mentioned it, since the function naming looked odd. :)
Answer: Try the option dataType: "json" for $.ajax.
Answer: Modify the click function:
$("#user-btn").click(function () {
    $.ajax({
        type: "GET",
        url: "../php/client/json.php",
        data: {
            type: "users"
        },
        dataType: 'json',
        success: function (data) {
            // Your code...
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});

Comment: @Marcel - That is not correct... `jqXHR.success` and `jqXHR.error` are being deprecated, but not the methods within the `ajax` call.
Comment: can you explain what is wrong with `done` (you have replaced it with `success` and `error`)?
Comment: It is suggested no longer to use `success` and `error` because they may be removed in the future. `done` is the way to go.
Comment: Nothing wrong with it but this is a much better approach, as I have been using it in most of my jQuery ajax calls! And they work perfectly fine!
Comment: @Will.i.am can you please explain why it is better apporach or give me any link so that I can study this topic?
Comment: Yes, sure. Here's is one [jQuery Ajax Function Example](http://www.jquery4u.com/function-demos/ajax/)! I hope it helps!
Comment: I disagree with the statement that @Will.i.am's solution is the "much better approach".  It is mostly a matter of preference.  I actually use the `success` and `error` approach myself most of the time, but there are certainly situations where the implementation of the `jqXHR` Promise implementation can be of benefit.

jQuery AJAX response type


Why Qt Creator can link dll correctly without .lib and LoadLibrary()?

Question: Usually when we link to a dll, we must use .lib as well so that the linker can tell it is dynamic linking.
However in Qt Creator we can do this without it.
I followed the instruction on youtube, and I simply the process as follows:

Prepared a TestMessagePack.dll, compiled by GCC;
Copy the dll to debug folder, where the exe locate in.
add the codes below, which also instructs where the include files locate in.

INCLUDEPATH += "C:\Users\***\Desktop\Brand New\CMakeStuff\include\qmsgpack"

LIBS += "C:\Users\***\Desktop\Brand New\CMakeStuff\bin\TestMessagePack.dll"

build and run.

Without step 2, the linker will fail.
This is obvious that, Qt Creator can link to a dll without .lib.
But how can the linker know without .lib file?
I need to know the principle inside
Comment: Step 2 is not required.  All that's required is to tell the linker that those functions exist somewhere, and you do that by specifying the lib file.  The steps you're following gives the erroneous idea (maybe inadvertently) that DLL's are used in the build process, when that is not the case.  Maybe the Qt system tries to find the "lib" file from the dll name you gave it, but by no means is the actual DLL file be required to build the application.  To **run**  your application, *then* the DLL becomes important.
Answer: You are using one of the various MinGW?? Windows ports of GCC. On Windows,
the GCC toolchain's linker (ld) supports direct linking of DLLs, unlike the Microsoft linker
which requires a proxy .lib import library. Documentation:

direct linking to a dll
The cygwin/mingw ports of ld support the direct linking, including data symbols, to a dll without the usage of any import libraries.
...

And MinGW: Specify the libraries for the linker to use

MinGW supports libraries named according to the ".lib" and ".dll" conventions, in addition to the normal "lib.a" convention common on *nix systems.
...

This behaviour is given by the MingGW?? linker you are using. It means that the linkage of dynamic libraries with ld can be done in the same way on Windows as on unix-like OSes, where import libraries do not exist.  Qt is not relevant.


atoi giving wrong result for alpha decimal strings

Question: I am trying to call atoi() on the following strings: "54" and "54df4". While the first input gave me the correct result of 54, the call on second string also gave me the result of 54. I assume that the function is converting the string to decimal as far as possible; instead, it should not convert at all.
Why is this so? The following is my code:
cout << "Wrong: " << atoi("54df4") << endl;

Thanks,Rakesh.
Comment: What makes you think it should behave any differently?
Comment: Thank you all for the pointers - I am just curious as to why it is defined to work partially. It shouldn't process such mixed strings right?
Answer: That's how atoi is specified to work. If you don't want to convert strings containing non-digit characters you have to pre-scan the string, or use a function such as strtol which can give back the location of the first non-digit character:
cons char *number = "54df4";
char *endp = NULL;

int value = strtol(number, &endp, 10);

if (endp != NULL && endp < (number + strlen(number)))
{
    printf("Stopped scanning in middle of string, it contains non-digit characters\n");
}

Answer: From the documentation of atoi

The string can contain additional characters after those that form the
  integral number, which are ignored and have no effect on the behavior
  of this function.
Answer: Because that's how atoi is defined. Taking this man page for instance:

The atoi() function converts the initial portion of the string pointed to by nptr to int.

Or in C standard:

C11 (n1570), § 188.8.131.52 The atoi, atol, and atoll functions
The atoi, atol, and atoll functions convert the initial portion of the string pointed to by nptr to int, long int, and long long int representation, respectively.

If you want to do complexer operations on the string to convert, use strtol instead (see this answer for instance).
If you don't agree with these specifications, write your own function!
Answer: From the following somewhat arbitrarily found man page for atoi....
http://linux.die.net/man/3/atoi
*The atoi() function converts the initial portion of the string pointed to by nptr to int. *
In short, the function is working exactly as it is defined.