Modify ListFragment in Master Detail flow

Question: I've created an app using the Master/Detail template, but instead of a list on the master view, I want to add other elements (in fact replace the list with a different layout and add the initial list in this layout)
How to acheive this?
The top layout contains a list fragment on the left for the master, and framelayout  on the right that will contains the detail fragment...
Is it possible to replace the master list fragment with a view that will contains the fragment?
I've created a specific layout (left_layout), that is referenced in the fragment xml, and changed my class inheritence to inherit from fragment and not list fragment, and I have the following exceptio when the application try to instanciate this fragment:
lang.RuntimeException: Unable to start activity ComponentInfo{com.digiwiz.tvtweet/com.digiwiz.tvtweet.ChannelListActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)

which is called from:
setContentView(R.layout.activity_channel_list);

and activity_channel_list is the master activity that has been modified:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/channel_list"
          android:name="com.digiwiz.tvtweet.ChannelListFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_marginLeft="16dp"
          android:layout_marginRight="16dp"
          tools:context=".ChannelListActivity"
          tools:layout="@layout/left_layout" />

Comment: @PPartisan :Yeah, I wasn't sure as I only ever use dynamic Fragments added to containers at runtime. In saying that though, the Android dev docs show using a `FrameLayout` in layout XML files to contain `` blocks so I thought it might be worth trying.
Comment: I think you need to put your `` inside something like a `FrameLayout`
Comment: @Squonk That should only be the case for dynamic Fragments.
Comment: Do you use `android.app.Fragment` or `android.support.v4.app.Fragment` ? If it's the second one, is your Activity a `FragmentActivity` or of a class that extends `FragmentActivity` (i.e. `AppCompatActivity`)? It may be an incompatibility.
Comment: I use android.app.Fragment
Comment: @tomsoft Try changing your import declaration to `android.support.v4.app.Fragment` - like Squonk, I never use static fragments, but [this answer](http://stackoverflow.com/questions/6424853/error-inflating-class-fragment) suggests it could cause the problem.
Answer: (this isn't realy a full answer to your question, but couldn't fit it in a comment.)
I think your book makes reference to the 'old' template for master-detail flow.  The new template was introduced around the time of SDK 23 I think.
The new one uses a different technique: there is no Master/List fragment class, there is just the layout for the list which acts as the list fragment.
Note that the list layout has a name attribute that ends with 'Fragment' - this attribute is not actually used but is an indication the element is being used like a fragment.  I believe you would replace this element with the layout or view that you want to use instead of the list.
More generally, if your master layout should have more then just the list (leaving aside header, toolbar, etc. which must go in the activity), you can add that stuff either:
- to the activity, along with header/toolbar, which only makes sense if you expect it to be different for single vs. dual pane (which is perhaps what Google has in mind for this).
- or to the item_list.xml files (one for each layout configuration) and replace the recyclerview with a different layout.
I'm sorry that they changed the template to do it this way.  I think the old template with 2 fragment classes and layouts was easier to comprehend and more flexible. eg. for situations like yours and for any case where one wants the list/master fragment to be something more then just a list (isn't that normal?).  I wasn't able to find any mention or explanation of the change they made.


OpenNMS Syslog Integration

Question: I am trying to configure OpenNMS to receive Syslog messages from an ASA. My syslogd-configuration file looks like so:
<configuration
    syslog-port="514"
    new-suspect-on-message="false"
    parser="org.opennms.netmgt.syslogd.CustonSyslogParser"
    forwarding-regexp="((.+?) (.*))\r?\n?$"
    matching-group-host="2"
    matching-group-message="3"
    />

The syslog messages arrive in this format:
Sep 13 08:36:37 192.168.75.254 %ASA-4-106023: Deny tcp src outside:22.214.171.124/
56607 dst inside:192.168.75.102/23 by access-group "outside_access_in" [0x0, 0x0]

With this config, I can get syslog messages into Opennms but they come through as indeterminate. It seems as though this regex cannot parse. When I test this regex in other websites like regex101.com it clearly says that there is not a match. I have created a regex that does match how I need:
\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*([\s\S]*)

