Q:

delphi 7 reading and processing xml file how and which component - update

I have a client who is supplying a file with mixed comma seperated data and xml.  The comma seperated is not a problem but the xml is all new to me.
I have tried to find a component to do what i need (omnixml -abandoned - using delphi built in xml component) seems possible...
I have data like the following :
<Passengers>
  <Passenger>
<No>1</No>
<Title>mrs</Title>
<ForeName>Anne</ForeName>
<SurName>XXXXXXXX</SurName>
<Age>33</Age>
<UWStatus>accept</UWStatus>
<Screening>
  <ScreeningData>
    <ScreeningPath SL="2.2" DATA="1">
      <MedicalRisk>4.01</MedicalRisk>
      <rootConditionId>1292</rootConditionId>
      <isAMT>false</isAMT>
      <regionId>4</regionId>
      <isWinterSport>false</isWinterSport>
      <isRetScheme>false</isRetScheme>
      <isPair>false</isPair>
      <LinkedCondition>3</LinkedCondition>
      <LinkedConditions>
        <LinkedCondition Name="High blood pressure" ICD="401.9" Type="D"/>
        <LinkedCondition Name="Renal failure" ICD="586" Type="D"/>
        <LinkedCondition Name="Abdominal aortic aneurysm" ICD="441.4" Type="I"/>
        <LinkedCondition Name="Peripheral vascular disease" ICD="443.9" Type="I"/>
        <LinkedCondition Name="Angina" ICD="414.9" Type="IS"/>
        <LinkedCondition Name="Enlarged heart" ICD="425" Type="IS"/>
        <LinkedCondition Name="Heart attack" ICD="414.9" Type="IS"/>
        <LinkedCondition Name="Heart failure" ICD="428.0" Type="IS"/>
        <LinkedCondition Name="Mini stroke" ICD="435.9" Type="IS"/>
        <LinkedCondition Name="Stroke" ICD="434" Type="IS"/>
      </LinkedConditions>
      <ScreeningHistory>
        <DeclaredCondition Score="3.56">
          <conditions>
            <Condition>
              <id>1292</id>
              <parentid>-1</parentid>
              <name>Epilepsy</name>
              <questions>
                <Question>
                  <id>1</id>
                  <Text>If awake#$ do you normally lose consciousness during a fit/seizure?</Text>
                  <currentAnswer>
                    <Text>Yes</Text>
                    <id>1</id>
                  </currentAnswer>
                </Question>
                <Question>
                  <id>2</id>
                  <Text>How many fits/seizures causing loss of consciousness have you had in the last four weeks?</Text>
                  <currentAnswer>
                    <Text>0</Text>
                    <id>1</id>
                  </currentAnswer>
                </Question>
                <Question>
                  <id>3</id>
                  <Text>How many fits/seizures causing loss of consciousness have you had in the last six months?</Text>
                  <currentAnswer>
                    <Text>0</Text>
                    <id>1</id>
                  </currentAnswer>
                </Question>
                <Question>
                  <id>4</id>
                  <Text>How many unplanned hospital admissions have you had for epilepsy/seizures in the last year?</Text>
                  <currentAnswer>
                    <Text>1</Text>
                    <id>2</id>
                  </currentAnswer>
                </Question>
                <Question>
                  <id>5</id>
                  <Text>How many different medicines do you take for your epilepsy/seizures?</Text>
                  <currentAnswer>
                    <Text>1</Text>
                    <id>2</id>
                  </currentAnswer>
                </Question>
                <Question>
                  <id>6</id>
                  <Text>How long ago was your first fit/seizure?</Text>
                  <currentAnswer>
                    <Text>6 to 12 months ago</Text>
                    <id>2</id>
                  </currentAnswer>
                </Question>
                <Question>
                  <id>7</id>
                  <Text>If not already declared to us#$ is your epilepsy/seizures caused by:</Text>
                  <currentAnswer>
                    <Text>None of these</Text>
                    <id>4</id>
                  </currentAnswer>
                </Question>
              </questions>
              <currentQuestionId>7</currentQuestionId>
              <isAMTExclusion>false</isAMTExclusion>
              <isWSExclusion>false</isWSExclusion>
              <Score>3.56</Score>
              <ICD>345.9</ICD>
              <Deterioration>0</Deterioration>
              <isOkForWS>true</isOkForWS>
              <isOkForAMT>true</isOkForAMT>
              <exclusionType>None</exclusionType>
            </Condition>
          </conditions>
        </DeclaredCondition>
        <DeclaredCondition Score="1.45">
          <conditions>
            <Condition>
              <id>1332</id>
              <parentid>-1</parentid>
              <name>Blood pressure</name>
              <questions>
                <Question>
                  <id>1</id>
                  <Text>How many medicines does your doctor advise you to take for high blood pressure?</Text>
                  <currentAnswer>
                    <Text>1</Text>
                    <id>2</id>
                  </currentAnswer>
                </Question>
                <Question>
                  <id>2</id>
                  <Text>Has your dose been increased or have you been prescribed a new tablet in the last six months?</Text>
                  <currentAnswer>
                    <Text>No</Text>
                    <id>2</id>
                  </currentAnswer>
                </Question>
                <Question>
                  <id>3</id>
                  <Text>Have you been advised to take a medication to lower your cholesterol level?</Text>
                  <currentAnswer>
                    <Text>No</Text>
                    <id>1</id>
                  </currentAnswer>
                </Question>
                <Question MQ="2">
                  <id>4</id>
                  <Text>Have you ever been a smoker?</Text>
                  <currentAnswer>
                    <Text>Yes - gave up less than a year ago</Text>
                    <id>3</id>
                  </currentAnswer>
                </Question>
              </questions>
              <currentQuestionId>4</currentQuestionId>
              <isAMTExclusion>false</isAMTExclusion>
              <isWSExclusion>false</isWSExclusion>
              <Score>1.45</Score>
              <ICD>401.9</ICD>
              <Deterioration>1</Deterioration>
              <isOkForWS>true</isOkForWS>
              <isOkForAMT>true</isOkForAMT>
              <exclusionType>None</exclusionType>
              <LinkedConditions>
                <LinkedCondition Name="High blood pressure" ICD="401.9" Type="D"/>
                <LinkedCondition Name="Renal failure" ICD="586" Type="D"/>
                <LinkedCondition Name="Abdominal aortic aneurysm" ICD="441.4" Type="I"/>
                <LinkedCondition Name="Peripheral vascular disease" ICD="443.9" Type="I"/>
                <LinkedCondition Name="Angina" ICD="414.9" Type="IS"/>
                <LinkedCondition Name="Enlarged heart" ICD="425" Type="IS"/>
                <LinkedCondition Name="Heart attack" ICD="414.9" Type="IS"/>
                <LinkedCondition Name="Heart failure" ICD="428.0" Type="IS"/>
                <LinkedCondition Name="Mini stroke" ICD="435.9" Type="IS"/>
                <LinkedCondition Name="Stroke" ICD="434" Type="IS"/>
              </LinkedConditions>
            </Condition>
          </conditions>
        </DeclaredCondition>
      </ScreeningHistory>
    </ScreeningPath>
  </ScreeningData>
</Screening>

The xml is all supplied in one field no spaces (i have formatted this) and where there is more than one person it appears this appears as a new passenger record.
I need to be able to process this and extract things like
Title/Forename/Surname fields from the passenger record
and then from the  branch  and from  the  and  which it relates to that is repeated for each answer to each condition.
I think it is fairly easy but I am struggling.
Code I have so far....
The first person is correct the 2nd one looses one of its siblings? Is there a bug or is it me?
StartItemNode:=XMLDoc.DocumentElement.ChildNodes.First;
ANode := StartItemNode;

repeat
  Title := ANode.ChildNodes['Title'].Text;
  Forename := ANode.ChildNodes['ForeName'].Text;
  Surname := ANode.ChildNodes['SurName'].Text;
  Age:=Anode.ChildNodes['Age'].Text;
  memo1.Lines.Add(Title+' '+Forename+' '+Surname+' '+Age);

  CNode:=Anode.ChildNodes.FindNode('Screening');
  CNode:=CNode.ChildNodes.FindNode('ScreeningData');
  CNode:=CNode.ChildNodes.FindNode('ScreeningPath');
  CNode:=CNode.ChildNodes.FindNode('ScreeningHistory');
  CNode:=Cnode.ChildNodes.FindNode('DeclaredCondition');
  CNode:=Cnode.ChildNodes.FindNode('conditions');
  CNode:=Cnode.ChildNodes.FindNode('Condition');
  (* Missing the 2nd illness on the 2nd node - but why *)

  repeat
   ill:=Cnode.ChildNodes['name'].text;
   memo1.Lines.add(ill);
   Unode:=Cnode;
   CNode:=Cnode.NextSibling;
  until cnode=nil;

Any help would be grateful received please.
Regards
Phil

A:

I did fix the problem and used Delphi7 built in XML object.
And for multiple people.
It was alot harder than I first thought.
As on the structure above I found if you declared a medical condition all was well but if the condition is implied e.g you have high blood pressure so therefore you may have raised cholesteral (spelling!) then the subsequent question are not under the main declared conditions branch but under conditions.
The code following does work for this - there is a large part of repeated quote BUT I wanted it to work rather than look pretty..
And I must admit i have learnt more about XML than I wanted to lol... And big thaks :-) to all the help that was offered - a lot of reading on stack overflow and some google searching and I now have a result!
procedure TForm1.Button1Click(Sender: TObject);
var
 StartItemNode:IXMLNode;
 ANode:IXMLNode;
 CNode:IXMLNode;
 LNode:IXMLNode;
 QNode:IXMLNode;
 UNode:IXMLNode;
 hnode:ixmlnode;
INode:IXMLNode;
number:widestring;
Title:widestring;
Forename:widestring;
Surname:widestring;
Age:widestring;
ill:widestring;
quest:widestring;
answer:widestring;
first:boolean;
who:string;
begin
 opendialog1.Execute;
 who:=extractfilepath(opendialog1.FileName)+extractfilename(opendialog1.filename)
 +'_TXT.TXT';
 XMLDOC.FileName:=opendialog1.FileName;

 XMLDoc.Active:=True;

memo1.Clear;
XMLDOC.SaveToFile('c:\philxx.xml');

StartItemNode:=XMLDoc.DocumentElement.ChildNodes.First;
ANode := StartItemNode;

memo1.Lines.add('Filename '+opendialog1.FileName);
if anode<>nil then
begin

