Angular 13 - Cannot use namespace as a type.ts(2709)

Question: Am working on angular 13 version.Trying to import and use action file inside a .spec file shows  an error like below
Cannot use namespace 'MyActions' as a type.ts(2709)

This is my spec file
import * as MyActions from '../../core/store/action/my.actions';
describe('MyActionComponent', () => {
  let myActions: MyActions;

Please excuse for full source code.
Thanks in advance
Comment: MyAction is a namespace and not a type. Use an exporting interface of the namespace like `let myActions: MyAction.SomeActionType`
Comment: @Deitsch it showing some other issue
Comment: What is the error now?
Comment: @Deitsch MyActions.loadMyActionSuccess' refers to a value, but is being used as a type here. Did you mean 'typeof  MyActions.loadMyActionSuccess'?ts(2749)
Comment: If you want to assign a value use the `=` operator. `:` is used for specifying a type. Also please edit your question and add the `MyActions` namespace so we can discuss this better.
Answer: MyAction is a namespace and not a type, hence the error.
You object can only be of type coming from said namespace (or any other namespace). You may want to use an exporting interface of the namespace:
import * as MyActions from '../../core/store/action/my.actions';

describe('MyActionComponent', () => {
    let myActions: MyAction.SomeInterface
    ...
});


Adding Node Reference to a Comment

Question: If I add a Node Reference field to a node content type (with Reference from URL as a widget,) this field appears in the rendered content and can be used to jump to the referenced node.
I am trying to get a similar result in the rendered comment of the same content type: If I add a Node Reference field with Reference to URL in the Comment Fields edit page of the content type, it doesn't show up in the rendered comment page.
Why do I want to do this? Because when one leaves a comment in the rendered content, a message is sent to the author of the post that a comment was posted. In the email, there is a link to see the comment. The link is of the form example.com/comment/000#comment-000 and that's not the original post with the comments below.
So I am trying to add a link to the comment page that would send the reader to the rendered node where the comment was originally posted.
Does this mean one cannot reference a node from the same node's comment page?
Or does it mean there is another way to accomplish this?
Answer: You could achieve this with Comment Notify module.
We use it on few sites and it works great out of the box.
From module page:

Features
Mail registered and anonymous users about comment follow-ups
Allow users to unsubscribe from notifications on a specific post with
  a single click
Allow registered users to preset their follow-up setting in their
  profile
Users can choose to get notifications about all comments on a node or
  just replies to their comment
  Registered authors can get notifications about comments on their nodes
  Note: Since it only notifies you about published comments, this is not a solution to notify admins when they need to moderate comments on their site
Comment: Interesting approach. I am going to look into it. Thanks. :)
Answer: You should be able to display a node reference in a comment, if your not seeing it show up, I would check ether your fields that are being displayed (at /admin/structure/types/manage/content_type/comment/display) or check your theme to see what's getting printed out.
That being said, if your just looking for a way to put a link in the outbound email to the parent node, there's easier ways to do this. You might want to take a look at Comment Notify, which has a fairly easy to use interface on the back end that allows you to send a template email to the node author that uses tokens for replacement values.
Another option is to just use Actions, which also uses tokens, and add the url to the module. This is handy, as it can be used to send emails to site admins.
Comment: Yes, got it fixed in the theme. I use comment notify, this is how the notification emails are sent. I tried to replace the default token with one that would send the reader directly to the node, but I couldn't find one, so the node reference link appears to be the only solution. Thanks for your help. :)

Adding Node Reference to a Comment


How to prove that if an entire function has uncountably many zeroes then it must be constant

Question: I am solving assignment questions of complex analysis which might not be discussed due to pendamic and I was unable to solve this particular question.

Let f be an entire function that has uncountably many zeroes .  Prove that it is constant.

I was unable to get an idea on which result to use although I am good in complex analysis. So, It's my humble request to you tp kindly guide me.
I thought  of $\prod_{r_i  varies in\in \mathbb{R}} (z-r_i) $ , and I don't know why it must be constant.
Answer: Hint: If for each $z\in S\subset\Bbb C$ we find $r_z>0$ such that the open ball $B_{r_z}(z)$contains no point of $S$ other than $z$, then the balls $B_{r_z/2}(z)$ are pairwise disjoint and each contains a point with rational coordinates.
Comment: What is S in 1st line?
Answer: Analytic functions which are non-constant are such that their zeroes are isolated, that is, for every zero $z_0$ of $f$ there is a neighborhood $U$ about $z_0$ where $f(z)\not=0$ except if $z=z_0$. We say that the set of zeroes is totally disconnected.
It remains to show that an uncountable set cannot be totally disconnected.
Comment: It is true that the zero set of an entire function is (either $\Bbb C$ or) totally disconnected, but really the characterising property is being *discrete*. All the more because totally disconnected uncountable spaces do exist: see for instance the irrational real numbers, or Cantor's set.


Meta tag page descriptions

Question:
Possible Duplicate:
Meta tags aren't saved with all content types

I'm using Meta Tags to control the meta data on my Drupal 7 site.  This module seems to give your nodes control over what your page descriptions display via the vertical menu at the bottom of the page you're editing.  This description doesn't show though.
The only thing I can think of is the global options which you can find by "configuring" the module itself.  If I set a global page description, it will show on all pages, and if I disable it, or leave it blank, there will be no description shown.
Why is the data set on individual nodes not overwriting this global quality?  There doesn't seem to be another module to help me with descriptions either.
Comment: What @googletorp said. I'm using Meta Tags in plenty of projects and have never had an issue like that...sounds like the problem is elsewhere
Answer: I've used this module successfully today actually - with no configuration alterations.
One reason for things not working for you could be your theme which after all does control the markup for your site.
Comment: I'm using the [Omega](http://drupal.org/project/omega) html5 theme as the base and I'm not using any template suggestions for the main page layout.  Thank you for narrowing it down.  I'll go see if the omega guys have anymore insight.
Comment: Ok I figured it out!  Whew!  I'm using Display Suite as well, and after you add the Meta Tags module, a "Meta Tag" field becomes available in the node display setup (Edit->Manage Display->Full Content).  All I had to do was pull that field up to a visible area.  Super unintuitive, but I'm so glad it's working now.

Meta tag page descriptions


Why is the whammy bar sometimes called a "Tremolo" arm?

Question: Who coined or mis-used the term Tremolo for the pitch-bending mechanism often found on electric guitars?
Tremolo cannot actually be effected by using the 'whammy bar'.
Answer: Fender corporation is a major contributor to the confusion of the term tremolo and vibrato, at least within the world of guitars.  They marketed the Stratocaster as having a "tremolo" arm, even though its use produces vibrato.  In addition, they had amp models, notably the Vibrolux, which were labelled as having a vibrato effect, even though the circuit produced tremolo.
The company itself recognizes this misapplication of the terms, c.f. Fender's discussion on tremolo/vibrato,
Comment: I have never heard an explanation as to *why* the Fender company deliberately misused these two terms in the first place. It is well-known that Leo Fender was an industrial designer and not a musician.
Answer: The correct technical term for this kind of tailpiece or bridge arrangement is vibrato bridge or vibrato bar. "Vibrato" is a rapid, regular modulation of a note by varying its pitch up and down; this is what such a tailpiece or bridge can be used to do.
This kind of tailpiece or bridge is most commonly refered to as a tremolo bridge, although this is a misnomer. One definition of "Tremolo" is a rapid, regular modulation in volume, not pitch. (the more common definition of "tremolo" is a rapid back and forth alteration between two or more distinct pitches, like what you can do on a piano or organ, or again, a rapid trilling of one pitch, like what you can do with a pick or your fingers on a mandolin or guitar.)
Both "vibrato" and "tremolo" are classical music terms (in Italian) which have been in use for centuries and applied to playing techniques for all kinds of musical instruments and the human voice, long before the vibrato tailpiece for an electric guitar was introduced in the late 1940s by Paul Bigsby.
The term "whammy" is an onomatopoetic slang term that has come into use since the 1950s. It is most often associated with bridges that can perform extreme pitch bends, first the Fender Stratocaster design, and later the Floyd Rose and Kahler designs. I suppose the classical equivalent to the term "whammy" would be portamento, which is to say a slow slide from one pitch to another, not a rapid vibrating effect.
Comment: Fender may actually be the cause of the confusion: they introduced a "vibrato unit" which created a tremolo effect, and a "tremolo bar" which is a vibrato arm.
Comment: Thanks, Wheat,for the definitions;'whammy' apparently refers to a sudden thing, more like sfortzando, so here's another misnomer ! Portamento seems not to encapsulate the effect either,sadly.  Horatio, I feel thet Fender probably called theirs a trem. unit first, but there's time for more answers. Intruiged to know how the tremolo effect worked, though.
Answer: I think the term Wham Bar or Whammy Bar came into use after Lonnie Mack's hit single, "Wham" which made extensive use of the tremolo arm.


How do I tell what is running on which ports in Ubuntu?

Question: How could I tell what is listening on which ports on Ubuntu?  In other words, how do I get a list of ports that are in use?
Answer: "In use" as in with an active connection, or that programs are listening on? Or both?
Run sudo netstat -lp in your terminal; this will tell you what ports are open to receive connections, and what programs are listening on them. Try sudo netstat -p for the same thing, plus currently-active connections.
Comment: `fuser -n tcp 8080` will approach it from the other end; showing you which process (if any) is listening on TCP port 8080.
Comment: I think both is best ;)
Comment: What was a little strange is that I have tomcat and apache servers running and neither port 8080 nor 80 showed up in the list.  Would you know why that would happen?
Comment: @Genadinik Verify what port they are configured to listen on; for Apache this is the Listen directive in its config file, but I don't know about Tomcat.
Comment: If what Kromey suggested didn't cut it, try `sudo netstat -tulpn`.
Comment: use `ss` now https://askubuntu.com/questions/1025568/has-netstat-been-replaced-with-a-new-tool


Is $H_0$ being a closed set a convention in hypothesis testing?

