I'm getting TypeError: Cannot setitem on a Categorical with a new category (Less than 35), set the categories first

Question: I have a dataframe with columns Age and MedianValue.  Both are numeric.  I want to bucket the Age variable into 3 groups and then perform an ANOVA analysis.  When I try to create the buckets, I get TypeError: Cannot setitem on a Categorical with a new category (Less than 35), set the categories first
Here's what I tried:
<code>df.loc[(df['AGE'] <= 35), 'age_group'] = 'Less than 35'
df.loc[(df['AGE'] > 35)&(df["AGE"] < 70), 'age_group'] = '35 to 70'
df.loc[(df['AGE'] > 70), 'age_group'] = 'Over 70'

# Separate samples into a variable each
a = df[df['age_group'] == "Less than 35"]["MEDV"]
b = df[df['age_group'] == "35 to 70"]["MEDV"]
c = df[df['age_group'] == "Over 70"]["MEDV"]

f_statistic, p_value = stats.f_oneway(a, b, c)
print("F_Statistic: {0}, P-Value: {1}".format(f_statistic,p_value))
</code>
The error is throwing on the first line. I'm in a Jupyter notebook running python 3.10
I have used this type of code before in other environments.  Either I'm missing something or was there a change in 3.10?
Comment: @toyota Please don't use the [tag:python3] tag unless the question is version-specific, and even then, include the [tag:python] tag too.
Comment: Please provide a [mre]. For specifics, see [How to make good reproducible pandas examples](/q/20109391/4518341).
Answer: I solved this using cut to create the age groups first and then add them to the dataframe
<code># Create the age groups
age_groups = pd.cut(df['AGE'], bins=[0, 35, 70, 100], labels=['Less than 35', '35 to 70', 'Over 70'])

# Add the age groups to the dataframe
df['age_group'] = age_groups

# Separate samples into a variable each
a = df[df['age_group'] == "Less than 35"]["MEDV"]
b = df[df['age_group'] == "35 to 70"]["MEDV"]
c = df[df['age_group'] == "Over 70"]["MEDV"]

# Perform ANOVA analysis
f_statistic, p_value = stats.f_oneway(a, b, c)