BUT when I add this to the config, I no longer get any Syslog Messages at all.
Does anyone have an idea of how I make this happen. I have spent wayyy too much time on this as is.
Answer: I'm not sure why the original regex nested the groups, but if you remove the outer () group, you'll need to reduce the group numbers for the host and message (since the outer group was group #1), so
matching-group-host="1"
matching-group-message="2"

Comment: When I use the good regex I did change the groups but the messages are discarded. I think I am confused on how to stop the default discard on match rule\
Answer: Ok so I seem to have figured this out. I am going to attempt to post a complete answer here hoping that it helps someone out. The docs are not the clearest on this.
References I used for the configuration are Syslogd and TechTarget
First you need to setup the $OPENNMS_HOME/etc/syslogd-configuration.xml to have the following:
<configuration
    syslog-port="10514"
    new-suspect-on-message="false"
    parser="org.opennms.netmgt.syslogd.CustomSyslogParser"
    forwarding-regexp="((.+?) (.*))\r?\n?$"
    matching-group-host="2"
    matching-group-message="3"
    />

<ueiList>
    <ueiMatch>
        <match type="regex" expression="YOUR REGEX HERE"/>
        <uei>uei.opennms.org/foo1/foo2/foo3</uei>
    </ueiMatch>
</ueiList>

The ueiList element was my first problem. This is where you actually map the syslog message to a custom uei. The uei can be customized to create any unique identifier you wish to have.
My second problem was with mapping the custom uei to have properties, such as an alert level. This is accomplished through the $OPENNMS_HOME/etc/eventconf.xml
file. I inserted the following code right below the </global> tag to configure properties for my new custom uei.
<event>00-custom.conf
    <uei>uei.opennms.org/foo1/foo2/foo3</uei>
    <event-label>Event Label Here</event-label>
    <descr>
           An event description here
    </descr>
    <logmsg dest='logndisplay'>Here is the Log: %parm[all]%</logmsg>
    <severity>Critical</severity>
</event>

With these in place syslog messages should come in with desired properties. NOTE: In my scenario I am using non-standard syslog messages which is why I have to use the parser="org.opennms.netmgt.syslogd.CustomSyslogParser" setting in my syslogd-confguration.xml file. If you are using Syslog-NG or a better formatted syslog there are other options.
To help with troubleshooting you can go to $OPENNMS_HOME/etc or $OPENNMS_HOME/bin and run the following: opennms -v status  this should show you every running process for NMS and their status.
NOTE: After changing a config file you must run service opennms restart (debian systems) to reload the new configuration. If you get the JVM error or "couldn't connect to local host" error it is most likely because you broke one of these two configs. Even adding an extra space at the top of the xml file will create this problem. Use care when editing the files and I highly recommend creating backups.

OpenNMS Syslog Integration


ASP Classic extract email address from string

Question: I need to be able to pull an email address from a string in ASP Classic.
Example string is "Please Contact Cp. from XXXX located in xxxx with regards to enquiry details - Hi, I am writing to you to cancel Thank you . Chris Pearson email address : email@example.com phone number : 07 56431545 Preferred contact method : Email"
With the result being "email@example.com"
note that the email wont always be in the same location within the string. there will however always be spaces either side.
i can do this in excel without issue, but cant find a script to do this. it doesn't have to be perfect. happy if it picks up the majority
Comment: There's a question on Experts Exchange with deals with this. https://www.experts-exchange.com/questions/26886544/VBSCRIPT-EXTRACT-EMAIL-ADDRESS-FROM-TEXT-FILE.html
Comment: Possible duplicate of [Extract email and name with regex](https://stackoverflow.com/questions/14010875/extract-email-and-name-with-regex)
Answer: <code>Function GetEmailAddrFromStr(TheString)
    If InStr(1,TheString,"@") > 0 Then
        TheAt = InStr(1,TheString,"@")
        StartMarker = InstrRev(TheString, " ", TheAt, 0)
        EndMarker = InStr(TheAt,TheString," ")
        GetEmailAddrFromStr = Trim(Mid(TheString,StartMarker,EndMarker-StartMarker))
    Else
        GetEmailAddrFromStr = ""
    End If
End Function

SomeText = "Hi, I am writing to you to cancel Thank you . Chris Pearson email address : firstname.lastname@example.com phone number : 07 56431545 Preferred contact method : Email"

Response.write GetEmailAddrFromStr(SomeText)
</code>


GROUP BY function cancels DISTINCT

Question: I have an SQL query that joins several tables that produces duplicates on two of the rows. I use the DISTINCT keyword to eliminate duplicates:
SELECT DISTINCT
          o.day as day,
          g.id AS id,
          g.name AS name,
          o.num AS num,
          o.version as version
        FROM
          table_one o
          INNER JOIN table_two t ON
            o.ID = t.ID
          INNER JOIN table_three g ON
            t.ID = g.ID
          INNER JOIN table_four gs ON
            g.ID = gs.ID
            AND
          INNER JOIN table_five s ON
            gs.ID = s.ID
          INNER JOIN table_six z ON
            s.ID = z.ID
          INNER JOIN table_seven bg ON
            bg.ID = g.ID;

This returns the two rows like I would want, that otherwise I would see duplicates if I did not use DISTINCT:
1/2/19, 5, first, 25, 1
1/5/19, 7, second, 20, 1

If I remove DISTINCT, then the two rows are duplicated, giving me four rows:
1/2/19, 5, first, 25, 1
1/2/19, 5, first, 25, 1
1/5/19, 7, second, 20, 1
1/5/19, 7, second, 20, 1

So my end goal is to use a GROUP BY function so that I can add up my o.num field and group them by the rest of the fields. If I add a GROUP BY function to the above query like so:
SELECT DISTINCT
          o.day as day,
          g.id AS id,
          g.name AS name,
          SUM(o.num) AS num,
          o.version as version
        FROM
          table_one o
          INNER JOIN table_two t ON
            o.ID = t.ID
          INNER JOIN table_three g ON
            t.ID = g.ID
          INNER JOIN table_four gs ON
            g.ID = gs.ID
            AND
          INNER JOIN table_five s ON
            gs.ID = s.ID
          INNER JOIN table_six z ON
            s.ID = z.ID
          INNER JOIN table_seven bg ON
            bg.ID = g.ID
        GROUP BY
          o.day as day,
          g.id AS id,
          g.name AS name,
          o.version as version;

I get two rows back, but the o.num amount is doubled (essentially performing  GROUP BY without DISTINCT:
1/2/19, 5, first, 50, 1
1/5/19, 7, second, 40, 1

NOTE: You may be wondering why I'm trying to use a GROUP BY when I get the results I want with the first query. I only included the rows that are being duplicated. For some reason all other rows aren't seeing this behavior. Is there a way I can get GROUP BY and DISTINCT to work together?
Comment: well….yes, you are grouping the original data set, and using sum over the duplicated values
Comment: @Lamak yes so my question is how to fix that
Answer: If you would like to remove duplicates and then sum values, insert your query into subquery.
select day, id, name, sum(num) num, version
from (
  -- your query here with DISTINCT clause
)
group by day, id, name, version

If you get duplicates, there may be some issues with join conditions. For me is't difficult to judge, don't know datasets.
Answer: You could use SUM(DISTINCT o.num):
SELECT o.day as day,
       g.id AS id,
       g.name AS name,
       SUM(DISTINCT o.num) AS num,
       o.version as version
FROM table_one o
INNER JOIN table_two t ON o.ID = t.ID
INNER JOIN table_three g ON t.ID = g.ID
INNER JOIN table_four gs ON g.ID = gs.ID
INNER JOIN table_five s ON gs.ID = s.ID
INNER JOIN table_six z ON s.ID = z.ID
INNER JOIN table_seven bg ON bg.ID = g.ID
GROUP BY o.day as day,
         g.id AS id,
         g.name AS name,
         o.version as version;

GROUP BY function cancels DISTINCT


Is it the math or a coding error?

Question: I'm writing a program to calculate surface gravity (http://en.wikipedia.org/wiki/Surface_gravity) of planets (yes, I know I can just Google it, but where's the fun in that?) however the numbers are not correct, nor are my printf methods working to contain the numbers in 2.2 format. What am I doing wrong here? Thanks!
import java.util.Scanner;

import java.io.PrintWriter;

import java.io.File;

import java.io.IOException;

public class GravityV1
{

static String [] planetName = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
static double [] planetMass = {3.30e23, 4.87e24, 5.97e24, 6.42e23,1.90e27, 5.69e26, 8.66e25, 1.03e26, 1.31e22};
static double [] planetDiameter = {3032, 7521, 7926, 4222, 88846, 74898, 31763, 30778, 1466};
static double universalConstant = 6.674e-11;

public static double getSurfaceGravity(double mass, double diameter)
{

    double g = (universalConstant * mass)/Math.pow((diameter / 2), 2);
    return g;

}

public static void printHeader()
{
   System.out.println("                       Planetary Data                       ");
   System.out.println("  Planet       Diameter (km)      Mass (kg)      g (m/s^2)  ");
   System.out.println("------------------------------------------------------------");
}
public static void tab()
{
   System.out.print("\t\t");
 }
public static void main(String [] args)throws IOException
{
PrintWriter outFile = new PrintWriter (new File("planetGravity.txt"));
printHeader();
outFile.println("                       Planetary Data                       ");
outFile.println("  Planet       Diameter (km)      Mass (kg)      g (m/s^2)  ");
outFile.println("------------------------------------------------------------");
   for(int index=0;index<planetName.length;index++)
  {
   double gravity = getSurfaceGravity(planetMass[index], planetDiameter[index]);
   System.out.print(planetName[index] + "\t\t");
   System.out.printf("%2.2f", planetDiameter[index]);
   tab();
   System.out.printf("%2.2f", planetMass[index]);
   tab();
   System.out.printf("%2.2f", gravity);
   System.out.println();
   outFile.println(planetName[index] + "\t\t" + (planetDiameter[index]) + "\t\t" + planetMass[index] + "\t\t" + gravity);
  }
  outFile.close();
}
}

Comment: Why are the numbers incorrect? How is `printf` not "containing" the numbers? What's the output you're getting, and what do you think it should be?
Comment: What is the expected/actual output?
Comment: Use %2.2e to get exponential value (e specifier rather than f). See Java Formatter class.
Comment: For one line:
Mercury  3032.00  330000000000000000000000.00  9583005.55

I expect it as:
Mercury 3032 3e23 .38
Comment: That is consistent with `%2.2f`.
Comment: I don't mean for 3e23 to have those trailing zeroes.
Comment: If you want accurate result. Use BigDecimal instead of double. Also use BigDecimal string constructor instead of double.
Comment: If you want, you can look at the enum tutorial as it provide the same functionality http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
Comment: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html
Answer: You need to do some conversion of units in order to fix your calculations.

Your planet diameters are given in miles. You need to convert them into meters. You could do this with some multiplications in your planetDiameter array. For example, replace 3032 with 3032 * 1000 * 1.609344. Or you could do it in getSurfaceGravity:
double g = (universalConstant * mass)/Math.pow((1000 * 1.609344 * diameter / 2), 2);

You should divide g by Earth's surface gravity (9.80665 m / s^2) before returning it from getSurfaceGravity. So the last line becomes:
return g / 9.80665;

Dividing by Earth's surface gravity is required because you say you're expecting 0.38 for Mercury. That means you want values in units of Earth's gravity. (Mercury's surface gravity = 0.38 * [Earth's surface gravity]).
As has been suggested in the comments, use %2.2e to format your numbers in scientific notation.
Agreed that it is more fun to calculate it yourself than to just Google it!

Is it the math or a coding error?


Does a "-" on guitar tab mean "play that string open"?

Question: I'm not a guitarist, I'm learning piano and I'm trying to translate some guitar tab for piano.
With this section of tab (for I Don't Want It by Ween, from the Ultimate Guitar site):
e--8-8-8---3-3----3-3-3-3-3-3---4-4--|
B--9-9-9---4-4----4-4-4-1-1-1---4-4--|
G--8-8-8---3-3----3-3-3-1-1-1---x-x--|
D-------------------------------3-3--|
A-------------------------------4-4--|
E------------------------------------|

At the start, the D A & E strings just have a "-".  Does that mean you don't play those strings, or does it mean you play them open?
Sometimes I've seen tab where the open strings are represented by having a "0", but I'm guessing that the convention may be to omit these as it makes the tab too cluttered and hard to read. Later on in that tab section there's an x on the G string, which I'm guessing means to mute the string.
That kind of suggests that we are supposed to play the E, A and D strings at the start, otherwise they would have x's too?  But I think this is one of those things that is ruled by convention rather than logic necessarily.
Answer: It means "don't play".
0 is open.
In your case, the 8-9-8 at the beginning is a Ab major triad, that would clash a lot with the open E and A strings ^^
Comment: Strictly speaking, not so! 'Let ring', maybe. But that doesn't account for the dashes *before* the numbers...
Comment: Thanks.  That makes my life easier :)  I guess I could have worked this out by trying to play all of the notes (including the unmarked strings) on piano and seeing if it sounded awful .   So, i guess the difference between "-" and "x" is that when the string you don't want to play is in the middle of some strings you do want to play, you have to mute that string since you can't simply **avoid** hitting it on a strum, which you can do if you only need to play the top three strings?
Comment: @Tim i think the dashes before the numbers are just spacing, as you suggest in your answer.
Answer: x means don't play that string at all. o means play that string open.
The dashes are just spacers, presumably some kind of timing device (there are 36 'zones' in a 'bar'). And although this would be a good idea, I don't think it's employed here, as the guitar starts at the very beginning of the bar - the chords shown don't!
The dashes actually do not mean don't play. If we go by the track, the chord played before the dashes actually rings on, until the next chord. This is one (of many for me!) problem with this sort of tab - it doesn't give as much detail as 'proper' music, in that unless there are notes or their stems shown as well, unless one knows how the song goes, one cannot know how the timing goes. And if one knows the song, then one is at least half-way to playing it anyway. Rave over!
So, basically, it means very little! Presumably, you've listened to the song. That will most likely give far more clues than blindly following what someone has tabbed. Seriously!
That apart, if you're learning piano, it's somewhat counter-productive to try to translate guitar tab (especially as you don't play guitar!). You will be better off finding proper piano music, and learning to translate that. Honest!
Comment: I think Tab is best viewed simply as an *aid* to learning a song, for people who already know what it sounds like, and is not to be looked into too deeply.  If you're getting really detailed with it you should probably be using sheet music - that is the way to prescribe exactly what to play.
Comment: @MaxWilliams Standard notation (shape notes) is essential, absolutely. But there are some details which are much easier for guitarists to glean from Tab, which is why most serious books include both staves. I started reading on piano and get a lot of theatre work as one of the few guitarists in Atlanta who is a fluent reader. I definitely appreciate and prefer shape notes. But I learned most of the 1,000+ pop/rock/blues songs I know by ear, and having taught for about 20 years I appreciate how Tab and aural skills benefit the student. All my kids learn how to read and appreciate both systems.
Comment: @MaxWilliams - that pretty well sums it up. Persevere with the ear, it'll pay off in the end (or well before that!) and chances are you'll understand my scepticism concerning a lot of tabs. Never understood why tab writers don't use, say, 16 or 32 'zones', which would pretty well cover most songs, albeit occasionally in a primitive way - but better than it is now.
Comment: x means mute the string, not 'don't play'.
Comment: @MaxWilliams - back in the 60s, I used to buy the sheet music - still have a load - and it really wasn't that helpful. Over time, I found it was easiest to listen to a track, and figure out first key, then sort of scale used,then chords, then voila! It put me in good stead for when students come and say they want to learn 'this piece' in this lesson. So it had to be done 'on the fly'. And also is invaluable when I'm in a house band at open mics, etc. Often the dots/chords are approximations - as are tabs...
Comment: @Tim I agree, I think it's best to go by ear generally, but sheet music and tab can save you some time.  I just meant that sheet music tends to be more in-depth than tab, really.
Comment: I take your point about proper piano music, but if I like a particular song, and want to play along on piano with the aim of ultimately singing it too, and it's not a massively well known song, then generally the piano part isn't available anywhere.  I can work it out by ear, slowly, but it's often very useful to see what notes the guitar is playing.  I'm actually writing a little computer script to process the tab and output which notes it should be on piano and this will help with that.
Comment: Another thing i've noticed about Tab is that it's more of a memory aid than an actual score.  That is, unlike sheet music, you can't read it religiously and translate it into music.  it's more like an aid to helping you work out the chords, and then you have to do the timing yourself, which is easy to do by ear.    So it's kind of akin to song lyrics, actually, in that they tell you the important stuff but don't tell you how to sing it.
Comment: In most - maybe all? of the tabs I've seen, each vertical does relate to a division of the bar, so they do show the timing. The dashes therefore do mean 'don't play' in the sense of 'don't pick/strum the string *at that time*'. I don't doubt that you may have seen more bad tabs than I have!
Comment: @topoReinstateMonica - if you mean the vertical lines represent bar lines, then yes, that's (usually) true. That hardly helps with the timing of individual notes, though, which is (one of ) my beefs.And yes, the dashes must be there to say 'there's nthing here to play' - but they don't signify silence or  held notes. So, they're not that self explanatory.
Comment: @dissemin8or - really don't want to get embroiled, but some x mean a particular note in the middle of a chord's fingering gets muted so it doesn't even get heard, can't help hitting it, but hopefully it won't add to the chord notes; but other x mean actually play the string muted so it **does** make a sound. More than a contradiction!
Comment: @Tim No, I'm agreeing with you that tab writers should use (say) 16 zones (or whatever's appropriate for the song), but saying that in my experience, they really do! Certainly that's how I write tabs, and the tabs I've come across seem to have been written like that too - meaning that the characters that line up vertically at one time position (whether numbers, or just '-' dashes) really do represent a well-defined time point (aside from considerations like 'feel' or slight degrees of swing, which even SN doesn't show).
Comment: @topoReinstateMonica -0.k. the one shown here has 36 segments, for wont of a better term, but the guitar part on the track starts on beat one. So why are there two segments empty before the numbers? And a lot of tabs I've seen have a couple of segments (dashes) *before* any first number, again not making sense. Just looked at a tab for happy b'day, and the timing was all over the place - not even an anacrucis!
Comment: @Tim I do also tend to find most things on Ultimate Guitar need fixing!
Comment: @MaxWilliams Before you waste hours of your time writing that computer script, download the free version of Sibelius (called Sibelius First) and you can do this in one Alt + Click. You can also do it with Copy + Paste. Sibelius will automatically translate any tab into standard notation on the staff of your choice, in any clef.
Comment: Also, @MaxWilliams proper tab includes rhythmic stems and (if written properly) can offer valuable information not found easily on a standard staff. For example, where specifically on the fingerboard to play the passage. Most melodies and chords can be played in multiple places on guitar, and only after years of experience might you know the best option for economy of motion and optimal results.
Comment: @NickGrooves - that much is so true. Why is it, then, that even my students question why certain passages have to be played in certain places, having found more suitable ones? And it does restrict fingerboard knowledge. One *ought* to be able to play the same passage in several places (otherwise one wouldn't know that the tab shown is best or not). If Brian May had relied on tab, when he broke a string at a concert, he'd have been stuffed. As it was, he knew other places, and no-one noticed!. And - is Sibelius prone to using the optimum places? How does it know? (If it can go the other way).
Comment: @Tim From my Sibelius experience (been using since 1997) it seems to prefer as many open strings and stay as close to open position as possible, but adjusting it is exceedingly fast and simple. Highlight the passage + down/up arrow to the proper string. Sibelius automatically adjusts the fret number to match. It will also put tab into standard notation / works both ways, so if you have tab and want the shape notes, it's two keystrokes away.
Answer: The dashes represent lines.  They are not meant to each be an individual symbol; they arise from trying to represent guitar tab using only typed symbols.  Take a look at printed tablature:

Image source
There is a 6-lined staff on which the fret number for each note is placed.
Comment: That tab is so inaccurate! For starters, in the Animals version, the top string gets played in every bar. thus 7 notes played, often. For seconds, the last note played, in most bars, is open 3rd (listen to youtube!), as the guitarist couldn't change chords quickly enough. Yet another reason I don't trust tab...  If tis is related to my recent question, I'm referring to tab with dashes, not solid lines looking like clefs.
Comment: @Tim an import detail in the tab in the question is that it is plain text file, not an image. How would you represent solid lines in a plain text file?
Comment: @ojs - even so, the tab is a poor representation of what actually was played on the original track. If one is going to portray such, it's important (to me, at least) to get it accurate! Dashes or lines are the least of the mistakes here.
Comment: @Tim I agree that this is a very bad transcription. But the context of the discussion was really the dashes or lines.


Copy and deliver a request to another nginx server for real traffic testing

Question: I have a Flask web service which runs on uwsgi+nginx and it works well.
I have another development version of the service which runs on another server. It also runs on uwsgi+nginx.
What I want to do is, test the development server with 'real' traffic(POST requests) I've done verifying the development server works well basically. Just want compare the two with same real traffic.
My basic idea for this is like below:
(A) is legacy server
(B) is test server

User requests
Nginx(A) get the request and deliver the request to uwsgi(A) for handling.
Nginx(A) 'copy' the request and deliver it to Nginx(B) for testing
uwsgi(A) handle the request in Flask App(A) and response to User (via Nginx(A))
Nginx(B) handle the request like legacy server does but not response to User (just logging)

Is this make any sense? What approach I should take?
Answer: I found the solution myself. So I share my finding here.
I used post_action directive for this.
location / {
    uwsgi_pass      unix:app.sock;
    post_action @post_action;
}

location @post_action {
    proxy_pass      http://dst_host:dst_port;
}

The request first delivered to unix:app.sock and when it completed,
post_action directive pass the request to named location, @post_action.
It works like a charm!
Comment: Note that this is dangerous, see http://mailman.nginx.org/pipermail/nginx/2012-November/036199.html because this will block the original thread while it waits for the shadow
Comment: When testing server load with [boom](https://github.com/rakyll/boom) `boom -n 100 -c 10 -m GET ...` I'm getting in 50% responses `EOF` or `read: connection reset by peer`. That's not good for high-availability :(.
Answer: location / {
      proxy_pass  http://y.y.y.y:port;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_connect_timeout      300;
      proxy_send_timeout         300;
      proxy_read_timeout         300;
      post_action @post_action;
    }

location @post_action {
    proxy_pass      http://x.x.x.x:port;
    access_log /var/log/nginx/c.log application;
    error_log /var/log/nginx/c.log error;
}

The request first delivered to http://y.y.y.y:port and when it completed, post_action not able to directive pass the request to named location, @post_action.Is there any other thing we need to do?


Using a keyword as variable name in an INI file

Question: I have the following in an INI file:
[country]
SE = Sweden
NO = Norway
FI = Finland

However, when var_dump()ing PHP's parse_ini_file() function, I get the following output:
PHP Warning:  syntax error, unexpected BOOL_FALSE in test.ini on line 2
in /Users/andrew/sandbox/test.php on line 1
bool(false)

It appears that "NO" is reserved. Is there any other way I can set a variable named "NO"?
Answer: Another hack would be to reverse your ini keys with their values and use array_flip:
<?php

$ini =
"
    [country]
    Sweden = 'SE'
    Norway = 'NO'
    Finland = 'FI'
";

$countries = parse_ini_string($ini, true);
$countries = array_flip($countries["country"]);
echo $countries["NO"];

Still you will need to use quotes around NO (at least), if you do
Norway = NO

you don't get an error but value for $countries["NO"] will be an empty string.
Comment: Thanks, that's probably the only way to do it.
Comment: Wouldn't this break if your values aren't unique? They are after all *values*, not keys.
Comment: I'm assuming that's the case here, @Pacerier as we are talking about countries and their short codes.
Answer: This propably comes a little late but the way PHPs parse_ini_file works bothered me so much that I wrote my own little parser.
Feel free to use it, but use with care it has only been shallowly tested!
// the exception used by the parser
class IniParserException extends \Exception {

    public function __construct($message, $code = 0, \Exception $previous = null) {
        parent::__construct($message, $code, $previous);
    }

    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

}

// the parser
function my_parse_ini_file($filename, $processSections = false) {
    $initext = file_get_contents($filename);
    $ret = [];
    $section = null;
    $lineNum = 0;
    $lines = explode("\n", str_replace("\r\n", "\n", $initext));
    foreach($lines as $line) {
        ++$lineNum;

        $line = trim(preg_replace('/[;#].*/', '', $line));
        if(strlen($line) === 0) {
            continue;
        }

        if($processSections && $line{0} === '[' && $line{strlen($line)-1} === ']') {
            // section header
            $section = trim(substr($line, 1, -1));
        } else {
            $eqIndex = strpos($line, '=');
            if($eqIndex !== false) {
                $key = trim(substr($line, 0, $eqIndex));
                $matches = [];
                preg_match('/(?<name>\w+)(?<index>\[\w*\])?/', $key, $matches);
                if(!array_key_exists('name', $matches)) {
                    throw new IniParserException("Variable name must not be empty! In file \"$filename\" in line $lineNum.");
                }
                $keyName = $matches['name'];
                if(array_key_exists('index', $matches)) {
                    $isArray = true;
                    $arrayIndex = trim($matches['index']);
                    if(strlen($arrayIndex) == 0) {
                        $arrayIndex = null;
                    }
                } else {
                    $isArray = false;
                    $arrayIndex = null;
                }

                $value = trim(substr($line, $eqIndex+1));
                if($value{0} === '"' && $value{strlen($value)-1} === '"') {
                    // too lazy to check for multiple closing " let's assume it's fine
                    $value = str_replace('\\"', '"', substr($value, 1, -1));
                } else {
                    // special value
                    switch(strtolower($value)) {
                        case 'yes':
                        case 'true':
                        case 'on':
                            $value = true;
                            break;
                        case 'no':
                        case 'false':
                        case 'off':
                            $value = false;
                            break;
                        case 'null':
                        case 'none':
                            $value = null;
                            break;
                        default:
                            if(is_numeric($value)) {
                                $value = $value + 0; // make it an int/float
                            } else {
                                throw new IniParserException("\"$value\" is not a valid value! In file \"$filename\" in line $lineNum.");
                            }
                    }
                }

                if($section !== null) {
                    if($isArray) {
                        if(!array_key_exists($keyName, $ret[$section])) {
                            $ret[$section][$keyName] = [];
                        }
                        if($arrayIndex === null) {
                            $ret[$section][$keyName][] = $value;
                        } else {
                            $ret[$section][$keyName][$arrayIndex] = $value;
                        }
                    } else {
                        $ret[$section][$keyName] = $value;
                    }
                } else {
                    if($isArray) {
                        if(!array_key_exists($keyName, $ret)) {
                            $ret[$keyName] = [];
                        }
                        if($arrayIndex === null) {
                            $ret[$keyName][] = $value;
                        } else {
                            $ret[$keyName][$arrayIndex] = $value;
                        }
                    } else {
                        $ret[$keyName] = $value;
                    }
                }
            }
        }
    }

    return $ret;
}

What does it differently? Variable names may only consist of alphanumerical characters but other than that no restrictions to them. Strings must be encapsulated with " everything else has to be a special value like no, yes, true, false, on, off, null or none. For mapping see code.
Answer: Kind of a hack but you can add backticks around the key names:
[country]
`SE` = Sweden
`NO` = Norway
`FI` = Finland

Then access them like so:
$result = parse_ini_file('test.ini');
echo "{$result['`NO`']}\n";

Output:
$ php test.php
Norway

Comment: That's no different than just renaming the variable to something else. With your solution, the variable name is \`NO\`, not NO. Could just as well do `πNOπ = Norway` in the config file.
Answer: I ran into the same problem and tried to escape the name in every possible way.
Then I remembered that because of the INI syntax both names and values will be trimmed, so the following workaround MAYBE should do the trick:
NL = Netherlands
; A whitespace before the name
 NO = Norway
PL = Poland

And it works ;) As long as your co-workers read the comments (which is not always the case) and don't delete it accidentally. So, yes, the array flipping solution is a safe bet.
Answer: I was getting this error when there were single quote combinations in the string such as 't or 's. To get rid of the problem, I wrapped the string in double quotes:
Before:
You have selected 'Yes' but you haven't entered the date's flexibility

After:
"You have selected 'Yes' but you haven't entered the date's flexibility"

Answer: From the manual page for parse_ini_file:

There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none.

So no, you can't set a variable NO.


Fibonacci Proof: Prove that $\frac{F_n-F_{n+16}}{7}$ is always an odd integer.

Question: Im stuck on this question,  i have to prove that $$\frac{F_n-F_{n+16}}{7}$$ is always an odd integer.   I tried induction to do this but i just can't see how to prove it.
thanks for any help
Comment: Is it true? It might be true that it is an integer, but I don't see how it could be true that it is always odd, since $$\frac{F_2-F_{18}}{7} = \frac{F_1-F_{17}}{7} + \frac{F_0-F_{16}}{7}$$
Comment: The divisibility by seven can be explained by studying the periodicity of the sequence of residues of the Fibonacci numbers. There are plenty of good questions and answers covering that on this site. But why do you claim that this is odd?
$$\frac{F_{17}-F_1}7=\frac{1597-1}7=228?$$
Comment: This can't be correct as written.  The Fibonacci numbers mod two go 'odd, odd, even, odd, odd, even', and since $16\bmod 3=1$, the difference of two Fibonacci numbers 16 apart might be the difference of two odd numbers (and thus even).
Comment: There is an explicit formula for $F(n)$, i.e., a solution for the recurrence $F(n+1)= F(n) + F(n-1)$. Can you use it?
Comment: And you do need to use two previous values in an induction hypothesis. This holds for all proofs by induction related to Fibonaccis. Note that the base case must then also handle two smallest values of $n$. No need to think in terms of periodicity of the sequence of residues as I initially thought.
Answer: I suspect that, instead, you are merely supposed to show that $$\frac{F_n-F_{n+16}}7$$ is an integer for all $n$. As discussed in the comments above, the integer needn't be odd.
I leave the two base cases to you (we need two of them for an induction proof).
Now, let's suppose that $$\frac{F_n-F_{n+16}}7$$ and $$\frac{F_{n+1}-F_{(n+1)+16}}7$$ are both integers for some $n$. Note, then, that
$$\begin{align*}
\frac{F_{n+2}-F_{(n+2)+16}}7&=\frac{(F_n+F_{n+1})-(F_{n+16}+F_{(n+1)+16})}7\\\\
&=\frac{F_n-F_{n+16}}7+\frac{F_{n+1}-F_{(n+1)+16}}7\;.
\end{align*}$$


Refactoring for DI on large projects

Question: I work on a large scale platform project supporting around 10 products that use our code.
So far, all of the products have been using the full functionality of our platform:

- Retrieval of configuration data from a database
- Remote file system access
- Security authorization
- Base logic (the thing we are paid to offer)
For a new product we've been asked to support a smaller subset of functionality without the  infrastructure the platforms bring along. Our architecture is old (start of coding from 2005 or so) but reasonably solid.
We're confident we can do that using DI on our existing classes, but the estimated times to do so range from 5 to 70 weeks depending who you talk to.
There's a lot of articles out there that tell you how to do DI, but I coulnd't find any that tell you how to refactor for DI in the most efficient way? Are there tools that do this rather than having to go through 30.000 lines of code and having to hit CTRL+R for extacting interfaces and adding them to construcors too many times? (we have resharper if that helps) If not, what do you find is the ideal workflow to quickly achieve this?
Comment: There are no tools for this. Think about it how you would analyze each class yourself to find out which dependencies to extract. A tool can't reliably do this analysis for you (or it will extract too much). There are tools however (such as Resharper and Code Rush) that will help you with extract method and extract class refactorings, but this will still be for a single class at the time; not one click for the complete project.
Comment: For me the ideal workflow is: only change what have to be touched. If there is a bug in a class, you will need to touch that class. Before you touch that class, you will need to test it. To be able to test it, you will need to refactor it. That's a good time for refactoring. Same holds for adding features or being able to supply a smaller subset. Only touch what has to be touched.
Comment: You could start out by refactor only the small subset of the code you need for the task at hand. In that way you and your team will get the feel of DI and gather some DI experience. Since the decoupled architecture that DI motivates is very test friendly, you can use unit testing to make sure you don't break anything.
Comment: This question is probably better suited to http://programmers.stackexchange.com
Comment: I've just inserted a DI container into a similar sized project 42K SLOCS and it took a little over 2 weeks to complete. The project was already written with DI in mind so constructor injection was already used and appropriate interfaces were already in place. I would suggest that Mark Seeman's book [Dependency Injection in .NET](http://www.manning.com/seemann/) would be a good starting point. Perhaps you could refactor to "DIY DI" as an intermediate step then move to a proper DI container after that. That's effectively what I did and it worked well.
Comment: I suspected as much. Was hoping that some of this might be automated since it does seem suitable for that. Thanks for the tips.
Answer: Thanks for all the replies. We're almost a year further now and I think I can mostly answer my own question.
We of course converted only the parts of our platform that were to be reused in the new product, as lasseeskildsen points out. Since this was only a partial conversion of the code base, we went with the DIY approach to dependency injection.
Our focus was making these parts available without bringing along unwanted dependencies, not to enable unit testing of them. This makes a difference in how you approach the problem. There are no real design changes in this case.
The work involved is mundane, hence the question of how to do so quickly or even automatically.
The answer is it cannot be automated, but using some keyboard shortcuts and resharper it can be done quite fast. For me this is the optimal flow:

We work across multiple solutions. We created a temporary "master" solution that contains all projects in all solution files. Though refactoring tools are not always smart enough to pick up the difference between binary and project references, this will at least make them work partially across multiple solutions.
Create a list of all dependencies you need to cut. Group them by function. In most cases we were able to tackle multiple related dependencies at once.
You'll be making many small code changes across many files. This task is best done by a single developer, or two at most to avoid having to constantly merge your changes.
Get rid of singletons first:
After converting them away from this pattern, extract an interface (resharper -> refactor -> extract interface)
Delete the singleton accessor to get a list of build errors. On to step 6.
For getting rid of other references:
a.  Extract interface as above.
b.  Comment out the original implementation. This gets you a list of build errors.
Resharper becomes a big help now:

Alt + shift + pg down/up quickly navigates broken references.
If multiple references share a common base class, navigate to its constructor and hit ctrl + r + s ("change method signature") to add the new interface to the constructor. Resharper 8 offers you an option to "resolve by call tree", meaning you can make inheriting classes have their signature changed automatically. This is a very neat feature (new in version 8 it seems).
In the constructor body assign the injected interface to a non-existing property. Hit alt + enter to select "create property", move it to where it needs to be, and you're done. Uncomment code from 5b.

Test! Rinse and repeat.

To make use of these classes in the original solution without major code changes, we created overloaded constructors that retrieve their dependencies through a service locator, as Brett Veenstra mentions. This may be an anti-pattern, but works for this scenario. It won't be removed until all code supports DI.
We converted about a quarter of our code to DI like this in about 2-3 weeks (1.5 persons).
One year further, and we are now switching all our code to DI. This is a different situation as the focus shifts to unit testability. I think the general steps above will still work, but this requires some actual design changes to enforce SOC.
Answer: I'm assuming that you're looking to use an IoC tool like StructureMap, Funq, Ninject, etc.
In that case, the work of refactoring really starts with updating your entry points (or Composition Roots) in the codebase.  This could have a large impact, especially if you're making pervasive use of statics and managing lifetime of your objects (e.g. caching, lazy loads).  Once you have an IoC tool in place and it wires the object graphs, you can start to spread out your usage of DI and enjoy the benefits.
I would focus on settings-like dependencies first (which should be simple value objects) and start making resolution calls with your IoC tool.  Next, look to create Factory classes and inject those to manage lifetime of your objects.  It will feel like you are going backwards (and slow) until you reach the crest where most of your objects are using DI, and corollarily SRP - from there it should be downhill.  Once you have better separation of concerns, the flexibility of your codebase and the speed at which you can make changes will dramatically increase.
Word of caution: don't let yourselves be fooled into thinking sprinkling a "Service Locator" everywhere is your panacea, it's actually a DI antipattern.  I think you will need to use this at first but then you should finish the DI work with either constructor or setter injections and remove the Service Locator.
Answer: You asked about tools. One tool that might help in a large refactoring like this is nDepend. I've used it to help identify places to target refactoring efforts.
I hesitate to mention it, because I don't want to give the impression that a tool like nDepend is necessary to undertake this project. It is, however, helpful to visualize the dependencies in your code base. It comes with a 14-day fully functional trial, which might be enough for your needs.
Answer: Don't think there is any tool to do this conversion of code.
Because ->
Using DI in existing code base would involve,

use of interface / abstract class. Again here right chioce should be taken to ease the conversion keeping DI principle & code functionality in mind.
Effective segregation / unification of existing classes in multiple / Single classes respetively to keep code modular or small resuable units.
Answer: The way I approach a conversion is to look at any part of the system that permanently modifies state; files, database, external content. Once changed and re-read, has it changed for good? This is the first place to look to change it.
So the first thing you do, is find a place that modifies a source like this:
class MyXmlFileWriter
{
   public bool WriteData(string fileName, string xmlText)
   {
      // TODO: Sort out exception handling
      try
      {
         File.WriteAllText(fileName, xmlText);
         return true;
      }
      catch(Exception ex)
      {
         return false;
      }
   }
}

Secondly, you write a unit test to make sure you aren't breaking the code while refactoring.
[TestClass]
class MyXmlWriterTests
{
   [TestMethod]
   public void WriteData_WithValidFileAndContent_ExpectTrue()
   {
      var target = new MyXmlFileWriter();
      var filePath = Path.GetTempFile();

      target.WriteData(filePath, "<Xml/>");

      Assert.IsTrue(File.Exists(filePath));
   }

   // TODO: Check other cases
}

Next, Extract an Interface from the original class:
interface IFileWriter
{
   bool WriteData(string location, string content);
}

class MyXmlFileWriter : IFileWriter
{
   /* As before */
}

Re-run the tests and hope all is good. Keep the original test as it is checking your older implementation works.
Next write a fake implementation that does nothing. We only want to implement a very basic behaviour here.
// Put this class in the test suite, not the main project
class FakeFileWriter : IFileWriter
{
   internal bool WriteDataCalled { get; private set; }

   public bool WriteData(string file, string content)
   {
       this.WriteDataCalled = true;
       return true;
   }
}

Then unit test it...
class FakeFileWriterTests
{
   private IFileWriter writer;

   [TestInitialize()]
   public void Initialize()
   {
      writer = new FakeFileWriter();
   }

   [TestMethod]
   public void WriteData_WhenCalled_ExpectSuccess()
   {
      writer.WriteData(null,null);
      Assert.IsTrue(writer.WriteDataCalled);
   }
}

Now with it unit tested and refactored versions still working, we need to make sure that when injected, the calling class is using the interface, not the concrete version!
// Before
class FileRepository
{
   public FileRepository() { }

   public void Save( string content, string xml )
   {
      var writer = new MyXmlFileWriter();
      writer.WriteData(content,xml);
   }
}

// After
class FileRepository
{
   private IFileWriter writer = null;

   public FileRepository() : this( new MyXmlFileWriter() ){ }
   public FileRepository(IFileWriter writer)
   {
      this.writer = writer;
   }

   public void Save( string path, string xml)
   {
      this.writer.WriteData(path, xml);
   }
}

So what did we do?

Have a default constructor which uses the normal type
Have a constructor that takes an IFileWriter type
Used an instance field to hold the referenced object.

Then its a case of writing a unit test for the FileRepository and checking that the method is called:
[TestClass]
class FileRepositoryTests
{
   private FileRepository repository = null;

   [TestInitialize()]
   public void Initialize()
   {
    this.repository = new FileRepository( new FakeFileWriter() );
   }

   [TestMethod]
   public void WriteData_WhenCalled_ExpectSuccess()
   {
       // Arrange
       var target = repository;

       // Act
       var actual = repository.Save(null,null);

       // Assert
       Assert.IsTrue(actual);
   }
}

Okay, but here, are we really testing the FileRepository or the FakeFileWriter? We're testing the FileRepository as our other tests are testing the FakeFileWriter separately. This class - FileRepositoryTests would be more useful to test the incoming parameters for nulls.
The fake is not doing anything clever - no parameter validation, no I/O. It is just sitting in so that the FileRepository can save content any work. Its purpose is two-fold; To speed up unit testing significantly and to not disrupt the state of a system.
If this FileRepository had to read the file as well, you could implement a IFileReader as well, (which is a bit extreme), or just stored the last written filePath/xml to a string in memory and retrieve that instead.

So with the basics over with - how do you approach this?
On a large project, which requires a lot of refactoring, it is always best to incorporate unit testing to any class that undergoes a DI change. In theory, your data should not be committed to hundreds of locations [within your code], but pushed through a few key locations. Locate them in the code and add an interface for them. One trick I've used is to hide each DB or index-like source behind an interface like this:
interface IReadOnlyRepository<TKey, TValue>
{
   TValue Retrieve(TKey key);
}

interface IRepository<TKey, TValue> : IReadOnlyRepository<TKey, TValue>
{
   void Create(TKey key, TValue value);
   void Update(TKey key, TValue);
   void Delete(TKey key);
}

Which sets you up to retrieve from data sources in a very generic way. You can switch from an XmlRepository to DbRepository by only replacing where it is injected. This can be extremely useful for a project migrating from one data source to another without affecting the internals of a system. It can be handful changing XML manipulation to using objects, but it is much easier to maintain and implement new functionality with this approach.
The only other advice I can give is do 1 data source at a time and stick do it. Resist the temptation to do too many in one go. If you really end up having to save to files, DB and web service in one hit, use the Extract Interface, fake the calls and return nothing. It is a real juggling act to do lots in one go, but you can slot them back in more easily than starts from first principles.
Good luck!
Comment: Your approach sounds reasonable. But wouldn't be better to use some mocking library to create a stub of the IFileWriter instead of creating a FakeFileWriter?
Comment: Yep mocking is fine. Saves you writing the unit tests for the dud implementations. Use the `CreateInstance` method again to set up the mock object and centralise the creation and necessary scenarios.
Comment: "Have a default constructor which uses the normal type" I think it is best to avoid this if possible. The problem is that your class is still hard wired to a concrete implementation of the interface. Ideally we only want to depend on interfaces. Default constructors force concrete dependencies.
Comment: @Robin - I agree. It should be just an intermediate step as you can imagine the code changes required to point to the other constructor or factory call. So as a compromise, if you do down this route, try adding the `Obsolete("Constructor will be deprecated shortly", false)]` to the default constructor at least get compiler warnings about it.
Answer: This book would probably be very helpful:
Working Effectively with Legacy Code - Michael C. Feathers - http://www.amazon.com/gp/product/0131177052
I would suggest starting with small changes. Gradually move dependencies to be injected through the constructor. Always keep the system working. Extract interfaces from the constructor injected dependencies and start wrapping with unit tests. Bring in tools when it makes sense. You don't have to start using dependency injection and mocking frameworks right away. You can make a lot of improvements by manually injecting dependencies through the constructor.
Answer: What you described is a big part of the process; going through each class, created an interface, and registering it.  This is most problematic if you commit right away to refactoring to the composition root, in the case of MVC that would mean assuming you were going to inject into the controller.
That could be a lot of work and if the code does a lot of direct object creation it could be very complex to try to do all at once.  In these cases I think it's acceptable to use the Service Locator pattern and manually call resolve.
Start by replacing some of your direct calls to constructors with a service locator resolve call. This will lower the amount of refactoring initially needed and start giving you the benefits of DI.
Over time your calls will get closer and closer to the composition root and then you can start removing use of the service locator.

Refactoring for DI on large projects


Averaging Data from a file

Question: I'm attempting to average each students grades from this file.  I have successfully listed the student names and their grades in the output of my code, but the final step is to output the average of the grades.  This is the code:
import java.util.Scanner;
import java.io.*;

public class Grades_Data
{
public static void main(String[] args) throws IOException
{

  Scanner keyboard = new Scanner(System.in);

 String filename = "student_data.txt";

  File file = new File("student_data.txt");
  Scanner inputFile = new Scanner(file);

  while (inputFile.hasNext())
  {

     String firstName = inputFile.next();
     String lastName = inputFile.next();
     String gradeone = inputFile.next();
     String gradetwo = inputFile.next();
     String gradethree = inputFile.next();

     System.out.println("first name: " + firstName + "\tlast name: " + lastName + "\tgrade one: " + gradeone +
     "\tgrade two: " + gradetwo + "\tgrade three: " + gradethree);
  }
  inputFile.close();
}
}

This is the output of my code:
first name: Willis  last name: McGee    grade one: 86   grade two: 91   grade three: 78
first name: Gladis  last name: Knight   grade one: 79   grade two: 93   grade three: 88
first name: John    last name: Wayne    grade one: 92   grade two: 89   grade three: 88
first name: Ginny   last name: Weasley  grade one: 68   grade two: 73   grade three: 89

I need it to say "average: " at the end of each line with the average grade of the student, using their grade one, grade two, and grade three values (the sum of the three grades divided by 3)
Answer: int average = ( Integer.parseInt(gradeone ) +  Integer.parseInt(gradetwo ) + Integer.parseInt(gradethree ) ) / 3;

  System.out.println("first name: " + firstName + "\tlast name: " + lastName + "\tgrade one: " + gradeone +
     "\tgrade two: " + gradetwo + "\tgrade three: " + gradethree + "\taverage: " + average );

add this.
You need to parse your String vaues to Integer, and calculate the average
Comment: Looks like you both answered at the same time.  This is exactly what I was looking for.  Thank you for the help!
Answer: Parse the string to int's (add them together divide by three)
int average = (Integer.parseInt(gradeOne) + Integer.parseInt(gradeTwo) + Integer.parseInt(gradeThree))/3;

add output to your string:
System.out.println("first name: " + firstName + "\tlast name: " + lastName + "\tgrade one: " + gradeone +
     "\tgrade two: " + gradetwo + "\tgrade three: " + gradethree  + "\taverage: " + average);

Comment: This was what I needed.  I was unaware that I had to parse them together.  I had just tried to create a variable that added them all up and divided by three.  Thanks for the help.
Comment: No worries, in future when writing questions to SO write about a specific problem you are having, or why you can't get it to work, and show what you tried. If it was something more complex you might not get an answer otherwise.
Answer: Try this
 System.out.println("first name: " + firstName + "\tlast name: " + lastName + "\tgrade one: " + gradeone +
     "\tgrade two: " + gradetwo + "\tgrade three: " + gradethree
+"\tAverage: "+ (gradeone+gradetwo+gradethree)/3
);
Comment: you need to parse the String values to int

Averaging Data from a file


Session value persist even after the value is unset PHP

Question: I have a problem resetting the value of session variable in PHP.
I cleared All my browser cookies and cache and load a page.
The controller of the page is called where the following code is written :
if(isset($_SESSION['event_generic_sequence'])){
        unset($_SESSION['event_generic_sequence']);
}
$_SESSION['event_generic_sequence'] = array();

This controllers calls a function in class file where it checks if the session is set and then value is appended to session:
$_SESSION['event_generic_sequence'][] = $image_name;

At the end of controller if the session value is printed, I get an array of having 4 values . Thus the count of array is 4:
[event_generic_sequence] => Array
    (
        [0] => 505_c.jpg
        [1] => 505_c-1.jpg
        [2] => 505_c-2.jpg
        [3] => 505_c-3.jpg
    )

When i reload the page. The controller gets called and the session value is set to blank array. But in class file if I print the session value . It shows the previous value of session. Why is class file not getting the current session value and the value of session seems to have been cached ?
If i clear the browser cookie and cache , The session value is blank and works fine. But if i don't the last value of session persist.
Comment: Please provide some more code/information.
Answer: You can use session_start(); to start a session and session_destroy(); to destroy the session else set the session of that particular variable to null or empty.
Comment: session_start() is used in index page at start. I cannot use that in class file again. Gives Notice "Session has already started" . I don't want to destroy whole session. Just want to reset a particular variable.


How do I get that Chris Stapleton Tennessee Whiskey Electric Guitar intro guitar sound?

Question: Tennessee Whiskey I Have a EPIPHONE  Joe Pass EMPEROR II Electric and a CUBE 20x Amp. I been told its because the GUITAR IS A Jazz guitar.
Tennessee Whiskey
SOLO SOUND IM SEEKING
Comment: Welcome! I'm afraid questions like this, about matching a certain sound, are not [covered here](https://music.stackexchange.com/help/on-topic). Feel free to edit this question or ask a new one.
Comment: It would be helpful to have a text description of the sound. Links have a tendency to go bad, and then the question loses at least some of its meaning.
Answer: A hollow body guitar like yours is considered to be preferable for jazz because of its acoustic properties combined with magnetic guitar pickups. However Ted Nugent proved you can play rock on what is considered a jazz guitar. He uses Gibson Byrdland hollow body guitars a lot. Electronically his guitar and yours are similar to a Gibson Les Paul, a guitar that can be a real screamer.
One important thing is the setup. If you set it up for jazz with heavy flat wound strings and medium to high action then jazz is going to be what it does best. It will have a fat dark sound and bending strings more than a semitone will be a real chore. If you set it up for pop/rock with lighter gauge round wound strings it won't sound as much like a jazz box but will allow you to get a more contemporary sound and bend strings more easily.
As for other elements of the sound, use the bridge pickup with the volume and tone all the way up. Experiment with the various settings on the amp for the overdrive/distortion sound that you think matches his sound. I would start with the overdrive setting, the gain around 6 or 7 and the master volume set according to how loud you want to play. From there try slight tweaks to the gain for more or less overdrive and distortion to find what works for you. There is some reverb used as well.
The bottom of line is you have to decide whether setting up your guitar in this manner will suit most or all your needs or not. If you're mostly playing jazz, you may want to consider buying a solid or semi-hollow body guitar to do this type of playing. One compromise would be a set or roundwound strings that are heavier than 9's or 10's but not as heavy as a jazz set.


Como faço para imprimir os resultados das condições dentro da index php?

Question: Estou fazendo desse modo e quando é para imprimir o resultado(Após o usuário selecionar o submit em outra index), não aparece nada. Fica em branco.
ONDE RECEBE OS DADOS VIA POST DO FORMULÁRIO DO TIPO RÁDIO E ESTABELECE AS CONDIÇÕES:
<?php
            // Recebendo as respostas do Usuário
            $perfil = $_POST["pergunta1"];
            $condicao = $_POST["pergunta2"];
            //Iniciando as variáveis
            $cpu = "cpu";
            $rom = "rom";
            $ram = "ram";

            // Primeiro caso: Perfil de uso - Dia a dia
            if ($perfil == "diadia" && $condicao == "economico") {
                $cpu = "Intel Celeron";
                $rom = "HDD 300GB";
                $ram = "2GB DDR3";

            } elseif ($perfil == "diaadia" && $condicao == "normal") {
                $cpu = "Intel Core i3";
                $rom = "HDD 500GB";
                $ram = "4GB DDR3";

            }
            // Segundo caso: Perfil de uso - Trabalho
            elseif ($perfil == "trabalho" && $condicao == "economico") {
                $cpu = "Intel Core i3";
                $rom = "HDD 500GB";
                $ram = "4GB DDR3";

            } elseif ($perfil == "trabalho" && $condicao == "normal") {
                $cpu = "Intel Core i5";
                $rom = "HDD 1TB";
                $ram = "8GB DDR3";
                $video = "2GB";
            }
            // Terceiro caso: Perfil de uso - Edição
            elseif ($perfil == "edicao" && $condicao == "economico") {
                $cpu = "Intel Core i5";
                $rom = "HDD 1TB";
                $ram = "8GB DDR3";
                $video = "2GB";
            } elseif ($perfil == "edicao" && $condicao == "normal") {
                $cpu = "Intel Core i7";
                $rom = "HDD 1TB";
                $ram = "12GB DDR3";
                $video = "4GB";
            };?>

ONDE SERÁ MOSTRADO AO USUÁRIO AS CONFIGURAÇÕES DE ACORDO COM AS CONDIÇÕES:

             <?php

            echo "Processador: $cpu " . "
";
            echo "Armazenamento: $rom " . "
";
            echo "Memoria RAM: $ram "  . "
";
            if ($perfil = "edicao" && $condicao = "economico"){
                echo "Placa de video dedicada: $video" . "
";

            } elseif ($perfil = "edicao" && $condicao = "normal"){
                echo "Placa de video dedicada: $video " . "
";
            };

            ?>

Answer: Olá,
Verifique se o código abaixo atende. Note que os ifs foram drasticamente reduzidos, e que se você quiser acrescentar novos perfis e condições, basta estender o array multidimensional.

//escolhendo computador conforme opções escolhidas
$computadores['diaadia']['economico']['cpu'] =  "Intel Celeron";
$computadores['diaadia']['economico']['rom'] =  "HDD 300GB";
$computadores['diaadia']['economico']['ram'] =  "2GB DDR3";

$computadores['diaadia']['normal']['cpu'] =  "Intel Core i3";
$computadores['diaadia']['normal']['rom'] =  "HDD 500GB";
$computadores['diaadia']['normal']['ram'] =  "4GB DDR3";

$computadores['trabalho']['economico']['cpu'] =  "Intel Core i3";
$computadores['trabalho']['economico']['rom'] =  "HDD 500GB";
$computadores['trabalho']['economico']['ram'] =  "4GB DDR3";

$computadores['trabalho']['normal']['cpu'] =  "Intel Core i5";
$computadores['trabalho']['normal']['rom'] =  "HDD 1TB";
$computadores['trabalho']['normal']['ram'] =  "8GB DDR3";
$computadores['trabalho']['normal']['video'] =  "2GB";

$computadores['edicao']['economico']['cpu'] =  "Intel Core i5";
$computadores['edicao']['economico']['rom'] =  "HDD 1TB";
$computadores['edicao']['economico']['ram'] =  "8GB DDR3";
$computadores['edicao']['economico']['video'] =  "2GB";

$computadores['edicao']['normal']['cpu'] =  "Intel Core i7";
$computadores['edicao']['normal']['rom'] =  "HDD 1TB";
$computadores['edicao']['normal']['ram'] =  "12GB DDR3";
$computadores['edicao']['normal']['video'] =  "4GB";

$cpu = $computadores[$perfil][$condicao]['cpu'];
$rom = $computadores[$perfil][$condicao]['ram'];
$ram = $computadores[$perfil][$condicao]['rom'];
if(isset($computadores[$perfil][$condicao]['video'])){
    $video = $computadores[$perfil][$condicao]['video'];
}

E na parte onde se exibe os dados:
   echo "Processador: $cpu " . "
";
   echo "Armazenamento: $rom " . "
";
   echo "Memoria RAM: $ram "  . "
";
   if (isset($video)){
       echo "Placa de video dedicada: $video" . "
";
   }

Comment: Certo, obrigado pela ajuda!
Comment: Cara, deu um problema, ao pressionar o submit, dá erro 500
Comment: Nesse caso, você precisa ver os logs do Apache para identificar a causa.
Comment: Fatal error: Cannot use temporary expression in write context in /home/defaultwebsite/public/descubraseupc/form/index.php on line 33
Comment: Linha 33:     $computadores = ['diaadia']['economico']['cpu'] =  "Intel Celeron";
Comment: Tinha um erro nas atribuições, mas já corrigi a resposta. Você pode verificar, mas essencialmente, estava atribuindo errado
Comment: /home/defaultwebsite/public/descubraseupc/form/index.php on line 63 Notice: Undefined index: in /home/defaultwebsite/public/descubraseupc/form/index.php on line 63 Notice: Undefined variable: condicao in /home/defaultwebsite/public/descubraseupc/form/index.php on line 63 Notice: Undefined variable: perfil in /home/defaultwebsite/public/descubraseupc/form/index.php on line 64 Notice: Undefined variable: condicao in /home/defaultwebsite/public/descubraseupc/form/index.php on line 64
Comment: Linha 63: $ram = $computadores[$perfil][$condicao]['ram'];
Linha 64: if(isset($computadores[$perfil][$condicao]['video'])){
Comment: Lembrando que fiz uma alteração 62 e 63, porque estava ao contrario, onde era para ser "ram" tava "rom"
Comment: Isso é pq não veio o valor de $perfil e $condicao.Verifique se os dados estão vindo corretamente  do formulário.
Comment: Ok, resolvido. No entanto, um dos problemas iniciais continua. Ele não imprimi os resultados das variáveis, as outras strings sim, como "Processador: "
Comment: Ele está funcionando aqui: http://sandbox.onlinephpfunctions.com/code/ce1554e10c213dea04c5268abcb7e091159d1528
Verifique atentamente o restante do seu código... E se ajudou, marque a resposta por favor.
Comment: Disponha. Estamos aqui para ajudar.


Reload Javascript after ajax event

Question: I have a module that uses a button to load an embed view everytime the button is clicked.
// function to print builder view
    function workout_builder_template() {
        $viewName = 'builder_view';
        print views_embed_view($viewName);
    }

workout_builder_template();

However after the button is pressed a new view is loaded and the view is no long ajaxified. For example, if I click the apply button after changing the exposed forms, the form submits to a new page. Before clicking the button that loads an embed view via ajax, the exposed form altered the view content via ajax.
Here is example html from the ajaxified view
<form accept-charset="UTF-8" id="views-exposed-form-builder-view-default" method="get" action="/drupal7/builder-view" class="ctools-auto-submit-full-form ctools-auto-submit-processed jquery-once-1-processed">

Here is example html from the ajax less view
  <form accept-charset="UTF-8" id="views-exposed-form-builder-view-default" method="get" action="/drupal7/builder-view" class="ctools-auto-submit-full-form">

In the example the ajax less view does not have processed classes added to it. From this I suspect that the new view does not get javascript attached to it after the first ajax event. I have been researching drupal.behaviors and thought about printing
$vars['scripts'] = drupal_get_js();
print $vars['scripts'];

in the workout_builder_template() function displayed above, but I am not sure how this is done
Answer: I could be wrong here but am going to assume that the fetching of the embedded view and HTML refresh on the client-side has been done using custom Javascript code.
Once new HTML has been added to the DOM in a custom way, then to attach all Drupal behaviors defined by active modules, from within the success callback of your XHR client (say jQuery.ajax()) you might have to manually call:
// $wrapper here is the jQuery object identifying the wrapper element to
// which your new HTML has been injected to. Eg. $wrapper = $('.my-view-wrapper')
Drupal.attachBehaviors($wrapper, Drupal.settings);

My recommendation would be to try and possibly switch to the Drupal AJAX API (Documentation) as it lets you keep this refresh logic on the server-side (one place). The other, obvious benefit is that Drupal.attachBehaviors() is called for you automatically.
Comment: i don't understand any of that, trying to learn attach behaviors, but got it to work by reloading the scripts after fetching the views embed view, which runs the js again after

Reload Javascript after ajax event


Give PHP access to coffee-script node module in OSX

Question: I've installed coffee-script module globally (with -g key). I can use it from terminal. But php can't do it with exec command. There is no output in exec command and no compiling.
In Windows i moved node_modules folder to Program Files instead /LocalRoaming, and then PHP can use coffee command. How to do it in OSX?
Coffee bin path is: <code>/usr/local/lib/node_modules/coffee-script/bin/</code>
Answer: exec() only returns the last line of the output - this may be blank. Pass the second and third params to it as references and var_dump their contents after running exec(). The third param will at least yield the exit code of the programme.
Failing that - give shell_exec() a try.
Comment: I made test case, and use that command: "coffee -bo ./ -c ./$coffee". It works, when I use php from shell, but not work, when it executes apache. It work from _www user, not from me.
Comment: Use the full path to coffee in your command - PHP won't have a $PATH. You're also using "./" presumably to specify the current directory. You'd do well to change directory to be sure you're in the right place. cd /path/to/where/it/should/run/ ; /usr/local/lib/node_modules/coffee-script/bin/coffee -bo ./ -c ./$coffee


Not sure how signal handler is being called

Question: Code:
#include <signal.h>

static void sigHandler(int sig) {
    printf("Ouch!\n");
}

int main(int argc, char *argv[])
{
    int j;

    if (signal(SIGINT, sigHandler) == SIG_ERR)
        perror("signal");

    for (j = 0; ; j++) {
        printf("%d\n", j);
        sleep(3);
    }
}

I am not sure how the code works. sigHandler clearly takes in one argument that is an integer. However, in the if statement we write (signal(SIGINT, sigHandler) == SIG_ERR). Clearly when we call sigHandler, we are NOT passing in an integer value so why doesn't the program tell us it's an error? Why does the program still work as intended? Also I am not sure how the "signal" function works either.
According to the Kerris textbook on linux the syntax for signal functions is as follows void ( *signal(int sig, void (*handler)(int)) ) (int); We can clearly see that the handler function in the syntax is a pointer but in the actual code, we are NOT using a pointer to a function. Why is that?
Answer:
Clearly when we call sigHandler, we are NOT passing in an integer value so why doesn't the program tell us it's an error? Why does the program still work as intended? Also I am not sure how the "signal" function works either.

Surely, "we" don't call the signal handler—the system does upon receipt of the signal.  The signal() system call just installs the handler: "signal() sets the disposition of the signal signum to handler, which is either SIG_IGN,  SIG_DFL,  or the address of a programmer-defined function (a "signal handler")." There you go.
Btw. to quote once again from the manual page: "The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux.  Avoid its use: use sigaction(2) instead."

We can clearly see that the handler function in the syntax is a pointer but in the actual code, we are NOT using a pointer to a function. Why is that?

The compiler makes the necessary cast automatically.
Answer: You need to brush up on C...

However, in the if statement we write (signal(SIGINT, sigHandler) == SIG_ERR). Clearly when we call sigHandler, we are NOT passing in an integer value

That statement doesn't call sigHandler. It calls signal. The parenthesis are a required part of the C function call syntax, so sigHandler there isn't a function call.

... the syntax for signal functions is as follows void ( *signal(int sig, void (*handler)(int)) ) (int); We can clearly see that the handler function in the syntax is a pointer but in the actual code, we are NOT using a pointer to a function. Why is that?

When you use a function name without the parenthesis, what you get is a pointer to that function. So that is using a function pointer.
Answer:
Clearly when we call sigHandler, we are NOT passing in an integer value so why doesn't the program tell us it's an error?

That line doesn't call sigHandler at all; it passes it to signal() as the function pointer.  That might be clearer written this way:
if (signal(SIGINT, &sigHandler) == SIG_ERR)

Notice the "address of" operator, &.  However, in this case it is actually optional -- just the name of the function will serve as a function pointer.
To explain a bit, the compiler checks that the signature of the function pointed to matches the parameter to signal().  If this passes, at runtime the system can call it with an int argument as required.  The signal() function is just a means of telling the system about the handler.
Answer: Signal handler types are fairly tricky. I think it works like this: when the compiler encounters this line:
static void sigHandler(int sig) {

It creates a symbol named "sigHandler". The type is void (*)(int). Your example declaration of signal() (the system call that sets a signal handling function) has a prototype argument void (*handler)(int). The "handler" token is just a dummy: you could put any valid C language identifier in for it, or nothing.
When the compiler gets to the actual invocation of signal(SIGINT, sigHandler) it checks to see if a symbol sigHandler of the proper type exists, and it does as you defined just such a symbol above the invocation of signal(). Sometime during linking (static and/or dynamic), the actual physical address of sigHandler gets into the code.
The actual mechanics of signal handling are also tricky.
Once the program starts running, the physical address of sigHandler gets passed as an argument to the system call signal(), along with the integer 2, which is the value of SIGINT manifest constant. That's where the function pointer exists - it's the physical address of sigHandler() at run-time. The Unix/Linux kernel will keep that address in some data structure associated with the process that matches the number SIGINT (2 by convention or standard) to that physical addres.
If and when a SIGINT arrives for your process, the Unix/Linux kernel arranges for your process to stop, and then does something like put together a stack frame for sigHandler() which contains a value 2 (SIGINT) for the int sigint formal argument of sigHandler(), change the stack pointer register to match the new stack frame, change the instruction pointer register to the physical address it stored when signal() got called. The next instruction executed is for sigHandler().  Lots goes on under the covers of signal handling.


How to display only one block in custom page using tpl?

Question: How to show only block and hide all other menus,blocks etc.,
This is my code
function example_menu() {
  $items['appointcal'] = array(
    'page callback' => 'example_show',
    'access callback' => TRUE,
     'type' => MENU_CALLBACK,
   );
     return $items;
}

function example_show() {
  return theme('example_cal');
}

function example_theme() {
  return array(
    'example_cal' => array(
      'render element' => 'elements',
      'template' => 'templates/examplecal'
    )
  );
}

My examplecal.tpl.php is

  <?php
    $block = module_invoke('views', 'block_view', 'example-block');
    print render($block['content']);
  ?>

There is need to show only region that is in red color and hide all other regions.
Comment: my example.tpl.php code is
Comment: Change tpl file name to "page--examplecal.tpl.php" and try.
Answer: You can use Context module for this purpose. It provides the same functionality as you require.
Note:  If you don't want to use any extra module, then it can also be done simply through block configuration setting. There are three options to control the block visibility.
Comment: I want to do it programatically , need not to use other modules
Comment: Then you're doing it wrong, the Context module is designed for tasks like this. The context module is used by over 188,000 sites and is rigorously tested, doing it programatically introduces scope for error.
Comment: Why are you going towards complexity? If you don't want to use any extra module then it can also be done simply through block configuration setting. There are three options to control the block visibility. Try this.
Answer: Create a Custom tpl for your page by editing page.tpl.php. Name should be page--yourmenuname.tpl.php.
In that page tpl remove all unwanted contents/regions and render your block in required region using [block_load($module, $delta)]1;
$block = block_load('name','delta');
$output = _block_get_renderable_array(_block_render_blocks(array($block)));
print render($output);

Hope this will help you..
Comment: Put **page--yourmenuname.tpl.php** in you /template folder of your active theme.
Comment: Just saying, this will unnecessarily process all the blocks, only to hide them later. So it is not the best in performance.
Comment: Can i include **page--yourmenuname.tpl.php** in mymodule folder.
Will this work?
Comment: did you changed **yourmenuname**  ..?? Change to **appointcal** in your case
Comment: This answer is correct @AAjayKumarReddy You just need to name your template `page--appointcal.tpl.php` because your menu path is `/appointcal`
Comment: This code seems to give a PHP warning: `Strict warning: Only variables should be passed by reference in include()...`
Answer: There are two things, depending on your requirements. (People finding this question may have different ideas what they want)
Programmatically controlling which blocks appear on a page.
Create a custom module with hook_block_list_alter(). There you remove all those blocks that you don't want, depending on the current page.
The advantage of this is that you prevent these blocks from being rendered and processed.
Showing a page without blocks / "decorations".
If you want a page with only the main content, and no sidebars, blocks and stuff, you can create a page callback which prints the page html directly, and then calls drupal_exit().
You still want to deliver a complete html page, so you need to make sure that your page callback does something like theme('html', ..). This is "homework" for you to figure out :)


Views Taxonomy Term argument to represent "no term"

Question: With Views 2.x, Drupal 6, I've created a taxonomy and have enabled it for a Content Type. I then create some content:
node_1 is associated with term_1 (tid=1)
node_2 is associated with term_2 (tid=2)
node_3 has no term association
I've created a Node View that has an Argument for "Taxonomy: Term ID". In the argument configuration, I enable "Allow multiple terms per argument".
Using the Live Preview for the View, I can pass in arguments. So I pass in "1" and the view shows me node_1. I pass in "2" and the view shows me node_2.  I pass in "1+2" and the view shows me node_1 and node_2. This is good.
What I can't figure out is how to pass an argument that will return me just node_3. Is there something I can pass to Arguments that essentially means "no argument"?
Answer: Just in case anyone else stumbles upon this answer, we solved this problem with the following approach:
<code>function MODULENAME_views_query_alter(&$view, &$query) {

  if($view->name == 'your_view_name')){

    //Flip the term table join to a LEFT join
    $view->query->table_queue['term_node_value_0']['join']->type = 'LEFT';

    //CLear the extra condition (removes a where clause on the join limiting only matching term ids)
    $view->query->table_queue['term_node_value_0']['join']->extra = null;

    //Look through the where clauses and add a null condition clause
    if($index = array_search('term_node_value_0.tid = %d', $query->where[0]['clauses'])){
      $query->where[0]['clauses'][$index] .= ' OR term_node_value_0.tid IS NULL';
    }
  }
}
</code>
It changes the JOIN type to a LEFT join, removes the limiting clause from that join and adds a condition to match against null values.  It's obvious limitation is that it should be using aliases instead of hard coding the field name.
The function should go in your modules views.inc file where Views expects to find this hook.


WCF Saving EF 4.1 item throws exception An item cannot be added to a fixed size Array of type

Question: I have searched google and exhausted a fair bit of my time trying to figure out what is going on with my WCF and client Windows form app.
I am continuously getting the following error
"Unable to set field/property Ingredients on entity type Datalayer.UnitOfMeasure. See InnerException for details."
...
inner exception is
"An item cannot be added to a fixed size Array of type 'Datalayer.Ingredient[]'."

Stack Trace -
    at System.Data.Objects.Internal.PocoPropertyAccessorStrategy.<AddToCollection>b__0[T](Object collectionArg, Object item)
       at System.Data.Objects.Internal.PocoPropertyAccessorStrategy.CollectionAdd(RelatedEnd relatedEnd, Object value)

The way I have configured my solutions I have a WCF web-service which reference my DataLayer class library, I have a windows app (test app) which references the WCF services as well as DataLayer project.
If I don't reference the DataLayer in my test app, this issues does not occur however I lose the ICollection<Ingredient> to simple Ingredient[] array. Now as you can see this becomes a coding pain to initialize the array every time.
Any idea anyone? thanks in advance.
Answer: I was running into this exact error, but the accepted answer wasn't quite the solution I needed. It turns out that the client was sending a List<Order> up to my WCF service, but since the Customer.Orders property was defined as an ICollection<Order>, the WCF deserializer deserializer just deserialized it in the simplest form it could, which was an array of type Order, i.e., Order[].
The only solution I was able to come up with was to change the property in question on my POCO objects from an ICollection<Order> to a HashSet<Order>. See Stop WCF Deserializing Empty ICollection into Zero Capacity Array for a few more details.
Answer: When you are adding reference to WCF service in the test using 'Add Service Reference' there is a option to configure the default collection type for the generate proxy on the client. The default i think is array, you can change it to a generic list.
In case you are using svcutil,that too allows the same thing.
Answer: Weird. I had this same error, and was doing the right thing, calling "ToArray()". Changed it to "ToList()" and it started working fine.
Comment: Pfffff.... I ended up here after googling this error. Found this answer and it worked a treat. Went to vote it up as the correct answer, only to realise it was posted by me two years ago! I suspect I ended up here then googling the same error in the same project.


What is the equivalent of field_view_field()?

Question: I am working on some code where I need to get some fields from a node. For the body, I want to display the summary, or the trimmed body if the summary is not there.
I found an example on the web using field_view_field(), which seems to do what I want it to do: return the body field using the summary_or_trimmed formatter.  But it seems this is a Drupal 7 thing.  I can't seem to figure out what or if there is an equivalent.
The Drupal 7 example went something like this:
<code>$x1 =  field_view_field('node', $node, 'body',
                                array('label'=>'hidden',
                                      'type' => 'text_summary_or_trimmed',
                                      'settings'=>array('trim_length' => 50)));
</code>
Note: I am trying to assemble text output for an email.  I thought I could do this by making a custom display view mode, 'alt-teaser', that is like 'teaser' for my content type, but I don't see a way to get rid of the title (!), which I do not want.
So that is why I now hope to get at individual fields, formatted.
<code> $viewBuilder = \Drupal::entityTypeManager()->getViewBuilder('node');
 $renderArray = $viewBuilder->view($node, 'alt_teaser');
</code>
Comment: Here is what worked for me (using d9)

 $body = $node->body[0]->view('alt_teaser');
 $display = \Drupal::service('renderer')->renderPlain($body);
 Thank you cilefen.
Answer: Drupal's change records usually indicate when an API has been removed or changed. This one is documented: https://www.drupal.org/node/2208327

In Drupal 8, those functions have been replaced by view() methods on, respectively, the FieldItemList object (i.e $entity->field_name, "the list of field items") and the FieldItem object (i.e. $entity->field_name[$delta], a specific item in the list). Their signatures have also been largely simplified.


Finite spanning set of the subspace.

Question: First first of all, I apologize if my question is repeated.
In my text, there was a question that I was supposed to find the distinct finite spanning set for the following subspace, and I tried to transform it from parametric form, but I still don't understand the general process to find the spanning set here.
$A = \{(x,y,z,w) \in \mathbb R^4 | x-y+z-w = 0\}$.
I do understand the way to write one parameter based on others but since here we got 4 parameters I'm not sure if that works. Could you please give me some hints?
Answer: The routine is generally given by

But in this case your "system" has only one equation, $x-y+z-w=0$, which means that you will have 3 degrees of freedom (4 variables total, 1 of them is the pivot).
So, choosing $x$ as the pivot, then $x=y-z+w$. Therefore,
\begin{align*}
\vec{x} = (x,y,z,w)\in A &\Longleftrightarrow \vec{x} = (y-z+w,y,z,w) \\
&\Longleftrightarrow \vec{x}= (y,y,0,0)+ (-z,0,z,0) + (w,0,0,w) \\
& \Longleftrightarrow \vec{x} = y(1,1,0,0) + z(-1,0,1,0) + w(1,0,0,1) \\
& \Longleftrightarrow \vec{x} \in span((1,1,0,0),\ (-1,0,1,0),\ (1,0,0,1) )
\end{align*}
Thus, $A = span((1,1,0,0),\ (-1,0,1,0),\ (1,0,0,1) )$
PS. In this case you can freely choose your pivot, so you can find other sets of generators for the same subspace.

Finite spanning set of the subspace.


Can we construct a pair of random variables having any given covariance?

Question: Consider a vector $r$ of $n$ random variables. Let $\mu = E[r]$ and $\Sigma$ denote the covariance matrix of $r$; that is,
$$\Sigma_{ij} = \sigma_{ij} = E\Bigl[\bigl(r_i - E[r_i]\bigr)\bigl(r_j - E[r_j]\bigr) \Bigr].$$
We know that $\Sigma$ is a positive semidefinite matrix, because we can show that
$$x^T \Sigma x = E\Bigl[ x^T r - E\bigl[x^T r\bigr] \Bigr]^2 \geq 0.$$
(The proof is by writing out the product in summation notation and doing some algebraic manipulation.)
I am currently proofreading a set of practice problems in which the student is asked to consider $r$ having a given $\mu$ and $\Sigma$. Specifically, $n=2$, $\sigma_{1}^2 = 0.1$, $\sigma_{2}^2 = 0.05$, and $\sigma_{12} = \sigma_{21} = -0.4$. Thus, the covariance matrix is
$$\Sigma = \begin{bmatrix}
0.1 & -0.4 \\
-0.4 & 0.05
\end{bmatrix}$$
which is not PSD: If  $x = (1, 1)$, then $x^T A x = -0.65 < 0$ as you can verify.
Am I correct to conclude that it is impossible for two random variables to have the given variances and covariances?
(Or are there additional assumptions that went into the proof that $\Sigma$ is PSD that, when relaxed, enable one to construct random variables with the given variances?)
Comment: Feels like a mistake when specifying the covariance matrix. Just a wild guess.
Comment: Because, for instance, the variance $$\pmatrix{1&1}\Sigma\pmatrix{1\\1}=-0.65\lt 0,$$ $\Sigma$ cannot be a covariance matrix.
Answer: Covariances cannot have arbitrary values in comparison to variances; $|\operatorname{Cov}(X,Y)| \leq \sqrt{\operatorname{Var}(X)\operatorname{Var}(Y)}$. So, Yes, it is not possible to find random variables that have the alleged covariance matrix, which is, as you have discovered, not a positive semidefinite matrix. For the given variances, $|\operatorname{Cov}(X,Y)|$ has maximum value $\frac{\sqrt{2}}{20} \approx 0.0707\cdots$, and the given value $-0.4$ is way out of range,
Comment: That inequality is just the determinant condition for a $2\times 2$ symmetric matrix to be PSD. Is that where that equality comes from, or does it follow from a prior principle?
Comment: @Max The root of the inequality you are asking about is the Cauchy=-Schwarz Inequality which was known long before covariance matrices (or even matrices) were thought of.
Comment: Specifically, Cauchy–Schwartz as applied to the respective definitions of the variance and covariance.
Comment: That a covariance matrix must be positive semi-definite can be proved simply by using that a variance cannot be negative.