Question: In the statistical hypothesis testing, the null hypothesis $H_0$ often takes the form of (at least in the books I've read):
$$
\begin{align*}
H_0:&\theta=\theta_0\\
H_0:&\theta\le\theta_0
\end{align*}
$$
or
$$
H_0:\theta_1\le\theta\le\theta_2
$$
Is it only a convention that the sets in $H_0$ are closed? Or are there any other reasons?
Comment: I'm pretty sure siyuang was demonstrating different forms the null hypothesis can take, in which case none of those hypotheses is supposed to be an alternative hypothesis (i.e. $H_1$). Also, in the future: this would have been more appropriate as a comment since you're not actually attempting to answer the question.
Comment: The second $H_{0}$ should be $H_{1}$. The two null hypotheses above are different. The first one is testing below some value, the second is testing between an interval. You can't use the same test for both.
Answer: If by open/closed you mean $[a,b]$ vs $(a,b)$, then it's in a continuous domain it doesn't make a difference. Consider a continuous pdf defined in the domain $a$ to $b$. The integral over $[a,b]$ will be equal to the integral over $(a,b)$ because the integral over a single point is zero, so excluding any countable set of points from the integrand won't change its value at all.
Now, on to some philosophy: generally, our null hypothesis is either an assertion that some population parameter is the same across treatments, or that the parameters are within some defined tolerance of each other. Since we are fixing this tolerance, it makes sense to define it with a closed set, where the set is closed up to the maximum tolerance, e.g. $H_0: \theta \le \theta_0$ where $\theta_0$ defines the maximum allowable tolerance. Since we are parameterizing our hypothesis with respect to the maximum allowable tolerance, it makes sense to use closed notation here. But, as described above, this hypothesis is functionally equivalent to $H_0: \theta \lt \theta_0$, but the interpretation is a little weirder now: $\theta_0$ now denotes the minimum rejection value of the parameter, so the allowable tolerance is infinitesimally close to but not equal to $\theta_0$. I think you'll agree that it generally makes more sense for the purposes of interpretation to define the null hypothesis with respect to the permissible range of parameter values.
If you meant something different by closed vs. open (maybe you meant it in some technical topological sense that I missed), please elaborate.
Comment: Unless one is operating in a Bayesian setting, no integration over the parameter $\theta$ is ever performed. This makes your initial paragraph quite puzzling: it seems like you have confused the random variable with the parameter.


Is there a term for tablature with numerals placed between the lines?

Question: In most of tablature notation for fretted instruments, each line represents a string and the numerals, representing the frets where to stop the string, are printed on the respective lines.
However, for 4-stringed instruments there exists literature [1, see picture] with the tablature consisting of five lines and the numerals printed in between those lines.
In this case a string is represented by a gap between two lines.
Is there nomenclature distinguishing between those two types of tablature?

1 Jehtro Burns and Ken Edison, Mel Bay's Complete Jethro Burns Mandolin Book, Mel Bay Publications, Inc., ISBN 1-56222-663-0 (1993)
Comment: It's still tab.  Not sure there is a different name.  I have seen this for guitar as well.
Comment: I'm not able to answer definitively, but I would just refer to it as Tab for mandolin as opposed to Tab for guitar.
Answer: Unlikely.
Your opening sentence is confirmed here:  "In tablature, the horizontal lines represent the strings of the instrument: six strings for guitar and dobro, four for mandolin and ukulele, five for banjo."  This notation guide uses a 6-, 5-, or 4-line staff, with a clef "TAB."
Your picture's omission of the unusual clef and usage of the common 5-line staff both suggest that this is a publisher's shortcut, not yet deserving the dignity of its own name.


Place sum beneath each column in range in Excel

Question: I have code that will clear everything below the "----" on a spreadsheet full of data. The "----"comes from an export into excel and I don't want data located under it, so I clear it.
After the code clears everything underneath the "----", I want to sum each column in a range and then place each column total underneath its column of data. The column range is  F  thru T. I'd like to be able to change this range in the code for other projects.
The row may not be the same each time, so the code must sum the columns after the last row of data.
Can anyone help with this, thanks!
Sub Remove_everything_under()

 Dim mtch As Long
    mtch = 0

    On Error Resume Next
        mtch = Application.WorksheetFunction.Match("----", ActiveSheet.Range("A:A"), 0) + 0
    On Error GoTo 0

    If mtch > 0 Then
        ActiveSheet.Range("A" & mtch, ActiveSheet.cells(Rows.Count, Columns.Count)).ClearContents
    End If

End Sub

Comment: The code in your question has nothing to do with what you're actually trying to do (?)
Answer: Sum-up Variable Sized Column Ranges
Description

Adjust the values in the constants section.
You can easily rewrite the procedure to use some of the constants as arguments for multi-purpose use.
The following will sum up the columns defined by cAddress and put the results (sums) to the cells below each non-empty column range. Executing it again will double the previous result each next time.

Some Challenges

Sum will fail if an error value so the cells of the column range have to be looped through. Solved.
Sum will sum up date values. Not solved, but not an issue when looping.
The loop will sum up TRUE as -1. Solved, but not an issue when Sum is used.

Option Explicit

Sub sumupVariableSizedColumnRanges()

    Const cAddress As String = "F:T" ' Columns Address
    Const FirstRow As Long = 2 ' First Row
    Const hasDates_Slow As Boolean = True ' If 'True', then loop always.

    Dim frOffset As Long: frOffset = FirstRow - 1 ' First Row Offset

    Dim rg As Range ' Initial Range: from FirstRow to last worksheet row.
    With ActiveSheet.Columns(cAddress)
        Set rg = .Resize(.Rows.Count - frOffset).Offset(frOffset)
        'Debug.Print "Initial Range address = " & rg.Address(0, 0)
    End With

    Dim crg As Range ' Column Range
    Dim rrg As Range ' Result Range
    Dim lCell As Range ' Last Cell (Range)
    Dim cError As Long ' Current Error Number
    Dim Result As Double ' Result

    ' If error, then loop.
    Dim Data As Variant ' Data Array
    Dim cValue As Variant ' Current Value
    Dim r As Long ' Data Array Rows Counter

    ' Starting idea if same last row for all columns:
'    Set lCell = rg.Find("*", , xlFormulas, , xlByRows, xlPrevious)
'    If lCell Is Nothing Then Exit Sub
'    Set rg = rg.Resize(lCell.Row - frOffset)
'    Debug.Print "Processing Range address = " & rg.Address(0, 0)

    For Each crg In rg.Columns
        Set lCell = crg.Find("*", , xlFormulas, , , xlPrevious)
        If Not lCell Is Nothing Then
            Set rrg = crg.Resize(lCell.Row - frOffset)
            'Debug.Print "Current Range address = " & rrg.Address(0, 0)
            If hasDates_Slow Then
                cError = -1 ' Dates are not summed up.
            Else
                On Error Resume Next ' Sum 'fails' if error values.
                Result = Application.Sum(rrg) ' Dates are also summed up.
                cError = Err.Number
                On Error GoTo 0
            End If
            If cError <> 0 Then
                'Debug.Print "Current Error Number  = " & cError
                cError = 0
                Result = 0
                If rrg.Rows.Count = 1 Then
                    ReDim Data(1 To 1, 1 To 1): Data = rrg.Value
                Else
                    Data = rrg.Value
                End If
                For r = 1 To UBound(Data, 1)
                    cValue = Data(r, 1)
                    If IsNumeric(cValue) Then
                        If VarType(cValue) <> vbBoolean Then ' exclude TRUE = -1
                            Result = Result + cValue
                        End If
                    End If
                Next r
                Erase Data
            End If
            lCell.Offset(1).Value = Result
            Set lCell = Nothing
        End If
    Next crg

End Sub


Test error increase with larger training set size

Question: Following scenario:

I trained an object detector (Viola Jones) on images of 8 subjects and evaluated on three other subjects (the test set) and achieved recall and precision values of roughly 82% and 80% respectively.
I trained Viola Jones on images of 14 subjects (including the above mentioned 8) and evaluated on the same test set and achieved recall and precision of 80% and 78%.

This was of great surprise to me, since I assumed the test set error should decrease with the increase of training set size. What could be possible reasons for this behaviour?
I can only think of:

Chance. But what exactly does that tell us about the method (Viola Jones) used?
The additional data is noisy. Possible, but unlikely...

PS: I also evaluated all subjects in scenario 1 and scenario 2 in a cross-validation manner, where I always left one subject out as test. Here, the performance drop in scenario 2 was even slightly more significant.
Answer: Recall and precision (and accuracy) depend on your observations. Your observations are random variables. Therefore your KPIs are also random variables. They have an expectation and a variance.
Plugging a particular set of observations into your model fitting algorithm and into your evaluation will lead to a particular realization of recall and precision.
The rule of thumb that more training data will lead to lower error refers to expectation. Even if the expectation of one random variable (e.g., precision from a large training set) is smaller than the expectation of a different one (e.g., precision from a large training set), a given realization from the first one may still be larger than one from the second one. For instance, if you draw one N(0,1) and one N(1,1) variable, the first one will still quite often come out larger than the second one.
And: eight, or even fourteen, samples are very little.
Comment: To clarify: subjects does not refer to samples, but individuals. What does it tell me about my classifier and/or dataset, when my KPIs have a high variance?
Comment: If your KPI has a high variance, then your results will vary a lot if you apply your model to different new datasets. That is, it is quite probable that model $A$ outperforms model $B$ on some *specific* new dataset, even though *in expectation* $B$ outperforms $A$.
Answer: when you refer 14 subject. you mean 14 pictures? if so, I think 8 or 14 pictures is a very small data set. so the result should be pretty random.
Comment: no, I mean 14 individuals.


It doesn't work without public_html symlink

Question: I have just updated to Ubuntu 20.04 so have a fresh install of everything.
I have a working Drupal 7 site I'll call mysite.
I have Drush-launcher installed globally at /usr/local/bin/drush
The file structure of the site is the following.

/var/www/mysite/composer.json (to install Drush 8.4.1)
/var/www/mysite/vendor/drush/drush/drush (local Drush 8.4.1 binary)
/var/www/mysite/web
/var/www/mysite/public_html (symlink to web)
/var/www/mysite/web/sites

Drush works with this configuration. drush status returns a full and accurate site description of about 15 lines.
If I remove the public_html link, the Drupal site runs fine but most Drush commands no longer work. drush status returns only the bare minimum of 7 lines as it does when it can't find the site. drush --version does return the correct version number either way and if I move the Drush 8 directory, all Drush commands return an error as expected. (This shows I'm still using the correct binary).
I have several Drupal 8 sites that are configured this exact same way (no public_html directory or link) and they work as expected.
I have searched in the ~/.drush directory for any reference to public_html and there are none related to this site. I have cleared the Drush cache. There are no references to public_html in my Apache config for the site. Searching isn't turning up anything useful.
I could just leave the public_html link in the filesystem but git wants me to add it or ignore which seems kinda silly.
What might I be doing wrong?
Comment: You say you have no references to public_html anywhere, but what made you try creating a symlink from public_html to web?
Comment: That's how I had it set up originally. I had copied that structure from prod. Prod does use the public_html. That was the easiest way for me to get git/drush to work back in the days when I had drush installed globally. I reorganized the structure on my local once I started installing Drush via Composer.
Answer: Solved it!
Thanks to @sonfd for making me think more about the composer installation. Look what I found in there:
"extra": {
  "installer-paths": {
    "public_html": [
      "type:drupal-core"
    ]
  }
},