# Print the results
print("F_Statistic: {0}, P-Value: {1}".format(f_statistic, p_value))`age_groups = pd.cut(df['AGE'], bins=[0, 35, 70, 100], labels=['Less than 35', '35 to 70', 'Over 70'])
</code>


Edit XML file on web page and save back to XML file using PHP

Question: I have an XML file with a list of events and need to edit them via a web page, and when the edited data is submitted then it needs to be saved back to the XML file.
I have used an XSL file to display the XML on the web page. For each node it displays an empty input box with the node value to the right. How can I get the node value to appear inside the input text box? And how can I get the node name to appear on the left of the input text box?
The next problem is that once this has been edited then how can I get it stored back in the XML file with exactly the same structure?
One more thing, how can I add or remove an event? Thanks.
Here's the XML file:
<?xml version="1.0" encoding="UTF-8"?>
<events>
    <event>
        <id>ev01</id>
        <date>31/12/2020</date>
        <start-time>09:00</start-time>
        <end-time>12:00</end-time>
        <title>Event #1</title>
        <cost>20</cost>
        <venue>London</venue>
        <available-places>10</available-places>
        <updates><![CDATA[We'll post updates here]]></updates>
    </event>
    <event>
        <id>ev02</id>
        <date>31/12/2020</date>
        <start-time>13:00</start-time>
        <end-time>17:00</end-time>
        <title>Event #2</title>
        <cost>20</cost>
        <venue>London</venue>
        <available-places>Sold out</available-places>
        <updates><![CDATA[We'll post updates here]]></updates>
    </event>
</events>

And here's the XSL file:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/events">

My events

  <form method="post" action="#edit_xml">
    <xsl:for-each select="event/*">

      <input type="text" id="" name="" value="">
      <xsl:value-of select="." />
      </input>

    </xsl:for-each>

<input type="submit" name="submit_data" value="Submit"/>

  </form>

</xsl:template>

</xsl:stylesheet>

Comment: Please see [how to ask](https://stackoverflow.com/help/how-to-ask) and provide an [MCVE](https://stackoverflow.com/help/minimal-reproducible-example).
Comment: @ArSeN , thanks for the pointer, I hope my questions are presented a bit better now.
Answer: To answer your XSLT questions to render HTML form:

How can I get the node value to appear inside the input text box? And how can I get the node name to appear on the left of the input text box? ... One more thing, how can I add or remove an event?

Consider adjusting XSLT to use name() and assign value with expression: {text()}. And even wrap node name inside  tag with styling for alignment. Even more, add a unique <input> id (for CSS/Javascript to identify) and name (for PHP to identify) using XSLT functions: name() and position(). For better management of each event, separate script into event and events templates
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/events">

My events

             <form method="post" action="#edit_xml">
                 <xsl:apply-templates select="event"/>

<input type="submit" name="submit_data" value="Submit"/>

             </form>

    </xsl:template>

    <xsl:template match="event">
        <xsl:for-each select="*">

                  <xsl:value-of select="name()"/>

              <input type="text" id="{concat(name(), position())}"
                     name="{concat(name(), position())}"
                     value="{text()}"/>

        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

Online Demo

To remove an element, run bracketed [] condition in <xsl:apply-templates> in top layer events template:

<xsl:apply-templates select="event[1]"/>

<xsl:apply-templates select="event[2]"/>

<xsl:apply-templates select="event[position() > 1]"/>

<xsl:apply-templates select="event[position() != 2]"/>

<xsl:apply-templates select="event[last()]"/>

For this non-XSLT question:

The next problem is that once this has been edited then how can I get it stored back in the XML file with exactly the same structure?

You need to handle the form submission with application layer like in PHP to receive input values and bind into XML document. In fact, you can set up another XSLT solution with exact original layout to receive parameters from PHP!
Comment: Likewise! Glad to help. XSLT is not designed to handle server-side processing of form data. So that is a different question. Before asking, please research and make an earnest attempt. Read up on 1) how to handle user submitted HTML forms and 2) how to edit or rebuild XML files with PHP variables.
Comment: Merry Christmas and thank you for your answer. I'd like to understand what you meant by "set up another XSLT solutions with exact original layout to receive paramenter from PHP. Are you able to explain here or should I ask a new question?
Comment: Ok I'll look into those topics. Thank you for your advice.


GMap Module - markers not showing up

Question: I can't seem to get my markers to come up in the Gmap module - I've changed permissions, I've checked the gmap_markers.js file, etc.
The map itself comes up, but I can't get any markers to appear.
What could cause this?
Could it be permission settings on my /default/files directory?
Comment: are there any javascript errors?
Comment: Not that I saw. I'll double check after work tonight, and also write down what my macro is.

The page is andrewjalexander.com/travel - I'm just trying to put down a few markers of different places I've visited and/or lived.
Comment: [gmap markers=red::42.333302, -83.048401 |zoom=5 |center=42.333302, -83.048401 |width=800px |height=600px |control=Small |type=Hybrid]

No Javascript errors.
Comment: are you using custom markers?  and a dumb question: are you sure that the map's javascript is firing on page load?
Comment: I am not using custom markers, no.

The map is popping up, so I would assume yes. Or are you asking about whether it is firing on page load specifically - if so, I'm not sure, but can check.
Answer: This question is obviously very old, but I spent the last few hours figuring out the same issue and figured this might help someone else who is Googling this problem.
The problem for me was this:
In Modules, "Location Entity" should NOT be enabled.  "Location CCK" (in the Fields section) should be.
Then, when modifying the Content Types, do NOT rely on the "Location" field that is there by default (machine name = locations).  You have to add your own, additional Location field (field type = Location; widget = Location Field).
This solved the problem for me.  I created a View (Page) for a Specific Content Type with Format = GMap and Data Source = Location.module.
Then it finally worked!  Hope this helps.
Answer: I looked everywhere for a way to fix this issue for me, and none of the answers I found worked. So I thought I'd post my solution here, in case it might help someone else in future. My problem was simply that I had the theme_debug variable set to 1. As soon as I turned theme debug back off, all my markers worked again! With drush you can just do (in Drupal 7) "drush vset theme_debug 0". That fixed my issue!

GMap Module - markers not showing up


Is the logic in the series random or is something happening here?

Question: My brother gave me a series to find the next number
11, 42, 93, 164, 255, 366, 497, 648, __.
The logic while making the sum was to append the square of the units digit to the left of the unit digit.
Example square of 1 is appended to 1 hence 11, square of 2 is left appended to 2 so 42...
When I was solving this I found that the series was following a pattern. When you subtract 2 consecutive numbers you get 31, 51, 71, 91, 101, 111, 131 etc.
I am just curious as to why the difference is increasing by 20. It would be really great if someone can give some explanation for this. Is it just by luck or something happening here?
NOTE: This series follows this pattern only till units digit as 9. After that the pattern of difference that I found breakes.
Comment: The votes to close here are bizarre.  In what sense is this question "opinion-based"?
Comment: Hint: as long as there's a single units digit $u$, you can write the expression for that term in the sequence by $10u^2+u$ — can you see why? Now try subtracting the $u$ term from the $u+1$ term with a little algebra.
Comment: @EricWofsey Voted to reopen : could be a duplicate but not opinion-based for sure.
Answer: For single digit $n$, the term is $10n^2+n$.
So the difference between successive terms is $10(n+1)^2+(n+1) -(10n^2+n) = 20n+11$ as in the pattern you have spotted.
If $n$ has two digits then the term is $100n^2+n$ with differences of $200n+101$ with a slight glitch when $n=9$ and $n+1=10$.  And similarly for larger $n$.
See OEIS A055436, A055437, A055438 for the three sequences
Comment: Thank you soo much! I got it now!


Algebraic expression in its most simplified form

Question: I am trying to simplify the algebraic expression:
$$\bigg(x-\dfrac{4}{(x-3)}\bigg)\div \bigg(x+\dfrac{2+6x}{(x-3)}\bigg)$$
I am having trouble though. My current thoughts are:
$$=\bigg(\dfrac{x}{1}-\dfrac{4}{(x-3)}\bigg)\div \bigg(\dfrac{x}{1}+\dfrac{2+6x}{(x-3)}\bigg)$$
$$=\bigg(\dfrac{x(x-3)}{1(x-3)}-\dfrac{4}{(x-3)}\bigg)\div \bigg(\dfrac{x(x-3)}{1(x-3)}+\dfrac{2+6x}{(x-3)}\bigg)$$
$$=\bigg(\dfrac{x(x-3)+(-4)}{(x-3)}\bigg)\div \bigg(\dfrac{x(x-3)+2+6x}{(x-3)}\bigg)$$
$$=\dfrac{x(x-3)+(-4)}{(x-3)}\times \dfrac{(x-3)}{x(x-3)+2+6x}$$
$$=\dfrac{x(x-3)+(-4)(x-3)}{(x-3)x(x-3)+2+6x} $$
$$\boxed{=\dfrac{-4(x-3)}{2(1+3x)} }$$ Which does not appear is not the answer. Am I close? Where exactly did I go wrong? I have tried this question multiple times.
Edit: Figured it out!
$\dfrac{x(x-3) - 4}{x(x - 3) + 2(1 + 3x)}\implies\dfrac{x^2-3x-4}{x^2+3x+2}\implies \dfrac{(x-4)(x+1)}{(x+2)(x+1)}$
$(x+1)$'s cancel leaving us with: $\boxed{\dfrac{x-4}{x+2}}$
Comment: Good work on the update! :-)
Answer: You did not distribute the term $(x - 3)$ in the denominator when you wrote:
$$\begin{align} & =\dfrac{x(x-3)+(-4)}{(x-3)}\times \dfrac{(x-3)}{x(x-3)+2+6x} \\ \\ & =\dfrac{x(x-3)+(-4)(x-3)}{(x-3)x(x-3)+2+6x} \end{align}$$
What would be correct is the following denominator:
$$\begin{align} & \quad\color{blue}{(x-3)}[x(x-3)+2+6x] \\ \\ & = \color{blue}{(x-3)}x(x-3)+\color{blue}{(x-3)}(2+6x)\end{align} $$

But note
$$\dfrac{x(x-3)+(-4)}{\color{blue}{\bf (x-3)}}\times \dfrac{\color{blue}{\bf(x-3)}}{x(x-3)+2+6x}$$
The highlighted terms cancel, leaving you:
$$\begin{align} & =\dfrac{x(x-3)+(-4)}{1}\times \dfrac{1}{x(x-3)+2+6x} \\ \\
& = \frac{x(x-3) - 4}{x(x - 3) + 2 + 6x} \\ \\
& = \dfrac{x^2-3x-4}{x^2+3x+2} \tag{$\diamondsuit$}
\end{align} $$
Now, all both the numerator and denominator of $\diamondsuit$ factor very nicely, and in fact, share a common factor, and hence, can be further simplified.

Recall: $$\frac{[b + c]a}{a[d+e]} = \frac{a[b+c]}{a[d+e]} = \frac{b+c}{d+e}$$
Or: $$\frac{a[b+c]}{a[d+e]} = \frac{ab+ac}{ad+ae}= \frac{b+c}{d+e}$$
Comment: Okay, but once at: $\frac{x(x-3) - 4}{x(x - 3) + 2(1 + 3x)}$ The (x-3)'s cancel Leaving the Numerator as x-4 but the denominator still has x+2(1+3x). What else am I missing here?
Comment: Got it. Redistributing and factoring again I get trinomials which simplify further $\dfrac{x^2-3x-4}{x^2+3x+2}\implies \dfrac{(x-1)(x+1)}{(x+2)(x+1)}$ (x+1)'s cancel leaving us with: $\dfrac{x-4}{x+2}$. Thanks alot amWhy!
Comment: @Amzoti Thanks!
Comment: @nitrous2 You're welcome!
Answer: Comment: After the calculation very well described by AWertheim and amWhy, we end up wit $\dfrac{x^2-3x-4}{x^2+3x+2}$.
Note that the calculation is not over. The top and bottom each factor nicely, and there will be some cancellation.


Yii multisort in CArrayDataProvider

Question: Does Yii supports built in multi column sort for CArrayDataProvider(Yii 1.1.2), if yes please let me know how we can do, i'm new to yii.
Thank You.
Comment: Probably this: http://www.yiiframework.com/doc/api/1.1/CArrayDataProvider?
Answer: Try the following (Yii API Doc example):
<code>$dataProvider=new CArrayDataProvider($rawData, array(
    'id'=>'user',
    'sort'=>array(
        'multiSort'=>true,
        'attributes'=>array(
             'id', 'username', 'email',
        ),
    ),
    'pagination'=>array(
        'pageSize'=>10,
    ),
));
</code>

Yii multisort in CArrayDataProvider


Events add all calendars in iOS 6.1?

Question: I tried to get calendar title from my iPhone (iOS 6.1), but nothing found inside.
How to get calendar title from iOS 6.1? please help me.
Thanks in Adnvance
I tried this:
EKEventStore *store = [[EKEventStore alloc]init];
EKEvent *event = [EKEvent eventWithEventStore:store];
NSArray *list = [[NSArray alloc]init];
list = [[store calendarsForEntityType:EKEntityTypeEvent] copy];
// Calendars deprecate in iOs 6.1
// Retain deprecate, so use "copy"

NSLog(@"list:  %d",[list count]);

for(EKCalendar *calendar in list)
{
    NSLog(@"list:  %@",calendar.title);
}

Answer: hope this helps....
EKEventStore *store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
    }];
NSArray *arrCalenders = [store calendars];//below iOS 6.o
NSLog(@"%@", arrCalenders);
NSArray *arrayCalndars = [store calendarsForEntityType:EKEntityTypeEvent]; // In ios 6.o
NSLog(@"%@", arrayCalndars);

This displays the Current list of calendars...

Events add all calendars in iOS 6.1?


IOS iphone 6 screen and tiny Font sizes

Question: Could anybody direct me how to correctly manage the fonts on mobile devices.
Currently my Font-Size is in PX. and i am also using media queries. Which look great on dektop and the page is responsive and the fonts are enlarged on small screen sizes.
However on an Iphone 6 , the screen does not go into Responsive as the screen size is 1200px + and so unfortunatly the fonts remain very small.
I have little idea how to further approach this problem. as any attempts i make to Compensate the font sizes on the iphone become greatly enlarged on Desktop.
iv done as much researh as i can get my head round includining using other methods of Font-size - i.e VW , Rem , EM ect and all have failed to produce consistant , readable fonts on the iphone.
i would list the code but its an awful lot at present, so i will try to offer what i can.
Any help would be greatly appreciated.
here is the code for the top banner.
HTML:

        <?php
        //TOP BANNER
        include('../../innerelements/topbanner/html/topbanner.php');

        //LOGO & SEARCH BAR
        include('../../innerelements/Searchbar/html/searchbar.php');

        ?>

PHP Included file - Topbanner.php

Hello  <text class='accountname'> matthew </text>

Daily Deals

Brand Outlet

Help & Contact

Sell

Watch List

My Vbay

CSS:
body{
-webkit-text-size-adjust: 100%;
padding:0px;
margin:0px;

}

.maindiv{
    position: absolute;
    width:100%;
    height:100%;
    padding: 0px 0px 0px 0px;
    MIN-WIDTH: 600px;
    display: block;
}
.topbanner{
    position: relative;
    width: auto;
    height: auto;
    padding: 0;
    display: flex;
    justify-content: space-between;
    font-family: "Helvetica Neue",Helvetica,Arial,Verdana,Sans-serif !important;
    font-size: 100%;
    border-bottom: 1px solid lightgrey;
    text-align: left;
    text-size-adjust: 100%;
    white-space: nowrap;
    /* line-height:14px; */
}

.accountname{
    font-weight:bold;
    margin-right: 36px;
    overflow: hidden;
}

.leftmenu{
    position: relative;
    width: auto;
    height: auto;
    padding: 6px;
    margin-left: 8px;
    margin-right: 4px;
    display: flex;
    line-height: 20px;
}

.leftmenuinner{
    height: auto;
    padding: 0px 4px 0px 4px;
    margin-left: 6px;
    margin-right: 6px;
    overflow: hidden;
    word-break: keep-all;
}

  .leftmenuinnername{
    height: auto;
    padding: 0px 4px 0px 4px;
    margin-left: 6px;
    margin-right: 6px;
    overflow: hidden;
    word-break: keep-all;
    }

.leftmenuinner:hover{
color:dodgerblue;
}

.rightmenu{
    /* right: 0px; */
    position: relative;
    width: auto;
    height: auto;
    padding: 6px;
    margin-left: 4px;
    margin-right: 18px;
    display: flex;
    line-height: 20px;
}

.rightmenuinner{
    padding: 0px 4px 0px 4px;
    margin-left: 8px;
    margin-right: 8px;
    width: auto;
    height: auto;
}

.rightmenuinner:hover{
color:dodgerblue;
}

.bellicon{
    position: relative;
    min-width: 20px;
    width: 100%;
    min-height: 20px;
    height: 100%;
    background-image: url(../assets/icons/bellicon.png);
    background-size: contain;
    background-repeat: no-repeat;
    margin-top: 0;
}

.bellicon:hover{
    background-image: url('../assets/icons/belliconhover.png');

}

.carticon{
    position:relative;
    min-width: 20px;
    width: 100%;
    min-height: 20px;
    height: 100%;
    background-image: url('../assets/icons/carticon.png');
    background-size: contain;
    background-repeat: no-repeat;
    margin-top: 0;
}

.carticon:hover{
    background-image: url('../assets/icons/carticonhover.png');

}

@media screen and (max-width: 800px) {

  .topbanner{
    font-size:300%;
    justify-content: space-between;
    }

  .leftmenuinner{
  display:none;
  }

   .leftmenuinnername{
    float:left;
    line-height: 30px;
    }

  .rightmenuinner{
     min-width: 30px;
     min-height: 30px;
     line-height: 30px;
     }

  .vbaylogo{
      display:none;
  }

  .searchcontainer{
      font-size:20px;
      margin-left:0px;
  }

  .catagory1{

  }

  .searchbutton{
     font-size:20px;
  }

  select{
      font-size:20px;
  }

  .searchbarinput{
      font-size:20px;
  }

}

if any1 can help i would be greatfull.
Thank you.
Comment: What do your metatags look like? Also, why are you not setting font-size: 100% on html tag and then a font size on body? These set default font size which you can then refer to using "inherit" through the rest of your styles so the cascade is kept.
Answer: Just use this in your head:
<meta name="viewport" content="width=device-width, initial-scale=1.0">.
This gives the browser instructions on how to control the page's dimensions and scaling.
Comment: @ShaneDee
Hey, I'm very glad it worked out! If you want to show other users that they have to do this to solve their problem, you can click the tick next to the votes! Have a nice day! :)

IOS iphone 6 screen and tiny Font sizes


Passing a JS callback function to C# RT Component error: "Unable to cast object of the type 'mydb.SQLite3JSNoCallback' to 'mydb.SQLite3JSNoCallback'"

Question: I have a Javascript Windows 8 App. I am writing a WinRT Component DLL using C# for interfacing with a database.
For all functions such as OpenDB, ExecuteUpdate, ExecuteQuery (returning one row, returning one column value), I have done a IASyncOperation and am pretty successful.
But for processing each row in a big resultset, one by one, I need to pass in a callback function from javascript to the C# WinRT Component DLL. so the code is like,
My.WinRT.Component.Object.processEachRowASyc(query, arguments, function(row) {
    /* Row specific processing */
}).then(function(result) {
    /* Process after Entire Row processing is Complete */
});

I have written the RT Component such as this,
namespace mydb
{
    public void delegate MyJSCallback(string msg);
    public class Database {

        public static IAsyncOperation<Database> OpenDB(string dbFile)
        {
           /* Open DB */
        }

        public IAsyncOperation<Database> ProcessEachRowASync(string sql,[ReadOnlyArray()] object[] arg, MyJSCallback myJSCallback)
        {
            return Task<Database>.Run(() =>
            {
            /* Query Processing */
            IDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                string toRet = "{\"Name\":\"Raju\", \"Age\":\"21\"}";

                //Javascript callback function called.
                myJSCallback(toRet);
            }
            return this;

            }).AsAsyncOperation();
        }
    }

}

Now, I am getting a typecasting error when I execute this from Visual Studio, I am sure I am erring somewhere in declaring the delegate or somewhere else,
Can somebody please enlighten me on where I am doing wrong and how this could be corrected.

URL for downloading a sample project for this is, http://sdrv.ms/18ff3Hl
To simplify this further, I have written another function in the RTComponent showing just the callback error, the code is as follows in the RT Component
public delegate void SQLite3JSNoCallback();
public IAsyncOperation<int> GetLastInsertRowId(SQLite3JSNoCallback someCallback)
{
    return Task<int>.Run(() =>
    {
        someCallback();
        return 0;
    }).AsAsyncOperation();
}

Now the error occurs in while performing someCallback(), the error is as same as the above screenshot with the change of the delegate alone. "Unable to cast object of the type 'mydb.SQLite3JSNoCallback' to 'mydb.SQLite3JSNoCallback'."
Comment: I am pretty sure you want to use http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx instead of `Serialize(myMap);` because your inability to communicate well I won't be returning to this question.  I am tired of having to read a new block of code every 2 hours.
Comment: Sorry for not being clear, believe as GetLastInsertRowId(SQLite3JSNoCallback someCallback) function also fails other Objects and function calls are irrelevant to the issue faced.
Comment: Update the question with the exact error because its not the one caused by the other line of code.
Comment: now removed all code which are misleading, just hard coded what I am expecting from the other code.
Answer: This happens because of asynchronicity, as you have noticed. I have found that by invoking the callback on the UI thread, it will now work as expected.
WinRT component:
public delegate void DoStuffCallback(int num);

public sealed class Test
{
   public void ShowStuffOnOutput(int x, int y, DoStuffCallback callback)
   {
       Debug.WriteLine("pre-callback");
       Debug.WriteLine(x);

       Task.Run(() =>
       {
           callback(15);
       });

       Debug.WriteLine("post-callback");
       Debug.WriteLine(y);
   }
}

Javascript universal app
 var obj = new CallbackComponent.Test();

 obj.showStuffOnOutput(1, 2, function(num) {
     console.log("callback in JS!");
     console.log(num);
 });

Solution:
Switch to
CoreApplication.MainView.CoreWindow.
 Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
{
    callback(15);
});

Answer: When I removed the IASyncOperation from the function, the js callback worked without issue.
There seems to be a problem because I am having a blocking callback function sent as the parameter, I believe. Can any one clarify how it can work with IASyncOperation present in my function.
Should I send in an ASyncCallback function to the C# RT Component to be able to get a callback.
Still the answer remains for the above problem to make the RT Component's function a blocking function if you need a javascript callback to successfully work,
Regards,
Jay


how to get the minimum scroll thumb height in javascript

Question: I am trying to get the minimum height of the div scroll thumb in javascript,
It looks like there is a minimum height that the browsers do not pass.
in chrome it is 16 px.
i need a formula to get it for all browsers
i am able to get the height if greater or equal to the minimum
Can you help?
https://i.stack.imgur.com/A0NhD.png
Answer: Note that it's really dependent on the browser and often the browser uses native OS widgets, and DPI settings. On mobile devices the scrollbar is usually hidden entirely.
Whichever "solution" you'll find, you shouldn't trust it to work everywhere. Even if you'd cover all cases now, it most likely breaks tomorrow.


What are voicings in jazz and how are they different from chord inversions?

Question: I've began studying jazz and I came across to something called "voicings","drop 2 voicings", etc. To me, voicings seem like chord inversions but from what I've found online it seems to be something more to them. Are they just shapes to play chords easier? How can I learn more?
Answer:
Voicings are about spacing of the notes of a chord into different octaves and sometimes doubling some of them.
Inversions are about what is the lowest note.

This example on Wikipedia has several different voicings for a C major chord. https://en.wikipedia.org/wiki/Voicing_%28music%29#Vertical_placement
If instead of C, say, E was the lowest note, then it would be the first inversion of C major.
https://en.wikipedia.org/wiki/Inversion_(music)#Inverted_chords
Voicings are used to get slightly different sounds and colors. An open voicing has a more open, wide and clear sound, and usually you don't want voices too close to each other in low octaves, because of the muddy sound. Sometimes you might actually want a muddy sound. But sometimes you play a different voicing just to make a chord easier to play on the guitar, when a different voicing has an easier fingering. You might also use different voicings to get the melody note as the highest voice.
Inversions are used for their slightly different harmonic functions. For example, in the chord progression C/G - G7 - C, the chord C/G gives a strong hint that a dominant G7 is going to come soon. With C/G you feel like almost being at G7 already, just expecting the inevitable dominant to happen. But if you play it as C - G7 - C, there's no such hint, unless one comes from the rhythmic structure, say, being near the end of an 8-bar passage.
As far as I can see, the musical genre such as jazz doesn't affect the meaning of the words in any way. Maybe in jazz, some effects are used more often.


Utilizar dados do componente no método create no VueJs

Question: Estou tentando passar dados de um componente para outro usando o método do $bus:
Vue.component('porcentagens',{
data: function(){
    return {
        porcentagemSangramentoMarginal: 0,
        porcentagemPlaca: 0,
        porcentagemOLeary: 0,

        selecionadosSangramentoMarginal: [],
        selecionadosPlaca: [],
        selecionadosPorcentagemOLeary: []
    }
},

created(){
    this.$bus.$on('faceSelecionada', function(idFaceSelecionada){

        if(idFaceSelecionada.charAt(0) == 's'){

        }

    })
},

Ele está escutando o evento 'faceSelecionada' normalmente e recebendo o parâmetro também, porém não consigo acessar os dados do próprio componente: ao receber o evento com parametro preciso adicionar o id recebido na lista dentro de data e mudar o valor que também está contido em data, mas ele não consegue acessar de jeito nenhum, já tentei usando o this e $.
Comment: Tente utilizar o lifecycle `mounted` no lugar de `created`
Answer: O problema é que usar uma função "normal" (function) muda o contexto de execução, e o this dentro dessa função não é o que esperas...
Tens duas soluções:
Usa Arrow functions
E assim o this é o mesmo que era fora da função:
created(){
    this.$bus.$on('faceSelecionada',(idFaceSelecionada) => {
        if(idFaceSelecionada.charAt(0) == 's'){

        }
    })
},

Usa um alias para o this
Se fizeres const self = this; fora da função podes então usar o self em vêz do this dentro da função pois essa variável não é alterada.
created(){
    const self = this;
    this.$bus.$on('faceSelecionada', function(idFaceSelecionada){

        if(idFaceSelecionada.charAt(0) == 's'){
          // aqui podes usar self.algumaPropriedadeReactiva = idFaceSelecionada;
        }

    })
},


Restoring Windows Server 2008 to 2012

Question: I am using Windows Server 2008 R2 and I am about to create a one time backup of a system drive (D: approx. 2TB - contains files and folders only), using the 'Windows Server Backup' tool. I'm planning on saving this backup to an external HDD.
I will then rebuild the server and installing Windows Server 2012 R2.
Is it possible to restore the Windows Server 2008 R2 D drive backup to the newly built Windows Server 2012 R2 server? Is there anything I should be aware of before commencing this backup and restore?
Comment: If you only want to restore files on the drive, you're good (but don't need Windows Backup, I reckon). Restoring AD or system state won't work, because they're quite different.
Comment: Possible duplicate of [Can I restore a backup made with Windows Server 2008 R2 in Windows Server 2012 R2?](https://serverfault.com/questions/674351/can-i-restore-a-backup-made-with-windows-server-2008-r2-in-windows-server-2012-r)
Answer: If you are talking about restoring files and folders then sure you will be able to restore them to the newly built Server 2012 R2 server, but you wont be able to restore system state. Why don't you do an in place upgrade instead?
Back everything up just in case things go wrong. If you do an in place upgrade all settings as well as applications and files and folders will be kept intact.

Restoring Windows Server 2008 to 2012


Has Vici CoolStorage been updated to work with WinRT / Metro?

Question: The project website does not indicate any support for WinRT.
Is there a way to do this? We (like many others, presumably) had bet on Vici CoolStorage for its cross-platform capabilities.
Comment: A version is in the works that will support .NET, Windows Phone 8, Windows 8 (RT), Xamarin.iOS and Xamarin.Android. It will be built as a PCL (portable class library).
Comment: Support for Windows Phone 7 will be dropped though
Comment: Why not ask/try it? https://github.com/viciproject/coolstorage
Comment: @PhilippeLeybaert, that's great to hear. Please add your comments as an answer, and I'll accept it. Also, is there a rough ETA? Cheers.
Answer: A version is in the works that will support .NET 4.5, Windows Phone 8, WinRT (Windows 8), Xamarin.iOS and Xamarin.Android. It will be built as a PCL (portable class library). Support for Windows Phone 7 will be dropped because the platform lacks too many common .NET framework features that are available on other platforms.
This new version will be available early December.
Comment: It is usable and stable. I'm currently using it in my own projects without any issues
Comment: is this ready for use? The website does not yet have any mention of these changes.
Comment: It is on GitHub but the release is not yet official
Comment: could you please provide any kind of update? Is the library usable currently? If not, what is the ETA? Many thanks.
Comment: @PhilippeLeybaert Please look at my problem and help me http://stackoverflow.com/questions/23669433/script-conflict-issue
Comment: @VigneshKumar That doesn't seem to be the correct link. At least it doesn't have anything to do with CoolStorage


How to implement something to differentiate nodes?

Question: I wonder how I could implement something in my Drupal site where nodes can be different and managed separately.
For example, in my site I want to add to nodes as shops, and every vendor must manage his/her shop, post news, add images, etc.
Any suggestions
Answer: You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.
For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".
Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


What is the difference in TMSCHEMA vs MDSCHEMA in DMV of Power BI models

Question: For example, what is the difference between in those 2 when querying DMV?
select * from $SYSTEM.MDSCHEMA_MEASURES

select * from $SYSTEM.TMSCHEMA_MEASURES

When those queries are going to return different results?
Comment: The technically correct answer is "always", because they have different schemas. `MD` = Multidimensional, `TM` = Tabular Model. Tabular model is largely compatible with multidimensional views and MDX queries, so you can consider the `MD` views a feature for backwards compatibility. As PowerBI always uses SSAS in tabular mode, there is largely no reason to use them.
Answer: The TM tables are generally the better ones to use for Tabular models, though you can use either for Tabular. The columns and sometimes the rows are different though. For example measures, I get an extra row on the MD query for a hidden measure:

You can see the columns for each using these links.
MDSCHEMA_MEASURES
TMSCHEMA_MEASURES
I do a lot with the TM DMV tables, and I think the only MD table I ever use is MDSchema_Dimensions to get row counts.
SELECT DISTINCT
  [CATALOG_NAME] as [Database],
  DIMENSION_CAPTION AS [Table],
  FORMAT(DIMENSION_CARDINALITY,'###,###,###') AS [RowCount]
FROM $system.MDSchema_Dimensions
WHERE DIMENSION_CAPTION <> 'Measures'  --table name
AND CUBE_NAME = 'Model'
ORDER BY DIMENSION_CARDINALITY DESC  --RowCount

You can also get row counts from DISCOVER_STORAGE_TABLES, but because you can't write full SQL (eg. GROUP BY) when using DMVs, you have to jump through hoops after the query to get the right answer.


Problema com autenticação Django

Question: Estou com problema na hora de validar o login, estou usando um banco legado firebird 2.5.
Alguém poderia me ajudar?
Comment: O banco de dados está sincronizado?
Answer: De acordo com a mensagem de erro que aparece no screen shot o problema é que a tabela USUARIO não possui a coluna USERNAME. Você já verificou se as colunas necessárias para a autenticação do Django funcionar já foram criadas na tabela USUARIO?
Pelos parâmetros que você está passando para o authenticate() parece você criou um backend de autenticação novo, se esse foi realmente o caso verifique se o método authenticate() do seu backend está pegando o usuário corretamente.

Problema com autenticação Django


variavel pegar determinado numeros

Question: Boa tarde pessoal.
Preciso que uma variável pegue sempre um determinado número de uma ordem, por exemplo:
o usuário digita 123456789

variavel a: pegara sempre o primeiro número da série, ou seja, 1
variavel b: pegara sempre o segundo número da série, ou seja, 2

e assim sucessivamente.
Comment: isso é para algum exercício? caso contrário não tem motivos para criar uma variável para cada ocorrência e sim um array
Comment: Pode mostrar o que você já tentou, qual a dúvida?
Answer: O método split separa caracteres de uma palavra quando o delimitador não é informado. Assim:
var variavel = "123456789";
var caractere = variavel.split(''); // aqui ele separa a string

var variavel_A = caractere[0]; // primeiro caractere
var variavel_B = caractere[1]; // segundo caractere
var variavel_C = caractere[2]; // terceiro caractere
var variavel_D = caractere[3]; // quarto caractere

alert(variavel_A ); // retornará "1"
alert(variavel_B); // retornará "2"
alert(variavel_C); // retornará "3"
alert(variavel_D); // retornará "4"

Se a variável for um número, você precisará transforma-lo em uma string antes de usar o split. Assim:
var num = 123456789; // numero
var variavel = num.toString(); // transforma em string
var caractere = variavel.split(''); // usa o split()

Você também pode usar o charAt, deste modo:
var variavel = "123456789";

var variavel_A = variavel.charAt(0); // primeiro caractere
var variavel_B = variavel.charAt(1); // segundo caractere
var variavel_C = variavel.charAt(2); // terceiro caractere
var variavel_D = variavel.charAt(3); // quarto caractere

Existe um modo mais indicado caso a variável seja uma String:
Conforme sugerido pelo @Isac e pelo @lazyFox.

você também pode usar o operador de indexação diretamente sobre uma
  string, sem a necessidade de usar o split ou chatAt

Deste modo:
var variavel = "123456789";
alert(variavel[0]); // retorna 1

Comment: Pode usar o operador de indexação diretamente sobre uma `string`, sem ter que fazer `.split('')` primeiro.
Comment: Se a variável já for uma string, nem precisa do charAt :) ou seja `"1234"[0]`.  `var a = 1234; a = a.toString()[0]`
Comment: @lazyFox kkkkk... vivendo e aprendendo... Vou editar a resposta e citar isso.
Comment: Nao sabia @Isac. Vou melhorar a resposta.
Answer: Você pode criar a quantidade de variáveis, dinamicamente, em função da quantidade de dígitos na string

 var variavel = "123456789";
 //quantidade de dígitos na variável acima
 var n = variavel.length;
 var caractere = variavel.split('');

  //criando as variáveis dinamicamente
  for (var i = 0; i < n; i++)
  {
  var char_A = i+1;
  var letra = (String.fromCharCode(char_A+64))
  window["variavel" + letra] = (caractere[i]);
  }

 //verificando algumas variaveis
 console.log( "O valor da variavelA é " + variavelA);

    console.log( "O valor da variavelB é " + variavelB);

 console.log( "O valor da variavelE é " + variavelE);

  //Para recuperar os valores de todas as variáveis
  for (var i = 0; i <n; i++)
  {
  var char_A = i+1;
  var letra = (String.fromCharCode(char_A+64))
  console.log(window["variavel" + letra]);
  }

O método split() divide um objeto String em um array de strings ao separar a string em substrings.
O método String.fromCharCode() retorna uma string criada ao usar uma sequencia específica de valores Unicode.

variavel pegar determinado numeros


The probability of getting a larger number in a specific dice

Question: Bob throws cube with the numbers 1-n
and Alice throws cube with the numbers 1-m
It is known that $m>n$,whoever gets a bigger number wins
What's the probability Bob will win?
(I thought of that answer,but I'm not sure I'm right)
$$\frac{n-1}{n}\cdot \frac{n-1}{m},$$ [because] the good numbers for Bob are 2 to n(because 1 can never win). Alice-Out of M numbers,from n to m,not good because we want Bob to win. Then we were left with only n-1 numbers that can lose(because the n number cannot lose).
Comment: Could you please include the steps, explained, that you took to arrive at your answer?  Thanks!
Comment: yes,the good numbers for Bob are 2 to n(because 1 can never win).
Alice-Out of M numbers,from n to m,not good because we want Bob to win.
Then we were left with only n-1 numbers that can lose(because the n number cannot lose)
Comment: Why not work an example using small $n,m$?  A few examples should make it easy to decide if your proposed solution might be right.
Comment: In your case, note that if $m=n+1$ and $n$ is large, your expression is effectively $1$.  Does that make sense?
Comment: Not really, can you explain where the mistake is?
Comment: Thanks for the information, @complex_stock; I edited your post to add the additional context you provided, there.
Answer: $\text{P(Bob`s number is 2 and Alice`s number is 1)}=\frac{1}{n}\times \frac{1}{m}$
$\text{P(Bob`s number is 3 and Alice`s number less than 3)}=\frac{1}{n}\times \frac{2}{m}$
$\text{P(Bob`s number is 4 and Alice`s number less than 4)}=\frac{1}{n}\times \frac{3}{m}$
...
$\text{P(Bob`s number is n and Alice`s number less than n)}=\frac{1}{n}\times \frac{n-1}{m}$
$$\frac{1}{n}\times \frac{1}{m}+\frac{1}{n}\times \frac{2}{m}+\frac{1}{n}\times \frac{3}{m}+...+\frac{1}{n}\times \frac{n-1}{m} =$$
$$=\frac{1}{n}\times(\frac{1}{m}+\frac{2}{m}+\frac{3}{m}+...+\frac{n-1}{m})=$$
$$=\frac{1}{n}\times (\frac{1+2+3+...+n-1}{m}) =$$
$$= \frac{1}{n}\times \frac{\frac{(n-1)\times n} {2}}{m} =$$
$$=\frac{n-1}{2m} $$
where $m > n$


jquery screen(position) of browser

Question: I am creating a zooming effect for pictures

         20 more same TDs

       20 more TRs

1- zooming is done successfully
2- top/left of magnifier has a problem
   that is i have positioned magnifier at the right side of source-img as
 $("source-img").mousenter(function(){
   $("#magnifier").css({
     top: $(this).top,
     left:$(this).offset().left()+$(this).width()+5//to improve left value
   });
 });

PROBLEM: if source-img is at the left most side of browser then I want to show magnifier at right side of source-img and vice versa, bcz now for left most source-img magnifier is displayed but can not be seen.
Answer: You will need to test the position of the magnifier element and it's width against the window width, and adjust the left position accordingly. Sample pseudo code below should help you along your way.
$(".source-img").mouseenter(function(e) {
    var w = $(window),
        elWidth = $(this).width(),
        offset = $(this).offset(),
        left;

    if (elWidth + e.pageX > w.width() + w.scrollLeft()) {
        left = e.pageX - elWidth;
    } else {
        left = e.pageX;
    }

    $("#magnifier").css({
        top: offset.top,
        left: left
    });
});

Additional settings can be applied to set predetermined margins for the magnifier to keep it spaced away from edges of the window if required.

jquery screen(position) of browser


Comunicação local através de aplicação on-line

Question: Estou desenvolvendo um sistema para pedidos de uma lanchonete/pizzaria. Vamos supor que o garçom faça o pedido com o Tablet (Android) na mesa do cliente ou o cliente vai e faz o pedido na recepção (Windows). Dependendo o pedido, o mesmo deverá ser impresso em uma impressora diferente, por exemplo: caso seja pedido x-salada deverá ser impresso em impressora no "setor" da cozinha correspondente e caso seja pedido uma pizza o mesmo deverá ser impresso em outro "setor" que seja correspondente à pizza.
Alguém poderia me indicar algum artigo, ou os comandos a fim de hora imprimir em uma determinada impressora e hora em outra impressora? Teria que haver uma codificação para cada sistema operacional ou a mesma serviria para ambos?
Obs: as impressoras são todas impressoras térmicas Epson.

Farei o teste para o Windows, mas no Android, como poderia fazer o gerenciamento de impressão? Também seria interessante no Windows Phone, pois o foco é atendimento dos garçons com um Tablet com menor custo, independente o sistema operacional.

A arquitetura proposta é esta, onde cada Tablet teria as impressoras instaladas e deles saíssem o comando de impressão de acordo com o tipo de pedido. Todas as estações acessariam o sistema via internet (sem servidor dentro do estabelecimento), onde nada em relação ao sistema seria necessário instalar nas estações além das impressoras.
Meu foco é trabalhar com impressões e impressoras via Android.

Como foi sugerido, e por sinal achei boa sugestão, utilizarei uma outra arquitetura, como mostrada na imagem

A nova dúvida é como posso enviar dados de uma aplicação on-line (utilizando  Tablet) para um servidor local?
Em princípio pensei enviar utilizando AJAX por aparentar ser uma solução mais simples, mas até o momento não encontrei referência de como enviar solicitação AJAX para servidor local através de uma aplicação on-line.
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54200/discussion-on-question-by-anderson-brunel-modolon-comunicacao-local-atraves-de-a)
Answer: Se a comunicação com o servidor for esporádica, e/ou iniciada pelo usuário (por exemplo, ao clicar em um botão de Atualizar), você deve implementar a busca dos dados no cliente usando AJAX, nesse caso não é uma comunicação sentido SERVIDOR <- CLIENTE, mas sim CLIENTE -> SERVIDOR, porém, com AJAX, ela acontece sem recarregar a página e a interface continua totalmente responsiva.
Caso precise de comunicação em tempo-real, por exemplo, para implementar um chat, ou um jogo multiusuário, ou uma implementação de uma interface colaborativa, onde usuários de computadores diferentes participam numa mesma tela (e isso é orquestrado pelo servidor), então o melhor é utilizar as novas funcionalidades para comunicação de baixa latência entre servidor/cliente.
Arquitetura para aplicação com servidor local e remoto
Para ter uma aplicação que tenha funções locais centralizadas (impressão) e também um servidor remoto que guarde as informações históricas, os cadastros de produtos, etc. o ideal é realmente dividir em camadas o aplicativo. Abaixo uma arquitetura proposta baseada em Android, servidor local ASP.NET Web.API 2/MVC 5, e servidor remoto usando API APPs do Azure com banco de dados SQL Azure (você pode modificar essa arquitetura completamente para usar Amazon AWS, ou até mesmo um servidor provisionado por você).

Nessa arquitetura todos os componentes da rede local compartilham o mesmo WiFi (ou rede ethernet para o caso do servidor local que pode estar ao lado do roteador). O servidor expõe um webserver (no caso IIS da Microsoft) com uma API desenvolvida em ASP.NET Web.APi 2. Esse servidor, por sua vez, se comunica com o servidor remoto implementando no Microsoft Azure que expõe uma API através do serviço de API APPS do Azure (que facilita demais gerenciar e criar APIs). Para podermos compartilhar a maior quantidade possível de código entre servidor remoto, local e app android, a app android pode ser programada em Xamarin em C# no Visual Studio, permitindo reutilizar classes de modelo de negócio e transporte de dados, bem como clientes das APIs, já que tudo será escrito em C#. O Xamarin cria aplicativos nativos para Android (iOS e Windows Phone), compartilhando mais de 95% do código entre eles. Os aplicativos tem a mesma performance dos escritos em Java no Android e em Objective-C no iOS, pois são compilados nativamente ao final do processo, ou dinamicamente na máquina virtual do android.
Comunicação de aplicação WEB com servidores
A implementação de comunicação web com servidores pode ser feita de diversas formas. Abaixo as mais comuns.
A opção de facto é WebSockets.
Um tutorial em português: https://www.html5rocks.com/pt/tutorials/websockets/basics/
Para PHP, uma biblioteca: http://socketo.me/
Documentação oficial: https://developer.mozilla.org/pt-BR/docs/WebSockets
Notas
Contudo, mesmo um cliente de chat, ou uma aplicação colaborativa podem funcionar com AJAX puro e operações de "polling" (o cliente consulta o servidor, por exemplo, à cada 30s para ver se há novos dados). Era assim que essa coisas eram feitas no passado recente.
Implementar comunicação em tempo-real não é algo simples. Normalmente os iniciantes cometem tantos erros que acabam desistindo e uma implementação em "polling" com AJAX pode ser mais simples para iniciar.
Contudo uma aplicação com baixa latência de atualização de dados é uma maravilha para o usuário final, como também gera muito orgulho em quem a construiu.
Existem também opções aos WebSockets, e camadas de abstração em cima deles também (que podem decair graciosamente para polling ou outro mecanismo mais simples em browsers que não suportem websockets, por exemplo).
Comment: @AndersonBrunelModolon se você criar uma aplicação web dentro dos tablets e não uma aplicação android, então você acessará os dados via AJAX acessando o servidor local. Somente o servidor local é que acessa o servidor remoto (para buscar novos produtos, novos preços, etc.). Se você usar uma aplicação ANDROID acessará o servidor local usando uma biblioteca para acesso a APIs REST, como Retrofit (https://square.github.io/retrofit/). Mesmo que vc use um website no android com AJAX, programe o servidor local para expor uma API REST, mesmo que seja em PHP: http://www.slimframework.com/
Comment: A comunicação seria esporádica após o usuário clicar em um botão na aplicação e ela passaria os dados para o servidor local. No caso fazendo em AJAX, seria necessário utilizar algo do tipo no-ip, ou apenas fixando o ip já seria o suficiente? A minha dúvida seria em fazer a aplicação on-line encontrar o servidor local para passar os dados.
Comment: @AndersonBrunelModolon o que você quer dizer como servidor local? A sua aplicação já não está conectada a um servidor, de onde ela é "servida" e lá roda sua lógica? Você quer que ela se comunique com um outro servidor à mais? Que servidor é esse? Explique melhor seu cenário na pergunta! Se for só para mandar os dados por AJAX para o servidor é trivial, vou até colocar um exemplo:
Comment: Sim, é apenas enviar os dados via AJAX da aplicação web para o servidor local. A minha dúvida é se basta apenas o servidor estar na mesma rede do dispositivo que acessa a aplicação (vamos supor, com ip fixo) ou tenho que fazer algo mais seja do lado AJAX ou do servidor. O servidor é PHP puro que estará preparado para receber os dados enviados via AJAX.
Comment: @AndersonBrunelModolon atualizei a resposta com uma arquitetura que considero mais robusta (lembrando que detalhes da arquitetura podem e devem ser adaptados para o seu caso e seu rol de conhecimentos)
Comment: Tem gente que fez confusão com a minha pergunta. Focalizei apenas na comunicação ao fato de já existir um sistema em PHP praticamente finalizado, mas sem estas novas funcionalidades pois surgiram de forma recente a idéia. Fica complicado utilizar .NET a este contexto.
Comment: @AndersonBrunelModolon aconselho veementemente que use android no app do garçom e não uma WebView que mostra um site mobile feito em PHP. Isso não vai funcionar para o tipo de problema. Agora, todo o resto da arquitetura que sugeri pode ser substituído por PHP. Basta que você publique uma API REST em PHP (não implemente uma API de outra forma que não REST!). Um framework indicado pra isso seria http://www.slimframework.com/ Você pode reutilizar o código PHP atual em boa parte da API, como também o banco de dados existente, etc.
Comment: No caso você está dizendo para o servidor local colocar algo do tipo um "no-ip" afim de que fique acessível via web e trabalho a comunicação entre ele o tablet com arquitetura REST?  (Tablet AJAX => SERVIDOR REST com no-ip)
Comment: @AndersonBrunelModolon não, nada disso. Seu servidor local fica local, na rede WiFi local (conforme expliquei no texto da resposta). Seu app android se comunica com esse servidor através do IP local dele (que deve ser fixo, ou via DNS se seu roteador permitir isso). No app você deve ter uma área administrativa para indicar o IP do servidor local. Você então consome essa API localmente indicando o IP do servidor local. É muito simples, não há necessidade de ser acessado remotamente! Ou esse app vai rodar FORA da rede local do restaurante?
Comment: O aplicativo ficará hospedado on-line e a comunicação com os Tablets é via internet Wi-Fi que tem no estabelecimento. No caso basta eu fixar o IP do servidor local (dentro do estabelecimento), gravando ele no Tablet e acessando via AJAX? O sistema por ser on-line tem uma área administrativa/relatórios que é possivel acessar fora sim, mas a parte dos Tablet's e comunicação com o servidor somente dentro do estabelecimento.
Answer: Considerando que a principal diferença entre o servidor de hospedagem e o seu servidor local é o fato de que um está online e o outro não, devido principalmente ao seu modem agindo como firewall, podemos dizer que a solução básica seria:

Realizar o redirecionamento de portas no seu modem para que seja possível acessar o seu servidor local pela internet (ver Port Forwarding);
Configurar sua aplicação online (hospedada) para consumir um serviço ou url através da biblioteca CURL.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://seuip:8080/teste.php");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$response = curl_exec($curl);
var_dump($response);

Mas atenção.. imagino que isso não passe de uma brincadeira. Pois não veja razão nenhuma nesse mundo que justifique expor seu servidor local na rede.
Comment: Na verdade é apenas um  servidor de impressão, e o fato de querer fazer via AJAX seria ao fato de não expor, pois não se sabe se futuramente virão outras necessidades com este servidor. Mas a principio a sua ideia é válida sim.
Answer: Resolvi postar algo simples após observar os comentários. Agora pude ter mais confiança sobre qual solução apresentar.
Eu penso sempre em soluções simples então vamos a uma alternativa realmente simples.
A questão aqui é como fazer o servidor "online" enviar dados para o servidor numa intranet.
Se focarmos nessa lógica sem observar o real cenário, vamos imaginar soluções inadequadas e confusas. Observando bem o cenário, o servidor na internet não precisa enviar os dados para as impressoras. Isso pode ser feito pelo tablet que está na página do servidor.
Achei que ficaria confuso explicar sem ilustrações, por isso fiz alguns rabiscos.
Primeiro vamos dar uma geral no cenário para melhor entendimento:

O cliente faz um pedido e o garçom dá entrada no sistema pelo tablet.

Quando completar, o servidor online retorna uma página com um formulário oculto com campos tipo hidden.
O action do form apontará para o endereço do servidor local na intranet.
Nesse exemplo, está sendo pedido uma pizza. Então no formulário será especificado o parâmetro "printer" com o valor "pizza".
<form action="http://192.168.1.50" method="POST">
<input type="hidden" name="printer" value="pizza">
<input type="hidden" name="data" value="os dados que deseja enviar para a impressora imprimir">
</form>

Note que o servidor online não tem acesso algum a rede local do restaurante, pois essa rede não está aberta na internet.
Essa comunicação é possível porque o processo se dá em client-side, pelo brower do dispositivo cliente, o navegador do tablet.
Tecnicamente, é o tablet que está enviando a requisição e não o servidor online.
Pode também implementar uma função que envie o formulário por ajax caso queira algo mais "refinado", mas não fará diferença alguma no resultado final.

O formulário oculto pode ter um botão para o garçom enviar manualmente ou pode ser disparado automaticamente.

Daqui para frente acredito que não preciso entrar em detalhes porque são coisas muito simples.
Se o servidor for Windows, pode usar as funções printer do PHP
http://php.net/manual/fa/function.printer-open.php
Pode implementar também a comunicação com as impressoras usando sockets http://php.net/manual/en/book.sockets.php
Simples assim, sem estruturas mirabolantes e custos monstruosos. É eficiente e simples de manter.
*Desculpe pelos desenhos exdrúxulos.
Comment: Exatamente o tipo se solução que eu buscava. Valeu!!


"Universal" $R$-bilinear map

Question: I am confused as to what "universal" means as used in my lecture course on Algebra in the context of $R$-bilinear maps where $R$ is a ring. The relevant section of my notes is:

Let $L, M, N, T$ be $R$-modules.
Suppose $\phi : M \times N \rightarrow T$ is $R$-bilinear, and $\theta : T \rightarrow L$ is linear.
Then $\theta \circ\phi: M \times N \rightarrow L$ is $R$-bilinear, so we get:
$\phi^* : \{\text{$R$-module maps } T \rightarrow L\} \rightarrow \{R\text{-bilinear maps } M \times N \rightarrow L\}$
Definition: $\phi$ is universal if $\phi^*$ is a one-to-one correspondence.

I am really confused as to what this means. What is $\phi^*$? Or rather, what is it doing? How does it depend on $\phi$? What does it mean for $\phi$ to be universal?
I would really appreciate some help understanding this, thank you.
Answer: The definition is a little bit sloppy. The role of $M, N, T$ is different from the role of $L$. You should see $M, N, T$ as "fixed": your definition will tell you something about a specific bilinear mapping $\phi: M \times N \to T$.
For each $L$, you have a mapping $\phi^*_L$ defined by
$$
\phi^*_L(\theta) = \theta \circ \phi.
$$
Check for yourself that if $\theta : T \to L$ is an $R$-module map, then $\theta \circ \phi: M \times N \to L$ is an $R$-bilinear mapping. Thus the definition of $\phi^*$ makes sense with the domain and codomain given in the question.
Now the definition should be: $\phi$ is universal if $\phi^*_L$ is a one-to-one correspondence for each $L$.

What does it mean for $\phi$ to be universal?

By definition it means what I wrote above.
How you work with it is roughly as follows. Suppose you have any $R$-bilinear mapping $\alpha: M \times N \to K$. You might want to say something about this mapping, but bilinear mappings are complicated and you don't understand them very well yet. The definition above says that $\alpha$ lies in the image of $\phi^*_K$, and in particular there is a unique $\theta: T \to K$ such that $\alpha = \phi^*_K(\theta) = \theta \circ \phi$. This means that to understand $\alpha$, you only have to understand $\phi$ -- which you typically have some kind of explicit construction for -- and $\theta$, which is an $R$-linear mapping and therefore quite possibly easier to understand.
In a sense, it tells you that a bilinear mapping $\alpha$ falls into two parts: a part $\phi$, which "takes care of the bilinearity", and a $\theta$, which "takes care" of the specific properties of the mapping $\alpha$. Note that $\theta$ depends on $\alpha$, but $\phi$ does not: in a sense $\phi$ is a blank template for all possible "bilinearity" of mappings out of $M \times N$. This might be why it is called "universal".

"Universal" $R$-bilinear map


If ngModel is used within a form tag set name or set standalone error

Question: I've just started developing my first Angular 2 app and I got the following confusing error message:

Error: If ngModel is used within a form tag, either the name attribute
must be set or the form
control must be defined as 'standalone' in ngModelOptions.
Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

This is where I get the error:
<button (click)="addRow()" class="btn">Añadir</button>
<form #productionOrderForm="ngForm" (ngSubmit)="onSubmit()">

 0">

                Nombre
                Num. items primer nivel
                Reducción
                Legislación
                Producto

                    <input name="Name-{{rowIndex}}" #name="ngModel" [(ngModel)]="productionorder.name" placeholder="Nombre" required>

                            Obligatorio.

                    <input name="NumItems-{{rowIndex}}" #numitems="ngModel" [(ngModel)]="productionorder.numitems" placeholder="Items por nivel" required>

                            Obligatorio.

                    <law (notifyParent)="getNotification($event)"></law>

                    <select [(ngModel)]="productionorder.productid" #productId="ngModel">
                        <option></option>
                        <option *ngFor="let product of products" [value]="law.lawId">{{law.name}}</option>
                    </select>

    <button *ngIf="productionorders?.length > 0 && law != ''" type="submit" class="btn btn-success" [disabled]="disableSubmit()">Guardar cambios</button>
</form>

I get the error at this line:

But the error message is confuse because I have set the name in the input field:
<input name="NumItems-{{rowIndex}}" #numitems="ngModel" [(ngModel)]="productionorder.numitems" placeholder="Items por nivel" required>

The others input in this form have the same structure and I don't get any error in them.
Where is this error coming from? How can I fix it?
Answer: I have found where the error is. I have put it here to help someone that has the same error and the same knowledge about Angular (or programming).
The error is in the following select, it hasn't a name. I did this to fix it:
<select name="ProductId-{{rowIndex}}" #productId="ngModel" [(ngModel)]="productionorder.productid" required>
    <option></option>
    <option *ngFor="let product of products" [value]="law.lawId">{{law.name}}</option>
</select>

Comment: Yes. From Angular 5 documentation (https://angular.io/guide/forms): "Defining a name attribute is a requirement when using [(ngModel)] in combination with a form."
Comment: This is definately the problem
Answer:
Error: If ngModel is used within a form tag set name or set standalone
  error

Simple Soultions:
Add name attribute to input field in case of ngform or ngsubmit you are using
Example 1: <input [(ngModel)]="User.age" name="age">

or

**if you are using direct [(ngModel)]="User.age" ,,,then add this [ngModelOptions]="{standalone: true}" to input field**

Example 2: <input [(ngModel)]="User.age" [ngModelOptions]="{standalone: true}">

Comment: What is "User" in "User.age"?
Comment: Thanks, the "standalone" option did it for me :)
Answer: Each input element has a name property that is required by Angular forms to register the control with the form. This is applicable to template-driven forms.
foo.html

Hero Power
<select class="form-control" id="power" [(ngModel)]="model.power" name="power"
 required>
  <option *ngFor="let pow of powers"  [value]="pow">{{pow}}</option>
 </select>

In Hero.model.ts
export class Hero{

constructor(
    public id:number,
    public name:string,
    public power:string,
    public alterEgo?:string
 ){}
 }

name property should be same in .html file.
In foo.ts file
   model = new Hero(13, 'Dr IQ', this.powers[1], 'abcd');

Answer: This can also happen if you have added ngModel to a button, by mistake.
<button type="submit" class="btn btn-primary" ngModel >Submit</button>
Just remove ngModel from button to fix this error.
Answer: when ngModel is used within a form tag set name or set standalone error
I did this to fix it:
<input [(ngModel)]="person.firstName" name="firstName">

Comment: provide some more details or example
Answer: Try this format
<input type="text" class="form-control" name="name" placeholder="Name"
                  required minlength="4" #name="ngModel"
                  ngModel>

        Please enter a name.

        Enter name greater than 4 characters.

Answer: Remove form tag in your HTML file then it automatically resolves your issue
Comment: Please don't misuse the formatting. When answering an older question with existing answers please take the time to explain what new aspect of the question your answer addresses.


Drupal 7: Permissions when Apache is running as user account

Question: My current host has it set up so that Apache runs as the same account that I use to manipulate files on the file system and, subsequently, the same user that I used to install Drupal 7.
I'm trying to pass the checks in the Security Review module, but it keeps complaining that (pretty much all) files and directories are accessible. I've looked at the handbook page and tried applying the script, but to no success.
Can anyone suggest the proper permissions for my files and directories?
Answer: If you're on a shared host this is to be expected, a lot of them operate like that.
Most use suEXEC as the Apache PHP handler which is what makes the web user have full read/write rights over the whole document root. Unless you have access to change the Apache PHP handler (or at least its settings) I doubt you'll be able to change this yourself.
Your hosting provider might do it for you if you get in touch with them, but going on past experience they're normally reluctant to change this sort of thing (in the case of a shared server they might not even be able to do it on a site-by-site basis).


Should guitar be de-tuned when not in use...?

Question: I bought a GB&A guitar almost an year ago. I play guitar mostly on the weekends. Recently I noted that my guitar bridge has got lifted off the body a bit. So I took it to the Guitar Shop. The owner of the shop suggested me that I should keep the guitar untuned if I am not using/playing it. I just want to know, should I tune the guitar only when I want to play it and de-tune it when not in use?
Also, If I tune, De-tune the guitar too often, won't it cause a problem to the nuts?
Answer: Generally, with a guitar in good condition, no.  The only time I've detuned a guitar was when shipping one via air, where it might be in an unpressurized baggage compartment.   I think the strings should be kept at pitch - but you should check and adjust them if they are getting sharp (which can happen with temperature and humidity changes.)
If you play a guitar that is in good condition regularly, you should notice any issues as they develop and address them before they get too serious.  I would think once a week would be often enough to adjust the tuning and notice if any problems were developing.
I suppose that if you are storing it for long periods and you aren't playing it regularly, detuning might be a reasonable precaution.  I would think in that case that tuning the strings down as much as one-whole step might be reasonable, but I wouldn't leave them totally slack.
I don't think you need to worry at all about the nut.  That should be a non-issue.
EDIT: On the other hand, if there is a structural issue with the guitar, it may well make sense to detune the guitar and keep it that way - until you get it repaired but detuning the strings is not a good alternative to getting the guitar repaired.  In your specific example, the bridge could still come off completely when you tune up the strings and possibly injure you or someone else, and cause more damage to the guitar.
Comment: But then how do I take care of lifted bridge issue? Is lifted bridge normal in acoustic guitars?
Comment: Baggage compartments are almost always pressurized (although, the plane is pressurized to like 8000ft, not sea level). If you think about it, it's easier to pressurize a tube than half a tube.
Comment: The bridge shouldn't lift. I have had three of my acoustics, including one 12 string, with steel strings on for years. I can only assume it has not been glued down correctly. Once it is properly done, and has solidified, having the strings back on should not cause issues.
Comment: The bridge should not be doing that, even with the guitar tuned up.  Having the guitar tuned down too much for too long as actually worse for the guitar, as the neck needs to be under that constant tension.
Comment: It is important to think about humidity levels when storing a guitar for long periods of time, string tension is often blamed for problems that are more likely caused by dryness. At the same time you want to avoid mold.
Answer: No. You shouldn't have to do that on a guitar that's made well. The fact that the bridge is coming up is indicative of an issue with the guitar itself and not the tuning / strings. You should try and get the bridge fixed, in general.
However, a quick google of GB&A guitars shows that they are very cheap acoustic guitars (~$70). I would not expect these guitars to be made well at that price. You could try detuning to help with the issue, it may or may not work, but assuming money is an issue it could be worth trying. I would suggest detuning a whole step or two so that there's still some tension on the strings. When you tune back up, do it slowly so that you don't exert sudden pressure on the guitar or strings (this might make them more likely to break). Also make sure that the strings are wound well at the top peg.
This is really a work around and I would not expect this guitar to be with you for life. The long term solution may be a new guitar, unfortunately. Hopefully you can make this one work long enough to decide if you really want to put the money in to the hobby.
Answer: Tune it One step down and consult a good guitar mechanic ASAP to get the bridge fixed. This sort of problem must not occur in future.
Answer: You shouldn't worry . The only time you have to un-tune your guitar is when you travel overseas and you need to put your guitar to fly with you . It's okay . Use heavy gauge strings or buy a new one . I strongly suggest you buy a new one and use heavy gauge strings .
Comment: Heavy guage strings will place *more* pressure on the already failing bridge.


Is Support Vector Machine sensitive to the correlation between the attributes?

Question: I would like to train an SVM to classify cases (TRUE/FALSE) based on 20 attributes. I know that some of those attributes are highly correlated. Therefore my question is: is SVM sensitive to the correlation, or redundancy, between the features? Any reference?
Comment: @Dougal: If there are methods to eliminate the effect of correlation, doesn't that imply that standard SVM is sensitive to correlation?
Comment: My guess would be no, since generating a separation based on one variable would make the other correlated variables weak regarding further separations.  There might be some instability regarding which variable is chosen, however.
Comment: Are you talking about a linear SVM, or RBF kernel, or...?
Comment: Hmmmm, I don't know... does the answer depend on that?
Comment: Yes, absolutely. You can design a kernel to explicitly deal with the correlations, if you'd like.
Answer: Linear kernel: The effect here is similar to that of multicollinearity in linear regression. Your learned model may not be particularly stable against small variations in the training set, because different weight vectors will have similar outputs. The training set predictions, though, will be fairly stable, and so will test predictions if they come from the same distribution.
RBF kernel: The RBF kernel only looks at distances between data points. Thus, imagine you actually have 11 attributes, but one of them is repeated 10 times (a pretty extreme case). Then that repeated attribute will contribute 10 times as much to the distance as any other attribute, and the learned model will probably be much more impacted by that feature.
One simple way to discount correlations with an RBF kernel is to use the Mahalanobis distance: $d(x, y) = \sqrt{ (x - y)^T S^{-1} (x - y) }$, where $S$ is an estimate of the sample covariance matrix. Equivalently, map all your vectors $x$ to $C x$ and then use the regular RBF kernel, where $C$ is such that $S^{-1} = C^T C$, e.g. the Cholesky decomposition of $S^{-1}$.
Comment: The inverse of covariance matrix in Mahalanobis distance is a key. If you can estimate it reliably, this effected can be accounted for.
Comment: This is a very interesting answer; I'd like to read more about how to mitigate these kinds of problems. Can you add a reference or two?
Comment: I don't know a good one off-hand, but I'll look around a bit for one, perhaps tonight.
Comment: Awesome! Inbox me if you happen to find a cool article. I'm glad that my (+1) could put you over 3k. (-:


How to read a video frame by frame?

Question: i would like to read a Mp4 file in java8-64bit frame by frame and write each frame as a jpg to my harddisk. my first attempt was to use JavaFX 2.2 media player to play the file
on a View component. i thought maybe there would be an option to register an observer to get an event each time a new frame was loaded and ready to be painted on the component surface but seems there is no such method.
it would be enough to grab just those frames/pixels that got painted on the component.
Can this be done by using the media player? the reason why i use the media player is bcs it was the simplest solution i got workin. i tryed vlcj, just 32bit, and gstreamer but without luck :(
what i got so far:
public class VideoGrabber extends extends JFrame {

// code for scene setup omitted

final MediaView view = createMediaView(...)

// some other stuff happens here

// now start the video
view.getMediaPlayer().seek(Duration.ZERO);
view.getMediaPlayer().play();
view.getMediaPlayer().setOnEndOfMedia(new Runnable()
{ // save image when done
  BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_BGR
  view.paint(img.getGraphics());
  ImageIO.write(img, "JPEG", new File("pic-"+System.currentTimeMillis()+".jpg"));
});

// somewhere else to create
private MediaView createMediaView(String url)
{
  final Media clip = new Media(url);
  final MediaPlayer player = new MediaPlayer(clip);
  final MediaView view = new MediaView(player);
  view.setFitWidth(VID_WIDTH);
  view.setFitHeight(VID_HEIGHT);
  return view;
}

is there somehow a way to do the following:
player.setOnNextFrameReady(final Event evt) { writeImage(evt.getFrame()) };

Thanks!
Answer: You can use the snapshot() of MediaView.
First connect a mediaPlayer to a MediaView component, then use mediaPlayer.seek() to seek the video position. And then you can use the following code to extract the image frame:
    int width = mediaPlayer.getMedia().getWidth();
    int height = mediaPlayer.getMedia().getHeight();
    WritableImage wim = new WritableImage(width, height);
    MediaView mv = new MediaView();
    mv.setFitWidth(width);
    mv.setFitHeight(height);
    mv.setMediaPlayer(mediaPlayer);
    mv.snapshot(null, wim);
    try {
        ImageIO.write(SwingFXUtils.fromFXImage(wim, null), "png", new File("/test.png"));
    } catch (Exception s) {
        System.out.println(s);
    }

Comment: Very underrated answer. Thank you.
Answer: Marvin Framework provides methods to process media files frame by frame. Below it is shown a simple video processing example that highlights the path of a snooker ball.

At the left the video is played frame by frame with an interval of 30ms between frames. At the right the video is played frame by frame, but keeping all positions of the white ball through a simple image processing approach.
The source code can be checked here and the video here.
Below the essential source code to request media file frames using Marvin:
public class MediaFileExample implements Runnable{

    private MarvinVideoInterface    videoAdapter;
    private MarvinImage             videoFrame;

    public MediaFileExample(){
        try{
            // Create the VideoAdapter used to load the video file
            videoAdapter = new MarvinJavaCVAdapter();
            videoAdapter.loadResource("./res/snooker.wmv");

            // Start the thread for requesting the video frames
            new Thread(this).start();
        }
        catch(MarvinVideoInterfaceException e){e.printStackTrace();}
    }

    @Override
    public void run() {
        try{
            while(true){
                // Request a video frame
                videoFrame = videoAdapter.getFrame();
            }
        }catch(MarvinVideoInterfaceException e){e.printStackTrace();}
    }

    public static void main(String[] args) {
        MediaFileExample m = new MediaFileExample();
    }
}

Comment: very nice, i will give it a try.
Comment: Link is broken, is the project dead or is it just the website that is down?
Comment: judging from a search at sourceforge the project is dead. https://sourceforge.net/directory/os:mac/?q=marvin The last update was 2016
Comment: The project is not dead. The site was down due to Sourceforge maintenance. The respository was moved to Github. You can find all this information on the website.
Comment: I think it's dead or too old by now, I was unable to use it.
Answer: Frameworks like ffmpeg come with command line tools to split a video into individual frames (i.e. images in a folder).
See this question: ffmpeg split avi into frames with known frame rate
The answers contains links to Java frameworks which wrap ffmpeg.
Comment: thank you for your reply. after i obtained the frame from the video in java i wanna do further processing on demand and than finally save it. can ffmpeg create a stream of images that i can somehow open in jave to process it, without writing all the data to disc?
Comment: You can try `https://code.google.com/p/jjmpeg/`. I don't recommend to use the command line to extract frame by frame into a pipe since the seeking in the video stream will be too expensive.
Comment: thanks again. unfortunately using jjmpeg would mean that i have to spend more time to do reverse engineering to get to know how to use it (no dcumentation at all available) than spending time on the actual tasks i have to perform. maybe some other answer will pop up with interesting solutions. but thx!
Comment: There is an example in the project's source code. See my edits.
Comment: Links for jjmpeg are dead :/
Comment: @bspkrs Thanks, fixed.
Comment: Link for jjmpeg is dead : 404 not found! @Aaron-Digulla
Comment: @yn97 See the question that I refer to; the links there have been updated.