repeat
  memo1.Lines.Add('====== New Person ======');
  number :=anode.childnodes['number'].Text;
  Title := ANode.ChildNodes['Title'].Text;
  Forename := ANode.ChildNodes['ForeName'].Text;
  Surname := ANode.ChildNodes['SurName'].Text;
  Age:=Anode.ChildNodes['Age'].Text;
  memo1.lines.add(number);
  memo1.Lines.Add(Title+' '+Forename+' '+Surname+' '+Age);

  CNode:=Anode.ChildNodes.FindNode('Screening');
  CNode:=CNode.ChildNodes.FindNode('ScreeningData');
  CNode:=CNode.ChildNodes.FindNode('ScreeningPath');
  CNode:=CNode.ChildNodes.FindNode('ScreeningHistory');

  HNode:=Cnode.ChildNodes.FindNode('DeclaredCondition');
  while hnode<>nil do
  begin
    unode:=hnode;
  memo1.lines.add('==== Illnesses ===');
  if unode<>nil then
  begin
   UNode:=Unode.ChildNodes.FindNode('conditions');
   Cnode:=Unode;
   Inode:=CNode.ChildNodes.FindNode('Condition');
  while unode<>nil do
  begin
   ill:=Inode.ChildNodes['name'].text;
   memo1.Lines.add(ill);
   lnode:=Unode;
   unode:=unode.nextsibling;
   if unode=nil then
    begin
     unode:=lnode;
     inode:=inode.NextSibling;
     if inode=nil then unode:=nil;
    end
    else
    begin
     CNode:=Unode.ChildNodes.FindNode('conditions');
     Inode:=CNode.ChildNodes.FindNode('Condition');
    end;

  end;

  end;
   hnode:=hnode.nextsibling;
  end;
  CNode:=Anode.ChildNodes.FindNode('Screening');
  CNode:=CNode.ChildNodes.FindNode('ScreeningData');
  CNode:=CNode.ChildNodes.FindNode('ScreeningPath');
  CNode:=CNode.ChildNodes.FindNode('ScreeningHistory');
  HNode:=Cnode.ChildNodes.FindNode('DeclaredCondition');

  while hnode<>nil do
  begin
    unode:=hnode;

  (* Gets all the questions but seems to have same issue with missing questions for 2nd illness *)
  if unode<>nil then
  begin
   UNode:=Unode.ChildNodes.FindNode('conditions');
   Cnode:=Unode;
   Inode:=CNode.ChildNodes.FindNode('Condition');

  while unode<>nil do
   begin
     QNode:=inode.ChildNodes.FindNode('questions');
     if qnode=nil then
      begin
       memo1.lines.add('=== No questions for Illness === ');
      end;
     if qnode<>nil then
      begin
        qNode:=qNode.ChildNodes.FindNode('Question');
        memo1.Lines.add('==== New Questions ====');
        while qnode<>nil do
         begin
          quest:=qnode.ChildNodes['Text'].text;
          memo1.Lines.add(quest);
          answer:=qnode.ChildNodes['currentAnswer'].ChildNodes['Text'].text;
          memo1.lines.add(answer);
          qNode:=qnode.NextSibling;
         end;
      end;
     lnode:=unode;
     unode:=unode.NextSibling;
     if unode=nil then
     begin
       unode:=lnode;
       inode:=inode.NextSibling;
       if inode=nil then unode:=nil;
     end
     else
     begin
      CNode:=Unode.ChildNodes.FindNode('conditions');
      Inode:=CNode.ChildNodes.FindNode('Condition');
     end;
   end;
  end;
   hnode:=hnode.nextsibling;
  end;

  ANode := ANode.NextSibling;
until ANode = nil;
end
  else memo1.lines.Add('No Illness or Questions Found ');
  memo1.Lines.SaveToFile(who);
  showmessage('done');


Q:

Search a multi-dimensional array for certain values

I have a multi-dimensional array in the following format:
[0] = (
    'id' => '1',
    'type' => 'fish',
    'owner' => 'bob',
)

[1] = (
    'id' => '2',
    'type' => 'cat',
    'owner' => 'mary',
)

[2] = (
    'id' => '3',
    'type' => 'dog',
    'owner' => 'larry',
)

[3] = (
    'id' => '2',
    'type' => 'cat',
    'owner' => 'fred',
)

I would like to search for a value, and they return an array that contains all keys from matching arrays and looks like this on a search for type=cat:
[0] = (
    'id' => '2',
    'type' => 'cat',
    'owner' => 'mary',
)

[1] = (
    'id' => '2',
    'type' => 'cat',
    'owner' => 'fred',
)

I know I'm trying to treat the array as a database, but in this case it's dynamic data that doesn't need to be stored once the program ends.
Any advice?

A:

Loop through the array:
function loopAndFind($array, $index, $search){
         $returnArray = array();
         foreach($array as $k=>$v){
               if($v[$index] == $search){
                    $returnArray[] = $v;
               }
         }
         return $returnArray;
}

//use it:
$newArray = loopAndFind($oldArray, 'type', 'cat');


Q:

Endurance vs. Technique in Boxing

I recently got in a debate with a friend; both of us do boxing, although he's been doing it for longer apparently. He seems to think endurance is far more important than technique, whereas I argue that while both are important, technique is a greater deciding factor - for instance, I would expect a boxer with decent technique and high endurance to lose against a boxer with great technique and decent endurance, since the latter would be more efficient at using his energy and would be able to dominate the fight more, eliminating his opponent's physical advantage. I also argued that boxing is very much a mental sport and requires a lot of fast thinking and neural training, which endurance on its own neglects. He doesn't seem to be convinced though.
While he has been boxing longer, my opinions are those of people who are better and more experienced than both of us (for instance, Johnny at expertboxing.com). Are my ideas unfounded? Are we both in the wrong?

A:

Conditioning and muscle endurance are the attributes which allow you to continue executing proper technique after the first few moments of a fight or bout. All the slick technique in the world is useless if you're too tired to execute that technique.
Technique is important, but it tends to degrades rapidly as one tires. Being in condition for boxing allows you to continue applying your technique after being gently concussed, after being punched in the gut, after throwing the same technique fifty times, after several minutes of high-intensity movement.

A:

When Mike Tyson knocks you out in the first round, is it because you don't have enough endurance or because your technique failed you?
I would argue that endurance is more important than technique when the fight goes the full distance. Having good technique is one thing, but it's your endurance that keeps you from making mistakes when you get tired. And making mistakes is what gets you knocked out. Conversely, if you want to end a fight quickly, your technique is more important, though it is obvious that both have their role.
Also, don't make the same mistake that every mediocre fighter makes: Don't focus on style and technique uber alles and in the process forget that boxing (or any martial art really) is about knocking the other guy out. Which is why Mike Tyson is world champion even though his technique looks boring. It's also why Joe Fraser managed to knock out Muhammad Ali.


Q:

T-SQL Help Needed in Converting an Appointment List into a Master Schedule

I'm a self-taught SQL amateur. I don't do this for a living, but I enjoy the challenge of teaching myself. However, I've hit a wall.
In this scenario, I essentially have a three column table of appointment date/times, the length of the appointment (numeric in minutes), and the associated name of the individual handling the appointment.
What I would like to create is a weekly master schedule consisting of appointment date/times (sorted ascending) in my left most columns, the names of each respective staff member handling an appointment that week as the column names, and the the appointment length in the corresponding cell (i.e., at the intersection of the correct appointment date/time and staff name).
Now my problem is that I want to make this as flexible as possible. Staff come and go, there may or may not be appointments on any give date or time, etc. Therefore hard coding columns just isn't a good solution for me. So I'm thinking I'll need some sort of dynamic SQL and that is when I reach the end of my expertise.
I can generate a single column table of all scheduled appointment/date times across all staff (this should be sufficient to generate my left most column) for the particular week I am looking at, but from there, I'm clueless how to join in the staff/duration portion (i.e., how do I take a staff name that is in a field and turn it into a column header, how do I list only the staff who have scheduled appointments, etc.)
I was thinking about the possibility of dynamically generating temp tables for each staff's respective appointments and then dynamically joining them, but I'm not sure if that is even possible.
I know that I'm essentially creating a pivot table and I could easily copy my original dataset into Excel and create what I want manually, but I want this code to be able to be used by anyone else after I'm gone so I'd like it to be able to do all the bells and whistles internally without going to an external piece of software.
Any suggested guidance?

A:

What you need is indeed a Dynamic Pivot. If the Appointments table looks like the following
CREATE TABLE Appointments
(
   ApptDatetime DATETIME,
   Staffname VARCHAR (50),
   ApptLength INT
)

Then the following will work:
DECLARE @ColumnList VARCHAR (MAX)
DECLARE @SQL VARCHAR(MAX)

-- Create a list of distinct Staffnames which will become column headers
SELECT @ColumnList = COALESCE(@ColumnList + '], [','[') + CAST(S.Staffname AS VARCHAR(12)) FROM (SELECT DISTINCT Staffname FROM Appointments) S
SET @ColumnList = @ColumnList + ']'

SET @SQL = '
SELECT
  [ApptDatetime], ' + @ColumnList + '
FROM
(
  SELECT
    A.[ApptDatetime],
    A.Staffname,
    A.ApptLength
  FROM
      Appointments A
  WHERE
    A.[ApptDateTime] BETWEEN GETDATE() AND DATEADD(DAY, 7, GETDATE())
)  T
PIVOT
(
    MIN(ApptLength)
    FOR T.Staffname IN (' + @ColumnList + ')
) AS PVT'
--PRINT @SQL
exec (@SQL)


Q:

(iOS MPMusicPlayerNotification) how to receive notification when app is in the background

I'm using [MPMusicPlayerController ipodMusicPlayer] to play songs in my application
so that the song experience doesn't get interrupted even if the app goes to the background.
I've registered MPMusicPlayerNowPlayingItemDidChangeNotification in my app delegate,
so that whenever the music changes I can stop the player for a while, do something, and
then re-play it again.
The problem is, I need to receive the notification even when the app is in the background
and my app is the only application that's using the ipodMusicPlayer. (that is, default music app isn't open).
I've been playing around with applicationDidEnterBackground, but I just can't get it to work.
How should I achieve this?
Thank You in advance

A:

I found a solution for this.
Declare all your notification receivers in your app delegate, along with
[[MPMusicPlayerController iPodMusicPlayer] beginGeneratingPlaybackNotifications];

Then, initialize a CLLocationManager object and start receiving location changes.
This way, your app will not be suspended even if it goes to the background,
and your appdelegate will keep receiving playbacknotifications.
However, if will only work with applications using GPS features.


Q:

« Je ly avons baillé la mitre » ?

Ailleurs, on nous présente l'emploi inusité et ancien du pronom je avec un verbe à la première personne du pluriel :

-Je + verbe à la 1e pers. du plur. : Je ly avons baillé la mitre. (Pass. Semur D.M., c.1420 [1488], 152).
[ DmF - Dictionnaire du Moyen Français (1330-1500) ]