I changed that from public_html to web and it works. Damn.


Issue with decoding characters in API response

Question: Having some trouble handling values coming from an external API service with Node.
http.get(
    endpoint,
    function(res)
    {
        if (res.statusCode != 200)
        {
            return next();
        }
        var pageData = '';
        res.setEncoding('utf8');
        res.on(
            'data',
            function(chunk)
            {
                pageData += chunk;
            }
        );
        res.on(
            'end',
            function()
            {
                waterfallCallback(null, pageData);
            }
        );
    }
);

I'm then deserializing the string with a xml2js parser and using the data accordingly. A few of my strings have foreign characters in them ie. Ciné when they get saved to db they don't record correctly.
I've attempted using the iconv package to convert from utf-8 to ISO-8859-1 but I'm not sure if this is the correct way to handle a situation.
Help by an expert is appreciated.
Thanks,
Dave
Comment: You are setting the encoding to utf-8. Are you sure the server returns utf-8 encoded strings? Is this res object reading the return mime-type and would work okay if you would not set the encoding manually? I do not know which API you use ;-(
Comment: It actually doesn't matter which API it is, as long as your application is only able to handle ISO-xxxx-x you will always run in to problems like this. You might fiddle around with encoding/decoding routines but on the long run you need to go at least with UTF-8 entirely (database, web server, php, application, ...). It's a lesson I had to learn as well :-(
Comment: Hmmm, thanks for your help guys. I'm removing my setEncoding now. The API isn't actually returning an encoding type (at least not in the headers). Do you think I should change my method perhaps?Specify the ISO then convert to UTF-8? Sorry I think I'm just having trouble determining what to do when I have an unknown encoding. Here's a sample of the data that's returned: http://pastebucket.com/15770
Comment: lol oh man, a colleague just pointed out that the XML declaration states the encoding directly (ISO-8859-1). I totally missed that. Lesson learned: understand your data fully before working with it.
Answer: I managed to get this going. Lesson learned: always understand the data your dealing with. Not just the format/structure but character encoding is absolutely vital.
The main issue was that characters were being sent as ISO-8859-1 but I had no idea. Once I found that out I converted everything to UTF8 which the database and all my own API endpoints serve up.
I changed my call to use the request node package, pulled it down as binary and used iconv to convert to UTF8. Here's some helpful code:
request(
    {
        uri: 'http://' + endpoint.host + endpoint.path,
        encoding: null
    },
    function(err, response, body)
    {
        if (! err && response.statusCode == 200)
        {
            var iconv = new icon('ISO-8859-1', 'UTF8');
            var converted = iconv.convert(body);

            callback(
                null,
                converted.toString('utf8')
            );
        }
        else
        {
            next();
        }
    }
);

The returned result is now exactly what I'm expecting. =)


android searchview setOnActionExpandListener on Honeycomb 3.2

Question: I'm developing an app for Android 3.2 and greater with android-support-v4. I need to implement OnActionExpandListener for "intercept" when SearchView in the actionbar is expanded and when is collapsed. My code for Android 4.0 and higher it's ok, but for 3.2 no.

menu.xml

<item android:id="@+id/menu_search"
    android:title="@string/menu_search"
    android:icon="@android:drawable/ic_menu_search"
    android:showAsAction="collapseActionView|always"
    android:actionViewClass="android.widget.SearchView" />

MyActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.reader, menu);

    final MenuItem searchMI = menu.findItem(R.id.menu_search);
    if(searchView == null) {
        //searchView = (SearchView) searchMI.getActionView();
        searchView = (SearchView) MenuItemCompat.getActionView(searchMI);
        searchView.setOnQueryTextListener(this);
        searchView.setOnSuggestionListener(this);
        searchView.setOnCloseListener(new OnCloseListener() {

            @Override
            public boolean onClose() {
                //some code
                return false;
            }
        });
    }

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
        MenuItemCompat.setShowAsAction(searchMI, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        MenuItemCompat.setOnActionExpandListener(searchMI, new OnActionExpandListener() {

            /* (non-Javadoc)
             * @see android.support.v4.view.MenuItemCompat.OnActionExpandListener#onMenuItemActionExpand(android.view.MenuItem)
             */
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                Toast.makeText(getApplicationContext(), "onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
                return true;
            }

            /* (non-Javadoc)
             * @see android.support.v4.view.MenuItemCompat.OnActionExpandListener#onMenuItemActionCollapse(android.view.MenuItem)
             */
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                Toast.makeText(getApplicationContext(), "onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    } else {
        searchMI.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {

            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                Toast.makeText(getApplicationContext(), "MenuItem#onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                Toast.makeText(getApplicationContext(), "MenuItem#onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }
}

Why, for Honeycomb, methods of listener is not invoked?
Thank you so much.
Comment: Just a passing note, since good answers are posted below. There are two problems: (1) should be "app:showAsAction", not "android:showAsaction", and also "app:actionViewClass". (2) The code itself should unconditionally use MenuItemCompat.setOnActionExpandListener regardless of platform. Ironically everyone who arrives here has problem #1; but OP's code doesn't have problem #1; it has problem #2. Just sayin'.
Answer: You probably missed the fact (like I did) that `MenuItemCompat.OnActionExpandListener' interface has a static implementation, and is not an instance method.
So, if you have a class that implements MenuItemCompat.OnActionExpandListener then in that class you need to install it as the listener like this:
MenuItem menuItem =  menu.findItem(R.id.search);
if (menuItem != null) {
  MenuItemCompat.setOnActionExpandListener(menuItem,this);
  MenuItemCompat.setActionView(menuItem, mSearchView);
}

The same paradigm applies to setActionView ... rather than invoke menuItem.setActionView(this), you pass the menuItem as the first argument to the static version MenuItemCompat.setActionView and follow with the other argument(s).
Comment: You solution works, thanks alot
One more thing the answer above you is also necessary for proper working
"For MenuItemCompat.setOnActionExpandListener to work you should add "collapseActionView" added in the menu item"
Answer: For MenuItemCompat.setOnActionExpandListener to work you should add "collapseActionView" added in the menu item -
for example -
<item android:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          app:showAsAction="ifRoom|collapseActionView"
          app:actionViewClass="android.support.v7.widget.SearchView" />

And in the onCreateOptionsMenu you can use it this way -
MenuItemCompat.setOnActionExpandListener(menu_search,
            new OnActionExpandListener()
            {
                @Override
                public boolean onMenuItemActionCollapse(MenuItem item)
                {
                    // Do something when collapsed
                    return true; // Return true to collapse action view
                }

                @Override
                public boolean onMenuItemActionExpand(MenuItem item)
                {
                    // Do something when expanded
                    return true; // Return true to expand action view
                }
            });

Answer: I found that MenuItemCompat.setOnActionExpandListener(...) is not working if you don't pass:
    searchItem
            .setShowAsAction(MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
                    | MenuItemCompat.SHOW_AS_ACTION_ALWAYS);

But this is changing the SearchView and is replacing the DrawerToggle with back arrow.
I wanted to keep the original views and still track the Expanded/Collapsed state and use supported Search View.
Solution:
When android.support.v7.widget.SearchView is changing the view state the LinearLayout view's, with id android.support.v7.appcompat.R.id.search_edit_frame, visibility value is being changed from View.VISIBLE to View.GONE and opposite. So I add ViewTreeObserver to track the visibility change of the search edit frame.
menu_search.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    android:title="@string/search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always"/>

</menu>

In the activity:
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;

..........

private View mSearchEditFrame;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    MenuItem searchItem = (MenuItem) menu.findItem(R.id.action_search);

    SearchView searchView = (SearchView) MenuItemCompat
            .getActionView(searchItem);
    searchView.setSubmitButtonEnabled(false);
    mSearchEditFrame = searchView
            .findViewById(android.support.v7.appcompat.R.id.search_edit_frame);

    ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        int oldVisibility = -1;

        @Override
        public void onGlobalLayout() {

            int currentVisibility = mSearchEditFrame.getVisibility();

            if (currentVisibility != oldVisibility) {
                if (currentVisibility == View.VISIBLE) {
                    Log.v(TAG, "EXPANDED");
                } else {
                    Log.v(TAG, "COLLAPSED");
                }

                oldVisibility = currentVisibility;
            }

        }
    });

    return super.onCreateOptionsMenu(menu);
}

Thanks!
Answer: Your Listener should be MenuItemCompat.OnActionExpandListener() .
MenuItemCompat.setOnActionExpandListener(searchItem,
            new MenuItemCompat.OnActionExpandListener() {

}

Comment: In my code: MenuItemCompat.setOnActionExpandListener(searchMI, new OnActionExpandListener() {...}) OnActionExpandListener is in MenuItemCompat class. Your suggestion not work.
Answer: thanks for your help,
your solution is work for me. and i'd like to vote you up, but i just realized i have only 1 reputation,(;′⌒`)
actually, my solution is similar to your, there is just one different in the menu xml file like this:
    <item
    android:id="@+id/apps_menu_search"
    android:icon="@drawable/ic_action_search"
    android:title="@string/apps_menu_search"
    android:visible="true"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="ifRoom|collapseActionView" />


want to send and receive json data in php

Question: As per application requirement, I am trying to develop two PHP which can communicate with each other via Json. I tried searching online but didn't found solution.
Can any one suggest me the right path for this?
I have data in mysql database, the converted data will be in json format as given below: (Also looking for code to get this data format via PHP-JSON object and array.)
{ "user" : [
             { "firstName" : "Vignesh",
               "lastName"  : "Prajapati",
               "age"       : 23,
               "email"     : ["firstname.lastname@example.com","email@example.com"],
               "subject"   : ["English","Gujarati", "Hindi"]
             },

             { "firstName" : "Vaibhav",
               "lastName"  : "Prajapati",
               "age"       : 19,
               "email"     : ["firstname.lastname@example.com","firstname.lastname@example.com","firstname.lastname@example.com"],
               "subject"   : ["English","Spanish", "Chinese","Sanskrit"]
             }
           ]
}

My Php code for sending Json data: (send.php)
<?php

$data = '    { "user" : [
                 { "firstName" : "Vignesh",
                   "lastName"  : "Prajapati",
                   "age"       : 23,
                   "email"     : ["email@example.com","firstname.lastname@example.com"],
                   "subject"   : ["English","Gujarati", "Hindi"]
                 },

                 { "firstName" : "Vaibhav",
                   "lastName"  : "Prajapati",
                   "age"       : 19,
                   "email"     : ["email@example.com","email@example.com","firstname.lastname@example.com"],
                   "subject"   : ["English","Spanish", "Chinese","Sanskrit"]
                 }
               ]
    } ';

$url_send ="http://localhost/rec.php";
$str_data = json_encode($data);

function sendPostData($url, $post){
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  $result = curl_exec($ch);
  curl_close($ch);  // Seems like good practice
  return $result;
}

echo " " . sendPostData($url_send, $str_data);

?>

My Php code for receiving Json data: (rec.php)
<?php

$json_input_data=json_decode(file_get_contents('php://input'),TRUE);

echo $json_input_data;

?>

Comment: If you already have data in json format so you shouldn't use `json_encode()` to encode it.
Comment: Build a `user` object, fill it with an array of objects that contain individual user information en `json_encode()` the result.
Comment: hi, @KristerAndersson, I have just manually written that json format data. Actually first I want data in that format and then I want to send.
Comment: @KristerAndersson, If I am wrong with my way then please suggest the direction.
Answer: Modify your function to send header of JSON_DATA in post request
function sendPostData($url, $post){
 $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($post))
   );
  $result = curl_exec($ch);
  curl_close($ch);  // Seems like good practice
  return $result;
}

In file use
<?php

$json_input_data=json_decode(file_get_contents('php://input'),TRUE);

print_r( $json_input_data);

?>

As everyone said there is no need of $str_data = json_encode($data);,Since data is already in json.
Comment: Then you should use JSON_ENCODE
Comment: Thanks @MADTerry, But if I have my data as $data = array('user' => array(
         array('firstName' => 'Vignesh', 'lastName' => 'Prajapati'),
         array('firstName' => 'Vaibhav', 'lastName' => 'Prajapati')
       ));  It is not working
Comment: I used it, and it worked. But still I am not able to print that json elements. It gives error - Notice: Array to string conversion. on rec.php file.
Comment: print_r( $json_input_data); should be used if you are testing variable values.
Comment: Is there any function that will print all these values of array sequentially. (last help?)
Comment: @ViGnEsHPrAjApAtI What sequence you want ?
Comment: I want such that it print all of the elements of an array one by one with their attribute name.
Comment: print_r($vjson_input_data) does the same.
Comment: yes, Also I want to store all these element to database (on other server) so again I need to store them to separate variables. thats why I need this.
Comment: then you should use json_encode($json_input_data) that will return a string.
Answer: Since you shouldn't use json_encode if the data already is in json format, change your code to something like:
$data = array('user' => array(
         array('firstName' => 'Vignesh', 'lastName' => 'Prajapati'),
         array('firstName' => 'Vaibhav', 'lastName' => 'Prajapati')
       ));

Of course you will need to add the other fields to the array as well.
Using json_encode() on the above data will return:
{
   "user" : [
     {
      "firstName" : "Vignesh",
      "lastName" : "Prajapati"
     },
     {
      "firstName" : "Vaibhav",
      "lastName" : "Prajapati"
     }
   ]
 }

Comment: Hey @Krister Andersson, thanks for your partial code it worked for me. ANd thanks for providing this understandings.!!
Comment: This right here is why I much prefer PHP5.4 when available. Square-bracket syntax is so much more readable when you're building a large, 4+ height tree as an array.
Answer: Remember that JSON means 'object notation', ie it's a way to describe an object in javascript. It's a great way to communicate at the network-level, but when you're in PHP you should be using the data structures that PHP is designed to use. Rather than work with JSON directly on either side, and especially as an alternative to a big JSON string, keep that data structured as an array and encode it right before sending. Your approach with curl is fine, though a bit custom - there's lots of nice routers that do a better job managing these sorts of requests (symfony is my favourite), but that's a separate issue.
e.g. instead of your big string, represent it as:
$data =
    [ "user" => [
                 [ "firstName" => "Vignesh",
                   "lastName"  => "Prajapati",
                   "age"       => 23,
                   "email"     => ["email@example.com","email@example.com"],
                   "subject"   => ["English","Gujarati", "Hindi"]
                 ]

etc..
When it comes time to send it to the other server, json_encode and go.
Comment: Hi Josh From Qaribou, Thanks for your message it helped me for understanding.!!


Are Poisson distributions only for arrivals?

Question: I have this data set:
<code>4.6093  3.8583  5.2921 11.8326  3.3745 14.3956
2.4541  1.1305  1.1191  2.9973  4.141   2.0066
2.7272  8.7227  2.1489  3.0065  2.338   2.6579
2.6083  4.8375  0.2878  2.6055  1.6949  0.3578
9.5841  1.7347  2.9482  6.7692 12.1024  4.1612
</code>
I'm trying to match it to a distribution. I graphed it in a histogram and it looked to me to match the Poisson distribution.
When I learned about the Poisson distribution, I thought it was used for arrivals but these are service times.  Is it possible for these to follow a Poisson distribution or is it another distribution?
Answer: It certainly does not look like Poisson data: Poisson distributions can only take on count values (i.e. whole numbers). The fact that there are decimals lets you know immediately know it cannot be Poisson.
If you are looking for distributions that are often used to model time to event, I would suggest looking at the exponential and Weibull distributions.
Comment: +1 I'd also have suggested the Gamma as a possible choice. Looking at a Q-Q plot vs exponential scores, the exponential doesn't seem too bad, but either of the other two would fit the left end better.
Comment: @Glen_b: yes, I certainly agree that gamma is another viable alternative. My experience is that in the field of survival analysis, the Weibull distribution is often preferred, although my only explanation for that the reason for this is that those who deal with survival analysis feel comfortable thinking about hazard rates and it's easier to understand the relation between hazard rates and the shape parameter for Weibull than for the gamma distribution.
Comment: Oh, and the proportional hazards and aft Weibull are identical (up to a linear transformation of variables). Neither of these are compelling reasons for choosing the Weibull over the gamma, of course.
Comment: In the case of service times, the gamma occurs (for example) as the time to the completion of $k$ independent exponentially-distributed service-components (each with the same scale), so it's often a reasonable first approximation in cases where there's several parts or stages to service.
Comment: @Glen_b: the theoretical motivation for gamma distribution is a nice aspect. The Weibull distribution apparently [ran into trouble with the reviewers](ftp://18.104.22.168/ExperimentsDesign/Weibull-ASME-Paper-1951.pdf) for not having theoretical motivation (see the middle of the second column on page 1).
Answer: A Poisson($\lambda$) random variable is discrete, therefore only takes integer values (0, 1, ...). However, there is a link between the Poisson and Exponential distributions. If an event occurs according to a Poisson process, i.e. if the number of events happening in an interval of length $t$ follows a Poisson ($\lambda t $) distribution, then the elapsed time between two events has an Exponential ($\lambda$) distribution, where the mean of the Exponential is  $1/\lambda$.
In your case, if our data actually represents elapsed times between events, Exponential might be a good choice. In this context, other choices would include Weibull and Gamma.


Postgre insert null in char(3) não funciona

Question: Abaixo o erro e o código que estou rodando
Tem dois campos desta tabela que são definidos como char(3), o campo uf e o campo ufcrm.
Será que alguém sabe como posso fazer este insert?
Erro de SQL:

ERROR:  value too long for type character(3)

No bloco:
INSERT INTO medico (crm,nome_med,fone1,fone2,fone3,celular,email,abrev,ufcrm,endereco,bairro,cep,cidade,uf,interno,senha,enviawww,padrao,chavesline,uncp_bak,unimed,uncp,status,cpf,espmed_id,datanasc,bpacns,bpacbo,login,obs_med,idopera_ultacao) values ('SP1913','Fulvius Titanero','11942993020',NULL,NULL,NULL,NULL,NULL,NULL,'Rua Eunice Weaver',NULL,'03333060','Sao Paulo','Sao Paulo',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1) RETURNING id

Muito obrigado, vou alterar o "uf" e vou rodar novamente para ver
Abaixo mais alguns erros que eu estava testando aqui
Erro de SQL:
ERROR:  syntax error at or near "Erro"
LINE 1: Erro de SQL:
        ^
No bloco:
Erro de SQL:
ERROR:  value too long for type character(3)
No bloco:
INSERT INTO medico (ufcrm,uf)
values ('1', '1') RETURNING id
ERROR:  syntax error at or near "Erro"
LINE 1: Erro de SQL:
        ^
No bloco:
Erro de SQL:
ERROR:  value too long for type character(3)
No bloco:
INSERT INTO medico (ufcrm,uf)
values ('', '') RETURNING id
OK OK OK>
resolvido era o tamnho da uf mesmo
obrigado a todos que ajudaram
Comment: uf está recebendo "Sao Paulo" que tem 9 caracteres, sendo que só suporta 3 caracteres. Neste caso, tem que denifir se São Paulo vai ser 'SP' ou vai ter que aumentar a capacidade do campo para mais caracteres.
O ufcms é a mesma coisa, está inserindo 'NULL' que tem 4 caracteres, num campo que só aceita 3 caracteres
Answer: Uf está recebendo "Sao Paulo" que têm 9 caracteres, sendo que só suporta 3 caracteres. Neste caso, tem que definir se "Sao Paulo" vai ser 'SP'(só a sigla do estado) ou vai ter que aumentar a capacidade do campo para mais caracteres (Ex: "Rio Grande do Norte" é o estado brasileiro com maior nome e tem 19 caracteres, essa teria que ser a capacidade máxima deste campo). O ufcms é a mesma coisa, está inserindo 'NULL' que tem 4 caracteres, num campo que só aceita 3 caracteres.
Comment: muito obrigado, eu estava com a cabeça e outras coisas e não fiquei atento com o básico, valeu @Edward Ramos


The server on localhost doesnt seen to accept connection

Question: <code>//serv.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{

    FILE *log;
    int port_no;
    struct sockaddr_in server_addr;
    struct hostent* server;    int port_flag=0;
    int c;
    while(1)
    {
        static struct option long_options[]=
        {
            {"port",required_argument,0,'p'},
            {"log",required_argument,0,'l'},
        };
        c= getopt_long(argc,argv,"p:l",long_options,NULL);
        if(c==-1)
            break;
        switch(c)
        {
            case 'l':
                if(optarg)
                {
                    if(optarg[0]!='-')
                    {
                        log= fopen(optarg,"w");
                    }
                    else
                    {
                        fprintf(stderr,"log requires argument\n");
                    }

                }
                break;
            case 'p':
                if(optarg)
                {
                    if(optarg[0]!='-')
                    {
                        port_no= atoi(optarg);
                        port_flag=1;
                    }
                    else{
                        printf("Usage --port=PORT_NUMBER\n");
                    }
                }
                else
                {
                    printf("Usage --port=PORT_NUMBER\n");
                }
                break;
            case '?':
                write(STDOUT_FILENO,"\r",1);
                exit(1);
                break;
            default:
                break;

        }

    }

int opt = 0, port_num, client_len;
    struct sockaddr_in server_addr, client_addr;
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket_fd < 0) { perror("Error opening socket"); exit(1); }
    memset((char*) &server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port_num);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    if(bind(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0)
    {
        perror("Error binding socket");
        exit(1);
    }
    listen(socket_fd,5);
    client_len=sizeof(client_addr);
    newsocket_fd=accept(socket_fd,(struct sockaddr *)&client_addr,&client_len);
    printf("accepting");
    if(newsocket_fd<0)
    {
        fprintf(stderr,"error on accept");

    }
    char buffer[256];
    memset(buffer,0,256);
    int n=read(newsocket_fd,buffer,255);
    if(n<0)
    {
        fprintf(stderr,"Error reading from socket");

    }
    printf("Here is the message: %s\n",buffer);
    n=write(newsocket_fd,"I got your message",18);
}
</code>
client.c
<code>int main(int argc, char *argv[])
{

    FILE *log;
    int port_no;
    struct sockaddr_in server_addr;
    struct hostent* server;    int port_flag=0;
    int c;
    while(1)
    {
        static struct option long_options[]=
        {
            {"port",required_argument,0,'p'},
            {"log",required_argument,0,'l'},
        };
        c= getopt_long(argc,argv,"p:l",long_options,NULL);
        if(c==-1)
            break;
        switch(c)
        {
            case 'l':
                if(optarg)
                {
                    if(optarg[0]!='-')
                    {
                        log= fopen(optarg,"w");
                    }
                    else
                    {
                        fprintf(stderr,"log requires argument\n");
                    }

                }
                break;
            case 'p':
                if(optarg)
                {
                    if(optarg[0]!='-')
                    {
                        port_no= atoi(optarg);
                        port_flag=1;
                    }
                    else{
                        printf("Usage --port=PORT_NUMBER\n");
                    }
                }
                else
                {
                    printf("Usage --port=PORT_NUMBER\n");
                }
                break;
            case '?':
                write(STDOUT_FILENO,"\r",1);
                exit(1);
                break;
            default:
                break;

        }

    }
    char buffer[256];
            socket_fd = socket(AF_INET, SOCK_STREAM, 0);
            if(socket_fd < 0) { perror("Error opening socket"); exit(0); }
            server = gethostbyname("localhost");
            if(server == NULL) { fprintf(stderr, "Cannot find host"); exit(0); }
            //Initialize the server address to zero and then correctly assign it
            memset((char*) &server_addr,0, sizeof(server_addr));
            server_addr.sin_family = AF_INET;
            memcpy((char *) &server_addr.sin_addr.s_addr,
                   (char*) server->h_addr,
                   server->h_length);
            server_addr.sin_port = htons(port_no);

if(connect(socket_fd,(struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { perror("Error connecting"); exit(0); }
        printf("Please enter the message");
        memset(buffer,0,256);
        fgets(buffer,255,stdin);
        int n=write(socket_fd,buffer,strlen(buffer));
        if(n<0)
        {
            fprintf(stderr,"error writing to socket");
        }
        memset(buffer,0,256);
        n=read(socket_fd,buffer,255);
        if(n<0)
        {
            printf("Error reading");
        }
        printf("%s\n",buffer);}
</code>
}
I don't know why but the server doesn't seem to accept the socket
connection from client. I have tried port numbers more than 1024. Just
doesn't work. port number is user entered. Is there a port_no only for which it will work?
Comment: Do you see your server listening on given port in output of netstat command?
Comment: What error do you get, and from where?
Comment: No error just hangs keeps waiting to connect
Comment: Assuming the above is the ACTUAL code you used in your test, port_num in serv.c hasn't been initialized... Can we assume you started "serv" first, and then "client"... which "hung"...???
Comment: Yes spot on  ! Ther serv.c and client.c both take port number as argument in --port= option in getopt long
Comment: perhaps your "getopt" handling is the problem... we have no idea because you didn't include that code... you should provide MCVE [link] (https://stackoverflow.com/help/mcve)     Additional suggestion: add a newline to your "printf()" statements, otherwise they may not appear until your program exits.
Comment: You can simply catch error in server client application by checking return values of send() connect() write() read() or etc.. functions.  see http://pubs.opengroup.org/onlinepubs/7908799/xns/syssocket.h.html
Comment: for write () see: http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_075.htm
Comment: I am checking as u can see but it doesnt send anything
Comment: Please provide a minimal, *runnable* demonstration of the problem.
Comment: ok guys i have put up full code with getopt hope you cn help me now
Answer: The "full code" you posted clearly isn't full, since it won't compile (hint: client.c doesn't include a single header file). With trivial fixes made, an important clue comes from compiling with warnings enabled:
<code>$ gcc -g serv.c -o serv -Wall -Wextra
serv.c: In function 'main':
serv.c:94:71: warning: pointer targets in passing argument 3 of 'accept' differ in signedness [-Wpointer-sign]
     int newsocket_fd=accept(socket_fd,(struct sockaddr *)&client_addr,&client_len);
                                                                       ^
In file included from serv.c:7:0:
/usr/include/x86_64-linux-gnu/sys/socket.h:243:12: note: expected 'socklen_t * __restrict__' but argument is of type 'int *'
 extern int accept (int __fd, __SOCKADDR_ARG __addr,
            ^
serv.c:79:5: warning: unused variable 'opt' [-Wunused-variable]
 int opt = 0, port_num, client_len;
     ^
serv.c:23:36: warning: variable 'port_flag' set but not used [-Wunused-but-set-variable]
     struct hostent* server;    int port_flag=0;
                                    ^
serv.c:23:21: warning: unused variable 'server' [-Wunused-variable]
     struct hostent* server;    int port_flag=0;
                     ^
serv.c:21:9: warning: variable 'port_no' set but not used [-Wunused-but-set-variable]
     int port_no;
         ^
serv.c:20:11: warning: variable 'log' set but not used [-Wunused-but-set-variable]
     FILE *log;
           ^
serv.c:111:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
serv.c:85:28: warning: 'port_num' may be used uninitialized in this function [-Wmaybe-uninitialized]
     server_addr.sin_port = htons(port_num);
</code>
Look at that last warning - "port_num" uninitialised? Look further up:  "port_no" initialised but not used? So that argument processing is in vain and you're listening on an arbitrary port - the suggestion of checking "netstat -l -p" by @Pras would have shown this too.
As a debugging strategy it's worth compiling with pedantic warnings (and try with a more diagnostic compiler like clang) to look for clues. As a common development strategy reduce the time spent debugging by always enabling warnings and fixing them before even running the code.
Answer: Since you are asking about the server here is what I noticed.
Both "port_no" and "port_num" declared, the user input it assigned to "port_no" but you are using "port_num" when calling htons().
You have a redeclaration of 'server_addr' after your switch case, and are also missing newsocket_fd
<code>$gcc -o server server.c
server.c: In function 'main':
server.c:80:24: error: redeclaration of 'server_addr' with no linkage
     struct sockaddr_in server_addr, client_addr;
                        ^~~~~~~~~~~
server.c:22:24: note: previous declaration of 'server_addr' was here
     struct sockaddr_in server_addr;
                        ^~~~~~~~~~~
server.c:81:5: error: 'socket_fd' undeclared (first use in this function)
     socket_fd = socket(AF_INET, SOCK_STREAM, 0);
     ^~~~~~~~~
server.c:81:5: note: each undeclared identifier is reported only once for each function it appears in
server.c:94:5: error: 'newsocket_fd' undeclared (first use in this function)
     newsocket_fd=accept(socket_fd,(struct sockaddr *)&client_addr,&client_len);
</code>
Either way I removed the switch case and manually assigned the port number to get it running, you need to check your inputs and clean up a few more errors but here is a working example of your code with comments about the changes.
I used netcat as a client to test the connection.
<code>$ netcat 127.0.0.1 5555
test message
I got your message
</code>
The output code was not changed from what you provided, this is what it will display. use "\n" for a newline.
<code>$gcc -o server server.c
example@pc:~$./server
acceptingHere is the message: test message
</code>
Here is the modified code:
<code>//serv.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{

    FILE *log;
    // Added socket_fd and newsocket_fd
    int socket_fd, newsocket_fd;
    // use uint16_t for port number
    uint16_t port_no;
    //Removed struct sockaddr_in server_addr;
    struct hostent* server;    int port_flag=0;
    int c;

    port_no = 5555;
    /* removed switch to show server does function
    while(1)
    {
        static struct option long_options[]=
        {
            {"port",required_argument,0,'p'},
            {"log",required_argument,0,'l'},
        };
        c= getopt_long(argc,argv,"p:l",long_options,NULL);
        if(c==-1)
            break;
        switch(c)
        {
            case 'l':
                if(optarg)
                {
                    if(optarg[0]!='-')
                    {
                        log= fopen(optarg,"w");
                    }
                    else
                    {
                        fprintf(stderr,"log requires argument\n");
                    }

                }
                break;
            case 'p':
                if(optarg)
                {
                    if(optarg[0]!='-')
                    {
                        port_no= atoi(optarg);
                        port_flag=1;
                    }
                    else{
                        printf("Usage --port=PORT_NUMBER\n");
                    }
                }
                else
                {
                    printf("Usage --port=PORT_NUMBER\n");
                }
                break;
            case '?':
                write(STDOUT_FILENO,"\r",1);
                exit(1);
                break;
            default:
                break;

        }

    }
    */

    // Removed port_num
    int opt = 0, client_len;
    struct sockaddr_in server_addr, client_addr;
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket_fd < 0) { perror("Error opening socket"); exit(1); }
    memset((char*) &server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    // using port_no in htons
    server_addr.sin_port = htons(port_no);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    if(bind(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0)
    {
        perror("Error binding socket");
        exit(1);
    }
    listen(socket_fd,5);
    client_len=sizeof(client_addr);
    newsocket_fd=accept(socket_fd,(struct sockaddr *)&client_addr,&client_len);
    printf("accepting");
    if(newsocket_fd<0)
    {
        fprintf(stderr,"error on accept");

    }
    char buffer[256];
    memset(buffer,0,256);
    int n=read(newsocket_fd,buffer,255);
    if(n<0)
    {
        fprintf(stderr,"Error reading from socket");

    }
    printf("Here is the message: %s\n",buffer);
    n=write(newsocket_fd,"I got your message",18);
}
</code>


Moq return same delegate as parameter

Question: I am very new to Moq and looking for a way to be able to mock up the following interface.
public interface ICacheProveder
{
    T GetOrAddToCache<T>(string key, Func<T> populateFunc);
}

This interface is currently being used to cache items such as code tables. The mock would need to return the result of anything that was passed into the via populateFunc. I am currently using Moq version 4.2.1502.911
Answer: To return the result of the Func passed as argument you can make use of Returns from Moq.
In the example below, for simplicity, I choose T to be a string, it can be changed based on your needs.
[Test]
public void TetMethod()
{
    //Setup
    var cacheProveder = new Mock<ICacheProveder>();

    cacheProveder.Setup(a => a.GetOrAddToCache<string>(It.IsAny<string>(), It.IsAny<Func<string>>()))
                    .Returns((string key, Func<string> populateFunc) => { return populateFunc(); });

    // rest of the code

}

Comment: Do you know if there is a way to use generics or will I need do run a setup method for each type I plan to mock?
Comment: @Aaron You have to run a setup method for each type you plan to mock.

Moq return same delegate as parameter


Difference Between IV and Control Function in a Non-Linear Model

Question: I've noticed that when addressing the problem of linear endogeneity that the different techniques result in the same estimator for the potentially endogenous variable. Specifically, the control function approach ends up with the same estimator as instrumental variable approaches.
Considering that, I've heard it mentioned that in non-linear models these approach do not result in the same estimator. Can anyone explain or potentially provide me with a good reference with the derivations? If so, that would be very much appreciated.
I quite like the Imbens and Wooldridge notes, but they're not very general.
Answer: I would still like others to maybe contribute if they have something substantive to say, but I think this personally cleared the issue up for me:
http://www.nber.org/WNE/lect_6_controlfuncs.pdf
So, it appears in the non-linear setting the CF approach imposes a linear conditional expectation on the endogenous variable, i.e. $E[u_{2}|z,y_2]$ has a linear conditional expectation. Note: I have listed $u_2$ as the error term in the regression of the endogenous variable, $y_2$ on the exogenous variables $z$. Apparently this assumption is more stringent than simply relying on linear projections as IV does.
Answer: Petrin and Train (2009) is one example of endogeneity being handled with a control function. E.g. a WP here: http://eml.berkeley.edu/~train/petrintrain.pdf
I have always found the distinction a bit tricky. I guess in CF you typically invoke more specific assumptions about how two error terms are related. In IV, you rely on an instrument. The classical example covered by Imbens and Wooldridge as well is the Heckman selection model: here, under normality, you get the inverse mill's ratio. Therefore, you can estimate the model even in absence of an instrument, just relying on functional form only (although it is not advisable).


How do I use the Rascal Evaluator to access Rascal functions from a compiled JAR?

Question: I have the a jar with the following structure:
main-app/
├─ META-INF/
│  ├─ maven.org.rascalmpl.runmain/
│  │  ├─ pom.xml
│  │  ├─ pom.properties
│  ├─ MANIFEST.MF
├─ rascal/
│  ├─ Main.tpl
│  ├─ MyModule.tpl
├─ Main.rsc
├─ MyModule.rsc

and I'm writing an Evaluator to run function from the JAR, so far I have the following:
    final GlobalEnvironment heap = new GlobalEnvironment();
    final ModuleEnvironment top = new ModuleEnvironment("test", heap);
    Evaluator eval = new Evaluator(vf, System.in, System.err, System.out, top, heap);
    eval.addRascalSearchPathContributor(StandardLibraryContributor.getInstance());
    eval.addRascalSearchPath(URIUtil.rootLocation("std"));

    ISourceLocation tmp =  URIUtil.correctLocation("jar", "", "/path/to/runmain-0.1.0-SNAPSHOT.jar!");

    eval.addRascalSearchPath(tmp);

    eval.doImport(null, "Main");
    eval.doImport(null, "MyModule");

    System.out.println(eval.getHeap().existsModule("Main")); // Check if module has been added to heap

    eval.call("main", tmp, null);

When I try to run this, it just prints out false, and then the following exception:
Exception in thread "main" org.rascalmpl.interpreter.staticErrors.ModuleImport: Could not import module Main: can not find in search path
How can I access either the .tpl files or .rsc files in the JAR to call arbitrary functions?
P.S: When I compiled the JAR the RASCAL.MF was not included in the output, is it necessary?
Comment: just fyi, currently rascal is not compiled yet. the `tpl` files are type check files. We are getting close to having a compiler form, but that would just be regular class files.
Comment: Noted, I was mistaking them for the compiled form.
Answer: If the run-main jar has a META-INF/RASCAL.MF in it with Project-Name: run-main in it, then the Rascal URI name resolver automatically registers lib://run-main and lets it point to the root of the jar. So that would enable you to do this:
ISourceLocation tmp =  URIUtil.correctLocation("lib","run-main","");

Instead of this, you can also use the jar scheme. But this requires you to find the jar file location:
jar+file:///path/to/run-main.jar/!/

After the ! is where the path into the jar files starts, and where .rsc files can be found. The earlier lib scheme does exactly that, but automatically based on searching through the classpath for RASCAL.MF files.
Comment: Ok thanks! That sounds like a good fix. Curious what your next step will be
Comment: Thanks this works and the lib is now being detected but I get a new error when I try to call a function like so: `eval.call("main", tmp, null);`.

The error is:
```Exception in thread "main" java.lang.NullPointerException: Cannot invoke "io.usethesource.vallang.IValue.getType()" because "v" is null
```
I'm not sure what it means.
Comment: I later fixed it by changing the call to `eval.call(null, "Main", "main");`


drupal_find_theme_functions called on every page - is our theme registry being rebuilt?

Question: Our new D7 site was running very slowly so I did some profiling with devel/xhprof and found that D7 was doing millions of preg_grep function calls within drupal_find_theme_functions() in theme.inc. This happened on every page load.
It's my understanding that the drupal_find_theme_functions function should only be called when the theme registry is being rebuilt - am I correct in that?
I made sure that "rebuild theme registry" was off in devel, and then disabled devel entirely. However, I'm still seeing those millions of function calls to preg_grep in drupal_find_theme_functions on every page load (I added a piece of code to theme.inc to log when the function was called).
We're using a theme based on Omega and if we are rebuilding the theme registry each time I'm not seeing how/why it's happening. We're turning off as many contrib modules as we can in the meantime. Any help/advice would be MUCH appreciated!!
Answer: Nice job on using XHProf to debug what's going on here. drupal_find_theme_functions() should get called once per registry rebuild for the core and installed modules, then once again as each installed theme is utilized.  Are you noticing it once per page load, many times per page load, etc?  I'm going to send you down a slightly different path on this as you should be more interested on what's causing the rebuild, not what happens when the rebuild occurs.
I'm assuming that you're working with a recent release of D7.  Use the devel module and put code below into drupal_theme_rebuild() at line 350 of includes/theme.inc to see what functions are being called on the way to the registry rebuild and that should give some clue as to what is triggering it.
<code>dsm(debug_backtrace());
</code>
A quick note on what you should expect to see.  I've done some testing and with a mostly empty Drupal install with only a few popular modules installed.  The registry rebuild is only happening when I clear the theme cache or perform some action that causes it to be cleared.  If you look at the functions being called prior to the rebuild, you should see some indication as to what was responsible for causing it.
When I clear caches from the normal admin screen (admin/config/development/performance) my call stack is 9 functions deep and it passes through a form submission handler that triggers the process.  When I clear the cache from the admin_menu contributed module, my call stack is 5 functions deep and it passes through a page callback that initiates the cache clear.  Your case should be showing something a bit out of the ordinary.
Comment: instead of using dsm(debug_backtrace()); you can directly use ddebug_backtrace();
Comment: Nice one junedkazi.  No matter how much one knows, there are always more tricks out there.  Thanks for your input.
Answer: Usually if that function is requested million of times, it's because in your theme settings, "Rebuild theme registry on every page" is checked. Uncheck it in production stage.


Column has a number in it, very few rows have text mixed in, can I create a new number column?

Question: I have a table that has a column that has the cost of a product, but some (very few) rows have text mixed in the column.
Would it be possible to create a new column, of a decimal type, and populate it with the other column and just ignore the rows with the 'bad' data in it?
I know I can do this via code, but was hoping I could do it with a sql query some how?
Answer: You can use a case to cast only the integer columns.  This would return NULL for non-numeric columns:
select
    case when isnumeric(col1) = 1 then cast(col1 as int) end
from YourTable

Or you can just ignore the non-numeric columns:
select *
from YourTable
where isnumeric(col1) = 1

Comment: I am getting: Error converting data type nvarchar to numeric.
I did: when isnumeric(pricetext) = 1 then  costPrice / cast(priceText as decimal)
Comment: +1, ISNUMERIC() is the way to go.  @Blankman, this is valid working code, I tested it on my system. What data type is `costPrice`? show your query and list column datatypes. my test case: `declare @YourTable table (RowValue varchar(10), x int);INSERT INTO @YourTable VALUES ('ZZZ',2);INSERT INTO @YourTable VALUES ('123',2);INSERT INTO @YourTable VALUES ('1A23',2);INSERT INTO @YourTable VALUES ('AAA',2);select case when isnumeric(RowValue) = 1 then cast(RowValue as int)/x end from @YourTable`
Answer: Yes what you are asking is possible to do.
Step 1: Add a new column
Add a decimal (9, 2) column (PriceOfItem) to your table (ItemPrices)
Step 2: Run this query (change object names as required)
Update ItemPrices
Set PriceOfItem = Convert (Decimal (9, 2), PriceText)
Where 1=1
AND IsNumeric (PriceText) = 1

Comment: I'm interested to know why you have "1=1" in the WHERE clause? It equates to true and would be optimised out.
Comment: @Tony: It is purely for ease of coding. If I have multiple `AND` clauses, and I have to comment them out or indent them, it is real easy. Try commenting out various parts of a `WHERE` with 3 `AND` parts to it, with and without a '1=1` and you will see what I mean.
Comment: Thanks for the explanation. I see what you mean, it makes it easy to remove parts of the clause.
Answer: How does this sound? I use it all the time.  Simple & quick.
NewColumn: iif(
               isnumeric([OldColumn]),
               cdbl([OldColumn])
           )

Comment: SQL Server does not support `iif`


Error on IIS App Pools after upgrading from Windows Server 2013 to Windows Server 2016 (or Win 8.1 to Win 10)

Question: After upgrading my Windows installation from 8.1 to 10, a number of App Pools were failing to start, showing the following entries in the Event Viewer:
Application:
Source: IIS-W3SVC-WP
Event ID: 2307
The worker process for application pool '<app pool name>' encountered an error 'Cannot read configuration file' trying to read configuration data from file '\\?\<EMPTY>', line number '0'. The data field contains the error code.

System:
Source: WAS
Event ID: 5189
The Windows Process Activation Service failed to generate an application pool config file for application pool '<app pool name>'. The error type is '5'. To resolve this issue, please ensure that the applicationhost.config file is correct and recommit the last configuration changes made. The data field contains the error number.

Source: WAS
Event ID: 5203
A process serving application pool '<app pool name>' reported a failure trying to read configuration during startup. The process id was '4120'.  Please check the Application Event Log for further event messages logged by the worker process on the specific error.  The data field contains the error number.

I've found a lot of people saying to reinstall IIS/WAS but, even after doing that, the error persisted.
For some reason, recreating the App Pool with another name would fix the error but I didn't want to keep it that way. After renaming the App Pool back to the original name, it started to fail again.
Comment: I really didn't get how this question is off-topic. The issue is obviously technical, it's  about server technologies, and it's about supported software and hardware. Can anyone explain it to me?
Answer: After using the excellent Process Monitor to analyze what files the Windows Process Activation Service was trying to read/create, I found these files and directories in C:\inetpub\temp\apppools that the Windows Upgrade process probably messed up with. I deleted those old files and directories and restarted the App Pools.
Everything is working fine now!
Comment: You should accept this as answer if it solved the issue


Simple data validation and math operation in JavaScript

Question: I need to create a simple calculator that computes 1% of the value submitted by the user. I also need to round it (floor) to the tenth part after colon.
Examples:
input    1%        output
12.34    0.1234    0.10
2345.34  23.4534   23.40

More info:
- users will submit monetary values. They can use dots or comma to separate the parts of the value. Both inputs 123.45 and 123,45 are valid.
- I need to calculate 1% of it, round it and display in "user friendly" form, for example XX.YY
I created following function so far. But it rounds the value in odd way. For example, for input "123.45" the output is 1.2000000000000002 (should be 1.20).
function calc(val)
{
var x = 0.1*Math.floor(0.1*val);
alert("your 1% is:\n"+x);
}

Javascript treats only values with dots as numbers. How can I easily convert values with commas to numbers?
And how to display the outcome with desired precision?
Comment: See [this](http://stackoverflow.com/questions/1074660/) and [this](http://stackoverflow.com/questions/2085275/) for info about working with different decimal separators.
Comment: Are users allowed to enter numbers with thousands/millions/etc separators? E.g. `1,234,567.89` and `1.234.567,89`?
Comment: No, it is rather not expected. I really do not have to deal with thousand/etc separators. Thanks for the links!
Answer: val = parseFloat(val.toString().replace(",", ".")); // just replace comma with dot
var x = (0.1*Math.floor(0.1*val)).toFixed(2); // toFixed leaves required amount of digits after dicimal dot.
alert("your 1% is:\n"+x);


Why is there a keywork sync - no star

Question: In generator's, we have async:

async to get an Future
async* to get a stream

And sync:

sync* to get an Iterable.

But what about sync no start* found in keywords:
Is async just a "fictional keyword"?
Comment: I don't understand what you mean by "fictional keyword", but there's no need for `sync` by itself because it would serve no purpose.  You would need to invent something for that keyword to do first.
Answer: The list of "keywords" that you link to is a list of identifiers (or would-be identifiers) that have special meaning anywhere in the Dart syntax.
Some of them are "reserved words", and can never be used as an identifier.
Some are "built-in identifiers" which can be used as identifiers in most, but not all, places (e.g., cannot be the name of a type).
Some are "contextual keywords" which only means something in a very specific place, where they are clearly distinguishable from a name. Those can be used as identifiers anywhere an identifier can be used - the special places where they mean something else are precisely ones where an identifier cannot be used.
A few are reserved words only in some contexts. Because history!
The identifier sync is on the list only because it's the identifier part of the contextual modifier sync*. The linked list a list of identifiers, so the sync* combination of identifier and operator cannot occur there.
So, if a word means something somewhere, it's on that list. That's all the list means. You don't need to memorize the list.
You should memorize all reserved words. Those can never be used as the name of a variable.
You might learn some of the built-in identifiers eventually, because you try to, say, use them as an import prefix (they're lower case, so you likely won't try to use them as a type name). Rarely an issue in practice.
And you're likely to completely forget that contextual keywords exist, because it's easy to think of their use in grammar as completely different from their use as variable names. If anything, primitive syntax highlighters might remind you that there is something special about that word that makes it purple when the variable next to it is orange.
Answer: Apart from the obvious, I like to ask questions, and it does indeed look like it is a fictional keyword. If you have a look in the analysis_server.
Occam's razor don't always apply in programming, but in this case - it will work, even you don't care ;-)

Why is there a keywork sync - no star


retorne somente a sua ultima movimentação de cada código

Question: Uma tabela regista a movimentação dos itens pelo código do item, data e hora da movimentação.
Logo a apresentação fica da seguinte forma:
CD_Item | DT_Mov
  15      10/04/2018 08:52:36
  15      21/05/2018 09:32:10
  15      20/05/2018 14:24:08
  15      10/04/2018 08:52:36
  08      26/05/2018 09:32:10
  08      27/05/2018 14:24:08
  69      16/05/2018 09:32:10
  69      20/05/2018 14:24:08

Quero fazer um select para pegar todos os itens, mas que ele me retorne somente a sua ultima movimentação de cada código.
Resultado:
CD_Item | DT_Mov
   15     21/05/2018 09:32:10
   08     27/05/2018 14:24:08
   69     20/05/2018 14:24:08

O banco é Oracle.
Pesquisei outras perguntas do tipo sugerida pelo próprio fórum, mas não me deram a uma solução.
Answer: Se a estrutura da tabela for essa que você colcou, basta:
Select
    cd_item,
    max(dt_mov) as ultima_data
from movimentacao
group by cd_item

Comment: Funcionou, eu estava agrupando com a data também e nunca ia...


Is it possible to style a javascript hosted elsewhere on www.tidetimes.org

Question: I need to display tide times on my website, however the only service to offer them in the UK in any decent form is www.tidetimes.org.
They offer a widget which runs a pretty standard Javascript (hosted on their site) to generate the tide times on your own site using document.write but I need to change the style. How would I achieve this?
Here's the link to the actual widget script and I'm trying to set it up for Bovisand Pier:
http://www.tidetimes.org.uk/widgets
And the actual javascript file:
http://www.tidetimes.org.uk/bovisand-pier-tide-times.js
I downloaded, edited and hosted the file locally, but I presume tidetimes.org edit the js file daily for the new times.
Comment: just a quick note that it's usually against the terms of service to modify any widget offered by a third party.
Comment: Have you tried cufon.js?
Comment: Hi, I haven't tried cufon.js, but I'd also need to remove the border and background gradient. Do you know if that's possible?
Comment: Hi Maximus, thanks for the hand. The trouble is the file changes daily according to new tide times. Whilst I can save the file and host it myself, it would update each day. Please please please tell me I'm wrong and stupid - I'd love a solution :-)
Comment: They have an RSS feed, would consuming that not be a more sensible option? http://www.tidetimes.org.uk/bovisand-pier-tide-times.rss
Comment: Funny you should mention the RSS feed - I have indeed played, but the format it pulls through in I've found very difficult to get looking like I want it.
Comment: THanks jbabey - I'm guessing that means I'll have to go the RSS route then. Anybody got ideas on how to separate the lines of the feed?
Comment: And I'm sorry for being so 'amateur' at this. I've not built any websites for around 15 years and have just started getting to grips with things again. I'm trying to make the feed nice and simple along the lines of the twitter feed. Here's the test site running: www.bovicam.com/test/indexworking.html
Answer: Consume their RSS feed (http://www.tidetimes.org.uk/bovisand-pier-tide-times.rss) with something like the Google Feed API instead. It will be a more maintainable, long term solution.
Answer: You'd have to loop through and clear out the styles manually.  In jquery:
$('#containerForWidget tr, #containerForWidget td').attr('style', '');

That gets all tr and td elements in your container and removes the inline styling.
Comment: You might want to make note that this uses JQuery.  I know a lot of people just assume that using the library is standard but it could *really* frustrate a noob trying to figure out how to make this work.
Comment: Thanks for that saml - looks like I may be brushing up on my javascript!
Answer: Create a simple javascript function(old style but working) like below:
 function changeStyle(){
    var divElements = document.getElementsByTagName("div");
    for (var i = 0; i < divElements.length; i++) {
        var divElement = divElements[0];
        //change the style
        divElement.setAttribute("style", "color: red;");
    }
 }

Call this function on HTML page  onload event.
Alternatively, add this code(anonymous block) in  section or down in the page after the link of the tide javascript file..

Comment: Thanks for all your fantastic assistance everyone :-)


Como comparar esses 2 arrays dentro deste while?

Question: Estou desenvolvendo um jogo semelhante à Forca, aonde o usuário tem que acertar a palavra escolhida pelo computador em até 8 tentativas.
A variável mascara é um array de caracteres que corresponde a palavra que o usuário vê na tela (que pode não mostra todas as letras) e a variável palavraSeparada é um array de caracteres que corresponde a palavra que o usuário deve adivinhar
Estou com dúvida no laço while abaixo. Como faço para verificar se o conteúdo dos dois arrays é igual?
while(acertou==false&&errou<8){

    for(int i=0;i<mascara.length;i++){
        System.out.print(mascara[i]);
    }

    System.out.println("");
    letraDigitada = input.nextLine().charAt(0);

    for (int i=0;i<palavraSeparada.length;i++){
        if (letraDigitada == palavraSeparada[i]){
            mascara[i]=letraDigitada;
        }
    }
}

Comment: Isso é pra implementar um jogo de _Mastermind_ (AKA Senha)? Qual o conteúdo de `palavraSeparada`? Qual o conteúdo esperado de `mascara`?
Comment: @LucasGoeten Tomei a liberdade de acrescentar um texto introdutório para dar mais contexto a quem estiver vendo esta questão. Caso discorde de algo ou queira acrescentar mais alguma informação, basta clicar no link de editar.
Answer: Primeiro, ao invés de acertou==false, use !acertou.
Segundo, use o método equals(char[], char[]) da classe java.util.Arrays.
Seu código deve ficar assim:
while (!acertou && errou < 8) {

    for (int i = 0; i < mascara.length; i++) {
        System.out.print(mascara[i]);
    }

    System.out.println("");
    letraDigitada = input.nextLine().charAt(0);

    for (int i = 0; i < palavraSeparada.length; i++) {
        if (letraDigitada == palavraSeparada[i]) {
            mascara[i] = letraDigitada;
        }
    }

    if (Arrays.equals(mascara, palavraSeparada)) acertou = true;
}

No código, ainda falta incrementar o errou no caso de o if que está dentro do for não entrar nenhuma vez. Isso deixo para você resolver, mas é fácil. :)


What are the typical trumpet parts in classical music?

Question: So I'm a pianist looking at one of my favorite concertos ever, the Rachmaninoff 2. I had been listening to some symphonic works prior to it, so for some reason I noticed that in the concerto, there was a distinct lack of trumpet lines. A copy may be viewed here.
My questions are: is it typical to not give trumpets that many lines in concertos or symphonies? If not, why? Is there an artistic reason that Rachmaninoff limited the number of trumpet lines in this concerto? I know trumpets can get really loud, but they can also be soft sometimes, right?
Also question for trumpetists: if you guys don't get that many lines, how can you stand the constant sitting around waiting? Is that something that dampens your enthusiasm for playing in an orchestra?
Part of my question relates to this piano concerto:

 at 21:04. There's a trumpet countermelody there that quite nice, and I was wondering why other composers don't do it too.
Comment: my question would be: are they payed by notes/minute they have to play or by hours they are sitting there? In the second case I would be happy to listen to so many classical concerts for free.
Comment: FYI, the same question could also be asked about trombone and tuba parts, and the answer would be pretty much the same as [MattPutnam's answer below.](https://music.stackexchange.com/a/89711/21557)
Comment: It's certainly not pure artistic reasons. E.g. Shostakovich's piano concerto is practically a double concerto for piano and trumpet.
Comment: "standing around waiting" --- more or less all the non-string players have long periods of silence in various orchestral numbers.    And for real fun, Google for stories from the pit orchestra members (those who play the backing music for musicals)
Answer: I'm a trumpet player who's played in many orchestras.
The first thing to understand is that historically, the trumpet is a relatively new addition to the orchestra. Before the mid-19th century, metalworking wasn't sophisticated enough to build valves, so trumpets from before this time were more like bugles, unable to play fully chromatically. With a limited set of notes, the instrument was necessarily limited to a supporting role. And especially considering its ability to play loudly, combined with the softer sound of gut strings and early bow design, it just makes sense to use it only to accentuate the loud parts.
Trumpet concertos do go all the way back to the Baroque period (e.g. the famous Brandenburg Concerto no. 2), but these are sort of insanely hard and you wouldn't be able to write lines like that in normal parts.
So by the time valves got invented, the orchestra had already been developing for centuries, and the trumpet had already been designated as a supporting instrument. And if you're looking at music from the Baroque, Classical, or about the first half of the Romantic periods, then those parts were written for valveless trumpets. Mid- to late-Romantic period composers started experimenting with brass (and saxophones, and other loud metal instruments), and modern composers have utilized the trumpet quite a bit more. Consider the fantastic trumpet parts in Mahler, Holst, Copland, and Bernstein just to name a few.
I don't buy this common idea that trumpets are just so loud that they can't balance. Trumpets are very capable of playing at a modest volume. But, in a concerto, you have to be especially careful not to cover up the soloist, so orchestra parts tend to be more conservative.

if you guys don't get that many lines, how can you stand the constant sitting around waiting? Is that something that dampens your enthusiasm for playing in an orchestra?

Part of being a mature musician is understanding that sometimes your instrument is needed, and sometimes it's not. You have to be able to appreciate a sparse part, and be willing to take on a supporting role sometimes. I would rather have a sparse part where every note I have is artistically meaningful, than a busier part where much of my material is filler that the orchestrator gave me out of pity. But, it's not for everyone, and I'll admit that I'm less enthusiastic about playing the insanely sparse parts in Classical period music. It's important for orchestra directors shy of the top professional level to program concerts that involve everyone to some degree.
Answer: The obvious comment is that in an orchestra, everybody can't be a "soloist" all the time.
With no disrespect to trumpeters, the trumpets actually have a fairly limited range of functions  in the orchestra. They can play the "Star Wars theme" type of solo passages, or they can blend in with the rest of the brass section to provide a "background layer" in the orchestration. Most of the time, they are doing the second option - or doing nothing at all, since the timbre of the trumpet doesn't blend with other families instruments in the same way as French horns do, for example.
In a piano concerto, a solo trumpet could easily overpower the piano all on its own, but the piece is a piano concerto, not a trumpet concerto.
See here for a large collection of orchestral trumpet solos, including recordings.
Comment: It's also possible for the trumpet to play the solo in concertos written for another instrument.  There's an excellent recording of Miles Davis playing the Rodrigo Guitar Concerto on a trumpet.  You could also play concertos written for most other wind instruments, possibly even violin (minus the occasional double-bowing.)
Answer: I believe that Rachmaninoff wrote exactly the amount of trumpet lines he wanted. The composer wrote the music he wanted to hear ( and play ) and orchestrated it that way. If, for some reason, one player would have a lot of rests, that was not the composers problem. He clearly wrote with the valved trumpet it mind, using it as a chromatic instrument. ( In comparison, up to about Beethoven, the trumpets mostly employed only the overtone series ) .
The limitations were and are more of the type of instruments and number of players -- it would be difficult to expect a piece written for 24 oboes, 12 bassons and one contrabasson to performed very often. ( You might check the original setting for Music for the Royal fireworks ). I guess, though, that sometimes parts were added to "union rules" so that all the players on payroll might get paid, I believe it could happen when the composer worked with a specific orchestra.
As a professional musician you play what is on your stand, you are paid to do that. As an amateur, I tend to like listening to the music as well as playing. Long rests do not disturb me. Having long rests in romantic type music is often a lesser problem than playing some of the contemporary art music when I cannot relate to the music and only finds it to be meaningless noise ( it happens, luckily not often ).
Answer: Here's a piano concerto with a good trumpet part: Shostakovich Piano Concerto 1.  It is also called Concerto for Piano, Trumpet, and Strings which makes the importance of the trumpet fairly obvious.