How to read a video frame by frame?


Using ASA 5505 Port Forwarding To Route Traffic to X Machines

Question: I have been asked to configure our ASA 5505 to route traffic from one external IP (let's call it 208.X) to an arbitrary number of internal static IPs. I was told to consider port forwarding/mapping. Given that I am still more or less clueless about anything network-related, I can't tell whether any information I find on this site or Google is relevant. Let's start at the beginning.

I understand there are multiple ways of doing what I need. Is using the ASA to route through multiple ports the best way?
If the answer to the above is yes...is this the appropriate config to add to open (for example) port 678 and 789? Assume the static IP is already configured.

access-list OUTSIDE_IN extended permit tcp any host 208.X eq www
access-list OUTSIDE_IN extended permit tcp any host 208.X eq 678
access-list OUTSIDE_IN extended permit tcp any host 208.X eq 789
access-group OUTSIDE_IN in interface outside
I feel like I'm moving in the wrong direction. Where is it defined that port 678 traffic goes to internal IP A, whilst port 789 traffic goes to internal IP B?
Thanks for your help. Once again, any education is much appreciated.
Comment: I was writing a lengthy answer, but I need to know a bit more details. What version of the asa software and what version of ASDM? "sh run | include asdm image" and "sh ver"
Comment: I won't have login privs until today, but looking at the ASA config in our source depository, the ASA version is 7.2. We don't have ASDM. (If we do, we're not using it.)
Answer: You are halfway there :)
In general, NATing firewalls have two basic necessities for moving traffic between interfaces.  In the strictest of senses there are many more, but the two below are the ones encountered most often.  The first is the access control and the second is a translation rule.  This paradigm is true for most firewalls -- even if they don't expose it in a limited GUI (SOHO/consumer firewalls/routers) -- the GUI may be doing it for you underneath.  On the CLI, however, you must take care to configure access control and the translation rules.
If your example you have configured the access control side of things with an access-list.  The OUTSIDE_IN access-list is bound to the outside interface in the IN direction.
Knowing that, your access-list is telling the ASA to permit TCP traffic recieved on the outside interface from any source IP/TCP port combination destined for 208.x on TCP/80, 208.x on TCP/678, and 208.x on TCP/789.
The next step (or first step depending on how you like to do things) is to create a translation rule so the traffic gets translated -- after passing an access control check of course.
In ASA 8.2 and earlier this is accomplished with the static command.  Major changes to NAT were implemented in ASA 8.3 and later -- so the following does not apply to 8.3 and up.
Assumptions:

126.96.36.199/TCP/80 <-> 192.168.1.100/TCP/80
22.214.171.124/TCP/678 <-> 192.168.1.101/TCP/678
220.127.116.11/TCP/789 <-> 192.168.1.102/TCP/789
192.168.1.0/24 on the inside interface

I have filled in the remaining octets of the external IP address with 1's to show clearly that we will be Port Address Translating (PAT), specifically static PAT, on a single external IP address.  This is opposed to the more traditional static NAT where each internal IP would have its own unique external IP.
<code>static (inside,outside) tcp 22.214.171.124 80 192.168.1.100 80 netmask 255.255.255.255
static (inside,outside) tcp 184.108.40.206 678 192.168.1.101 678 netmask 255.255.255.255
static (inside,outside) tcp 18.104.22.168 789 192.168.1.102 789 netmask 255.255.255.255
</code>
In general static PAT should be avoided as it is the ugliest type of NAT from both a management and technical standpoint.  If you need to expose many internal servers to the Internet, the cleanest way to make it happen is with traditional static NAT -- where each server would have its own external IP.
Ref:
ASA 7.2 Command Reference
ASA 7.2 Command Reference static Command
-Weaver


A specific example of a CW complex and a few questions concerning it.

Question: The question I am facing is this one:
Construct a CW complex X with a 0-cell x(n) for each natural number $n \geq 0$ and a 1-cell $D_{n}^1, n \geq 1$ which is glued to $x(0)$ at one end and $x(n)$ at the other.  For each natural number $n \geq 1$ consider the segment:
$$I_n = \{t*e^{2\pi i/n }, 0 \leq t \leq 1 \}\space \mathbb{C} \cong \mathbb{R^2}$$
which has boundary points $0$ and $e^{2\pi i/n }$  From these we form the space $Y = \bigcup_{n \geq 1} I_{n} \subseteq \mathbb{C} \cong \mathbb{R^2}$ endowed with the subspace topology.
1) Give a sketch proof of the fact that Y is a closed subspace of $\mathbb{C}$. Thus $Y$ is a compact space.
2) Construct the obvious map which sends $\psi:X \rightarrow Y = \bigcup_{n \geq 1} I_{n}$ which sends $x(0)$ to the origin $0 \in \mathbb{C}$ and $x(n) \in e^{2\pi i/n }$
3) Show that $\psi$ is not a homeomorphism.
Now I am not really sure how to go about doing these, but for 1) I know that for Y to be
closed, that all the $I_n$'swould have to be closed.  Now does this directly follow from $0 \leq t \leq 1$ as this is a closed interval?
for 2) are they just wanting
$0, (n = 0)$
$e^{2\pi i/n}, n > 0$     ?
I feel like there has to be something more than this.. especially as t is removed, but could we do something like this: $e^{(2\pi it/n)} -1$ as we recover $0$ if $t = 0$ and $e^{2\pi i/n}$ otherwise?  Am I supposed to keep the $t$?
3) If we take the differential $\frac{de^{2\pi it/n}-1}{dt} = \frac{2\pi i}{n} e^{2\pi it/n}-1$
Then we have a problem at n = 0.  Not sure how to prove that it is not homeomorphic though.
Anyways, I might be way off on all 3 thoughts for the 3 parts, but any help would be truely appreciated.  Note:  This is not homework that I have to turn in.
Thanks,
Brian
Comment: Another thing I don't understand in this question assumes a 1-cell $D_{n}^1, n \geq 1$.  I however thought a 1-cell is an open Disk.
Comment: About your observation for 1): Remember that arbitrary unions of closed sets are not necessarily closed. With that being said, each $I_n$ is closed because it is compact, since each one of them is the image of a continuous function from a compact set (the interval [0,1]) to $\mathbb{C}$.
Comment: I don't quite get what you are calculating with the differential, but with CW-complexes you should forget about all these analytic methods. CW-complex is an abstract *topological* space and *analytic* methods aren't very useful here. Note that your CW-complex is not even metrizable (in particular it can't be embedded in any $\mathbb R^n$, which makes analysis useless here).
Comment: @Relative0: Does my answer help? Do you have any questions?
Answer:
We will show that the complement is open. Note that your space is inside the closed ball $\bar B(0,1)$. Take any point outside the ball. It clearly has a neighbourhood disjoint with $Y$ (enough to take a neighbourhood disjoint with $\bar B(0,1)$). Now take any point $x \in \bar B(0,1)\setminus Y$. In polar coordinates it is given by $(\phi,r)$ for some $(\phi,r)\in (0,2\pi)\times (0,1]$. There is a unique $n$ such that $\frac{2\pi}{n+1}<\phi<\frac{2\pi}{n}$. Now for appropriately small $r$ the open ball $B(x,r)$ is disjoint with $Y$ (easy and very formal details left to the reader).
They want $x(0)\mapsto 0$ and $x(n)\mapsto e^{2\pi i/n}$, $D^1_n \overset{f_n}{\to} I_n$, where $n>0$. More precisely if $D_n^1=[0,1]$, then the map $f_n$ is $f_n(t) = t\cdot e^{2\pi i/n}$.
The inverse function is not continuous. The sequence $y_n=e^{2\pi i/n}$ approaches $y_1=e^{2\pi i}=1$, but $\psi^{-1}(y_n)=x(n)$ doesn't approach $\psi^{-1}(y_1)=x(1)$ (you can easily find an open neighbourhood of $x(1)$ disjoint with other $x(n)$ - such a neigbourhood is for example the image of $(0,1] \subseteq D_1^1$).

3,5. Bonus. Actually the topology of $X$ and $Y$ differ also at $x(0)$ and $0$ ($\psi^{-1}$ is not continuous at $0$). Imagine the following open neighbourhood of $x(0)$:
$N=\bigcup_{n=1}^\infty [0,1/n)_n$, where $[0,1/n)_n\subseteq [0,1]_n=D_n^1$ (it is open as its inverse image is open in every cell). Its image via $\psi$ (inverse image via $\psi^{-1}$) is not a neighbourhood of $0$: the sequence $z_n=\frac{e^{2\pi i/n}}{n}$ obviously approaches $0$ (in polar coordinates the radius tends to $0$), but it is disjoint with $\psi(N)$ (sequence $a_n$ has limit $a_0$ if and only if for each neighbourhood of $a_0$ there are only finitely many $a_n$ outside it). The same with different words: there is no ball around $0$ in $Y$ that could be included in $\psi(N)$.


Proving $\sin((n+1)a)=2\cos a\sin(na)-\sin((n-1)a)$ and $\cos((n+1)a)=2\cos a\cos(na)-\cos((n-1)a)$

Question: I have to prove the following Simpson formulas:
a) $\quad\sin((n+1)\alpha)=2\cos( \alpha)\sin(n \alpha)-\sin((n-1)\alpha)$
b) $\quad\cos((n+1)\alpha)=2\cos(\alpha)\cos(n \alpha)-\cos((n-1)\alpha)$
I am assuming that $n \in \mathbb{Z}$
Can I know which identities I have to use and how?
Answer: Using sum to product formula we have
cos(a)+cos(b)=2cos(a+b)/2 . cos(a-b)/2
a=(n+1)x    b=(n-1)x
cos(n+1)x + cos(n-1)x = 2cosnx.cosx
sin(a)+sin(b)=2sin(a+b)/2 . cos(a-b)/2
Answer: Hint:
Use the addition formulæ with $\cos(n+1)\alpha=\cos(n\alpha+\alpha)$, $\;\cos(n+1)\alpha=\cos(n\alpha-\alpha)$, and similarly for the sine.
Comment: For what? The general addition formulæ?
Answer: After transposing you should use addition formulas for sines and cosines in order to obtain their products.


