Definition of the note C

Question: That I'm using the note C is arbitrary, I could be using any other. How would you define a C? If you define it as the tone with frequency 261.6 Hz (or 2^n * 261.6) then you run into problems when you change tuning - the note C in pythagorean tuning does not have the same frequency as in equal temperament, yet regardless they are both called C - so frequency can't be the answer.
I'm very new to music theory, but from what I can gather, most tunings use letters A-G along with the sharps and flats, so that there are 12 different symbols which are assigned to 12 notes of different frequencies. The letter C just represents the 4th note (ordered in ascending pitch) of these 12 notes. Is this correct?
I'm just a bit confused because if I talk, for example, about the note G# on a piano keyboard, in a certain context it cannot be called G# and must be called A flat, or so I hear.
Comment: Some possibly-relevant information on the adoption of modern tuning: http://music.stackexchange.com/questions/18969/why-is-a4-the-standard-pitch-reference-for-tuning
Answer: The very simplest answer is that A is 440Hz (* 2^n, as you say) and that C is a minor third higher than that (523.251 Hz).
However, the mapping of absolute pitches to note names is only a convention, and in reality the absolute pitch of C only needs to be agreed between the people performing a piece of music.

When I pick up my guitar, for me C is the pitch I get when I play the third fret of the A string. Even if the guitar is only "in tune" relative to itself.
If I tune my guitar by ear, without external reference, then as long as the E string feels about right, I'll probably tune everything else relative to that. So C is 4 semitones lower than whatever arbitrary pitch the E string is at.
If I tune my guitar with a tuning fork or an electronic tuner, then C is about 523Hz -- unless I change my tuner to a difference reference pitch.
If I decide a song would be easier to sing if I put a capo on the 2nd fret, I have a choice. When I play the third fret relative to the capo, I can call it D -- so all the chord shapes I know have changed their names -- or I can continue to call it C, even though its pitch has risen by a tone.
If I'm in a band, and we all decide it would sound better if we all dropped our tunings by a tone, we have a choice. We can define C according to the fingerings we're used to on our instruments -- which most people are going to find easier -- or we can say that C is still 523Hz, in which case if someone says "play C", I must fret the D position.
In an orchestra, C is whatever comes out of the oboe when the oboist fingers a C note. Everyone else tunes to the oboe.

... and so on.
To complicate matters more, you could end up in a situation where different band members have different definitions of C. For example, Adam is band-leader, Bill is a keyboardist at standard tuning, Charlie is a novice guitarist with a capo on the 2nd fret. "Right," says Adam, "Bill, you're playing D,G,G,D."  Then turning to Charlie: "You're playing C,F,F,C".
Exactly this happens in orchestras, since some (mostly brass and wind) instruments are "transposing instruments" -- What is a transposing instrument?

As for G# vs Ab, it's simplest to think of these as the same pitch. That pitch is given different names for convenience when working in a particular key.
A western major or minor key consists of 7 notes out of the 12 available. For example C major uses A,B,C,D,E,F,G and omits C#,D#,F#,G#,A#.
D major is:   D E F# G A B C#
Why isn't D major: D E Gb G A B Db ?
Well, it's more difficult to think about, described in that way. It has two Gs, one natural and one flattened, and to Ds in the same way. It's much simpler if we organise things so that a scale has all the letters in it, and we can remember that a particular note letter is always flattened or sharpened. Hence, D major goes DEFGABC, with F and C sharpened.
To be super-pedantic, players of some instruments will play Gb and F# as slightly different pitches, and if you get into the maths of tuning in more depth, you'll find out why.
Answer: This is a very good question, and you're on exactly the right track to be looking away from frequency. I think the place to start is with taking apart some concepts that, for convenience, most of us group together most of the time. This means defining some terms, but I'll try to keep it to the most essential.
When you ask to define "a C", you are asking to define a pitch-class, which isn't the same as a pitch. "Middle C" (aka C4) is an example of a pitch, and one octave above it (C5) is a different pitch. When we talk about pitch class, we are asserting pitches that form perfect octaves are fundamentally equivalent (which is a really well-supported, useful concept, even though in some contexts the differences between different members of the pitch-class C).
The concept of pitch-class is particularly important to the atonal, 12-tone music of the 20th century, but it is not limited to that context. Importantly, the concept of pitch-class does not depend on another concept associated with that kind of music (and musical analysis): enharmonic equivalence. Enharmonic equivalence is the principle of the piano keyboard: that C# = Db. If you are going to consider the music of someone like Webern, you would be entirely lost without using the concept of enharmonic equivalence; however, as you noted in the last sentence of your reply, enharmonic equivalence definitely does not always apply. For our broader purposes, therefore, we want to consider C# to be a different pitch-class than Db (whereas in 12-tone music, both would be part of pc 0). This means we have a lot more than 12 pitch-classes: in fact, 35 (7*5, i.e. Cbb, Cb, C, C#, C##, Dbb, etc.).
To define what a pitch-class is, then, we need to look at what makes G# (to use your example) different from Ab. Let's imagine a piece in the key of C major:

G# in that key, would be most likely as part of a secondary dominant chord (E-major) leading to the submediant chord (A-minor). Imagine a (bad, awkward) melody starting in C major that is going along and comes to ... B G# C. These notes might be harmonized by iii V/vi vi (i.e. {E G B} {E G# B} {A C E}), which could begin a modulation into the relative minor key, A minor.
Ab, on the other hand, might occur as an added seventh in a fully-diminished B chord (viiº7). Consider the same melody, but spelled as ... B Ab C. Fully-diminished chords normally occur in minor keys, so here, the harmony would likely be iii viiº7 i (i.e. {B D F Ab} {C Eb G}) and imply a modulation into C minor, the parallel key.

Even if played on a piano, where in isolation they would be indistinguishable from one another, G# and Ab convey very different musical meanings about the further direction of the piece.
By calling a pitch-class C, then, what we are doing is representing through a notation certain kinds of relationships between members of pitch-class C and members of pitch-classes G#, Ab, and so on. Any C and any G# will have the same kind of relationships to one another (of course, there are other relationships that will be specific to context.
It is impossible to make a comprehensive list of all these relationships, especially because many of them derive from the socially-constructed understanding of how Cs have been used in music throughout the centuries. Trying to understand these functional relationships is one of the major tasks of the field of music theory. One example: the relationship between C and G is very like the relationship between G and D, and we call that kind of relationship a "perfect 5th".
These relationships are very strongly related to frequency ratios and the physics of sound/overtones, but as you observed, they are not identical, for two reasons:

First, the trivial: tunings and temperaments define the ratios between frequencies, but don't specify an absolute reference frequency. For much of history, this was not at all standardized, beyond perhaps whatever the local organ happened to be tuned to. Even today, while A = 440 Hz is very prevalent, A = 415 Hz is common in performances of early music, and some orchestras are now tuning sharper (e.g. to A = 443 Hz).
Secondly, the ratios themselves are adjusted from the "pure" small-whole-number forms to fit the needs of the tuning system. Even the octave, which because it's so critical is kept in its perfect 2:1 ratio in virtually every system, can in principle be adjusted. In Equal Temperament, every ratio except the octave is adjusted away from its ideal value — yet we consider the relationship between C and G (or whatever) to be more alike than different, and the Well-Tempered Clavier to still be the same piece of music when played in Equal Temperament.

So in brief, a C (or any other pitch-class) is an abstract category which signifies that its members possess certain types of relationships to each of the other pitch-classes.
Answer:
How would you define a C?

You define it using frequency, like you said. But usually, people don't calculate the frequency of the note C, but the frequency of the note A. The 'standard' tuning pitch that is used nowadays for most Western music, is 440 Hz, is named a′ or A4.
I think this thread will also help you:

Why is music theory built so tightly around the C Major scale?

most tunings use letters A-G

This is correct, but I think you are a bit confused. The letters A-G are used to represent notes; the tunings in any instruments are notes, so they do use the letters A-G.
In some other countries/languages/cultures, instead of the letters A-G they use do-re-mi-fa-sol-la-si, each of which corresponds to a letter.

The letter C just represents the 4th note (ordered in ascending pitch) of these 12 notes. Is this correct?

Yes, it is.If you see the letters A-G, with A as the first letter, the C is the 4th note, on the chromatic scale. A (1st), A# (2nd), B(3rd)  and then C (4th), but it is the 3rd if you use the Aminor/Cmajor scale, since there is not A# in it.

I'm just a bit confused because if I talk, for example, about the note G# on a piano keyboard, in a certain context it cannot be called G# and must be called A flat, or so I hear.

Yes, this is correct. Sometimes you write it G# and sometimes Ab, and that depends on the content. For more insight on this topic, look at this thread:

Should one write # or b?
Comment: It's important to point out that a 12-note scale is only one type of scale. Other composers use 24 or 48-note scales, dividing the octave into many microtones. It is also important to remember that tuning systems have changed dramatically over the past few hundred years, and even vary by country today. Really, the frequency for a note encompasses a range of frequencies, and not any one particle single number. This question is similar to "why is the sky called Blue?"
Answer: Music is completely different from math, and therefore there is no right (in the sense of correct) choice. Even if you may have set up up your instrument tuner to the desired reference frequency (however you determined it) and it flashes the green light, as soon as your buddy on the piano has a different C, you lost since more likely than not, none of you is able to re-tune a piano.
Note, that there is a trend to increase the base frequency hertz by hertz: for greater brilliance or without plausible reason for this nonsense, depending on whom you ask.
So 442 Hz is quite common for an orchestra, but 444 Hz is also not unheard of.
Answer:
How would you define a C?

It's a note (a set of notes, one for each octave) in the scale. If you specify the scale AND the tuning, then you'll have a frequency for it. As you rightly noted, there's no single frequency. But...
The beauty of equal temperament is that the frequency for C is fixed, regardless of the root note and scale.
Comment: I understand what you mean about a fixed frequency for C using equal temperament, but strictly speaking it's fixed *relative* to whatever your overall concert pitch is. Implicitly this would be the current standard of A440, but this need not (and has not) always been the case. Sorry to nitpick...
Comment: Might be better to describe it as a fixed frequency *relationship* with other pitches when using equal temperament.
Answer: I assume you are working with the chromatic scale. The chromatic scale has an evenly distributed 12 semitones per octave. This means that going up 12 semitones equals doubling the frequency. Going up 1 semitone it therefore equal to multiplying the frequency with
2^(1/12) ≈ 1.06
If you have a base frequency of 440Hz for A4, then C3, which is 9 semitones lower, will have a frequency of
440*2^(-9/12) ≈ 261.6Hz
This way you can calculate any frequency based on your base frequency.
Answer: The way you define C is that its a note between previous and next note. (Unless on 1 tone tunings where with only C note).
The C means nothing more than this as everything else is arbritary.