Dans la Passion bourguignonne de Semur (« Mystère en 2 journées composé en Bourgogne au XVe s., s'inspirant de la Passion de Sainte-Geneviève »), on retrouve l'extrait particulier dans le quatrain suivant :

[Vivant] Par le grant Dieu, ce faison mon, Mes mieulx
  choisir l'on ne pourroi, Sur tous autres estre le doit. Je ly
  avons baillé la mitre.
[ Le mystère de la Passion en France du XIVe au XVIe siècle : étude
  sur les sources et le classement des mystères de la Passion ;
  accompagnée de textes inédits: [...] La Passion de Semur,[...], 1904
  ]

De quoi parle-t-on dans la strophe et que dit-on exactement dans la dernière phrase en particulier (quel sens de bailler/mitre, et "lui" quoi/qui/où/de quoi) ?

A:

Cette strophe relate l'ordination d'une personne dans le français du XVème siècle (une explication de la cérémonie apparemment de cette époque ici).
« Bailler » a ici une définition désuette au sens de « donner » et la mitre désigne aujourd'hui la coiffe des évêques.
Il n'y avait bien sûr pas encore d'évêques lors de la passion du Christ, il faudrait donc une analyse plus détaillée du texte complet pour comprendre de qui il s'agit (le Christ ou un apôtre ?).
Ci-dessous, une tentative de réécriture dans un français plus moderne. Les passages ou tournures non adaptées sont en italique et la réponse est en mode wiki pour que chacun puisse corriger.

Par le grand Dieu, le faisant mien,
  Mais mieux choisir l'on ne pourrait,
  Au dessus de tous les autres, être, le doit.
  Je lui ai remis la mitre.


Q:

Meaning of the word "congratufukinlation"

What does congratu-fukin-lations mean?

A:

This is expletive infixation: where an expletive is added into the middle of a word to give extra impact (or sometimes sarcasm).
See this question for more discussion.

A:

This isn't really a typical word. It's "congratulations" with "fukin" (a slight misspelling of an expletive) inserted in the middle.
How that expletive changes the meaning depends a bit on context. In general the intention would be to intensify the sentiment. However, the sentiment could actually be sarcastic. In that case it would be something along the lines of "I guess that's great for you but it doesn't do anything for me".


Q:

What's the correct way to attach stovepipe to a wood stove?

Look where the stovepipe sits on the flue collar of this woodstove. I don't see any way to secure the pipe to the stove. There is a gap because the stovepipe is not perfectly round.
At the other end of the stovepipe I will use 3 sheetmetal screws, but that won't work here.
The manufacturer's manual for the stove doesn't say anything.
How should I secure the stovepipe to the stove?
How should I seal the joint?
(click for full size)

A:

I didn't see it before, but there were two small holes in the stove's flue collar. I put sheet metal screws through the holes in to the stovepipe, and things feel really solid.
Before inserting the pipe, I put some fire cement on the crimped end. After inserting, I spread some more around the joint, like caulking around a bathtub.
(click for full size)


Q:

What is the mental illness of Tiffany in Silver Linings Playbook?

Tiffany in Silver Linings Playbook said she was depressed. So, I guess she had at least one depressive episode. Does she have MDD, BD (like Pat), BPD or PTSD? I read some speculation on Tiffany having at least one of those, but I don't think she was diagnosed. Was she? Is there any official word on this?

A:

The official word (from the book blurb) is that she's suffering from clinical depression.

When Pat meets the tragically widowed, physically fit, and clinically
  depressed Tiffany, she offers to act as a liaison between him and his
  wife, if only he will give up watching football, agree to perform in
  this year’s Dance Away Depression competition, and promise not to tell
  anyone about their ‘contract.’ All the while, Pat keeps searching for
  his silver lining.

As far as her 'undiagnosed' conditions are concerned, the author has suggested (in this interview) that she may also be suffering from anxiety issues:

Could you tell me about the creation of Tiffany? Was the character inspired by anybody you know?
It’s funny; people ask me that all the time, like, “Did you know someone who needed to sleep with everybody in the office?” and the
  boring answer is “no.” I think what Tiffany really represents is that
  explosive quality that forces you to take a hard look at yourself. Pat
  is delusional – especially in the book, he’s much more delusional in
  the book. He just does not want to face reality and Tiffany is the one
  that grabs Pat’s head and makes him look squarely in the mirror at
  someone that he doesn’t want to see.
...
Growing up in a blue-collar neighborhood, you didn’t talk about stuff like that. To use the word “depression,” that was not something I was
  comfortable with for most of my life and I think my wife really forced
  me to look at the fact that I was not happy, I was depressed, I had
  anxiety issues and I wasn’t really living the life that I wanted to
  live. That was a hard thing for me to admit in my 20’s. I think,
  metaphorically, that experience probably inspired, on a subconscious
  level, Tiffany.


Q:

angular2 bootstrap with data from ajax call(s)

I want to bootstrap my application with data I am retrieving from a service. I am doing something along the lines of
let dependencies = [
    //... a load of dependencies
    MyService
];

let injector = Injector.resolveAndCreate(dependencies);
let service: MyService = injector.get(MyService);

service.getData() // returns observable
    .toPromise()
    .then((d) => {
        // use data to append to dependencies

        bootstrap(App, dependencies)
    });

This works fine, but I do not like using the dependency array twice, is there a cleaner way of doing this? Can I add things to the application injector after bootstrap? Also I notice that the bootstrap function returns a promise, can I use this promise to prevent bootstrap of the application until after my ajax request finishes?
Of course for the Injector I could use only those dependencies required by MyService but this makes it very brittle as you can imagine.

A:

The problem here is that Angular2 doesn't give you access to the application reference and its injector before bootstrapping the main component on it. See this line in the source code: https://github.com/angular/angular/blob/master/modules/angular2/platform/browser.ts#L110.
An approach could be to implement a custom bootstrap instead of using the default one. Something like that that splits the application creation and the boostrapping on the application component on it. This way you will be able to load something between the two tasks.
Here is a sample implementation:
function customBoostrap(appComponentType, customProviders) {
  reflector.reflectionCapabilities = new ReflectionCapabilities();
  let appProviders =
    isPresent(customProviders) ? [BROWSER_APP_PROVIDERS, customProviders] : BROWSER_APP_PROVIDERS;
  var app = platform(BROWSER_PROVIDERS).application(appProviders);

  var service = app.injector.get(CompaniesService);

  return service.getCompanies().flatMap((companies) => {
    var companiesProvider = new Provider('companies', { useValue: data });
    return app.bootstrap(appComponentType, [ companiesProvider ]);
  }).toPromise();
}

and use it this way:
customBoostrap(AppComponent, [
  HTTP_PROVIDERS,
  CompaniesService
]);

Companies will be automatically available for injection within the component for example:
@Component({
  (...)
})
export class AppComponent {
  constructor(@Inject('companies') companies) {
    console.log(companies);
  }
}

See this corresponding plunkr: https://plnkr.co/edit/RbBrQ7KOMoFVNU2ZG5jM?p=preview.
At this time, it's a bit hacky but such approach could proposed as a feature request...
Edit
After having a look at the doc for the ApplicationRef class, I saw that there is a simpler solution ;-)
var app = platform(BROWSER_PROVIDERS)
   .application([BROWSER_APP_PROVIDERS, appProviders]);

service.getCompanies().flatMap((companies) => {
  var companiesProvider = new Provider('companies', { useValue: data });
  return app.bootstrap(appComponentType, [ companiesProvider ]);
}).toPromise();

Here is the corresponding plunkr: https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p=preview.


Q:

Should questions/answers dealing with "adult" software be flagged as inappropriate?

This question is being posted largely in response to this answer describing the "Adult Lens and Porn Scope" and how to install it.
As Roland Taylor and I commented on the answer, we have concerns over whether this material should be posted at Ask Ubuntu. Besides the fact that someone under legal age could easily install and use the lens by following the posted instructions, some of us also have concerns that it is indecent and inappropriate to even mention on the site.
It was pointed out in the reason for my rejected flag that a chat discussion over the answer eventually decided that it was on-topic and therefore stay. It was also noted, however, that a Meta question would be the proper way to handle this issue, and so here it is.
So, in summary: should we not allow questions or answers which discuss the usage of software intended for use with adult materials?

A:

Yes, they must be allowed
We don't even have a choice in the matter, because we're unable to form any policy that would be fair and respectful to the vast majority of users if we start deleting any content on moral grounds.

We don't make the moral rules.
And if anybody is offended by any kind of content, that's not nice. But the alternative, imposing our own morals on the community, is far worse.
The case against pornographic material, at this level of abstraction, is weak at best.
If someone posts outright adult content, it will be deleted - of course - because it has no place on a site like Ask Ubuntu. The post in question is legal, and decent enough such that "being offended" is not a good enough argument against it.
Consider other types of content that will offend people:

Political content (e.g. right wing news lens for unity)
Lèse-majesté / dissent (e.g. proxy software to circumvent government censorship)
Religious content (e.g. Bible/Koran/Torah  software)
LGBT content (e.g. gay-friendly genealogy software)[1]
Online gambling (e.g. hosting your own gambling site with ubuntu/foss)
Free expression (e.g. the political cartoon of the day desktop widget)

Pornography firmly belong on that list.

The values of Ubuntu include freedom. A discussion about the morals of any kind of behaviour belongs into politics, not software. Which means:

if you are offended by anything, it's no excuse to exclude people from the Ubuntu community.
Being respectful demands that we not judge people by arbitrary standards.
Concretely, the only valid reason for an Ask Ubuntu moderator to judge someone is the law, which is - I think - pretty clear: Mentioning the existence of pornography is not illegal, requires no age limit[2].

If I delete any content on moral grounds, one of two conditions are met:

It's illegal (e.g. hate speech)[3]
It doesn't belong on Ask Ubuntu (e.g. "what's a good porn site?")