Define multi-dimensional array via macro with arduino

Question: I would like to define a multi-dimensional array via a macro with the Arduino language. I am trying to save sketch/RAM space.
I would like to do something like so:
<code>#define MYARR {{8, 0}, {8, 1}, {8, 2}, {8, 3}, {8, 4}, {8, 5}, {8, 6}}

function_that_uses_array(MYARR);
</code>
but I just can't seem to get it to work, and get a multitude of errors. I have tried several different ways of defining the array in the macro, but I am admittedly not even sure this is possible to do.
Is this possible, and if so, how?
Answer: Not an answer you may expect but instead of using multi-dimensional array maybe you could use a one-dimensional array mapping multiple dimensions and use setter/getter functions to work with values as explained in this thread ?
Helper functions are not necessary if you define dimension sizes as global constants to calculate  index value for given dimensions' indexes - you can work with the 1D array directly then.
EDIT(5/4/15):
Other thing is I doubt array can be initialized using a pre-processor macro as:

All arrays consist of contiguous memory locations

(source)
For this reason array must be an initialized variable. It can be initialized in different ways - one using data defined in a macro is described in a link in my comment to this answer however a multi-dimensional array can be also initialized directly:
<code> #define MAX_ROWS 3
 #define MAX_COLS 3
 const int a[MAX_ROWS][MAX_COLS] = { {1,2,3},
                                     {4,5,6},
                                     {7,8,9}  };