Definition of the note C


HP ProLiant DL365 G5, USB and PS/2 Do not work during Boot

Question: Good evening all,
The situation up until the REAL point of failure;

Dual Opteron 2300 Quad-Core (I'm not positive but I think theyre running at 2.6Ghz)
24Gb RAM (2Rx4 PC2-5300P-555) (lost 8Gb to a bad stick on Friday)
RAID: HP Smart Array P400i/256MB with BBWC (RAID 0/1/1+0/5)

Failure;
I am attempting to enter setup (F2 @ Boot...) to deal with a separate HDD issue (I/O error, Invalid or non-system disk, I think I've got that one covered though).  However when attempting to enter setup, NONE of my USB or PS/2 port(s) are operational.
caveat: If booted to a LiveCD USB and PS/2 work just fine making me think physical layer is out of the equation.
Here's a breakdown of what I've done so far:

Multiple Keyboards on all USB ports

Rebooted (Rebooted between keyboards too)

Multiple Keyboards with "USB > PS/2" adapters (single PS/2 port)

Rebooted (Rebooted between keyboards too)

Attempted to change BIOS to enable USB

(BIOS is password Protected...)

Shut Down

Pulled the CMOS and let it sit for about 20-min

(Returned CMOS "its in the proper way I checked")

Booted

Adjusted Maintenance Jumper 5 to ON "Power-On Password is Disabled"
Adjusted Maintenance Jumper 6 to ON "System Config invalid to clear NVRAM"

Rebooted

So for now I'm at a loss.  If anyone's got any brilliant ideas (except Drop Tests...) I'm open to ideas...
Edit1: iLO Port was never configured to my knowledge, think of me as the dying server parts-yard for future emergent repairs...
Comment: Please leave a comment if down-voting...
Comment: I believe these things are really finicky.  Try to get hold of a pure PS/2 keyboard and don't use an adapter.  I had to deal with a couple of these some time back and I recall USB keyboards never worked for me either.
Comment: Sadly thats not likely to happen. Was in front of it a bit ago and happened to catch a brief glimpse of a power flicker to the keyboard on insertion.  Repeatable with USB or ps2.  Like it reads it and then kills it.  If that helps any...
Comment: critical bits of info - what os was it running? are you trying to recover data or getting it booting again?
Comment: The HDD?  WinServr 2k3.  Just formatting it,  it would have been previously raided (1+0) and I have no way knowing which drives are it's little brothers...  I'm not really concerned about that.  The ps2 and or USB being operational are my main goal here.  After that I'm good.
Answer: Fourth attempt for NVRAM to clear finally worked,  make sure the maintenance switch jumper #6 is set to ON.  Power the system on, and in the middle of POST, kill power.  Swap jumper number 6 back to off and boot
BIOS is wide open after this so if your in a secured environment you'll need to reconfigure evahreythang. ..


What is the difference between "spark-shell" and "spark-shell --master=local"?

Question: Can someone help me in understanding what is the difference if I open Spark using the following two commands?

spark-shell
spark-shell --master=local
Comment: `spark-shell` will utilize all the cores you have in your machine as local[*] whereas `spark-shell --master=local` will utilize only one core of your local machine.
Comment: Thanks a lot Ramesh!
Comment: Please see my answer below :)
Answer: When you start spark shell without --master option, then all the cores of your local machine is utilized as you can see in the log that it starts with following message
Spark context available as 'sc' (master = local[*], app id = local-1519264959885).
Spark session available as 'spark'.

But when you start with --master local option, it starts utilizing only one core of your local machine as you can see in the log
Spark context available as 'sc' (master = local, app id = local-1519265031949).
Spark session available as 'spark'.


Why is this guitar making so much noise?

Question: My brother has an electric guitar which he has not played or even touched for at least fifteen years. It's a cheap strat-like guitar, equipped with three unknown (most likely stock) single coil pickups. Last weekend I was visiting him and he gave it to me.
When I got home, I plugged it into my amplifier and it started to make a very loud buzzing noise. I noticed that the noise is significantly reduced whenever I touch some metal parts, such as the bridge or the input jack. As suggested by this question and many other references that I have found during a quick research, this scenario suggests grounding issues.
A quick note: I have been playing guitar for many years now, but I never tried to fix the problems of any of my guitars - I have always handed them to professionals. Since this is a cheap and old guitar, I figured this would be a great opportunity to learn a bit of guitar electronics and maintenance.
So yesterday I opened the guitar and worked on it a bit. Many components were oxidized; so, apart from checking and resoldering the ground wiring, I replaced the following components with brand new ones:

All three potentiometers
The input jack
Every wire except the ones that come from the pickups

Still, the guitar is making a loud noise when plugged into an amplifier. I really don't think it's just a single coil hum, since it is way too loud even if the volume on the amplifier is low. Also, from what I have read in the past few days, the fact that touching metal parts basically cuts off the noise seems to suggest this is indeed a grounding issue.
I took the time to analyze the guitar wiring and made this simple diagram:

Is the wiring correct? While searching on the internet, I didn't find a guitar wiring diagram that looks like this one. Since I don't know much of electronics, I'm not sure if this guitar was already wrongly wired/grounded.
And in case the wiring is correct, what else could be causing the loud noise?
Comment: Are you getting ONLY noise, or is guitar signal coming through also?  Most likely you have a cold solder joint somewhere, or possibly something touching where it shouldn't.  Retouch all the solder points and check that the signal pins on the pots aren't touching the casing or other wire points.
Comment: Hi, thanks for your comment. There is also guitar signal, not only noise. I resoldered the entire ground wiring yesterday and checked it again today with a multimeter - it all seems to be OK. Your second suggestion seems very plausible, I'll give it a try later. I have noticed the cavities on this guitar are somewhat tight. Maybe there's some extra touching going on.
Answer: When you have a hum or buzz that is eliminated or affected by touching a metal part of the guitar, this is most likely caused by a grounding issue.  On a guitar that has not had electricity run through its circuit in 15+ years I could see one or more exposed wires and/or solder joints degrading due to oxidation.
The remaining hum could come for several sources:

Single coil pickups will by their very nature pickup 60Hz hum (And
it's harmonics).  This is a type of inducted noise.
Electical noise from dimmers, fluorescent lights, A/Cs and
compressors (just to name a few sources) as well as RF frequencies in
the environment are another type of inducted noise that pickups or
tube amps can receive and inject into your tone chain
The higher your gain setting, the more sensitive your rig becomes to
inducted noise.  Even humbuckers will pick up inductive noise
especially under very high gain scenarios.
Conducted noise sources include things like ground loops, noise that
enters the system trough a noisy power source and noise added by
components in your signal chain

Using a multi-meter with a continuity test function you should be able to easily track down any grounding problem within the guitar itself.
As for the rest of the noise, this is tougher.
First, if a guitar is not shielded, noise can enter through the pickups and the wiring, pots and switches in the control cavity.  Your guitar is essentially a giant electro-harmonics antennae.  Shielding the control cavity can provide a good amount of noise reduction.  Shielding pickup cavities can provide a small amount of reduction but is far less impactful than shielding the control cavity.  If the only wire in your tremolo cavity is a ground wire, shielding the tremolo cavity will have no effect.  ALL SHIELDING MUST HAVE CONTINUITY TO GROUND IN ORDER FOR THE SHIELDING TO WORK.
Next, getting a good noise suppressor will help.  Note I said suppressor not gate.  There is a difference.  Noise suppressors include both a gate and a filter whereas a noise gate only includes the gate.  A good 2 connection suppressor will take a lot of inducted noise out of your tone.  Examples of good noise suppressor include the Boss NS2 and my personal favorite the ISP Decimator G String.  The only Decimator you want is one of the G series... either G string for a pedal or Pro Rack G for rack.  You need to go through the noise suppressor to your amp input, then connect it into your amps effect loop.  This will make a big difference in the inducted noise in your signal.
Next for conducted noise get a good power conditioner for your effects and peripherals.  You should not connect your amp to a power conditioner.  Modern amps exhibit variable power consumption which a power conditioner may have problems with.  For the amp, there are ground isolators like the HummX or one made by Logsdon (cannot remember the name).  If you want to go really crazy there are isolation transformers like those used for sensitive medical equipment.  These are expensive and heavy.
Never, ever use a ground lift as a permanent solution to grounding problems!  You are playing Russian Roulette if you do.  Ground lifts are fine for diagnosing problems, but they are not a permanent solution!
How far you want to go is your own personal choice.  I think at minimum you need to deal with the grounding on the guitar.  Especially if your other instruments do not exhibit such a glaring noise problem.  A poorly grounded guitar is unsafe and could lead to serious injury or even death.  You do not want to act as the ground for part of your system!  The further you go with the steps outline above, the more you will tame the noise in your rig.
Answer: It is very easy to see if it is, if fact, from the single coil pickups. Does the hum diminish in the 2nd and 4th switch positions when the two single coils on are humbucking? If yes, it IS the single coil pickups. Get some noiseless (stacked humbucking single coils) OR just use the 2nd and 4th positions and don't go above 6 or so on your tone knobs. oh yea, almost forgot, I also use a passive two channel "hum eliminator" and I use both channels in series (floor effects to input channel one, out to input channel two, then out to the amp. Simple cheap add to the signal chain to reduce hum. It is just velcro'd on the back of my amp.
I have tried the conductive shielding lining of the cavity and I am not convinced that it is effective. I have learned that quality cables DO make a big difference. A cheaper quality cable may work with another guitar fine but may introduce grounding issues with this one. Try that. Also, try other rooms and outlets and make sure you use one outlet for your effects and your amp as to not create any unwanted loops. My guess is that you will eliminate everything else and be back to the noisy cheap single coil pickups in there.
Answer: I've read the answers above and noticed one glaring omission. All answers are focused on the guitar itself. However, the grounding process also includes the guitar cable and amplifier. A quick continuity check with the cable plugged into the guitar and the amp, checking continuity from the shielding in the guitar to the amp chassis, might reveal dirty or corroded connectors or a problem with the guitar cable. The continuity reading should be 0 ohms, otherwise you'll have some hum.


How can I download django-1.2 and use it across multiple sites when the system default is 1.1?

Question: I'm on Debian Lenny and the latest backports django is 1.1.1 final. I don't want to use sid so I probably have to download django.
I have my sites located at: /www/ and I plan on using mod_wsgi with Apache2 as a reverse proxy from nginx.
Now that I downloaded pip and virtualenv through pip, can someone explain how I could get my /www/ sites which are yet to be made to all use django-1.2?
Question 1.1: Where do you suggest I download django-1.2? I know you can store it anywhere but where would you store it?
Question 1.2: After installing it how do you actually tie that django-1.2 instead of the system default django 1.2 to the reverse proxied Apache conf?
I would prefer it if answers were more specific than vague and have examples of setups.
Answer: Ensure you consult:
http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
for how to setup mod_wsgi with virtual environments.
That way you can leave any existing Django alone and install new one into virtualenv and have your WSGI application under mod_wsgi use it.
Answer: Ended up following the excellent guide @ http://www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/
I really like comprehensive tutorials like this, instead of some RTFM link to these types of things which do NOT cover integration of different services.
Answer: Simply remove the Django package provided by Debian and install from the tar.gz download or use svn to get the latest.
See http://docs.djangoproject.com/en/1.2/topics/install/#installing-official-release
Comment: Is that the preferred way of doing it, though? And how would you handle the situation if you wanted your existing sites to use `1.1.1` but multiple, newer sites using `1.2`?
Comment: I believe Graham Dumpleton's answer covers all that.


Where can I add core  elements with Views RSS

Question: I'm trying to set up a podcast feed with Views RSS. I think I've succesfully set up the module and the core <channel> elements.
I am now trying to set up the core <item> elements, as explained here. However, I have no idea if I'm looking in the correct place.
I go to admin/structure/views/view/gentle_podcast/edit/feed_1 and under Format I see:

Format: RSS Feed | Settings
Display: Fields | Settings

(I'm translating from Dutch, so labels may be off). When I click the Settings next to Display, I get a popup where I can set Title, Link, Description, Creator, Publication date and Guid.
How can I set all the other items that the documentation mentions?
Does it check the fields I've added to the view? Because I've added a field that has the URL of my podcast file (an mp3), but I don't see anywhere to set the <enclosure> item.
You can see the current result of my view here (as feed) and here (as page).
Comment: Can you clarify which version of views (2.x or 3.x?) and Drupal you are using?
Answer: It sounds like you're missing a couple things. First, make sure that you have the Views RSS: Core Elements submodule enabled -- this is what allows you access to the many other fields. This may already be enabled and if so, the reason you're not seeing the fields is that you need to switch your format to RSS Feed - Fields, ex:

by clicking the 'RSS Feed' link in your Format Settings.
Now, when you adjust the settings for this, you'll see the options for the item elements you were looking for.

You'll need to add the appropriate fields from your content to have them appear in the select lists.
Comment: Thanks. I had the module enabled, but the Format was on RSS Feed, not RSS Feed - Fields. Stup how I overlooked that.


How does one create a Terminal I/O connection to a Telit BLE module?

Question: I'm writing a progressive web app for an android tablet which should be able to read and write to a device with an embedded Telit BLE module via a BLE connection.
I am able to open a BLE connection and discover services and characteristics.  I am unable to establish a connection over BLE using Telit's Terminal I/O (TIO) protocol.
My remote (server) device is a Falcom Fox3 tracker unit.  A notification event can be read from the Fox3 serial port when a connection is established.  This has been successfully tested by connecting to the Fox3 using Telit's android terminal app: https://play.google.com/store/apps/details?id=com.telit.tiosample
I have put together a short function which should connect via BLE, establish a TIO connection and request UART credits before listening for incoming data from the server.
I have based my code on a simple script from Smashing Magazine :
https://www.smashingmagazine.com/2019/02/introduction-to-webbluetooth/
The process of initiating the TIO connection follows is that given in Telit's Terminal I/O Profile Client Implementation Guide .

the Terminal I/O connection setup consists of the following steps:
The Terminal I/O client scans for Bluetooth Low Energy devices advertising the Terminal I/O service.
The Terminal I/O client establishes a Bluetooth Low Energy GATT connection to a detected Terminal I/O server.
The Terminal I/O client performs a service discovery on the Terminal I/O server.
For the retrieved Terminal I/O service, the Terminal I/O client performs a characteristics discovery.
The Terminal I/O client subscribes to indications of the UART credits TX characteristic (see 7.4).
The Terminal I/O client subscribes to notifications of the UART data TX characteristic (see 7.2).
The Terminal I/O client transmits initial UART credits to the server (see 7.5).
Once the Terminal I/O client has received the response for the transmitted UART credits, the Terminal I/O connection is considered established and indications for the UART credits TX characteristic and notifications for the UART data characteristic shall be expected at any time.
The order of the connection setup sequence is mandatory.

My code is as follows, where log is a function which outputs to the screen.
const SERVICE_UUID         = "0000fefb-0000-1000-8000-00805f9b34fb";
const UART_RX_UUID         = "00000001-0000-1000-8000-008025000000";
const UART_TX_UUID         = "00000002-0000-1000-8000-008025000000";
const UART_RX_CREDITS_UUID = "00000003-0000-1000-8000-008025000000";
const UART_TX_CREDITS_UUID = "00000004-0000-1000-8000-008025000000";

async function tio_connect() {
  let device = await navigator.bluetooth.requestDevice({
  filters: [{ namePrefix: 'FOX' }],
  optionalServices: [SERVICE_UUID]
  });
  log(" - Connecting
");
  let server = await device.gatt.connect();
  log(" - Getting Primary Service
");
  let service = await server.getPrimaryService(SERVICE_UUID);
  log(" - Subscribing to tx credits
");
  let tx_credits = await service.getCharacteristic(UART_TX_CREDITS_UUID);
  log(" - Subscribing to tx data
");
  let tx_data = await service.getCharacteristic(UART_TX_UUID);
  log(" - Requesting credits
");
  tx_credits.writeValue(new Uint8Array([255]));
  log(" - Starting listener
");
  tx_data.addEventListener('characteristicvaluechanged', e => {log (e.value)});
  tx_data.startNotifications();
}

This runs without error and appears to establish a bluetooth connection on my client android device.  I expect the server to respond to the connection, trigger an event and report it back.  No such connection event occurs.
I am new to web bluetooth and a little rusty with JavaScript, so unsure whether I am using the correct calls - particularly for 'subscribing'.  If anyone could clarify what subscribing involves in this context it would certainly help my understanding.
Edit:
I was able to get the connection running once I figured out how the Terminal I/O connection instructions translate to JS.
I performed these steps like this:
"For the retrieved Terminal I/O service, the Terminal I/O client performs a characteristics discovery."
let tx_credits = await service.getCharacteristic(UART_TX_CREDITS_UUID)
let tx_data = await service.getCharacteristic(UART_TX_UUID)
let rx_credits = await service.getCharacteristic(UART_RX_CREDITS_UUID)
let rx_data = await service.getCharacteristic(UART_RX_UUID)

"The Terminal I/O client subscribes to indications of the UART credits TX characteristic (see 7.4)."
await tx_credits.addEventListener('characteristicvaluechanged', e => {log ("
tx_credits: " + e.value)});
await tx_credits.startNotifications();

"The Terminal I/O client subscribes to notifications of the UART data TX characteristic (see 7.2)."
await tx_data.addEventListener('characteristicvaluechanged', e => {
  for (i=1;tx_data.value.getUint8(i);i++){
    log(String.fromCharCode(tx_data.value.getUint8(i)))
  }
}
await tx_data.startNotifications();

"The Terminal I/O client transmits initial UART credits to the server (see 7.5)."
let rx_credit_level = await rx_credits.writeValue(new Uint8Array([255]))

Answer: You may want to await writeValue and startNotifications.
...
log(" - Requesting credits
");
await tx_credits.writeValue(new Uint8Array([255]));
log(" - Starting listener
");
tx_data.addEventListener('characteristicvaluechanged', e => {log (e.value)});
await tx_data.startNotifications();

Comment: That certainly helped.  The problem really rested on getting all the right steps done in the right order - and I needed to add some extra steps before my device registered a connection.


rsync --files-from equivalent

Question: I'm attempting to back some stuff up from a server that runs an old version of rsync - for various reasons I can't just upgrade the software.
Usually, I'd use --files-from and give a list of files and directories to back up, but this version of rsync doesn't have that switch.  Is there a way, with other switches, to make an older rsync behave the same way?
I've tried a combination of --include-from= --exclude=* but that looks to be insufficiently recursive (eg. /etc/* only backs up things directly below /etc).
Answer: I suspect that xargs is your friend in this instance.
Completely untested:
 # cat file | xargs -IREPLACE rsync -v REPLACE server:/path

xargs will take data from stdin and add it to the commandline one parameter per input line until it fills the command line length, and then runs a separate command until all the input lines have been used up. This will mean that rsync could well run more than once. This shouldn't be a problem in this case, but could be with other commands.
Usually xargs just sticks the arguments on the end of the line, but with rsync you'd want to have the destination last, so we use the -I option to replace a string with the arguments. (This is the bit that's untested). I'm also a little unsure what rsync will do with the paths, so please test this carefully before using it in anger.
If you do have a problem with xargs, you could use something like:
for i in $(cat file); do rsync -v $i server:/path; done

If your file is larger, you probably want to use a while/read loop instead. This will be much slower as it will do a single file at a time.
Comment: It would be a problem if the rsync runs more than once, since some files will be copied that are meant to be excluded.
Comment: Only if the list of files overlap with each other, i.e. if you had a directory and a list of files in that directory.
Answer: If your includes/excludes aren't recursing, perhaps you haven't specified -r?  If you're used to using --files-from then you might have gotten out of the habit.
Apart from that, giving the exact command you're using might help.  include-from/exclude-from definitely recurse nicely for me.
Answer: Silly no nonsense solution I've had to use before on some servers when rsync alone doesn't want to place nice. Use tar to only grab files you want:
cat INCLUDES
/home/user/index.htm
/home/user/robots.txt

tar cf INCLUDES.tar INCLUDES
for file in `cat INCLUDES`; do tar -r --file=INCLUDES.tar $file; done

rsync -avzP INCLUDES.tar email@example.com:./remote_path

--- Now on remote server

mkdir INCLUDES
tar xf INCLUDES.tar -C ./INCLUDES
rsync -avzP INCLUDES/home/user/ /home/user/

rsync --files-from equivalent


Is the new Documentation feature (beta) for Stack Overflow offered to community StackExchange sites like ours?

Question: There already appears to be something kicked off over at Stack Overflow for Magento, but it would seem like our Magento Stack Exchange site would be the ideal place for this to exist vs. there...
Has the Stack Exchange community engagement team reached out to any of our Moderators to discuss this?  I hate to see effort wasted and it also feels like we might be an ideal candidate for beta-testing this feature given Magento's recently emphasized transparency and support of the Magento Dev Docs effort...
After digging into this a bit more I've discovered @7ochem has a related post on the newly established Magento SO Documentation Beta Site
Comment: I think it was a @7ochem initiative I hope hell be able to enlight you
Comment: Thanks for that update, Raphael - I've updated the post with a link to @7ochem meta post
Answer: I'm not 100% sure about this, but I think that the documentation feature is available only for the mothership website.
I randomly clicked on a few websites in here and none of them have this feature.
My bet (read hope) is that when this feature gets out of beta it will be available for some websites in the SE network.
But to answer your question, no, nobody reached out to the moderators for this.
Comment: Happy birthday then, and have fun at MT USA. Say hello from me to the people there.
Comment: Thanks for digging into this for us, Marius! I'll follow up when I return home from MageTitans USA and see what I can dig up. This helps and is enough for me to get back to celebrating my 40th birthday with our #RealMagento community down in Austin, TX.
Answer: Sorry, have been away for a full month :D
The Documentation site is a separate site within the StackExchange network and is not only a sub-site for StackOverflow (although it is located there). It can facilitate documentation on all kinds of topics (as you can see) from big names like PHP/.NET/SQL/Java to "never-heard-of-it" stuff like Jekyll/lodash/zeromq. Documentation sections (tags) are created by the community and thus I've proposed a Magento tag/documentation.
So what is the Documentation's place in all that's Magento? There's Magento SE for specific Q&A and there's the Magento official Docs for basic walk-through style reads. Documentation falls in between, with an overlap here and there. Documentation is all about giving many examples on general cases. So it is not as specific as Q&A, and where the official docs may lack examples on every use case, the SE Documentation site can provide that.
Also it allows for examples of full modules, something that will be flagged as too broad here on the Q&A.
In addition to that, you are encouraged to link to the documentation sections. This will the writer/contributer of a documentation topic a reputation bonus for being referenced (cited): https://stackoverflow.com/help/whats-reputation (look for "cite")
There's a lot of meta discussions on the new Documentation site, so feel free to browse https://meta.stackexchange.com/ for it


Mixed logistic ridge regression

Question: I would like to build a logistic regression model in which I will be looking for predictor variables having a significant effect on the breeding success of a raptor bird.
The predictors in the dataset are highly correlated, which led me to consider logistic ridge regression. Furthermore, I investigated different breeding grounds in which one or multiple birds have been breeding. Since this makes the data clustered, I would need to add the breeding ground as a random effect in the model.
Thus, I would need a 'mixed logistic ridge regression' approach if I am getting things right here. This paper suggests this approach too for another problem:
http://www.ncbi.nlm.nih.gov/pubmed/22049265
Are there any people aware of the availability of an R package or something related having implemented a mixed logistic ridge regression approach as the paper and myself just described? I did not succeed in finding one.
Thank you.
Comment: `library("sos"); findFn("lasso mixed")` and `findFn("ridge mixed")` are pretty good starting points ...
Answer: There is an R package named glmmLasso that performs variable selection and shrinkage for generalized linear mixed models using the L1 penalty (the Lasso):
http://cran.r-project.org/web/packages/glmmLasso/index.html
The Lasso isn't the same as ridge regression (which uses the L2 penalty) but will still perform shrinkage of coefficients for correlated variables.
Comment: In addition to the papers referenced in the glmmLasso documentation, there is this 2011 study which incorporates ridge regression with linear mixed effect models (alas not logistic regression): http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3202941/. Maybe the same approach could be used with logistic regresion?
Comment: That's correct, Robert. I found the paper too. I also agree this same approach could be used with logistic regression. However, I am afraid that it has not yet been implemented in any R package.
Answer: This might do what you want:
http://cran.r-project.org/web/packages/ridge/index.html
From the description:

Linear and logistic ridge regression for small data sets and genome-wide SNP data
Comment: This is not what I need as it cannot incorporate random effects in the model.

Mixed logistic ridge regression


Find if an array exists in dict and is not empty

Question: I want to check if an element exists in my JSON input and it looks that the code snippet below works
import json
y = {
    "attributes": [
        {
            "name": "test"
        }
    ]
}

p2 = json.dumps(y)

if 'attributes' not in p2:
    print("not found")
else:
    print("found")

I would now want to check if the attributes element is of type list and the list size
What is the pythonic way to achieve this?
Comment: `type(y['attributes']) == list` will work
Answer: The result of json.dumps is a JSON-formatted string, so if you were to search p2 you would have to do some kind of string matching. I.e. 'attributes:[' in p2 would match is somewhere in your JSON there is an "attributes" key name followed by an array. This solution isn't ideal though as it doesn't handle the case when your JSON string is formatted differently (e.g. with an indent).
The pythonic way is to check y itself, like the other answers suggest. Namely
('attributes' in y)  # True because it exists
(isinstance(y['attributes'], list))  # True because it's a list

The most pythonic way would be simply to assume it's a list and handle a failure if you hit one.
I also wanted to add a quick shoutout to the Marshmallow serialization library. It is intended to handle more sophisticated schema validation tasks, but you could apply it here as well to validate that the attributes field exists and it maps to a list. I.e.
y = { ... }  # like before...

from mashmallow import Schema, fields
class AttributesList(Schema):
    attributes = fields.List(fields.Dict())

al = AttributesList()
al.dumps(y)

Answer: use isinstance() to check the type, it will return boolean
y = {
    "attributes": [
        {
            "name": "test"
        }
    ]
}

# p2 = json.dumps(y)

if 'attributes' not in y:
    print("not found")

else:
    print(y['attributes'])
    print(isinstance(y['attributes'], list))
    if isinstance(y['attributes'], list):
        print('its a list')
        print(len(y['attributes']))
    print("found")

output:
[{'name': 'test'}]
True
its a list
1
found

Answer: In your code snippet p2 is a string (json.dumps converts y to a valid JSON object in a string)
isinstance is the preferred way to check so you would use:
if isinstance(y['attributes'], list):
    len(y['attributes'])

Answer: json_data = json.dumps({
    "attributes": [
        {
            "name": "test"
        }
    ]
})

item_dict = json.loads(json_data)
print(type((item_dict['attributes'])))    # list
print(len((item_dict['attributes'][0])))     # 1


Affine local property of reducedness

Question: Suppose $X$ is a scheme, and $\operatorname{Spec}A$ is an affine open sunset of $X$ with $(f_1\dots f_n)=A$. Then $\bigcup_{i=1}^n \operatorname{Spec}A_{f_i}=\operatorname{Spec}A$. Further assume that each $\operatorname{Spec}A_{f_i}$ is reduced, where we define reduced to mean that $\mathcal{O}_{\operatorname{Spec}A}(U)$ has no nonzero nilpotents for every open subset $U$ of $\operatorname{Spec}A$. I'd like to understand why this means that $\operatorname{Spec}A$ is also reduced.
So let $U$ be an open subset of $\operatorname{Spec}A$. Then $U$ is the union of some of the $\operatorname{Spec}A_{f_i}$. Then perhaps we could look at the restriction map $\mathcal{O}_{\operatorname{Spec}A}(U)\rightarrow \mathcal{O}_{\operatorname{Spec}A}(\operatorname{Spec}A_{f_i})$. However, I am not sure where to go from here. If we have some nilpotent $f\in\mathcal{O}_{\operatorname{Spec}A}(U)$, then this restricts to an element in a reduced ring.
Comment: The issue isn't that your definition isn't standard (this definition is standard). The issue is that if you don't include your definition, it's difficult to give you a good answer. If I use an alternate definition you don't know yet without explaining how it connects to what you know, that's going to require some extra work (you comment, I comment, you comment, I edit, etc) to straighten everything out. It's best to avoid this by putting the relevant definitions in your post to start with.
Comment: What's your definition of reduced? One standard definition is that all the stalks are reduced, which would resolve this pretty quickly.
Comment: @KReiser So then the stalks of each $\operatorname{Spec} A_{f_i}$ are reduced, and so any section of an open set of $\operatorname{Spec} A_{f_i}$ contains no nilpotents. But what about a general open set $U$ of $\operatorname{Spec} A$? I know it's a union of the $\operatorname{Spec} A_{f_i}$'s, and so any section on $U$ can be restricted to a section on the stalk due to the definition you give, and since these are reduced, $U$ is as well?
Comment: The definition I'm using isn't important here, the definition *you're using* is. Please add this to the post. What exactly is your definition of reduced?
Comment: @KReiser I have added the definition. I didn't realize it was nonstandard.
Answer: Exercise: $X$ being reduced (in the sense that $\mathcal{O}_X(U)$ is a reduced ring for all open $U\subset X$) is equivalent to $\mathcal{O}_{X,x}$ being reduced for all points $x\in X$.
Hint/Solution outline:

 For $\Rightarrow$, consider what would happen if you had a nonzero nilpotent in the stalk and derive a contradiction. For $\Leftarrow$, embed $\mathcal{O}_X(U)$ in the product of it's stalks.

With this in hand, since the stalk at $\mathfrak{p}\in\operatorname{Spec} A$ is the same as the stalk at $\mathfrak{p}_f \in\operatorname{Spec} A_f$, we have the result immediately.
Comment: +1, definitely the right way to do things. If one doesn't mind reinventing the wheel a little bit, then you can argue explicitly with a partition of unity argument. Namely, suppose $x \in A$ is a nilpotent element. Then $x$ is likewise nilpotent in each $A_{f_{i}}$, hence $0$, so it follows that there exists $k_{i} \in \mathbb{N}$ such that $xf_{i}^{k_{i}} = 0$. Since $(f_{1}^{k_{1}}, ..., f_{n}^{k_{n}}) = A$, there exist $y_{1}, \ldots, y_{n} \in A$ such that $f_{1}^{k_{1}}y_{1} + \cdots + f_{n}^{k_{n}}y_{n} = 1$. Multiplying both sides by $x$, we conclude $x = 0$.

Affine local property of reducedness


Reconnecting to a Mapped Drive after Server Restart from within PowerShell Script

Question: I have a PowerShell v1 script that connects to a remote server via a mapped drive and moves files back and forth the remote server is identified by drive number "M" and also by UNC path REMOTESERVER\DATA:
(M:) \\REMOTESERVER\DATA

When the remote server reboots, I think that I am screwed because now the mapped drive will be inaccessible by the script.
How is this situation handled programmatically from within a PowerShell script?
Is there a way to reconnect to the mapped drive by writing some PowerShell code?
The issue is not when the mapped drive actually disappears, it is that after reboot, authentication is needed and Windows apparently will not remember that.
Just curious how this is accomplished?
Answer: There are a couple of ways. First, you could map the drive on the server using the net use command with the /persistent switch for the drive to remap at logon. Next, specifically in powershell you could map the drive using the new-psdrive cmdlet and just refer to the drive that way, you wouldn't even need a drive letter.
If you go with the second option I would either make sure whatever context the script is running under has permissions to the share, or if that's not possible then there is a way where you can store the credentials needed encrypted in a text file so that they can be imported by the script when needed, but as a word of caution the encryption is reversible, in case someone who is crafty and willing enough gets ahold of your script.
http://technet.microsoft.com/en-us/library/hh849829.aspx
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/net_use.mspx?mfr=true


Erro ao tentar rodar aplicação JSF

Question: Galera estou começando a estudar JBoss, Maven, etc. Porem quando vou executar uma pagina que criei para testes aparece esse erro:
Could not find backup for factory javax.faces.context.FacesContextFactory

No meu projeto tenho um diretório chamado Maven Dependencies e dentro dele está o .jar javax.faces-api-2.2.jar Alguem sabe o que pode ser? Obrigado
Comment: primeiramente, você se você está no JBoss, você não pode empacotar junto da sua aplicação qquer jar referente ao JSF pois ele já está disponível dentro do própio JBoss. No maven, coloque o JSF como provided, restarte sua aplicação, e diga se o erro continua o mesmo. Seria bom também você editar a pergunta e colocar seu faces-config.xml, pom.xml e web.xml.
Comment: Era isso mesmo, coloquei o provided e deu certo. Poste esse comentário como resposta para que eu marque como solução
Answer: Se você está no JBoss, você não pode empacotar junto da sua aplicação qualquer jar referente ao JSF pois ele já está disponível dentro do própio JBoss (Ver neste link recursos disponíveis dentro de um container JEE 6). No maven, coloque o JSF como provided:
<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.2.0</version>
    <scope>provided</scope>
</dependency>

Erro ao tentar rodar aplicação JSF


WSO2 ESB applying security policies at binding hierarchy

Question: I am trying to apply multiple security policies to a proxy service defined in WSO2 ESB 4.0.3.
I need to apply one policy at operation level and other at message level.
I  am using source view to directly define proxy service instead of using Web UI/Policy Editor.
I tried defining each policy as described here:
http://docs.wso2.org/display/ESB403/Policies+for+Service
but generated WSDL shows it is getting applied at wrong hierarchy.
Please advice if this capability is supported in WSO2 ESB or am I doing wrong!
My Proxy
<proxy name="StockQuoteProxy" transports="https http" startOnLoad="true" trace="disable">
    <target endpoint="SimpleStockQuoteService_noSuspendOnFailure_TCPMon">
        <inSequence>

        </inSequence>
        <outSequence>
            <send/>
        </outSequence>
    </target>
    <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_3.wsdl"/>
    <policy key="sec_operation-Policy"/>
    <policy key="sec_InOut-Policy"/>
    <enableSec/>
</proxy>

My message level Policy
<wsp:PolicyAttachment wsu:Id="Service_message_policy_attachment"
            xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
            xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
            xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:AppliesTo>
<policy-subject identifier="binding:soap11/operation:getQuote/in"/>
<policy-subject identifier="binding:soap12/operation:getQuote/in"/>
</wsp:AppliesTo>
<wsp:Policy wsu:Id="Service_message_policy">
    <wsp:ExactlyOne>
        <wsp:All>
            <sp:SignedParts>
                <sp:Body />
               <sp:Header Name="To"
                  Namespace="http://www.w3.org/2005/08/addressing" />
               <sp:Header Name="From"
                  Namespace="http://www.w3.org/2005/08/addressing" />
               <sp:Header Name="FaultTo"
                  Namespace="http://www.w3.org/2005/08/addressing" />
               <sp:Header Name="ReplyTo"
                  Namespace="http://www.w3.org/2005/08/addressing" />
               <sp:Header Name="MessageID"
                  Namespace="http://www.w3.org/2005/08/addressing" />
               <sp:Header Name="RelatesTo"
                  Namespace="http://www.w3.org/2005/08/addressing" />
               <sp:Header Name="Action"
                  Namespace="http://www.w3.org/2005/08/addressing" />
            </sp:SignedParts>
            <sp:EncryptedParts>
                <sp:Body />
            </sp:EncryptedParts>
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>
</wsp:PolicyAttachment>

Comment: This functionality is of course supported. May be you have missed something or seeing a bug. To clarify, by "operation level" you meant binding operation level, right?
Comment: I was trying to find a way to apply multiple security policies to different policy-subjects without manually editing through WSO2 ESB policy editor.  I was expecting there may be a way to define it through Synapse Configuration Language.
Answer: This is supported by WSO2 ESB.
Actually the problem is with the message level policy that you are trying to engage. You are trying to provide a Policy Attachment element, not a policy element. This approach works if you are trying to engage multiple policies to an Axis2 service through its services.xml. But if you are using the Carbon policy editor, it expects you to provide a valid policy element.
Following policy element can be derived from the policy attachment element you have used.
<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Service_message_policy">
    <wsp:ExactlyOne>
        <wsp:All>
            <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <sp:Body />
                <sp:Header Name="To" Namespace="http://www.w3.org/2005/08/addressing" />
                <sp:Header Name="From" Namespace="http://www.w3.org/2005/08/addressing" />
                <sp:Header Name="FaultTo" Namespace="http://www.w3.org/2005/08/addressing" />
                <sp:Header Name="ReplyTo" Namespace="http://www.w3.org/2005/08/addressing" />
                <sp:Header Name="MessageID" Namespace="http://www.w3.org/2005/08/addressing" />
                <sp:Header Name="RelatesTo" Namespace="http://www.w3.org/2005/08/addressing" />
                <sp:Header Name="Action" Namespace="http://www.w3.org/2005/08/addressing" />
            </sp:SignedParts>
            <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <sp:Body />
            </sp:EncryptedParts>
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>

Hope this helps !
Answer: You can edit the policy through policy editor to apply the policy to different policy subjects in the binding hierarchy. You may refer to Securing request and response messages with different security policies which walks though a sample that demonstrates how to apply different security policies to in and out messages.
This sample directly edits the services.xml of an axis2 service.
You will get the same effect if you change the policy through policy editor of ESB and save.
If it still doesn't work for you, please attach the edited policy.xml and the resulted wsdl which will help to provide more insight into the issue.
Comment: Thank you for point me to the right example. I am trying to accomplish  similar multi-policy binding for each endpoint references(EPR) in a single WSDL which is exposing a backend secured web service through WSO2 ESB. Using ESB, I want to modify and route incoming  requests to appropriate backend service endpoint based on the  incoming  security token(UT or X509).

The goal is to configure my STS proxy that will expose WSDL similar to following WSDL
    http://svn.apache.org/repos/asf/cxf/trunk/services/sts/sts-war/src/main/webapp/WEB-INF/wsdl/ws-trust-1.4-service.wsdl
Comment: I noticed WSO2 ESB generate proxy endpoints automatically(http https soap sopa12). How do I control the generation of those endpoints? In my case I need one for each policy and all should be HTTP.

---
From your explanation, I understand that it is not possible to apply multiple security policies to different policy subjects in the binding hierarchy using Synapse Configuration Language. I will try it through policy editor.
Answer: After doing some research, I found some potential solutions and like to share with you.
Problem 1: Unable to apply security policies  at granular level.
Solution :
I was able to apply security policies  at
1.) root level
2.) operation level and
3.) message level
using operationName & operationNamespace
<proxy name="StockQuoteProxy" transports="https http" startOnLoad="true" trace="disable">
    <target endpoint="SimpleStockQuoteService_noSuspendOnFailure_TCPMon">
        <inSequence>

        </inSequence>
        <outSequence>
            <send/>
        </outSequence>
    </target>
    <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_3.wsdl"/>

    <policy key="sec_SigOnly"/>

    <policy key="SigEncrSTS" operationName="getFullQuote" operationNamespace="http://services.samples"/>

    <policy key="sec_InOut-Policy" operationName="getQuote" operationNamespace="http://services.samples" type="in"/>
    <enableSec/>
</proxy>

Problem 2: when a proxy service is deployed,  published WSDL is automatically generated and we have limited/no control to customize it.
Solution :
Using  Property useOriginalwsdl,  I was able to publish original supplied WSDL with only IP/Port changed  to Proxy IP/Port.
<proxy name="STSProxy" transports="https http" startOnLoad="true" trace="disable">
    <target endpoint="PingSTS_UT">
        <inSequence>
            <property name="preserveProcessedHeaders" value="true" scope="default"/>
            <log level="full"/>
        </inSequence>
        <outSequence>
            <send/>
        </outSequence>
    </target>
    <publishWSDL key="wsdl_sts"/>
    <parameter name="useOriginalwsdl">true</parameter>

I wish WSO2 support to apply both of those solutions at the same time. i.e., able to control how published WSDL is generated and apply security policies at granular level.
PS:  When Security Polices are applied by directly editing in Source View, the UI is still showing Unsecured . it will only show Secured when built-in security policies are applied through Web UI or the policy name match to one of the built-in policy


Plugged my US(110v) Fender Rumble into EU(240v) socket

Question: For reasons I wont go into I accidentally fried my amp.
My question: Is it possible to fix? I know sometimes the Power transistor 'blows'.
At the moment the LED doesn't even light up.
I'd like to replace whatever it takes rather than just buy a new one.
Can anyone guide me on how to resistance check from the power plug forward to the power transistor or is it nigh on impossible to do this ?
Comment: First check any internal fuses.
Answer: There's going to be a few components between the mains input and the power transistor!   With any luck, the first thing you'll find after the power socket is a fuse.  With even more luck, it's blown - and that's ALL that's blown.  Beyond that, take it to a repair shop.  It'll be cheaper in the end.
Answer: You're confusing transistor with transformer! A transistor amplifies, the power transistors in an amp are near the very end of a long and complicated circuit.
The first thing the mains power hits when you plug it in is a transformer that separates the mains voltage into the 2 or 3 different voltages the amp will run off. This is the thing that was expecting 110v but you gave it 230v.
As others have said, with any luck there will be a fuse, likely a glass one, in that initial loop between the mains input, on switch and transformer 'primary' coil. SOME modern amps have an annoying fuse built into the transformer which is next to impossible to replace. Hopefully you don't have that and can see a glass fuse in a little holder somewhere near where the power comes into the amp. When checking this make sure the amp is fully unplugged. This part of the circuit is live with mains voltage whenever it's plugged in, even if the amp is switched off.
If you can see it's blown look for the rating stamp on one end of it. It will probably say something like 250v T2a or similar. The 250v is nothing to do with uk or us mains, it just means that if it blows it will guarantee breaking the circuit up to 250v. The important thing to match is the amp rating (eg. 2a or 2A), replace with exactly the same. Note the T next to the amp rating. T means timed, also called slow-blow, meaning it won't blow when you get a brief spike of current when you turn the amp on, if it doesn't say T it's just a normal medium speed fuse. You also see F which means fast acting, and other markings which, if you come across, are worth a Google, but in that part of the circuit it'll probably just be a T.
It's easy enough to find glass fuses in all specs all over the web, just make sure you replace with EXACTLY the same fuse. Failure to do so will result in the fuse instantly blowing again, or the amp potentially frying itself to death being allowed to run in a fault condition without the fuse doing its job.
If the fuse blows again, or the amp still doesn't work then it is not something you will be able to fix on your own. Conventional wisdom says suspect the transformer last, but in truth that's mainly because diagnosing a transformer fault is not straight forward, and a new transformer is expensive and requires skill to fit. Ie, exhaust all other possibilities before trying to diagnose a faulty transformer. To exhaust all other possibilities you need to be good at safely testing rail voltages when the amp is open and turned on, DO NOT DO THIS unless taught how to do it safely and probably under observation the first few times.
Transformers don't have a huge amount you can test them on, they are two (or a few more) coils of wire with relatively low resistance per coil when working, when blown they appear much the same, the only way you can tell from a resistance reading that your 18 Ohm primary coil is shorted is knowing that before it was shorted it used to read 24 Ohm. Transformers come in a vast array of types, usually fairly bespoke to a particular family of amps from a manufacturer, there's no standard reading you can expect to measure without having the exact data sheet of the transformer you have.
A lightbulb limiter is often used 'in the trade' to diagnose a faulty transformer but you have to make that and get to know how to read its behaviours. Failing that you just have to get a schematic, identify the two primary wires and the 3-10+ secondary wires (and which ones are paired, or have centre tap), disconnect it all from the circuit and test you're getting the expected input and output voltages. Again this is dangerous, sometimes complicated work, and you have to put it back together correctly or it will definitely fry something.
In short, check the fuse, if it's not that, take it to a good tech! It's unlikely to be completely ruined, though if it comes to a new transformer it could be an annoying bill.


What does it mean to have (or not have) convicing evidence in statistics?

Question: I know how to calculate the confidence intervals for proportions and means at various confidence levels.
I'm having trouble when I'm asked to say whether there is (or isn't) convincing evidence as to whether a claim is true.
The question does not require knowledge of hypothesis testing, so I have to say whether there is (or isn't) convincing evidence that a claim is true using the confidence interval. In other words, I have to use the confidence interval to evaluate a claim.
For example, I have a confidence interval of (0.5, 0.6) at the 95% confidence level for some proportion. If someone claims that the proportion (of apples falling from a tree or something) is more than 0.55, how do I know whether there is (or isn't) convincing evidence that this claim is true?
Another question. Confidence level is 95% and confidence interval is (0.5, 0.6) for some proportion. Someone claims that the true proportion (of getting into a car accident or something) is more than 0.3. How do I know whether there is (or isn't) convincing evidence that this claim is true?
Yet another question. Let's say confidence level is 95% and confidence interval is (10, 15) for some mean. Someone claims that the true mean is different than 12. How do I know whether there is (or isn't) convincing evidence that this claim is true?
Another one. Let's say confidence level is 95% and confidence interval is (10, 15) for some mean. Someone claims that the true mean is 12. How do I know whether there is (or isn't) convincing evidence that this claim is true?
Statistics is, I think, a very carefully worded subject. What the "convincing" evidence exactly mean? Does it mean that there's "enough" evidence?
And another question. Does statistically significant mean that the value I'm looking at is "significantly different" from what I would normally get (values in the confidence interval)?
I apologize for asking so many questions at once. I've been grappling with these concepts for too long that I gave up and decided to post the questions here.
Answer: The word "convincing" is not standard statistical wording, but rather subjective. You may have a lecturer who taught you how to use it, but that would be their personal usage really. Some people use specific different wordings depending on the test or confidence level, i.e., "there's some evidence that a mean is not 0" if it is rejected at 5% or - equivalently - it isn't in the 95% confidence interval (CI), "strong evidence" at 1%/99% etc. Probably you were taught to use "convincing" for a certain level, but that's not a standard.
What can be said is that the CI is a set of parameter values that are all compatible with the data (at the given level). So for example if the CI is (10,15), surely there can't be "convincing evidence" that the mean is 12, because it might well be 13 or 10.2 or 14.8. Same if the CI is (0.5,0.6), the true mean can well be 0.52, so this doesn't give you evidence that it's >0.55. However, means lower 0.3 would, at level 95%, not be compatible with the data, so yes, one can say there's evidence (with whatever additional word your lecturer would like to use) that the true mean is larger than 0.3.
"Significant" would normally refer to significance tests, however there is a mathematical correspondence between tests and CIs, so if the 95% CI is (0.5,0.6), this also means that a standard 5% test of the null hypothesis mean=0.3 would be rejected, so the mean is significantly different from 0.3.
However we've got to be careful not to put too much trust in words. For example, if you compute 100 CIs at level 95%, chances are on average 5 of them will not include the true value, so one shouldn't say every single one provides "convincing" or "enough" evidence - one shouldn't be too convinced that they all cover the true value. And then all this is based on model assumptions which in reality are not normally true (one may wonder whether a "true" mean that is not directly observable even exists), and then there's more than one way to test the same hypothesis and different tests may give you different results. Sorry for making things even more confusing but you've got to accept, indeed, statistics is difficult (and asking questions like you do is a good start).


How to consolidate data for a row before adding it using Datagridview.rows.add()?

Question: I bumped into this problem because I would like my code to work even though I have added new columns to the source.  My code adds a row based on the number of rows of the source.  My code lacks the ability to consider the number of columns.  Here is my code:
For Each srow As datagridviewrow In mytempDG.Rows
   dataGridView1.Rows.Add(srow.Cells(0).Value.tostring, srow.Cells(1).Value.tostring, _
   & srow.Cells(2).Value.tostring, srow.Cells(3).Value.tostring,srow.Cells(4).Value.tostring, _
   & srow.Cells(5).Value.tostring, srow.Cells(6).Value.tostring)
Next

The code above works okay given that I have 7 columns from tempDG (which is my datasource btw).  But what if I have added two more columns (which makes it 9).  I would then have to edit the code from the source (add "srow.cells(7).value.tostring, srow.cells(8).value... etc")
I know how to loop through the column but I do not know how to convert it to a data that can be read by rows.add function.  This is what I've tried so far:
Dim finrow As List(Of String)
finrow = New List(Of String)

For Each srow As datagridviewrow In mytempDG.Rows
   finrow.clear
   For Each scol As DataGridViewColumn In mytempDG.Columns
      finrow.add(srow.Cells(scol.Index).Value.ToString)
   Next
   dataGridView1.Rows.Add(finrow)
Next

How can I create a collection of data first before adding it using the rows.add() function?  Also may I know what kind of data is needed by rows.add()? I am assuming it is a list of values (in my case, I used List(of String)).
Thank you guys in advance and have a nice day!
Answer: You can supply an array of object to the Add method of the DataGridView:
For Each srow As DataGridViewRow In mytempDG.Rows
   Dim obj(mytempDG.Columns.Count) as Object
   For col as Integer = 0 to mytempDG.Columns.Count - 1
       obj(col) = srow.Cells(col).Value.ToString()
   Next
   dataGridView1.Rows.Add(obj)
Next

I'm assuming myTempDG is a DataGridView, in that case you can cast the rows of the myTempDG to an array of DataGridViewRow and then AddRange:
Dim rows() As DataGridViewRow
rows = myTempDG.Rows.Cast(Of DataGridViewRow)().ToArray
dataGridView1.Rows.AddRange(rows)

Comment: 'Cast' is not a member of 'System.Windows.Forms.DatagridviewRowCollection'.. I've also tried casting from a datarow.. cast is also not a member as per error
Answer: OK I GOT IT
Dim numcol As Integer = mytempDG.Columns.count
Dim finrow(numcol) As String

For Each srow As datagridviewrow In mytempDG.Rows
   For Each scol As DataGridViewColumn In mytempDG.Columns
      finrow(scol.Index) = srow.Cells(scol.Index).Value.ToString
   Next
   dataGridView1.Rows.Add(finrow)
Next

But it seems a little slow..
This is much better.. after considering to not transfer the dataset to tempDG..
For each xrow as DataRow in ds.Tables(0).Rows
   datagridview1.Rows.Add(xrow.ItemArray)
Next

Comment: Have you tried setting the `Datasource` of `datagridview1`? `datagridview1.DataSource = ds` This will copy the dataset rows into the dgv.


Sequence $\{f_n\}$ of Lebesgue-Integrable functions which converges to Lebesgue-Integrable function $f$ but $\int f\neq \lim_{n\to\infty}\int f_n$

Question: I want to find some sequence $\{f_n\}$ of Lebesgue integrable functions on an interval $I$ such that the pointwise limit exists almost everywhere on $I$, the limit function $f$ is Lebesgue-integrable on $I$ but:
$$\int_I f \neq \lim_{n\to\infty}\int_I f_n.$$
In Dominated Convergence Theorem we have that if $f_n$ is dominated by some Lebesgue integrable function $g$ we don't even need the hypothesis of $f$ being Lebesgue-Integrable. But what happens if we add it but remove the hypothesis of $g$ dominating the sequence?
Comment: Let $f_n=n1_{[0,1/n]}$, then $f_n$ conveges to $f=0$, but $\int f_nd\mu=1$.
Answer: Let the underlying space be $(0,1)$ with Lebesgue measure. Let $f_n=n\cdot 1_{(0,1/n)}$. Then $f_n\to 0$ pointwise, but $\int_0^1 f_n=1$.
Comment: You mean pointwise a.e.
Comment: @zhw. Corrected, thanks.
Answer: You can always look at the classical $f_n(x) = nx^n$ on $(0,1).$
Answer: For an example consisting of continuous functions on a closed interval and pointwise convergence everywhere (to a continuous function), consider $f_n:[0,1]\to \mathbb{R}$ given by a graph of a triangle with one foot on $0$, basis $\frac{1}{2^n}$ and height $2^n$, and $0$ everywhere else.


phpMyAdmin says mcrypt is missing, but it's not; cannot log in

Question: I've just compiled a web stack on Solaris 10.  This is a fairly standard Apache 2 / MySQL 5 / PHP 5 stack with all the most recent stable versions.  I dropped phpMyAdmin on the server and set up httpd.conf to get that online.  When I browse to the page, login fails, and a persistent message appears beneath the login form:

The mcrypt extension is missing. Please check your PHP configuration.

However, I compiled PHP with the --with-mcrypt flag.  A file, info.php:
<?php phpinfo(); ?>

shows that mcrypt support is enabled.  Running:
php -m

on the command line shows that mcrypt is loaded.
Google hasn't been much help, and I was hoping someone around these parts could throw some help my way.  If I need to provide any further detail, please let me know what you need to know.
Comment: What does `php -i | grep "^mcrypt"` say?
Comment: Also verify that you have `libmcrypt` (not a PHP dependency).  The documentation also mentions that it should be compiled [without posix threads](http://www.php.net/manual/en/mcrypt.installation.php).  This may affect Apache, but not the CLI, so it may be worth checking.
Answer: Compiling php with mcrypt support is not the same as actually installing mcrypt.  In your phpinfo() what does it say about supported ciphers and modes?  If it shows "none" for both of those, then your php is ready for mcrypt but the actual extension itself is not installed.
You'll want to download, and build libmcrypt with --enable-dynamic-loading.  Once that's done, and the actual mcrypt extension is in place, then you should see some changes in the mcrypt portion of phpinfo();


What's the primary differences between CLI and tf.exe command line in TFS?

Question: There has been a powerful tf.exe command line tool in TFS. Why do we need this new command line?

What's the main function and advantage of it?
Since the command line is using VSTS xxx, does this feature also have support for on-premise TFS?
Is this similar to Azure CLI?
Comment: Which version of TFS are you working on?
Comment: @Jane Please update your question with proper details as well as add more specific tags
Comment: Working on TFS2017 update3.
Answer: CLI is a new cross-platform command line interface, which great for interactive use or for scripting. As a developer you can use it for your everyday workflows, like creating pull requests, opening bugs, and more. Bash, PowerShell, etc. users can easily incorporate the VSTS CLI in their scripts.

Here are a few of the highlights:

Supports VSTS and TFS (2017 Update 2 and later)
Runs on Windows, Linux, and macOS. It is also available as a Docker image, which lets you run VSTS CLI almost anywhere. See the vsts-cli
  Docker repo.
Integrates with the Git CLI. Once you enable Git alias support via the vsts configure command, you can create a VSTS pull request (and
  perform other Git related operations) by typing: git pr create. If
  the current directory is a local Git repository connected to VSTS (or
  TFS), no other arguments are required. Learn more about using VSTS
  CLI with Git.
Natural for Azure CLI users. If you already use the new Azure CLI, you will feel right at home with the VSTS CLI. Both are built on the
  same platform and are designed to feel natural for users that love
  command line.
Open source on GitHub. We invite you to open issues and suggest new commands. Visit the vsts-cli repository.

More info to get started, please see the VSTS CLI documentation on learn.microsoft.com.
As for tf.exe command, the full name is Team Foundation version control commands.  You can use version control commands to do nearly all tasks you can do in Visual Studio, and also several tasks that can't be done in Visual Studio. You can use the tf.exe tool to run version control commands from a command prompt or within a script. However, you couldn't use it for a Git repository and area.


Guitar held flat? how is this way of guitar playing called?

Question: The boy on the right keeps the Guitar in a different way than usual. I wonder how you call this style.
Comment: I just googled using your search terms. First result is "lap style"
Comment: Emmett's playing slide on a dobro. It looks like it has a square neck and super-high action. This guitar would not be playable in traditional guitar style: it's specifically made and set up for lap slide. Another search term is "lap steel"
Comment: Lap guitar.....
Comment: Can you say where in that video we could see this boy?  I can't bear to listen to it, and watching for five minutes with the sound muted seems like a waste of five minutes.
Comment: @DoktorMayhem  - exactly what I was about to comment!
Comment: @Tim and DoktorMayhem: this not true! If I google with my terms I can't find an answer. But I'm quite proud about my English progression as  I obviously used  the correct terms. Can you tell me what exactly you have googled?
Comment: haha I'll tell you the seconds: you can see him at sec. 50 ... I agree, I can't bear this voices too. ;) but the question seems to be answered!
Answer: The guitar being played "lap style" standing up is unique type of guitar commonly referred to as a resonator, or more commonly a Dobro. They are naturally loud and employ open tuning which allows them to be played using a metal bar. The action is usually set quite high and there is no effort to actually fret the note by pushing the strings down. Instead the "bar" acts as a movable fret. The guitar is held in the flat position in order to access the strings from the top instead of the front. Personally, I liken it to an acoustic version of an electric steel guitar, although I recognize a number of differences. The sound of this instrument immediately catches your attention when you hear it. It is uniquely American, but was developed by European immigrants to the U.S.  It's history is approximately 100 years old.
Comment: @phoog- you can find what you want to know by googling "John Dopyera". Wikipedia has the information you are probably looking for. I hope that helps you.
Comment: "was developed by European immigrants to the U.S.": do you have more information about that?


How can I make a snare hit with my electric guitar and pedals?

Question: How can I make a sound like a snare drum hit using my electric guitar and multi-fx pedal? I imagine it's possible to get a more "authentic-sounding" snare hit than just strumming muted strings without any effects, but I haven't managed through my own experimentation.
Comment: Are you talking about making isolated sounds, or do you want to have a snare-like sound while you're also playing other things, the way acoustic players might tap their guitar for percussion sounds?
Comment: @YourUncleBob Isolated, should have mentioned that. I'm using a looper pedal to first lay a bass line, then the snare hits, etc.
Comment: I'm also trying to make hi-hat sounds and haven't managed at all, but I guess that's another question
Comment: Connect a drum module via MIDI. Every drum sound available is there.
Comment: Thank you @Tim I didn't think of that option at all! Getting one of those would solve many of my challenges
Comment: @Tim were you thinking of controlling the MIDI module from the guitar, or from a more straightforward midi controller?
Comment: @topomorto - OP asked about guitar source, can't see why it shouldn't work. My Roland GR55 does it - although I've never used it as such.
Answer: The first thing I would do is put lots of nonlinear distortion on the signal, to squelch the actual guitar-string character. With sufficient distortion, any sound like muted-string-strum will become more or less a white noise burst, which is also the most important component of the sound of both a snare and hi-hats.
Unfortunately, almost all guitar distortion effects work by the principle of clipping, i.e. they boost the signal beyond what the circuit can actually handle, so that the peaks are truncated. The transient edges of this truncation are what causes the bright fuzz sensation, but as a side effect, the signal is strongly compressed because the small-level is boosted while the louder notes are simply reduced to a square wave.
That compression is normally desirable for guitar, but if you want percussion it works against you. There is also a completely different kind of distortion which instead clips the low-level signal to zero. The recent Gamechanger Plasma Pedal is based completely on this. Software-based distortion such as iZotope Trash can also do it easily.
After such a distortion, the signal will sound very percussive and noisy, but it won't have the spectral character of the perc instrument you actually want. There's a nifty way to get that though: convolution between white noise and a given sound sample will give you the spectral details of that sample its ring-out sound, while retaining all the dynamic response of the noise "trigger" signal.
Convolution is nowadays a standard part of every amp simulation. It is usually used to simulate the speaker cabinet and room reverb, but you can also load any other sound into it, such as an actual snare drum sample. In fact, iZotope Trash used to come with a snare "cabinet" sim, which does just that. Most amp sims until recently didn't allow loading custom impulse response files, but I think the newer ones like Bias FX do. In a DAW, you can also use a convolution reverb plugin, which does exactly the same.
The result of all this will sound neither like a snare nor like a guitar, but it will be usable in broadly the same musical way.

Related: I imitated an acoustic drumset using only a simple Monotron synth and the convolution technique, i.e. basically guitar effects, when I made this – ahem... very mature video ages ago:

I also made another video then explaining the setup used:


One Table for all enum types in Hibernate

Question: I have a Class let say Employee as follows;
public class Employee{
    ... Other attributes ...
    @Column @Enumerated(EnumType.Ordinal)
    private Gender gender;

    @Column @Enumerated(EnumType.Ordinal)
    private EmployeeType employeeType;
    ... Getters & Setters ...
}

My Employee table is something like this.
Employee{
    ... other columns ....
    gender int,
    employeetype int,
    ...
}

and I have a generic lookup table lookups
Lookups{
    id long,
    lookName String,
    lookId int,
    lookValue String
}

I want Genders, and EmployeeTypes to be persisted in Lookups table by hibernate as follows, How can I do that;
+--+-------------+---------+------------+
|ID|LOOKUPNAME   |LOOKUPID | LOOKUPVALUE|
+--+-------------+---------+------------+
+--+-------------+---------+------------+
|1 | GENDER      | 1       | MALE       |
+--+-------------+---------+------------+
|2 | GENDER      | 2       | FEMALE     |
+--+-------------+---------+------------+
|3 | EMPLOYEETYPE| 1       | TEAM MEMBER|
+--+-------------+---------+------------+
|4 | EMPLOYEETYPE| 2       | TEAM LEADER|
+--+-------------+---------+------------+
|5 | EMPLOYEETYPE| 3       | MANAGER    |
+--+-------------+---------+------------+

Answer: Create the Lookups class. Then, for the Gender and EmployeeType fields of Employee class, replace them with a Lookups field. Then remove the Enumerated annotations.
Comment: then how will be the data published?
Answer: What i understand is, you want to store all your constants/Enums in one table only in automated way.
To do this, you can have

Some XML/property file, which will be loaded on server startup to read this data.
The class, which will read property/XML file on server startup and check if lookup data exists or not.

If not, then it will persist the data in the DB.
If data is there, set some flag on DB. If this flag is true, the startup class will not invoke the check again on next server startup.

This way, the startup class can check the data at startup and insert it if its not there.
Comment: how can I do this with hibernate.
Comment: - To read property, you can use `ResourceBundle`.
- To read XML file, you can use Spring Bean/XML to Object (Castor/XStream/JAXB etc...)
- The startup class need to check if data not exists in the lookup table (By checking count of rows etc...). Then it needs to read data from prop/XML to Hibernate entity and persist it.

- There are lots of examples available for this, this is just a starting point for you to learn it...
Answer: perhaps you could put them together as follows and persist them?
import java.util.*;
enum Gender {
    male, female
}
enum EmployeeType {
    member, leader, manager
}
class Lookups {
    public String toString() {
        return id + " " + lookName + " " + lookId + " " + lookValue;
    }
    private Lookups(Enum e) {
        id = ++n;
        lookName = e.getClass().getName();
        lookId = e.ordinal() + 1;
        lookValue = e.name();
    }
    private static void create(Enum e) {
        for (Object o : e.getDeclaringClass().getEnumConstants())
            lookups.add(new Lookups((Enum) o));
    }
    final long id;
    final String lookName;
    final int lookId;
    final String lookValue;
    static long n;
    static Set<Lookups> lookups = new LinkedHashSet<Lookups>();
    static {
        create(Gender.values()[0]);
        create(EmployeeType.values()[0]);
    }
}
public class Main {
    public static void main(String[] args) {
        for (Lookups lookups : Lookups.lookups)
            System.out.println(lookups);
    }
}


Como importar dados do excel pro R?

Question: Tenho uma tabela no excel que preciso importar para o R. Conseguia fazer isso tranquilamente com a função read.csv quando a tabela em questão estava online, mas estou tendo dificuldade para importar o arquivo direto do meu computador.
Como o código que estou fazendo será enviado para outra pessoa, não posso colocar um caminho absoluto, e estou tendo dificuldade para aplicar a função para um caminho relativo.
Answer: Há algumas formas de fazer isso. Não consegui entender a situação muito bem, mas aqui vão algumas opções para ler arquivos Excel:
Com o pacote gdata:
require(gdata)

df = read.xls ("myfile.xlsx"), sheet = 1, header = TRUE)

Com o pacote RODBC`` :
require(RODBC)

conn = odbcConnectExcel("myfile.xlsx") # Abre uma conexao com o arquivo excel

sqlTables(conn)$TABLE_NAME # mostra todas planilhas

df = sqlFetch(conn, "Sheet1") # le uma planilha

close(conn) # fecha a conexao com o arquivo

Com o pacote xlsx:
require(xlsx)

read.xlsx("myfile.xlsx", sheetName = "Sheet1")

Caso você não tenha problema com inglês, ainda mais outros métodos podem ser visto em: http://www.r-bloggers.com/read-excel-files-from-r/
Comment: Muito obrigado pela resposta, vejo que poderia resolver meu problema de várias formas. No fim das contas eu consegui resolvê-lo usando a função read.csv2. O código ficou assim:

setwd("C:/Users/PEDRO/PUC/TPE/Trabalho 2/G2")
file = "dados/Empresas.csv"
base = read.csv2(file, sep = ";")

O problema estava na definição do endereço do arquivo.
Comment: Se quiseres podes aceitar a resposta do @mechanical_fan, ou adicionar o teu cometário como resposta e aceita-la. Aceitar respostas que te ajudam faz parte da etiqueta do SO, e ñ é errado aceitar respostas de nós próprios.
Answer: Atualmente, a melhor forma de importar do excel é usando o pacote readxl. Ao contrário do pacote xlsx, ele não depende do rJava, o que o torna mais portátil e fácil de instalar.
Você pode instalar o pacote usando:
install.packages("readxl")

Exemplos de uso:
library(readxl)

# Abre tanto arquivos xls como xlsx
read_excel("my-old-spreadsheet.xls")
read_excel("my-new-spreadsheet.xlsx")

# É possível especificar a aba tanto por um número quanto pelo nome
read_excel("my-spreadsheet.xls", sheet = "data")
read_excel("my-spreadsheet.xls", sheet = 2)

# Se valores omissos (NA's) forem representados por outro
# valor que não seja uma célula vazia.
read_excel("my-spreadsheet.xls", na = "NA")

Answer: Bem, em relação ao trecho:
"Como o código que estou fazendo será enviado para outra pessoa, não posso colocar um caminho absoluto, e estou tendo dificuldade para aplicar a função para um caminho relativo."
Nós podemos saber o que colocar no caminho (path) através do uso de duas funções:
getwd()

e
setwd()

getwd é semelhante ao comando pwd no terminal de sistemas Linux e, retorna o caminho do diretório corrente, no qual você está. Exemplificando:
getwd()

retorna algo parecido com:
/home/seunome/Documents/meu.xlsx

setwd é semelhante ao comando cd no terminal de sistemas Linux e, muda o diretório corrente para o que você precisa. Vamos supor que o arquivo que você queira importar esteja na pasta Downloads, você pode fazer isso:
setwd(dir = "/home/seunome/Downloads")

E mudar o diretório de trabalho para a pasta Downloads:
Agora, você pode importar seu arquivo desta pasta com este comando:
library(rio)

lista_1 <- import_list(file = "home/seunome/Downloads/meuarquivo.xlsx")

Onde "home/seunome/Downloads/meuarquivo.xlsx" é o caminho do seu arquivo em Excel.
Este pacote (rio) é bem fexível e, a vantagem em aprendê-lo frente aos que foram citados nas respostas anteriores, é o de tentar padronizar a importação de dados em muitos outros formatos, não apenas em Excel, mas também csv por exemplo.
Maiores detalhes sobre este pacote você encontra aqui.
Comment: Se quem deu downvote pudesse me explicar o problema da resposta para que eu pudesse melhorá-la, eu ficaria grato.
Comment: Não é nem por mim que fico questionando os downvotes, mas sim pelos usuários que podem ver a resposta (que está correta) e pensarem que esta solução é errônea ou pouco útil. Bom, citei a vignette do pacote para maiores detalhes sobre a função que utilizei na resposta.

Como importar dados do excel pro R?


In C# how do you output a string x times?

Question: In Python, you can write 2*'hello' in the shell and the IDLE will output 'hellohello'.   Is there a way to output 'multiples' of a string in C# to do the same thing?
Comment: just use a for loop, haven't heard of it beeing as simple as in python
Comment: Unfortunately you can do it e.g. in foreach loop
Comment: Does this answer your question? [Is there an easy way to return a string repeated X number of times?](https://stackoverflow.com/questions/3754582/is-there-an-easy-way-to-return-a-string-repeated-x-number-of-times)
Comment: Does this answer your question? [Is there a built-in function to repeat a string or char in .NET?](https://stackoverflow.com/questions/3754582/is-there-an-easy-way-to-return-a-string-repeated-x-number-of-times)
Answer: You can use Enumerable.Repeat

Generates a sequence that contains one repeated value.

Then String.Concat

Concatenates one or more instances of String, or the String
representations of the values of one or more instances of Object.

Example
Console.WriteLine(string.Concat(Enumerable.Repeat("hello",3)));

Output
hellohellohello


Difference between coefficient of determination and explained variance

Question: I'm trying to evaluate how good my model predictions w.r.t. the true values (paired). I came across two method coefficient of determination (https://en.wikipedia.org/wiki/Coefficient_of_determination) and explained variance (http://scikit-learn.org/stable/modules/model_evaluation.html#explained-variance-score) to do this but I can't really see what the difference between the two are and the pros and cons. The formulas seem about the same...
Can someone explain the difference and pros and cons?
Answer: Let $X$ be a random vector, and $Y$ a random variable that is modeled by a normal distribution with center $\mu+\Psi^\textrm{T}X$, in this case, the proportion of randomness $\rho_C^2$ equals the squared coefficient of determination, $R^2$.
Note the strong model assumptions: the center of the $Y$ distribution must be a linear function of $X$, and for any given $x$, the $Y$ distribution must be normal. In other situations, it is generally not justified to interpret $R^2$ as proportion of explained variance. What Does Explained Variance Explain?
Answer: They are the same. Using a bit of algebra, we can see that they are equivalent.
$R^2 = 1 - \dfrac{Sum\ of\ squared\ errors}{Total\ sum\ of\ squares}$
$Sum\ of\ Squared\ Errors = \sum(Y - \hat Y)^2$
$Total\ Sum\ of\ Squares = \sum(Y- \bar Y)^2$
$R^2 = 1 -\frac{\sum(Y - \hat Y)^2}{\sum(Y- \bar Y)^2}$
According to your source,
$ Explained\ variance\ score\ = 1 - \dfrac{Var(Y- \hat Y)}{Var(Y)}$
$Explained\ variance\ score\ = 1 - \dfrac{\cfrac{\sum[(Y - \hat Y ) - E(Y - \hat Y)]^2}{n -1}}{\dfrac{\sum(Y- \bar Y)^2}{n-1}}$
$\sum[(Y - \hat Y ) - E(Y - \hat Y)]^2 = \sum(Y - \hat Y)^2$, i.e. SSE
So,
$Explained\ variance\ score\ = 1 - \dfrac{\dfrac{\sum(Y - \hat Y )^2}{n -1}}{\dfrac{\sum(Y- \bar Y)^2}{n-1}}$
$Explained\ variance\ score\ =  1 -  \dfrac{(n-1)\sum(Y - \hat Y)^2}{(n-1)\sum(Y - \bar Y)^2}$
$Explained\ variance\ score\ = 1 - \dfrac{\sum(Y - \hat Y)^2}{\sum(Y - \bar Y)^2} = R^2$
Why are there two different names for the same thing? Because, statistics. Maybe there is some deeper reason, but often different terms for the same thing arise because of disciplinary differences.
Comment: @Hugh they are the same if the mean residue is zero, which is an assumption of OLS. Otherwise they are different things. See https://stackoverflow.com/questions/24378176/python-sci-kit-learn-metrics-difference-between-r2-score-and-explained-varian
Comment: According to wiki this isn't true in general. "it is generally not justified to interpret $R^{2}$ as proportion of explained variance." I don't understand it but perhaps you will  https://en.wikipedia.org/wiki/Explained_variation#Correlation_coefficient_as_measure_of_explained_variance
Comment: @Hugh only justified under the strict assumptions of ols, not for glm. I think the interpretation of R^2 as explained variance is somewhat controversial even in the case of ols.