Okay. Sorry about babbling on for so long. (:
[1]: For instance, GRAMPS. Which also allows for children born out of wedlock, I'm told.
[2]: I am not a lawyer of course, but I think it's fairly clear that preventing "dissemination of pornography to minors" is YouPorn's job, not Ask Ubuntu's. In a similar fashion, Google doesn't need to block it from search results.
[3]: We've actually had a case of that here. Needless to say, it was deleted instantly.

A:

We allow it...
The context here that started all this is an answer which describes an addon that allows somebody to search for porn. The answer itself is not pornographic.
If somebody is offended by porn they don't look at it. That's usually fairly simple. If somebody looked at this answer, they would not see porn so nobody has been harmed.
If somebody has a child or employee who they don't want to view porn, they need a solution, but not one that involved us self-censoring. There are technological and educational steps to reduce the problem, and if they want to ask about them here, that's great but we're not here to hold a curtain around certain subjects unless they're off-topic, unhelpful or illegal.
...within reason
If somebody posts actual pornographic material to the site, it's hard to imagine how that would be required to answer a question and we would delete or edit it accordingly.
That's nothing new, it's just as we would (and do) delete hate speech, rants, trolls and most other sorts of unneccessary, unhelpful posts.

A:

It is not the responsibility of Ask Ubuntu or OMG! Ubuntu! to educate and protect minors. It is their parents' job.
What was described in that answer was a technical interface. If it would be like that we shouldn't allow any question or answer related to browsers because people may browse for pornography with their browser.
It is totally on topic and should not be removed just because some people don't like it.


Q:

What are viable approaches to a circuit to detect wet/moist cloth (bed-wetting)?

Trying to design a circuit that can reliably detect a situation where a child wets their bed. The 3 key requirements are --

Reliability of the approach
Ease of use, i.e. a no-fuss approach
Child's safety (from harm) due to electronics

Can the soil moisture detection technique be used ?
How can I make this easy-to-use given s.t. while changing bed line ? This shouldn't require messing with the device, rewiring etc.

A:

Conductivity is probably the easiest method.  However, this is a case where you have to be extra extra careful about safety.  This would be a good thing to power off of two AA cells.  The output could be a opto, which can then go to anything else powered other ways.  The lines going to the bed would ONLY connect to the battery powered circuit, with a good 5 mm or more gap to anything else.
Detecting water is not that hard, and urine is going to be more conductive than clean water.  Two lines go to the bed.  Each can be driven strongly high or low, or with a weak pullup or pulldown (weakly driven high or low).  Each also goes into a A/D converter.
Most of the time nothing is going on and both lines can be weakly pulled to ground.  The micro periodically wakes up to run a test.  There are 4 separate tests, but the micro only needs to run one of them each time it wakes up.  It should cycle thru all of them in sequence to avoid any net DC flow.  It drives one line solidly high or low, puts the weak pullup/pulldown on the other line in the opposite direction, waits a while, then takes a A/D reading of the second line.  The four cases are which line is driven, and whether it is driven high or low.
After a complete suite of A/D readings you should know whether there is enough conduction between the two lines to declare the bed wetted.  You probably want to see this asserted several times in a row to to be sure.  A few seconds delay isn't going to matter, and that's a very long time for a microcontroller.
Added:
Here is more detail on the circuit I was talking about:

To take one of the four readings, for example, the micro would set digital output 1 high, output 4 low, wait a while (a few ms), then read A/D input 2.  With no connection between the electrodes, the A/D will read 0.  With a direct connect, it would read nearly full scale because the the 1K driving resistor R1 is 100 times lower than the pulldown R4.
In practise you can double up the A/D input and the first digital output for each line to use only two microcontroller pins per electrode.  I showed the three separate to make the functions more clear.
The four different combinations come from the two choices of which electrode is driven and which is the sense wire (A was driven an B the sense in the above example), and whether the driven electrode is high or low (high in the above example).  The reason for these measurements is to cancel out bias caused by any battery effects, diode effects, and to avoid net DC to keep the electrode symmetric due to electrolysis.
You should use electrodes that aren't corroded by urine, so in theory there shouldn't be diode or battery effects, but stuff happens, and doing the logic is trivial anyway.
I was envisioning parallel wires loosely stitched to the top of the mattress below any of the sheets, held maybe a inch or so apart.  One pair running accross the expected wet area side to side should be enough, but you could use two or three wires for each electrode alternating to cover more area.
I don't know what a good choice of wire is, but certainly not copper.  Nichrome might be good, but you have to check yourself.  I don't know which metals won't be corroded by urine that you can find wires of that don't cost a fortune.  For example gold would work great chemically and electrically, but would break easily, and of course cost a lot even if you could find it.  Platinum wire exists and might be suitable other then very expensive.  Check out nichrome first.
Added 2:
There is apparently still confusion about the test sequence I am talking about.  Here are the 4 tests:

   Num       Drive A       Drive B   Read
   ---   -----------   -----------   ----
     1   strong high      weak low      B
     2      weak low   strong high      A
     3    strong low     weak high      B
     4     weak high    strong low      A

The final result is then (#1 + #2) - (#3 + #4).  #1 and #2 should be high readings and #3 and #4 low readings.  By doing all four and adding up the result as I show, you cancel out both common mode noise and any fixed differential signal, like could be caused by battery effect due to assymetric corrosion.
If you don't believe this, work thru a example or two.

A:

I'll add a big one to your list of requirements:  no direct electrical contact with the, um, liquid.  That liquid is corrosive, foul, and a host of other things.  For safety you'd prefer to not have direct contact, but for "sensor lifespan" you also don't want it.  Further, you want cleanup to be super easy.
Here's what I would do...
I would use a capacitive touch sensor.  Something based on the Cypress PSoC "CapTouch" stuff, or similar.  This would allow you to sense the liquid in a non-contact way.  The captouch sensors are etched onto a standard PCB and covered with soldermask and other stuff.  Slip this under a 1/4 to 1/2 inch thick cotton pad, and under the sheets.  When it gets wet, the captouch sensor will register something.
I did a quick test of this here in my office.  No, I didn't wet the bed.  We have a touch panel based on this technology.  I took a wet paper towel and pressed some buttons and it worked fine.  I then took a "liquid substance inside of a sealed plastic bag" and repeated the test with success.
The cotton pad is to separate the person from the sensor to avoid false triggers.  It also helps to contain the mess, should it happen.  Throw the pad into the washing machine as needed.
I think this meets all of your needs:

Reliability:  Based on 2 minutes of testing, it seems to be reliable!  :)
Ease of use:  Just set it down and go for it.
Safety:  No direct electrical contact.  Should be safe.  Can be battery powered for an extra level of protection.
Clean-up:  A washing machine and some wipes are all you need.

A:

I like @DavidKessner's solution, but a PCB on the mattress seems ... uncomfortable to me. I would sew in conductive thread (google for other suppliers) into several bedtime underwear, creating several lines across the area that gets wet. Connect every other line together so you now have a pair of sensor lines. Visualize it this way:
+----------------------------------- A
+  -----------------------+
+-----------------------  +
+  -----------------------+
+-----------------------  +
   -----------------------+--------- B

When the underwear gets wet, the resistance between A and B will go down dramatically. You could connect A and B to any kind of small snap connector (I'm thinking of a 9V battery connector) which then leads away to the actual circuit which could be tiny and zippered/buttoned to a convenient location on the leg/front/back of the pyjama. You could power this off a couple of coin cells, and there are NUMEROUS "water detector" circuits online which could be made VERY small and light.
Washing is as simple as unsnapping the underwear from the circuit and tossing in the wash.


Q:

how to handle event for userControl properties?

I have a property for userControl like this:
    public enum Mode { Full, Simple }
    public Mode NavigatorMode { get; set; }

and now, I need to write an event, when user change the property (NavigatorMode) form Full mode to simple mode, or reverse
how can I do that?

A:

Implement INotifyPropertyChanged to your class:
public class YourClass : INotifyPropertyChanged
{
    // Your private variable
    private Mode mode;

    // Declare the event
    public event PropertyChangedEventHandler PropertyChanged;

    public YourClass()
    {
    }

    public Mode NavigatorMode
    {
       get { return mode; }
       set
       {
          mode = value;

          // Call OnPropertyChanged whenever the property is updated
          OnPropertyChanged(mode);
       }
    }

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(Mode modeParam)
    {
       PropertyChangedEventHandler handler = PropertyChanged;
       if (handler != null)
       {
          handler(this, new PropertyChangedEventArgs(modeParam));
       }
    }
 }


Q:

Efficiently finding the positions of a large list of targets in another, even larger list

I have a big list. It contains nearly 60,000 sub-lists. It's structured like
bigList = {{x1,y1,z1},{x2,y2,z2},{x3,y3,z3},.....,{x60000,y60000,z60000}};

I have picked 1200 elements from the bigList at random.
smallList = {{x1,y1,z1},{x2,y2,z2},......,{x1200,y1200,z1200}};

I want to find the positions of the smallList elements in the bigList. To that end I wrote the following code.
Flatten[Map[Position[bigList, #]&, smallList]]

It's working fine, but it takes 30 seconds to evaluate.
Timing[Flatten[Map[Position[bigList, #]&, smallList]]]

How can I reduce that evaluation time?

A:

I will use big and small rather than bigList and smallList, for brevity.
As stated by others if you can select the positions at random in the first place this will be faster, e.g.:
pos = RandomSample[Range @ Length @ big, 1200];

You can then get the small list with: small = big[[pos]].
To carry out the specific operation you describe the key detail will be to not scan the big list again for every element of small but rather find a way to scan it only once.
One of the simplest methods is to use MapIndexed to build a list of replacement rules that yield positions from elements.  MapIndexed is easily extendable to array and tensor elements as well.  Dispatch can be used to optimize this list of replacement rules.
Example data:
big = Array[{"x", "y", "z"} # &, 60000];

small = RandomSample[big, 1200];

Build the dispatch table:
rls = MapIndexed[Rule, big] // Dispatch;

Find the positions:
pos = small /. rls;

Together both operations take less than a tenth of a second on my machine:
First @ Timing[small /. Dispatch @ MapIndexed[Rule, big];]

0.0966

Confirmation of accuracy:
Extract[big, pos] === small

True

Lists with duplicates
The method above assumes that your big list does not have any duplicate elements; that is, there is a one-to-one mapping of element and position.  If there are duplicates you will need an additional GatherBy step as follows.
Data with duplicates:
big = Array[{"x", "y", "z"} Mod[#, 5000] &, 60000];
small = RandomSample[big, 1200];

Build rules, Gather them, and build the Dispatch table:
rls2 =
 Dispatch[
   #[[1, 1]] -> #[[All, 2, 1]] & /@
     Rule ~MapIndexed~ big ~GatherBy~ First
 ];

Find the positions in big at which the first element of small appears:
First @ small /. rls2

{2659, 7659, 12659, 17659, 22659, 27659, 32659, 37659, 42659, 47659, 52659, 57659}

Instead of GatherBy you could also use Sow and Reap, e.g.:
rls2 = Dispatch @ Reap[MapIndexed[Sow[#2, #] &, big], _, # -> Flatten@#2 &][[2]];

Alternative method
To provide an alternative approach you can use DownValues definitions in place of the Dispatch table.  I shall illustrate the method for a list with duplicates as that is more interesting.
Data:
SeedRandom[1]
big = RandomInteger[9, 50];
small = {6, 3, 9, 7, 2};

Build the definitions:
Clear[posfn]

posfn[_] = {};

AppendTo[posfn[#], #2[[1]]] & ~MapIndexed~ big;

Test the function:
posfn /@ small

{{8, 20, 23}, {17, 27, 30, 32, 34, 36, 42}, {37, 43}, {4}, {18, 22, 35, 41, 50}}

Confirmation:
big[[ posfn[3] ]]

{3, 3, 3, 3, 3, 3, 3}

A:

Prompted by comments conversation with Mr. Wizard, a routine I use:
findMultiPosXX[list_, find_, allowBits_: False, skipCands_: True] :=
 Module[{f = DeleteDuplicates[find], o, l, oo, bitmax = 20, cands, dims},

  If[allowBits && Length@f <= bitmax,
   With[{r = If[Length@(dims = Dimensions@list) == 1, Range@Length@list,
                Array[List, dims]]}, Pick[r, BitXor[list, #], 0] & /@ f],

   If[skipCands,

    (* This is the core explained below *)

    (l = Length@f;
     oo = Ordering[o = Ordering[Join[f, list, f]]];
     Inner[o[[# ;; #2]] &, oo[[;; l]], oo[[-l ;;]], List][[All, 2 ;; -2]] - l),

    (* end of core method *)

    (cands =
      SparseArray[
        BitAnd[UnitStep[list - Min@f], UnitStep[Max@f - list]]]["NonzeroPositions"];

     cands[[#]] & /@ (l = Length@f;
       oo = Ordering[o = Ordering[Join[f, Extract[list, cands], f]]];
       Inner[o[[# ;; #2]] &, oo[[;; l]], oo[[-l ;;]], List][[All, 2 ;; -2]] - l))]]];

Use:
test = RandomInteger[10, 20]

findMultiPosXX[test, {5, 10, 8}]

(*

{10, 0, 1, 4, 10, 5, 7, 2, 7, 7, 1, 4, 9, 3, 3, 7, 7, 8, 2, 5}

{{6, 20}, {1, 5}, {18}}

*)

With default argument (just the target and searches), can beat GatherBy by order of magnitude, and Position with Alternatives (which leaves you with only positions but no mapping to values) by a factor of 5 or more.
When searching for scalar values at the top level, setting the third argument to True will use bit-map search for 20 or fewer search terms, upping the performance typically by 4-10X. Also for scalar searches, if one knows the search space spans a small range of the data range, setting the fourth argument to False causes the search space to be narrowed, boosting performance from 2X to over an order of magnitude.
E.g., testing against several of the answers and Position with Alternatives, using the OP specified sizes with test = RandomInteger[1000000, {60000, 3}] and
finds = RandomSample[test, 1200], the speed advantage results expressed as time/mytime were {7.4286, 6.1429, 20.857, 21.143, 419.71}.
An explanation of the core method (when no optional arguments are set):
Let's take an example list:
test = RandomInteger[5, 20]

(* {5, 3, 2, 5, 0, 4, 3, 4, 4, 0, 0, 5, 4, 0, 5, 5, 5, 4, 0, 2} *)

Say we want to look for threes and fives. We'll call that lookfor, and prepend/append that to the target list:
lookfor = {3, 5}
work = Join[lookfor, test, lookfor]

(*
   {3, 5}

   {3, 5, 5, 3, 2, 5, 0, 4, 3, 4, 4, 0, 0, 5, 4, 0, 5, 5, 5, 4, 0, 2, 3,5}
*)

Now, let's use Ordering to get the positions from work in its sorted incarnation, along with the ordering of that order. That is just the permutation of the range of the length of work by a permutation list of the order (you can do it that way, but somewhat surprisingly, using Ordering on an order is faster):
Column[{order = Ordering[work],orderOforder = Ordering[order]}, Left, 2]

(*
  {7,12,13,16,21,5,22,1,4,9,23,8,10,11,15,20,2,3,6,14,17,18,19,24}

  {8,17,18,9,6,19,1,12,10,13,14,2,3,20,15,4,21,22,23,16,5,7,11,24}
*)

Now, here's the "magic". Take note of the first and last two entries of the permutation (two being the length of our lookfor list):
lengthOflookfor = Length@lookfor;

transposed = Transpose[{orderOforder[[;; lengthOflookfor]],
                        orderOforder[[-lengthOflookfor ;;]]}]

(* {{8, 11}, {17, 24}} *)

These pairs are in essence nothing more than spans, corresponding to the positions, for each of our lookfor elements, in the first ordering, mapping us the corresponding position(s) if any in the work list:
Column[{span = Span @@@ transposed, places = order[[#]] & /@ span,
         work[[#]] & /@ places}, Left, 2]
(*

{8;;11,17;;24}
{{1,4,9,23},{2,3,6,14,17,18,19,24}}
{{3,3,3,3},{5,5,5,5,5,5,5,5}}

*)

So we see that following the order from positions 8 to 11 and 17 to 24, we recover the positions of the elements we're interested in from the work list.
All that's left to do is to trim our padded element entries from the result and adjust the positions to get the actual positions from the original list:
Column[{recovered = ArrayPad[#, -1] & /@ places - lengthOflookfor,
         test[[#]] & /@ recovered}, Left, 2]

(*
{{2,7},{1,4,12,15,16,17}}
{{3,3},{5,5,5,5,5,5}}
*)

Because Ordering is, in general, very fast, this trick allows us to recover the positions of a large subset of elements (or show non-existence) from the target list very quickly.

A:

bigList = RandomSample[DeleteDuplicates[RandomInteger[{1, 255}, {70000, 3}]], 60000];
smallList = RandomSample[bigList, 1200];
First@AbsoluteTiming[Map[Position[bigList, #] &, smallList]]

needs less than a second on my machine.


Q:

How setup Google Drive Credentials within Android App?

The app was registered in the "Google API console" as an "installed application" - seems that this is the right setting for an Android app, no?
So I do have a Client-Id and no Secret-Id. To make it clear: It's no Web-app and no Google Drive-App - it's an Android App accessing other users data in the Google Drive cloud.
Within the app I fetch the account (works) and I do request a token (works). Now I want to connect to Google Drive with that token and the Client-Id. The result is a "401, invalid credential". What's wrong with this code?
public class ActivityMain extends Activity implements DialogInterface.OnClickListener {

    // https://developers.google.com/drive/scopes
    private static final String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/drive";

    // https://code.google.com/apis/console/
    private static final String CLIENT_ID = "999999999999999.apps.googleusercontent.com";

    private AccountManager accountManager;
    private Account[] accounts;
    private String authName;
    private String authToken;

    @Override
    public void onClick(final DialogInterface dialogInterface, final int item) {

        processAccountSelected(accounts[item]);
    }

    @Override
    public void onCreate(final Bundle bundle) {
        super.onCreate(bundle);

        setContentView(R.layout.activitymain);

        accountManager = AccountManager.get(this);
        accounts = accountManager.getAccountsByType("com.google");

        if (accounts == null || accounts.length == 0) {
            // TODO
        } else if (accounts.length == 1) {
            processAccountSelected(accounts[0]);
        } else if (accounts.length > 1) {
            showDialog(MyConstants.DIALOG_ACCOUNTCHOSER);
        }
    }

    @Override
    protected Dialog onCreateDialog(final int id) {
        switch (id) {
            case MyConstants.DIALOG_ACCOUNTCHOSER:
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

                String[] names = new String[accounts.length];

                for (int i = 0; i < accounts.length; i++) {
                    names[i] = accounts[i].name;
                }

                alertDialogBuilder.setItems(names, this);
                alertDialogBuilder.setTitle("Select a Google account");
                return alertDialogBuilder.create();
        }

        return null;
    }

    private void processAccountSelected(final Account account) {
        if (account != null) {
            authName = account.name.toString();
            if (!Tools.isEmpty(authName)) {
                Toast.makeText(this, authName, Toast.LENGTH_LONG).show();

                accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, this,
                        new AccountManagerCallback<Bundle>() {

                            public void run(final AccountManagerFuture<Bundle> future) {
                                try {
                                    authToken = future.getResult().getString(
                                            AccountManager.KEY_AUTHTOKEN);
                                    processTokenReceived();
                                } catch (OperationCanceledException exception) {
                                    // TODO
                                } catch (Exception exception) {
                                    Log.d(this.getClass().getName(), exception.getMessage());
                                }
                            }
                        }, null);
            }
        }
    }

    private void processListFiles(final Drive drive) {
        List<File> result = new ArrayList<File>();
        Files.List request = null;
        try {
            request = drive.files().list();
        } catch (IOException exception) {
        }

        do {
            try {
                FileList files = request.execute();

                result.addAll(files.getItems());
                request.setPageToken(files.getNextPageToken());
            } catch (IOException exception) {
                // --> 401 invalid credentials
            }
        } while (request.getPageToken() != null && request.getPageToken().length() > 0);
    }

    private void processTokenReceived() {
        if (!Tools.isEmpty(authToken)) {
            final HttpTransport transport = AndroidHttp.newCompatibleTransport();
            final JsonFactory jsonFactory = new GsonFactory();
            GoogleCredential credential = new GoogleCredential();
            credential.setAccessToken(authToken);
            Drive drive = new Drive.Builder(transport, jsonFactory, credential)
                    .setApplicationName(getString(R.string.txt_appname))
                    .setJsonHttpRequestInitializer(new GoogleKeyInitializer(CLIENT_ID))
                    .build();

            if (drive != null) {
                processListFiles(drive);
            }
        }
    }
}

I have to say that this is a full load of mess. There are so many pages in the web showing parts only and there are so many pages using deprecated, missing or different methods to do the same. There are, in my opinion, not two pages showing the same way to get data from Google Drive from within an Android app.
Any help is highly appreciated.
EDIT: I could solve it myself. It was a combination of different changes:

Had to set android:minSdkVersion="11" as a requirement
Had to use this current libraries: google-api-client-1.11.0-beta.jar, google-api-client-android-1.11.0-beta.jar, google-api-services-drive-v2-rev9-1.8.0-beta.jar, google-http-client-1.11.0-beta.jar, google-http-client-android-1.11.0-beta.jar, google-http-client-gson-1.11.0-beta.jar, google-http-client-jackson2-1.11.0-beta.jar, google-oauth-client-1.11.0-beta.jar, gson-2.1.jar, guava-11.0.1.jar, jackson-core-2.0.5.jar, jsr305-1.3.9.jar

This is the current part to get the Drive Object:
    GoogleCredential credential = new GoogleCredential();
    credential.setAccessToken(authToken);

    HttpTransport transport = AndroidHttp.newCompatibleTransport();

    JsonFactory jsonFactory = new AndroidJsonFactory();

    drive = new Drive.Builder(transport, jsonFactory, credential)
            .setApplicationName(getString(R.string.txt_appname))
            .setJsonHttpRequestInitializer(
                    new GoogleKeyInitializer(APIKEY_SIMPLE))
            .build();
    if (drive != null) {
    }

A:

Yeah, the documentation is quite hard to catch on.
Just change
new GoogleKeyInitializer(CLIENT_ID)

to
new GoogleKeyInitializer(SIMPLE_API_ACCESS_KEY)

and it should work.
You can find your SIMPLE_API_ACCESS_KEY in Google's APIs Console under the Simple API Access section of the API Access page (the API key). If this section is not available, you have to first activate Drive API access on the Services page.


Q:

Is there a windows sidebar widget that shows temperature from sensors inside the computer?

Is there a windows vista sidebar widget that shows temperature from sensors inside the computer? I have found Speedfan. Would like something that runs as a sidebar widget.

A:

SpeedFan Temperature Monitor
This is a Yahoo Widget - uses SpeedFan, a popular utility, to display your processor temperature simply and concisely.

Some Gadgets for Vista - take a look
Have a look at this thread, also for Vista you need Everest for it though


Q:

Why is my slideshow not centered on the page?

Why is my slideshow not centered on the page? The nav bar is in another file.
Already tried with width: auto and text-align: center.
I already searched the internet and could not find anything that would help my problem. But from what I realize it's because of a padding-left but I can not find it.
Sorry for the classes and IDs in Portuguese and for my English.

PS.: If I do this, it stays the same.
#conteudo{
    text-align: center;
}

#conteudo{
    padding: 5px;
    text-align: center;
}

main {
    height: auto;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
}

div{
    background-color: transparent;
}

.div_top_img_pagina {
    background-image: linear-gradient(rgba(8, 124, 8, 0.5), rgba(0,0,0,0.9)), url("../videos/img\ top.png");
    background-position: center;
    background-repeat: no-repeat;
    background-position-y: 50px;
}

.jogos{
    display: inline-block;
    margin: 5px;
    height: 279px;
    width: 279px;
    border-radius: 20px;
    background-color: blue;

}

.jogos:hover {
    box-shadow: 0 0px 20px black;

}

#slideshow {
    display: block;
    overflow: hidden;
    height: 510px;
    width: 1100px;
    margin: 0 auto 20px auto;
    text-align: center;
    border-radius: 20px;
  }

.slide-wrapper {
    width: 5500px;
    animation: slide 35s ease infinite;
}
.slide {
    float: left;
    height: 510px;
    width: 1100px;
}

.slide:nth-child(1) {
    background: #D93B65;
}

.slide:nth-child(2) {
    background: #037E8C;
}

.slide:nth-child(3) {
    background: #36BF66;
}

.slide:nth-child(4) {
    background: #D9D055;
}
.slide:nth-child(5) {
    background: rgb(185, 30, 216);
}

.slide-number {
    color: #000;
    text-align: center;
    font-size: 10em;

}

@keyframes slide {
    0% {margin-left: 0px;}
    10% {margin-left: 0px;}
    20% {margin-left: -1100px;}
    30% {margin-left: -1100px;}
    40% {margin-left: -2200px;}
    50% {margin-left: -2200px;}
    60% {margin-left: -3300px;}
    70% {margin-left: -3300px;}
    80% {margin-left: -4400px;}
    90% {margin-left: -4400px;}

}

Eventos

Notícias

TOPs

Análises

Galeria

Vídeos

Livestreams

Cronologia

Sobre nós

VIDEOS

1

2

3

4

5

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

Entre em contacto connosco através das redes sociais

Facebook | Instagram | Twitter |

A:

Because you set its size to width: 1100px;.
Here is an example with a size in percentage (width: 80%;) so it will depends on the size of its container and adapt to any screen size:
Note: I also convert the @keyframes and widths to percentage, to keep it consistent.

#conteudo{
    padding: 5px;
    text-align: center;
}

main {
    height: auto;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
}

div{
    background-color: transparent;
}

.div_top_img_pagina {
    background-image: linear-gradient(rgba(8, 124, 8, 0.5), rgba(0,0,0,0.9)), url("../videos/img\ top.png");
    background-position: center;
    background-repeat: no-repeat;
    background-position-y: 50px;
}

.jogos{
    display: inline-block;
    margin: 5px;
    height: 279px;
    width: 279px;
    border-radius: 20px;
    background-color: blue;

}

.jogos:hover {
    box-shadow: 0 0px 20px black;

}

#slideshow {
    display: block;
    overflow: hidden;
    height: 510px;
    width: 80%;
    margin: 0 auto 20px auto;
    text-align: center;
    border-radius: 20px;
  }

.slide-wrapper {
    width: 500%;
    animation: slide 35s ease infinite;
}
.slide {
    float: left;
    height: 510px;
    width: 20%;
}

.slide:nth-child(1) {
    background: #D93B65;
}

.slide:nth-child(2) {
    background: #037E8C;
}

.slide:nth-child(3) {
    background: #36BF66;
}

.slide:nth-child(4) {
    background: #D9D055;
}
.slide:nth-child(5) {
    background: rgb(185, 30, 216);
}

.slide-number {
    color: #000;
    text-align: center;
    font-size: 10em;

}

@keyframes slide {
    0% {margin-left: 0%;}
    10% {margin-left: 0%;}
    20% {margin-left: -100%;}
    30% {margin-left: -100%;}
    40% {margin-left: -200%;}
    50% {margin-left: -200%;}
    60% {margin-left: -300%;}
    70% {margin-left: -300%;}
    80% {margin-left: -400%;}
    90% {margin-left: -400%;}

}

VIDEOS

1

2

3

4

5

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste


Q:

Apache Camel modifies JSON when CONTENT_TYPE is application/json

I'm building my REST-API with Apache Camel and I use "bindingMode(RestBindingMode.json)" for my restConfiguration with jetty. In one of my Processors I set the "body" of the "out" object with a String that actually is a JSON object. When I set the Exchange.CONTENT_TYPE to "text/plain" the response comes in as expected and can directly be parsed to a JSON object.
{"mockBasicData":"123"}

But when I set the Exchange.CONTENT_TYPE to "application/json" or if I don't set it at all, Camel manipulates the body and escapes it, like it wouldn't already be a JSON object.
{\"mockBasicData\":\"123\"}

Is there a way to avoid that auto-escaping in Camel, as I need the CONTENT_TYPE to be "application/json"?

A:

Adding "bindingMode(RestBindingMode.off)" directly to the route (not to rest()!) solved it for me.


Q:

Where does a new DotA 2 player start?

I recently received DotA 2 as a gift from a friend. It was very generous of him, but I have absolutely no idea what I'm doing. It seems like it is even harder than Team Fortress 2 (which is actually very simple once you get the hang of it). This similar question does not seem to answer the question.

A:

Welcome to Dota, you suck. This aptly titled guide is by far the best for new players to learn Dota2. It's all-encompassing and should have everything you need to get started, but feel free to follow up with additional questions if anything seems confusing.
Here is another great all-purpose guide. It's a little newer so it's not as finely tuned, but it's incredibly detailed and very thorough.
If you haven't gotten an invite to play Dota2 yet, they are very plentiful nowadays and you can easily grab one from Reddit's Share Dota2 Subreddit or this cool bot.
Good luck. =)


Q:

Error: Unable to display this Web Part

I am receiving the following error message when trying to display my web part.
Unable to display this Web Part. To troubleshoot the problem, open this Web page in
a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft
SharePoint Designer. If the problem persists, contact your Web server administrator.

Correlation ID:e1c61ac1-788a-46c6-9311-495a5fa0603f
I had gone to Central Administration, to the Secure Store Services and created the "Target Application ID" and have already set permissions and credentials. Also, I have set the permissions in the "Business Data Connectivity Application". This removed the - BDC and NT\Authority errors that I had, now I have the error noted above and don't remember how to remove it. Thank you for your help.

A:

I Fixed it! What I learned is that parameters were not set. This has happened to me twice. When parameters/filters are not set, the return of data is too large to be passed and an error as the one noted is given. I tried going back to add filters/parameters, but instead recreated the ECT, the only difference was this time filters were added. :)


Q:

no matching function for call to for_each

here is the code:
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <iostream>
using namespace std;

map<string, int> g_map;
void read_item(const pair<string, int>& p) {
   g_map[p.first] += p.second;
}

void myprint(std::pair<const string, int> ci) {
   cout << "first : " << ci.first << "seconde : " << ci.second << endl;
}

void myprint(int ci) {
   cout << ci << endl;
}

int main()
{
    string a = string("nail");
    string b = string("hammer");
    read_item(make_pair(a, 100));
    read_item(make_pair(b, 2));
    read_item(make_pair(b, 10));
    read_item(make_pair(a, 200));

    std::for_each(g_map.begin(), g_map.end(), myprint); // can't find the matching function here
    vector<int> vec;
    vec.push_back(3);
    vec.push_back(3);
    std::for_each(vec.begin(), vec.end(), myprint);  // and here
    return 0;
}

I overloaded the function myprint, I think it should be working, but it doesn't. when I change the first myprint to myprint1 and the second to myprint2, it works. any body can help? the compile error is:
funcTemOverload.cpp: In function 'int main()':
funcTemOverload.cpp:29:54: error: no matching function for call to 'for_each(std::map<std::basic_string<char>, int>::iterator, std::map<std::basic_string<char>, int>::iterator, <unresolved overloaded function type>)'
funcTemOverload.cpp:29:54: note: candidate is:
In file included from d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/algorithm:63:0,
         from funcTemOverload.cpp:2:
d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/bits/stl_algo.h:4436:5: note: template<class _IIter, class _Funct> _Funct std::for_each(_IIter, _IIter, _Funct)
d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/bits/stl_algo.h:4436:5: note:   template argument deduction/substitution failed:
funcTemOverload.cpp:29:54: note:   couldn't deduce template parameter '_Funct'
funcTemOverload.cpp:35:50: error: no matching function for call to 'for_each(std::vector<int>::iterator, std::vector<int>::iterator, <unresolved overloaded function type>)'
funcTemOverload.cpp:35:50: note: candidate is:
In file included from d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/algorithm:63:0,
         from funcTemOverload.cpp:2:
d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/bits/stl_algo.h:4436:5: note: template<class _IIter, class _Funct> _Funct std::for_each(_IIter, _IIter, _Funct)
d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/bits/stl_algo.h:4436:5: note:   template argument deduction/substitution failed:
funcTemOverload.cpp:35:50: note:   couldn't deduce template parameter '_Funct'

A:

As requested, the reason that your original code fails is that the UnaryFunction template parameter of std::for_each is only used in a "non-deduced context", and is not explicitly specified. [temp.deduct.type]/4:

... If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

UnaryFunction is treated as a non-deduced context because of [temp.deduct.call]/6

When P [UnaryFunction] is a function type, pointer to function type, or pointer to member function type ... If the argument [myprint] is an overload set (not containing function templates), trial argument deduction is attempted using each of the members of the set. If deduction succeeds for only one of the overload set members, that member is used as the argument value for the deduction. If deduction succeeds for more than one member of the overload set the parameter is treated as a non-deduced context.

One option is to add casts:
std::for_each(
    g_map.begin(), g_map.end(),
    static_cast<void (*)(std::pair<const string, int>)>(myprint));

std::for_each(
    vec.begin(), vec.end(),
    static_cast<void (*)(int)>(myprint));

Another option is to make myprint be a function object, so that overload resolution occurs inside std::for_each:
struct myprint {
    void operator()(std::pair<const string, int> ci) const {
        cout << "first : " << ci.first << "seconde : " << ci.second << endl;
    }
    void operator()(int ci) const {
        cout << ci << endl;
    }
};

std::for_each(g_map.begin(), g_map.end(), myprint());
std::for_each(vec.begin(), vec.end(), myprint());


Q:

What do I do wrong to get hip aches after biking?

I ride about 17 miles each session. After the ride, the outside of my hips sore: only the parts near the outermost joints, most likely the tendon (although this is only a guess). My knees are fine, my ankles are fine, etc.
The only thing that might not fit perfectly for me is the seat height. I'd rather have a longer post so I can lift the seat up an inch or two. Do you think this might create the soreness in the area of the outer hips?

A:

I have personally experienced that precise symptom, from mountain biking rides or from commuting rides.
Although I am not sure what causes it, I have observed that when it happens to me, I have ridden up steep inclines in "too high" gears while remaining seated or seated too far back on the saddle. For these reasons I have changed my pedaling technique a bit, using a lot more gearshifts.
I can also recall that my problems appeared when I changed my saddle for a narrower one, so later I found that to accommodate my sit bone, I tended to sit further back, so I could catch a wider part of the saddle. No doubt I changed my saddle's fore/aft position by half an inch towards the front.
In some rare occasions I have gotten hip pain from riding in too tight, non stretching pants, like jeans, specially carrying objects in my pockets. I suspect the problem here is the pressure the clothing excepts over the hip joint while flexing up the leg. Objects like phone, keys or tools in the pockets make this worse.
Check if any of these issues is affecting you and, if you find so, try changing one thing at a time, to see if something helps.

A:

I might be inclined to try out a different saddle, look for a smoother route, or invest in wider tires (if your bike will accommodate them). If heltonbiker is correct (above), your bursae may be absorbing more shocks than they can handle, causing the pain you're feeling. If you're a woman riding on a man's saddle, consider looking for a women's saddle, as women's sit-bones are usually further apart than men's.
If you're able to consult the medical establishment, it may be worth trying for a referral to a physical therapist. Lacking that, a good massage therapist can be a wonder-worker.
Good luck! I hope you can get back to biking pain-free.


Q:

Should I cater to student interests?

I am a tenured full professor in the humanities, teaching at an elite liberal arts institution. Currently our department is struggling to attract majors and student scholars in our particular humanities field, for a number of reasons - the academic work is perceived as exotic, irrelevant vis a vis the more valuable STEM fields, and considered intellectually "useless" for those whose primary goal is "getting jobs" after graduation. I would still like to teach courses in my area, because I consider this to be valuable. My institution permits me to teach whatever I wish, but our students have requested courses that are more general and more suited for non-majors and non-scholars. Does it make more sense to offer courses for those few students who desire deep study in narrow topics, or should I cater to student demands for general classes that appeal to non-humanities undergraduates? I do not wish for my courses to be seen as irrelevant, but I resist "trends" and the constantly shifting and sometimes fickle interests of the students in popular subject matter.

A:

I'm not sure what your discipline is, but I understand the situation you're describing.  Does your school have a general education-type program in which you could offer some tantalizing courses?  We've had a lot of success with a course on "banned books," "Shakespeare on Film," or "The Vampire Tradition."  Such courses, if interesting enough, might bring more students into your major.  I taught a "Fundamentals of Lit" class that was intended for non-majors, and I had Engineering and Computer Science students who told me it was the first time they'd read a story in college and they really enjoyed the class.
The other point you raise somewhat indirectly -- the value of the study of humanities.  This is one of those "don't get me started" kinds of topics, because I believe the value of it is tremendous in a number of ways, but most important to other majors is the increased ability to communicate effectively.  Business majors may get what seems to be a "good-paying job" upon graduation, but without the communication and critical thinking skills they would learn in the Humanities, they're not going to progress very far.

A:

This question seems too general for a proper answer, but here are a few comments that point to my belief in having to weigh options and make compromises:

As someone in a STEM field (pure math) at a large state school, I still find it difficult to some things I want to teach, even at the graduate level, and have to make comprises for what would best serve our students (or at least serve our students reasonably well).  This is not just about the level at which I can teach courses, but about what kinds of topics I can cover.
Interesting courses for non-majors can often attract students to take more classes in an area, possibly resulting in an increase in the number of majors, and thus more opportunities for advanced classes later.  This is one thing some departments focus on to help grow their major.
In many departments, getting enough students to run advanced courses is a challenge.  I don't know if this is a concern for you, but if so, you need to read the situation, because you may not even have the option to run the courses you want in the near future.  Related to the previous comment, one can often try to generate interest for a specific course by motivating it in a more popular introductory course.
I personally like teaching different things and experimenting with my courses, so often I will try to mix material that I like with the material that the students come into the class wanting to learn.  (And of course, I try to motivate this well.)
Different classes, as well as different majors, have different goals.  It may be okay to have some small specialized classes (and in fact good if there are a small but serious group of students who want to pursue these topics), but if all the classes in a department are like that with shrinking enrollments, the department will probably shrink too.


Q:

Is there any way to embed a youtube video that is disabled to be embedded on sites?

Is there any way to embed youtube videos that is disabled embedding by request on youtube. Perhaps by embedding them on a custom iframe or youtube-api?
The example video I am looking at is this: http://www.youtube.com/watch?v=fhG5ToCpNh4&feature=c4-overview-vl

A:

Using http://youtube.com/v/fhG5ToCpNh4/ in an iframe yields these attributes for the YT player:
x-frame-options:SAMEORIGIN
x-xss-protection:1; mode=block;

Sorry but I think you are out of luck, the only known work-around for the same-origin policy is to write a server-side proxy. Which in this case you may as well download the .flv and host it yourself.


Q:

c# Should I use a service or just poll the database

I don't know too much about services so if I am trying to do something they are not intended for please forgive me.
I am trying to wright dispatching software for a family member. They plan on starting with 3 or 4 dispatchers but it may scale in the future. I need the software to constantly (every 5 or 10 seconds at the very least) check and see if a new unhandled call has been placed when not in a call or  if they are in a call see if another dispatcher updated the call (due to a call in with additional information).
Which option would be better for the above scenario
A) Have a table in a database that tracks updates to calls/ new calls and poll it every 5 - 10 seconds from every instance of the software.
B) Have a service running on the machine that has the database and have that service take care of all SQL. Create an instance of each call in the service and then just ask the service if there are any changes or unhandled call.
If B, is it possible to create a delegate in the service that the software on another (networked) machine can subscribe to? If so where might I find information on doing that, I could not find anything on google.

A:

This is kind to broad.
However, you can use the following

DB Trigger to watch for inserts ect, then do and fabulous db stuff when triggered.
Create a Windows Service that polls, thats not a problem at all.

You could even self host a WCF server with a Duplex Contract that other software subscribes to, you could then send notifications ect via that channel.
or use SignalR for notification which would work just fine in this situation as well, and is a 5 minute job to get working.

Though, there is lots of approaches here, You really need to do some research to find what suits you most


Q:

How to consolidate results from multiple IEnumerable using LINQ

I could have multiple (upto 5) IEnumerable<ResortSupplier> and would like to consolidate them into single IEnumerable<ResortSupplier> grouping by SupplierCode. My objects looks like this:
Here are my objects:
[Serializable]
public class ResortSupplier
{
    public string SupplierCode { get; set; }
    public IList<Product> ResortProducts { get; set; }
}

[Serializable]
public class Product
{
    public string Code { get; set; }
    //Other fields...
    public IList<PerPricing> PricingDetail { get; set; }
}

[Serializable]
public class PerPricing
{
    //Other fields..
    public decimal? Price { get; set; }
    public Error PricingError { get; set; }
}

Data in multiple IEnumerable could look like this:
----------------------------------------
IEnumerable<ResortSupplier> - 1

Hyatt Resort
  Standard Room
    PricingDetail-1
  Superior Room
    PricingDetail-1

Sandals Resort
  Standard Room
    PricingDetail-1
  Delux Room
    PricingDetail-1

----------------------------------------
IEnumerable<ResortSupplier> - 2

Hyatt Resort
  Standard Room
    PricingDetail-2
  Superior Room
    PricingDetail-2
  One Bed Room Suit
    PricingDetail-2

Sandals Resort
  Standard Room
    PricingDetail-2
  Honeymoon Suit
    PricingDetail-2
----------------------------------------
IEnumerable<ResortSupplier> - 3
.....
----------------------------------------
IEnumerable<ResortSupplier> - 4
.....
----------------------------------------
IEnumerable<ResortSupplier> - 5
.....
----------------------------------------

My consolidated result should contain:
IEnumerable<ResortSupplier> - Consolidated

Hyatt Resort
  Standard Room
    PricingDetail-1
    PricingDetail-2
  Superior Room
    PricingDetail-1
    PricingDetail-2
  Bed Room Suit
    PricingDetail-2

Sandals Resort
  Standard Room
    PricingDetail-1
    PricingDetail-2
  Delux Room
    PricingDetail-1
  Honeymoon Suit
    PricingDetail-2

----------------------------------------

What is the best way to handle this? I tried simple IEnumerable.Union and GroupBy clauses but doesn't get me the results I want.

A:

If I'm understanding you, you should use Concat to get them into one big collection, then you can group however you want
IEnumerable<ResortSupplier> master =
    result1.Concat(result2).Concat(result3); //etc

Then group like you normally would:
var resultGrouped = master.GroupBy(rs => rs.SupplierCode);

A:

I think you want something like:
// You can construct this with an array if it isn't already in this form.
IEnumerable<IEnumerable<ResortSupplier>> supplierLists = ...

var query = from suppliers in supplierLists
            from supplier in suppliers
            group supplier by supplier.SupplierCode into g

            let products = g.SelectMany(s => s.ResortProducts)
                            .GroupBy(p => p.Code)
                            .Select(prodGroup => new Product
                                    {
                                       Code = prodGroup.Key,
                                       PricingDetail = prodGroup
                                                       .SelectMany(p => p.PricingDetail)
                                                       .ToList()
                                    })

            select new ResortSupplier
            {
                SupplierCode  = g.Key,
                ResortProducts = products.ToList()
            };

That's a really horrible-looking query though. I strongly recommend factoring out the different components of the query into separate (well-named) methods.


Q:

Google Cloud Endpoints SPI restricted

I defined a simple API using Google Cloud Endpoints:
@Api(name = "realestate", version = "v1")
public class RealEstatePropertyV1 {

    @ApiMethod(name = "properties", httpMethod = "GET")
    public List<RealEstateProperty> list() {
        return ofy().load().type(RealEstateProperty.class).list();
    }
}

I also configured web.xml:
 <servlet>
  <servlet-name>SystemServiceServlet</servlet-name>
  <servlet-class>com.google.api.server.spi.SystemServiceServlet</servlet-class>
  <init-param>
   <param-name>services</param-name>
   <param-value>com.realestate.api.v1.RealEstatePropertyV1</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>SystemServiceServlet</servlet-name>
  <url-pattern>/_ah/spi/*</url-pattern>
 </servlet-mapping>
</web-app>

I launch the API in eclipse and execute curl http://localhost:8888/_ah/spi/realestate/v1/properties. The response is
<title>Error 405 HTTP method GET is not supported by this URL</title>

Error 405 HTTP method GET is not supported by this URL

The server log is:
Jun 20, 2013 9:22:14 PM com.google.appengine.tools.development.DevAppServerImpl start
INFO: Dev App Server is now running
Jun 20, 2013 9:22:29 PM com.google.api.server.spi.SystemServiceServlet init
INFO: SPI restricted: true

Do you know what does SPI restricted means? I'd like to mention that I did not register anything in the Google API console. My goal is to first test the API locally.

A:

To test your application, try
curl -X POST -d "{}" \
> -H "Content-Type: application/json" \
> http://localhost:8888/_ah/spi/realestate/v1/properties

Better yet, test your application using the APIs explorer
http://localhost:8888/_ah/api/explorer

As for SPI restricted in your logs, this just indicates whether or not that method has auth set up. In your case, for this method, it was true.


Q:

Vue.js import Array from App.vue in Component

I'm facing a problem with importing an Array from the App.vue file to a component. But first I should explain the purpose of this project. There's a component (navigation-drawer) and an App.vue file. The Navigation drawer has vue props in it, which you can dynamically change in the App.vue file. Now, my problem is that the component does not import the array properly. It only shows around 70 or 80 bullet points but it doesn't show the actual content from the array.
App.vue
<template>

    <navigation-drawer links= "[ {title='Google' , link='https://www.google.ch' },{ title='Youtube' ,link='https://www.youtube.com' } ]"
    />

    <HelloWorld msg="Welcome to Your Vue.js App"/>

</template>

Navigation-Drawer.vue
<template>

    ☰

        ×

{{ link.title }}

</template>

A:

As everyone explained you are not passing Array to NavigationDrawer component. Currently, you haven't binded Array so it is just string.
TIP: Use prop validation to mitigate this kind of issues
To solve your issue all you have to do is bind it using v-bind
<navigation-drawer
  :links="[
    {title='Google', link='https://www.google.ch'},
    {title='Youtube', link='https://www.youtube.com'}
  ]"
/>

This should fix your issue.


Q:

Why does this command line code skip every other characters?

Problem:
I'm struggling to figure out why this command line code skips every other characters?
The %INPUT_NAME% var looks like this: "Justified-S06E12-SindependenceDay-36770989-0"
The result of the code below: Instead of returning "Justified", I get something like "Jsife061".
The Goal: To strip out everything after the first "-" and use the result (In this case "Justified") to perform a search.
Any help would be much appreciated.
Current Code Iteration:

::Remove any Spaces from Search Name
set HAYSTACK=%INPUT_NAME%
set HAYSTACK=%HAYSTACK: =%
echo.%HAYSTACK%

SET SEARCHNAME=
:GetUntilDash_loop

IF %HAYSTACK% EQU "" GOTO :EOF
   IF %HAYSTACK:~0,1% EQU "-" GOTO :SearchFile
      SET SEARCHNAME=%SEARCHNAME%%HAYSTACK:~0,1%
        echo.%HAYSTACK:~0,1%
      SET HAYSTACK=%HAYSTACK:~1%

GOTO :GetUntilDash_loop

:SearchFile

A:

there is a much easier way to do this:
for /f "delims=-" %%i in ("%INPUT_NAME%") do set string=%%i

the for command divides your variable into "tokens". You can define, which char is the delimiter (in your case -). If you don't tell for which token to take, it takes the first one - exactly, what you want.


Q:

$H$ is a subgroup of index 5. $ a \in Z(G) , ord(a)=3$. Show that $ a \in H $

$H$ is a subgroup of $G$ so that $G:H=5$
$ a \in Z(G) , ord(a)=3$
Show that $ a \in H $
What I did:
if $ a \notin H $ then:
$ G/H = \{ H, aH,  a^2H, gH, agH \} $ for some $ g \in G-H $
But I don't know how to procceed...

A:

As in Cihan's answer, let $A = \langle a\rangle$. Since $a \in Z(G)$, $AH$ is a subgroup of $G$ containing $H$. As $[G : H]$ is prime, $AH = H$ or $AH = G$. In the latter case, $G = H\cup aH \cup a^2H$, a union of at most 3 left cosets of $H$, contradicting $[G:H] = 5$. So $AH = H$, which implies $a \in H$.


Q:

Is an "If statement" the exact same as a "Switch statement" in Java?

Performance aside, I'm wondering if there are certain situations where only an If statement can be used and not a Switch statement and vice versa?
As in, are they completely interchangeable? Could I swap an entire section of code From Switch statements to If statements and vice versa if I so desired or would that break specific programs?
Not that I would want to but just theoretically and out of curiosity as I am new to Coding and have been wondering this.
I couldn't really find the answer I was looking for so I apologize if this is a duplicate.

A:

They are fundamentally different in what they can do - if statements can check any logic you can distil down to a boolean value in some way, while switch statements compare exact values for each case - see the docs for details.

An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

This means if you want to do more complex logic than 'does this value equal this number, enum or string' for each case, you need if statements (or some other way of managing flow) rather than a switch.
A simple example is checking if a number is over 10 but under 9000.
if (value > 10 && value < 9000) {
    ...
}

Converting this to a switch statement would mean doing something insane like have a case for every possible value over 10 but under 9000)


Q:

Using a preset variable to pull a column name, then use it within a query

I am trying to create a pricing system for a bookings company, I have a DataBase table full of prices. A typical row looks like this:
priceID  |  manufac  |  model  |  janDay  | janWeek  |  febDay  |  febWeek  |  etc etc
--------------------------------------------------------------------------------------
1        |Chevrolelt |  Matiz  |  40.00   |  133.00  |  40.00   |  133.00   |  etc etc

Basically I have a variable:
$startmonth

This variable is set by my code finiding out the month, and depending on its number assigning it a value. In this instance lets assume that it has gone through that and obtained the value:
$startmonth = 'febWeek';

I then have another query that finds out the model of a car, I have tested this and it returns the model, so we know that:
$model = 'Matiz';

Then I execute another query to gain the price:
$getprice = mysql_query("SELECT '".$startmonth."' FROM prices WHERE model = '".$model."' ");
while($ppdrow = mysql_fetch_assoc($getprice)) {

   $priceperday = $ppdrow;

}

I have tried this query numerous ways and I always end up with errors or an undesirable result. When it should return 133.00.
What it actually returns:
( [2] => 2 )

I am proobably doing something really stupid, but can anyone tell me what please?

A:

You can try this
$getprice = mysql_query("SELECT ".$startmonth." FROM prices WHERE model ='".$model."'   ");
while($ppdrow = mysql_fetch_assoc($getprice)) {

 $priceperday = $ppdrow[$startmonth];

}

A:

Try this query instead:
$getprice = mysql_query("SELECT `".$startmonth."` FROM prices WHERE model = '".$model."' ");

Note the backticks (around the column name) in the place of the single quotes.
And as for the while loop, you are trying to set $priceperday equal to $ppdrow, which is an array. You want to set it to the correct value (column) within the array:
while($ppdrow = mysql_fetch_assoc($getprice)) {
   $priceperday = $ppdrow[$startmonth];
}

Please also read about why not to use mysql_*


Q:

Contention on tempdb due to high concurrency temp table creation from multiple databases?

I have an environment with ~100 databases, all with the same schema.  There is a stored procedure on each database that creates a #temp table and drops it, and is running very often (every 30 seconds or so per user, and there are 1000+ users). It's doing a lot more than just this: We are loading potentially thousands of rows into this temp table and just dumping the whole thing out, basically it aggregates a bunch of data.
Since all the databases create the same temp table, are they all competing with each other?  Or does each database get its own version of the temp table in tempdb?
It seems like they are having contention because I see a large amount of PAGE_LATCH waits, all on the same page in tempdb (2:3:1041580), which is not a GAM, SGAM, or PFS page, and 90% of the waits seem to be from this same stored procedure across all databases.  These waits are 90% of the overall waits on the server and are causing blocking.
I did a DBCC PAGE, and it appears to be sysobjvalues (from the object_ID 60 in the header).  I ran:
SELECT OBJECT_Name(object_ID), *
FROM sys.dm_db_database_page_allocations(2,60,NULL,NULL,'DETAILED')

I get 153 rows, not sure exactly what I'm looking at here.  Looks like it's IN_ROW_DATA and LOB_DATA in allocation_unit_type_desc.
I have 8 tempdb files on a separate volume from the other files.  I have 16 cores but my understanding is that since it's not an allocation page it might not help to increase the number of files.  Using SQL Server 2017 Enterprise.
I feel like the best bet is to just tell the developers to remove the temp table here but that will require reworking the logic and will take some time.  Is there anything else I can do to avoid these page latches while I wait for the dev fix?

A:

We are loading potentially thousands of rows into this temp table and just dumping the whole thing out, basically it aggregates a bunch of data.

Temporary tables can be a big performance and reliability win, when used correctly.
For example, it can be very useful to store a relatively small (and narrow) intermediate result set in a temporary table so SQL Server can compute automatic statistics on the data, or so the user can add specific indexing.
Temporary tables are most useful when they allow the optimizer to produce a better sequence of plans overall than a single monolithic query.
It is also possible to use temporary tables poorly. Simply storing rows in a temporary table before "dumping the whole thing out" sounds counter-productive. Always bear in mind that temporary tables are not free, and can contribute to contention.
Aside from using temporary tables in a sensible way, try to arrange things so you take advantage of temporary table caching. See my article SQL Server Temporary Object Caching for details.
Ensure you are running the latest cumulative update, since there have been several performance optimizations and bug fixes employed, for example:

PFS page round robin algorithm improvement in SQL Server 2016 and 2017 (2017 RTM CU7)
FIX: Heavy tempdb contention occurs in SQL Server 2016 or 2017 (2017 RTM CU5)


Q:

Ignoring directories when using git pull

:)
I have a production *nix server that gets the updated files from github using "git pull".
My problem is that there are outdated versions of some plugins in "app/code/community/", which would be pulled and would overwrite my local (up-to-date) files and folders.
I do not know how to tell git to just ignore this directory when I pull from github... Can anybody help me out here?
Thanks in advance!
Chris

A:

You can do the following:

git pull it will replace you {up-to-date} files with old
git checkout --ours -- <filename> to revert you files to your version
git add and commit

Hope this solves your problem!
For more details try going through: Simple tool to 'accept theirs' or 'accept mine' on a whole file using git
Happy Gitting!


Q:

King wall heater - fan works but no heat

The other day our King wall heater stopped working.  The fan spins but no heat.  I took it apart and cleaned it, I also reset the breaker and the unit itself (via the instructions to turn off the thermostat for 10seconds).  However nothing has fixed it.
During cleaning there seemed to be some bits of the heating coil so Im thinking that somehow that broke.
Is there any way to replace just the coils?  I couldn't find them anywhere.
Barring replacement of just the coil I need to replace the whole unit, but I dont understand these stickers and what model I actually have installed.
This seems like the right replacement model but the measurements dont line up (am I missing something)?
Amazon replacement
damaged coils:

the measurements I read are 11.5" x 8.75"

A:

I finally heard back from King today (very helpful once you get a response).  It answers my questions.
also i verified it was the heating "element" by taking it out of a working one, so i only had to replace that!!!
response from King (manufacturer):

Yes this is our W series https://www.king-electric.com/pdfs/W_WEB.pdf
  These have a 1 year warranty.
Here is the element
  http://www.morelectricheating.com/default.aspx?page=item+detail&itemcode=KINGELECTRIC50303&catlist=1363&parent=7983
Its best to go by our catalog for dimensions. Other sites are popular
  for getting the diminsions wrong. The dimensions have been the same
  since the unit came out in 1992
Here is the unit you need
  http://www.morelectricheating.com/default.aspx?page=item+detail&itemcode=KINGELECTRIC12743&catlist=262&parent=1366


Q:

How to populate a column in one dataframe by comparing it to another dataframe

I have a dataframe called res_df:
In [54]: res_df.head()
Out[54]:
       Bldg_Sq_Ft        GEOID       CensusPop  HU_Pop  Pop_By_Area
0     753.026123  240010013002022       11.0     7.0          NaN
7      95.890495  240430003022003       17.0     8.0          NaN
8    1940.862793  240430003022021       86.0    33.0          NaN
24   2254.519775  245102801012021       27.0    13.0          NaN
25  11685.613281  245101503002000      152.0    74.0          NaN

I have a second dataframe made from the summarized information in res_df. It's grouped by the GEOID column and then summarized using aggregations to get the sum of the Bldg_Sq_Ft and the mean of the CensusPop columns for each unique GEOID. Let's call it geoid_sum:
In [55]:geoid_sum = geoid_sum.groupby('GEOID').agg({'GEOID': 'count', 'Bldg_Sq_Ft': 'sum', 'CensusPop': 'mean'})
In [56]: geoid_sum.head()
Out[56]:
                      GEOID    Bldg_Sq_Ft  CensusPop
    GEOID
    100010431001011      1   1154.915527        0.0
    100030144041044      1   5443.207520       26.0
    100050519001066      1   1164.390503        4.0
    240010001001001     15  30923.517090       41.0
    240010001001007      3   6651.656677        0.0

My goal is to find the GEOIDs in res_df that match the GEOID's in geoid_sum. I want to populate the value in Pop_By_Area for that row using an equation:
Pop_By_Area = (geoid_sum['CensusPop'] * ref_df['Bldg_Sq_Ft'])/geoid_sum['Bldg_Sq_Ft']
I've created a simple function that takes those parameters, but I am unsure how to iterate through the dataframes and apply the function.
def popByArea(census_pop_mean, bldg_sqft, bldg_sqft_sum):
    x = float()
    x = (census_pop_mean * bldg_sqft)/bldg_sqft_sum
    return x

I've tried creating a series based on the GEOID matches: s = res_df.GEOID.isin(geoid_sum.GEOID.values) but that didn't seem to work (produced all false boolean values). How can I find the matches and apply my function to populate the Pop_By_Area column?

A:

I think you need the reindex
geoid_sum = geoid_sum.groupby('GEOID').\
              agg({'GEOID': 'count', 'Bldg_Sq_Ft': 'sum', 'CensusPop': 'mean'}).\
               reindex(res_df['GEOID'])

res_df['Pop_By_Area'] = (geoid_sum['CensusPop'].values * ref_df['Bldg_Sq_Ft'])/geoid_sum['Bldg_Sq_Ft'].values