</code>
Comment: Interesting, though I suppose that still leaves me in a situation where I still can't figure out how to define an array via a macro in the arduino language. Could you be of help with that?
Comment: Have a look at the second answer here: http://stackoverflow.com/questions/27784649/initialize-a-2d-array-of-unknown-size-using-macros-in-c You still have to initialize a variable though (int v[][MAXCOLUMNS] = VALUE; in the linked the answer).  Code compiles but I have no chance at the moment to check it with a real AVR.


Installing spark on hadoop

Question: I installed hadoop 2.7 on my mac. Then i want to install spark on it. But there is no any document for this.can anybody explain step by step how to install spark on hadoop?
Comment: If you like my answer, don't be tight-lipped ... pls vote/accept the answer as owner.
Answer: Steps to Install Apache Spark
1)  Open Apache Spark Website http://spark.apache.org/
2)  Click on Downloads Tab a new Page will get open
3)  Choose Pre-built for Hadoop 2.7 and later
4)  Choose Direct Download
5)  Click on Download Spark: spark-2.0.2-bin-hadoop2.7.tgz  and save it on your desired location.
6)  Go to the Downloaded Tar file and Extract it.
7)  Again Extract the spark-2.0.2-bin-hadoop2.7.tar [File name will differ as version changes] to generate spark-2.0.2-bin-hadoop2.7 folder
8)  Now open Shell Prompt and go to the bin directory of spark-2.0.2-bin-hadoop2.7 folder [Folder name will differ as version changes ]
9)  Execute command spark-shell.sh
You will be in Spark Shell you can execute the spark commands
https://spark.apache.org/docs/latest/quick-start.html <-- Quick start Guide from spark
Hope this Helps!!!
Answer: For running spark on yarn cluster there is lot of steps to install hadoop and spark and all so i write one blog on it step by step you can install it and run spark shell on yarn see the below link
https://blog.knoldus.com/2016/01/30/spark-shell-on-yarn-resource-manager-basic-steps-to-create-hadoop-cluster-and-run-spark-on-it/
Answer: Here are the steps I took to install Apache Spark to a Linux Centos system with hadoop:

Install a default Java system (ex: sudo yum install java-11-openjdk)
Download latest release of Apache Spark from spark.apache.org
Extract the Spark tarball (tar xvf spark-2.4.5-bin-hadoop2.7.tgz)
Move Spark folder created after extraction to the /opt/ directory (sudo mv spark-2.4.5-bin-hadoop2.7/ /opt/spark)
Execute with command /opt/spark/bin/spark-shell if you wish to work with Scala or /opt/spark/bin/pyspark if you want to work with Python

Installing spark on hadoop


Nodejs: process exits while promise is pending

Question: Excerpt of a lambda function using nodejs 12.
There is a promise (aws dynamo db document client query) nested inside a promise (node-fetch API request).
The first promise works fine. It executes the request, waits for the promise to resolve, and then enters the .then(...) to execute some code. Next, it executes the database query, but then it exits the whole function without waiting for the promise to resolve, even though there are still callbacks. It doesn't throw errors either. (I know the database query is being executed , as extra logging showed it's status to be <pending>)
When I try var dbscan = await db.scan(...) using await, I get the error await is only valid in async function. But the handler function is already async, and await is working for the fetch promise.
Q: how can I use await inside the .then(...) of the first promise?
Q: why is the process exiting without waiting for the promise to resolve?
exports.myhandler = async (event, context, callback) => {

    var response = await fetch(url, {... my options ...})
    .then(res  => res.text())
    .then(data => {
        // do some stuff with the data ...

        var dbscan = db.scan({...my params ...}).promise()
        .then(res => {
            // do some stuff with result ...
            callback(null, <some message>);
        }).catch(err => {
            console.log(err);
            callback(null, <some message>);
        });

    })
    .catch(error => {
    console.log('error', error);
    callback(null, <some message>);
    });
}

Answer: You have to add async to the beginning of the function in which you want to use await.
.then(async(data) => {
  var dbscan = await ...
})

Answer: Since you're already using the async/await-syntax, you shouldn't have to resolve to using .then(..) chains.
You could flatten most of your code like this:
const response = await fetch(url, {... my options ...});
const data = await response.text();
// Do some stuff with the data...
const result = await db.scan({...my params ...});
// Do some stuff with the result...


Running Robotium Test Cases directly on a phone ( Not the emulator )

Question: I couldn't find any useful resource on the net regarding how robotium can be used to execute the test cases directly on the phone , rather than on the emulator ( which is the usual case )
Some More Details
I have a branded android phone. This phone has a builtin app which is manufactured by the phone manufacturer ( not a google app ) .. i don't either have the apk or the source code of the app. Given this situation  - Is it possible to use robotium for testing this app ?
Any help regarding this please ?
Answer: You need to root your phone and then pull the apk from the device, resign it with the same certificate that your test project uses and then push it back on the phone.
To run the tests on device instead the only thing you need to do is to connect it to your computer (use adb devices to make sure it is properly connected). Then the tests will be run on your device instead.
More information on this can be found on the Robotium wiki pages:
Robotium for preinstalled applications
Answer: You do not need to root the phone. You might be able to use Robotium, but you would have to delete the signature, and the sign with the debug. This might be hard since it is a Verizon built app. I am currently testing Verizon apps, and in order to test their app with Robotium, I had to sign the test with the Verizon signature and build the test with ant before I run it.
Hope this helps.


Can I use ANOVA if a sample is not normally distributed

Question: My data are not normally distributed. I have to compare three groups for their achievement in skill learning. $n=4$ in each group. I have used three methods ($M1$, $M2$ and $M3$) to teach one skill to developmentally delayed children.
Can I still use ANOVA?
Do I have to use repeated measures of ANOVA or a time series? Please throw some light
Comment: How do you know that your data are not normally distributed? If you only have 4 data points per group, I guess you don't have a lot of power to detect non-normality. Remember that if you want to check normality, you should check it *within* groups, not across all groups.
Answer: You do not say whether the same four children are taught with each method (i.e. child #1 is taught a skill using $M1$ and measured, then child #1 is taught a skill using $M2$ and measured, then child #1 is taught a skill using $M3$ and measured, etc.). Without this vital information, one cannot say whether or not you have a repeated measures design (although, given your sample size, I imagine the answer is yes).
With such a small sample size, I would imagine that violations of the normality assumption could well affect your results. So you might be interested in using a nonparametric variation of oneway ANOVA such as the Kruskal-Wallis test if your data are not from a repeated measures design (with Dunn's test for post hoc comparisons), or using a nonparametric variation of the oneway repeated measure ANOVA such as the Friedman test if your data are from a repeated measures design (I not familiar with this test, but a good nonparametric statistics text should be able to offer post hoc procedures).
Because both the Kruskal-Wallis and Friedman tests are based on ranks across the whole data set, simply performing a garden variety rank sum test as a post hoc procedure ignores the rankings used to produce the omnibus tests. Likewise, the rank sum tests ignore the pooled variance implied by the null hypothesis or both Kruskal-Wallis and Friedman tests.


Formula for PERT - Pessimistic time and optimistic time

Question: I found PERT examples include a formula
(a + 4m + b)/6
where a= optimistic time , b= pessimistic time and m= actual time to complete the task
but how to calculate a and b?
please help me as soon as possible
Answer: You don't calculate a and b, you estimate them. And m is usually the most likely time (estimate) not the actual time.

How do you estimate them?

That's a hard question... you need to consider the best possible scenario, and the worst. It takes practice and experience. You will likely get it wrong the first few times.
Comment: @karthi: No there is not. From the page you linked to "The activity time estimates are somewhat subjective and depend on judgement."
Comment: http://www.netmba.com/operations/project/pert/

This link says

"Optimistic time - generally the shortest time in which the activity can be completed. It is common practice to specify optimistic times to be three standard deviations from the mean so that there is approximately a 1% chance that the activity will be completed within the optimistic time" -- > is there any mathematical formula to calculate it?
Answer: The most pessimistic (P) case when everything goes wrong
The most optimistic (O) case where everything goes right
The most likely (M) case given normal problems and opportunities
Pert Chart Formula: (O + 4M + P)/6