text:
Q: ERROR: there is no unique constraint matching given keys for referenced table "abteilung" I get this error:

ERROR:  there is no unique constraint matching given keys for referenced table "abteilung"

For this schema:
CREATE TABLE Person (
    svnr VARCHAR(40) PRIMARY KEY,
    anschrift VARCHAR(40) NOT NULL,
    name VARCHAR(20) NOT NULL
);

BEGIN;

CREATE TABLE Mitarbeiter (
    svnr VARCHAR(40) PRIMARY KEY REFERENCES Person(svnr),
    beschaeftigt_seit DATE NOT NULL,
    gehalt NUMERIC(5,2),
    CHECK(gehalt > 0),
    abteilung INTEGER NOT NULL,
    krankenhaus INTEGER NOT NULL
);

CREATE TABLE Krankenhaus (
    kid INTEGER PRIMARY KEY DEFAULT nextval('seq_krankenhaus'),
    anschrift VARCHAR(40) NOT NULL,
    name VARCHAR(20) NOT NULL,
    geleitet_von VARCHAR(40) REFERENCES Mitarbeiter(svnr) DEFERRABLE INITIALLY DEFERRED
);

CREATE TABLE Abteilung (
    abid INTEGER DEFAULT nextval('seq_abteilung'),
    name VARCHAR(40) NOT NULL,
    anschrift VARCHAR(40) NOT NULL,
    koordiniert VARCHAR(40) REFERENCES Mitarbeiter(svnr) DEFERRABLE INITIALLY DEFERRED,
    krankenhaus INTEGER REFERENCES Krankenhaus(kid),
    PRIMARY KEY (abid, krankenhaus)
);

ALTER TABLE Mitarbeiter ADD CONSTRAINT fk_abteilung FOREIGN KEY (abteilung, krankenhaus) REFERENCES Abteilung(abid, krankenhaus) DEFERRABLE INITIALLY DEFERRED;

COMMIT;

What I am doing wrong?
After adding a column krankenhaus to the table mitarbeiter and changing the alter table command but I still get the same error ...

A: The primary key of the table Abteilung is (abid, krankenhaus). As a foreign references references exactly one row, you also need to use both columns in the foreign key constraint definition.
But as you don't have a column krankenhaus in your table Mitarbeiter you can't reference Abteilung.
You either need to reduce the primary key of Abteilungto (abid) (which would be possible as it is a generated, artificial key anyway) or add a column Krankenhaus to your Mitarbeiter table.

A: This should work:
CREATE TABLE person (
   svnr text PRIMARY KEY
 , anschrift text NOT NULL
 , name text NOT NULL
);

CREATE TABLE mitarbeiter (
   svnr text PRIMARY KEY REFERENCES person
 , beschaeftigt_seit date NOT NULL
 , gehalt numeric(5,2)
 , abid int NOT NULL
 , CHECK(gehalt > 0)
);

CREATE TABLE krankenhaus (
   kid serial PRIMARY KEY
 , anschrift text NOT NULL
 , name text NOT NULL
 , geleitet_von text REFERENCES mitarbeiter(svnr) DEFERRABLE INITIALLY DEFERRED
);

CREATE TABLE abteilung (
   abid serial PRIMARY KEY
 , kid INTEGER REFERENCES krankenhaus(kid)
 , koordiniert text REFERENCES mitarbeiter(svnr) DEFERRABLE INITIALLY DEFERRED
 , name text NOT NULL
 , anschrift text NOT NULL
);

ALTER TABLE mitarbeiter
   ADD CONSTRAINT fk_abteilung FOREIGN KEY (abid)
   REFERENCES abteilung(abid) DEFERRABLE INITIALLY DEFERRED;

Use a serial column for surrogate PKs:

*

*Auto increment table column
Don't use varchar(n) with arbitrary limitations for string length, unless you really need to enforce a maximum length and its not going to change. See:

*

*Any downsides of using data type "text" for storing strings?
Go with just abid as primary key for abteilung. There would be a related application for a redundant column included in a FK constraint, but that's not what your model does right now:

*

*Complex foreign key constraint in SQLAlchemy
No need to use an explicit transaction (BEGIN ... COMMIT) for part of the code.
The real difficulty with these circular references is entering and changing data. You probably made your FK constraints DEFERRABLE INITIALLY DEFERRED - which is going to make some queries considerably slower.
You could go with just plain default IMMEDIATE FK constraints, if you wrap INSERT / UPDATE on related rows into data-modifying CTEs. See:

*

*How to deal with mutually dependent inserts


text:
Q: Parseable output from NPM I am trying to write a small application that wraps some functions inside of NPM from another language.  "npm list" is giving me output with a nice visual tree, but I need something easier to parse.  -parsable is giving me a flat list of modules, but I would like to have some of the metadata available in "npm ll".  Is there a switch or something for NPM that lets me get JSON output?  Right now the only way I can figure to do this is to write a node app that uses the npm module to push json to the standard output.

A: I think you want to do
npm ls --json

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I detect when I view an email in gmail with google-apps-script script? I'd like to trigger a script every time I view an email in gmail. Does anyone know if there a trigger for detecting this which i can bind to?
I'm open to doing this with any platform, not just google-apps-script.

A: Short answer
At this time Google Apps Script doesn't have a triggers for Gmail events.
Explanation
On Google Apps Script there are three kinds of scripts, bounded, stand-alone and web apps, and two kinds of triggers, simple and installable
Scripts only could be bounded to documents, forms and spreadsheets.
The available simple triggers are:

*

*onOpen(e)1,2,3

*onEdit(e)2

*onInstall(e)4

*doGet(e)5

*doPost(e)5
The available installable triggers are:

*

*Time-driven triggers

*Google Apps triggers

*

*on open1,2,3

*on edit2

*on change2

*on submit form2,3
Triggers by app
The triggers works on the following "environments":

*

*Google Documents editor

*Google Sheets editor

*Google Forms editor

*Add-ons

*Web Apps

Note: There are no simple nor installable that works on the Google Forms Viewer (response submission).
References

*

*https://developers.google.com/apps-script/guides/standalone

*https://developers.google.com/apps-script/guides/triggers/

*https://developers.google.com/apps-script/guides/triggers/events


text:
Q: Dropbox Core API for Swift:Cannot initialize DBSession? I was following the link below in order to use the Dropbox Core API in my iOS application: https://www.dropbox.com/developers/core/start/ios
However, this is all written in Objective C. I have gotten it so that I have imported the DropboxSDK into my project but I can't seem to find the Swift equivalent code of beginning the authorization process. I have tried  looking at all of the given functions in DBSession and DBSessionDelegate that look similar to those in the example tutorial above but I haven't had any luck. Any ideas how to do this? The following is the code in Objective C that I am trying to translate into Swift.
DBSession *dbSession = [[DBSession alloc]
      initWithAppKey:@"INSERT_APP_KEY"
      appSecret:@"INSERT_APP_SECRET"
      root:INSERT_ACCESS_TYPE]; // either kDBRootAppFolder or kDBRootDropbox
[DBSession setSharedSession:dbSession];

Specifically, I can't seem to find any function to allow me to initialize my application key app secret, or root. If anyone could help me out, that'd be great! Thanks.

A: let session = DBSession(appKey:"...", appSecret:"...", root:...); works in my testing.
You may want to read https://www.dropbox.com/developers/blog/109/swift-apps-with-dropbox for the basics of using Dropbox SDKs in Swift. (That blog post doesn't deal specifically with the Core SDK, but the steps there still apply.)


text:
Q: Getting GLIBC_2.28 not found I running node -v command getting error:-
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)

Any solution

A: Finally I got solution by running by running following commands.
sudo apt-get remove nodejs
nvm install 16.15.1

node v16.15.1 version and npm v16.15.1 is installed.
For same make sure nvm is installed in your machine.

A: you can install node v17.x by nvm(nodejs version manager).
my OS version: Ubuntu 18.04.6 LTS
I tried three ways to install node and npm in my pc:

*

*(fail) apt-get, the version is very old
$ sudo apt-get install nodejs
$ sudo apt-get install npm
$ node -v
v8.10.0
$ npm -v
6.1.0

*(fail) script from source code of nodejs, only node is updated, npm is not.
https://github.com/nodesource/distributions/blob/master/README.md#using-ubuntu-1
$ curl -sL https://deb.nodesource.com/setup_14.x -o /tmp/nodesource14_setup.sh
$ node -v
v14.20.1
$ npm -v
6.1.0

*(success) use nvm
https://github.com/nvm-sh/nvm#installing-and-updating
$ sudo apt-get remove nodejs
$ sudo apt-get remove npm

$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash
$ chmod +x ~/.nvm/nvm.sh
$ source ~/.bashrc

$ nvm -v
0.39.2

$ nvm install 14

$ node -v
v14.20.1
$ npm -v
6.14.17

$ nvm install 16

$ node -v
v16.18.0
$ npm -v
8.19.2

$ nvm install 17

$ node -v
v17.9.1
$ npm -v
8.11.0

# failed to install 18
$ nvm install 18

$ node -v
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)
$ npm -v
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)

A: You got the issue because node version is not compatible with ubuntu. IN my case, I got the same issue with Ubuntu 18 & Node 16.15.1.
Using this command to check GLIBC version
ldd --version

My version is 2.27. So I has tried to fix by change the nodejs version.
sudo apt-get remove nodejs
nvm install 14.17.6

A: You likely have a node version installed that is compiled for a different ubuntu release to the one you are running.
I would suggest removing it, then installing the nodesource binary distribution. It should auto-detect your ubuntu release and install the correct node release.

A: i had this issue  using :

*

*ubuntu 18.04 WSL2

*Windows 11

after updating NVM and NPM...
i fixed it by updating ubuntu to 20.04
tutorial here :
https://www.nextofwindows.com/how-to-upgrade-existing-wsl-wsl2-ubuntu-18-04-to-20-04

A: the root cause is the latest node need glibc2.28 but the Ubuntu 18 only includes glic2.27.
Solution: 1. use a lower version node, e.g. "sudo apt-get remove nodejs
nvm install 16.15.1". refer to "Abhay Kumar Upadhyay"'s answer.
Solution 2: upgrade glibc to glic2.28+. refer to:  https://www.digitalocean.com/community/questions/how-install-glibc-2-29-or-higher-in-ubuntu-18-04
Solution 3: upgrade Ubuntu 18 to 20. refer to "'Hállex da S. Costa"'s answer.

A: I'd had the same problem when installing Node with versions greater than  or equal 18.
My solution was upgrade my distribution Ubuntu to version 20.04, followings the steps:
My requirements before upgrade:

*

*Node.js (v18.x)

*Windows 10

*WSL 2 (Distribution Ubuntu-18.04)

Making a backup from your WSL system (for your security)

if you don't use WSL you can skip the steps:

*

*Open CMD or PowerShell as Admin.

*Stop the WSL instance with wsl --shutdown

*Create folder wsl-backup with the command mkdir C:\wsl-backup\.

*Run command wsl --export Ubuntu-18.04 C:\wsl-backup\ubuntu-18.04.tar.

If there is a problem in the process, you can restore your WSL using the command mkdir C:\WSL and wsl --import Ubuntu-18.04 C:\WSL C:\wsl-backup\ubuntu-18.04.tar to recover.

Upgrading Ubuntu 18.04 to 20.04

*

*Removing the Snapd package:

For me it was necessary to remove the snapd package, because ubuntu was not allowing me to upgrade to 20.04 LTS version

sudo apt purge snapd

*Run commands to update and upgrade packages:

sudo apt update
sudo apt list --upgradable
sudo apt upgrade -y

*Install the update-manger-core package:

It's essential to install this update manager core package this will trick the system into thinking there is a new LTS available and allow you to do an in-place upgrade.

sudo apt install update-manager-core

*Install the new version with:

sudo do-release-upgrade

if you are using an LTS version (recommended) and found that there is no new LTS version available it will show this message
Checking for a new Ubuntu release
There is no development version of an LTS available.
To upgrade to the latest non-LTS development release
set Prompt=normal in /etc/update-manager/release-upgrades.

If it's not relevant to you to not use LTS versions, you can change the Prompt to normal in /etc/update-manager/release-upgrades file and rerun the previous command.
sudo do-release-upgrade -d

*During installation, will need your interaction to allow installation of the additional packages that come in version 20.04 (Including lib6 that is required by node).

*Finished, now can verify your distribution version  ubuntu using the command:
lsb_release -a

You should get an output similar to this
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.5 LTS
Release:    20.04
Codename:   focal

Now you can use node version >=18
Install Node 18 with NVM
Installing node LTS

In the current date (26/nov/2022) is v18

nvm install lts
# or nvm install --lts

Use LTS version
nvm use lts

Check node version
node -v
# v18.12.1

References:
Upgrade Ubuntu Version on WSL
22.04 LTS "sudo do-release-upgrade" does not work
Can't upgrade to Ubuntu 21.04 : "Restoring original system state. Aborting"

A: GitHub Actions
I ended up here after my GitHub Actions build failed with the error:

node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)

The problem is ubuntu-18.04 not supporting node 18 (as explained [here](node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node))) because of the glibc version bump.
The solution is to update to ubuntu-20.04 or higher.

A: Agree with others to remove and reinstall the nodejs, but if you don't want to uninstall it or you are not sure to remove it, change the version.

nvm use 16

Or any version that works for your test. it worked for me!

A: As per @ys_sunshine, I had change a few things for Rasberry Pi.
After installing the LTS version as per the following instructions:
https://pimylifeup.com/raspberry-pi-nodejs/
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -

I got the following error:
$ node -v
node: /lib/arm-linux-gnueabihf/libm.so.6: version `GLIBC_2.27' not found (required by node)
node: /lib/arm-linux-gnueabihf/libc.so.6: version `GLIBC_2.25' not found (required by node)
node: /lib/arm-linux-gnueabihf/libc.so.6: version `GLIBC_2.28' not found (required by node)

This meant I couldn't run anything, so I tried the following:
$ sudo apt-get remove nodejs
$ sudo apt-get remove npm

$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh > install.sh
$ chmod +x install.sh
$ source ~/.bashrc

$ nvm -v
0.39.2

$ nvm install 14

$ node -v
v14.22.2

$ npm -v
6.14.17

A: This issue can be resolved by switching to stable available node version. You can switch to the stable node version with the below command.
nvm install --lts

Then, Use nvm alias default {VERSION} to switch the version of Node.js used by default when starting a new shell.


text:
Q: Select tags with js how can I make a select elements with js?
Imagine somethings as:
<button class="" type="button" role="option"> Tag1 + </button>
<button class="" type="button" role="option"> Tag2 + </button>

And when I click on one of the buttons, it receives the active class as follows :
<button class="active" type="button" role="option"> Tag1 + </button>
<button class="" type="button" role="option"> Tag2 + </button>

Any help? Cheers everyone!

A: I think you need a code like the following :
Css :
<style type="text/css">
        .active {
            color: white;
            background-color: black;
        }
</style>

Html :
<button class="" type="button" id="tag1" onclick="addClass()" role="option">Tag1 </button>

JS :
<script type="text/javascript">
    function addClass() {
       var tag1 = document.getElementById("tag1");

          if (tag1.classList.contains("active")) {
             tag1.classList.remove("active");
          } else {
             tag1.classList.add("active");
          }
    }
</script>


text:
Q: Selecting and writing paragraphs with matching starting terms I have a doc/pdf file which contains legal terms defined in english as well as in translation in another language. The format is like this:
Term 1- defined in english
Term 2- defined in english
Term nth- defined in english

Term 1- defined in other language

Term 2- defined in other language

Term nth- defined in other language

What I am looking for is to use regex to select paragraphs of terms in english and the translated language and write them one after the other to a text file like this:
Term 1- defined in eng

Term 1- defined in other lang

Term 2- defined in eng

Term 2 - defined in other lang.

Can you please help me with regex on this?

A: I don't think it's a good idea to use Regular Expressions for this. Regular Expressions are used for searching for particular patterns or replacing text in strings based on a particular pattern (usually for changing some format of a string in a linear fashion).
It may be better to simply read them as two arrays then use a for loop:
var lang1=["One","Two","Three"];
var lang2=["Uno","Dos","Tres"];
var newStr="";
for(var i=0; i<lang1.length; i++){
    newStr+=("Term "+(i+1)+" in lang1 - "+lang1[i]+"\n");
    newStr+=("Term "+(i+1)+" in lang2 - "+lang2[i]+"\n");
}

Here is an example in JavaScript: http://jsfiddle.net/U4HbB/


text:
Q: Imprimir datos json en etiqueta span soy nuevo en esto del JSON y trata de datos por medio de JS, quisiera su ayuda con lo siguiente:
Trabajo por horas para una empresa que ofrece servicios sistemas de reservas y me pidieron con ayuda de documentación y todo lo demás crear o modificar un script que es "nuevo" para hacer un filtro al estilo de trivago, pero me dieron un código que ya imprimía precio de habitación, nombre de hotel y un botón que genera un enlace externo (esta parte funciona bien), el cual modifique y logre incluir el logo del hotel, pero ahora tengo otra función que debo hacer lo mismo y he intentado de muchas formas algunas de las que estarán incluso comentadas, pero todo me lleva a lo mismo a imprimir el JSON en su totalidad y no solo las partes que necesito del mismo.
Explico un poco más la parte que estoy intentando imprimir es wb.rooms() donde debo tratar de imprimir el nombre de la habitación, la descripción y la o las imágenes que contenga, para poder seguir avanzando con la creación, como mencioné allí es donde está el problema, pego mucho más del código en el que tengo dudas para darles más contexto. De Antemano muchísimas gracias por su ayuda y apoyo prestado.
  //Variable action que genera enlace para el boton reservar ahora
                                                var action = "wbs[" + n + "].open({open_on_tab: 1, dfrom: '" + mp_dfrom + "', dto: '" + mp_dto + "', occupancies: '" + guests + "'})";

                                                //imprime los resultados obtenidos de la consulta de disponibilidad
                                                mp_jquery('#mp_results').append('

Mejor precio para:

 ' + parseFloat(price).toFixed(2) + '  Por Persona y por Noche
  <button class=" btn btn-danger btn-flat" onclick="' + action + '">Revervar Ahora</button>
');

                                                wb.rooms({}, function(data) {
                                                    var roomsR = {
                                                        data
                                                    }
                                                    var rooms = JSON.stringify(roomsR);
                                                //document.getElementById("rooms").innerHTML=JSON.stringify({ data });
                                                         var valor = '';
                                                          data.rooms.forEach(data => {
                                                            valor += '
'+
                                                             '' + rooms.id + '	'+
                                                             '' + rooms.name_es + '	'+
                                                             '' + rooms.desc_es + '	'+
                                                             '' + rooms.images + '	'
                                                             ;
                                                          })
                                                          $('#rooms').html(valor);
                                                //document.getElementById("rooms").innerHTML = JSON.stringify(data)

                                                //document.getElementById("rooms").innerHTML+="
id="+rooms;
                                                //html.innerHTML+="
name="+rooms.data.name;
                                                //console.log(JSON.stringify({ roomsR }));

                                                    console.log(roomsR);
                                                })

                                                //recoje todos los valores del resultado de la consulta de disponibilidad
                                                wb.overview({
                                                    'currency': currency
                                                    //'descr_es': descr_es,
                                                }, function(data) {
                                                        //Moneda
                                                    mp_jquery('.mp_result_lcode_' + data['lcode']).find('.mp_currency').text(data['money_sym']);
                                                    //Nnombre del Hotel
                                                    mp_jquery('.mp_result_lcode_' + data['lcode']).find('.mp_name').text(data['name']);
                                                    //Logo del HOtel
                                                     mp_jquery('.mp_result_lcode_' + data['lcode']).find('img').attr('src', data['hotel_logo_url']);

                                                    mp_jquery('.mp_result_lcode_' + data['lcode']).find('.mp_value').text((parseFloat(mp_jquery('.mp_result_lcode_' + data['lcode']).find('.mp_value').text()) * data['currency_conversion']).toFixed(2));


text:
Q: Change Object Fields with Data from Array For each user in my array I want to take their positionTitle if the 'isPrimary' is set to true and use this positionTitle to replace all positionTitle's of the same user in my object.
Both data sets have 'fullName' which I think should be used as there can be multiple positions which leads me to think the positionID can not be used.
The code I have does replace the titles but doesn't work if a user has multiple positions.
Side note: if there are no primary positions I would like the first position for a user in the array to be used.
The isPrimary in the object is basically irrelevant.
My object:
graphData = {

  "name": "Annual meetings",
  "engagementAreas": [{
    "id": "1",
    "engagementTypes": [{
      "name": "forestry",
      "engagements": []
    },{
      "name": "houses",
      "engagements": [{
        "name": "engagement1",
        "members": [{
          "id": "e334", "account": {
            "id": "123", "fullName": "jim bean"
          },
          "position": {
            "id": "3434",
            "positionTitle": "Manager",
            "isPrimary": false
          }
        }]
      }]
    },{
      "name": "landscaping",
      "engagements": [{
        "name": "engagement1343",
        "members": [{
          "id": "e334", "account": {
            "id": "123", "fullName": "john boer"
          },
          "position": {
            "id": "4545",
            "positionTitle": "Managing Director",
            "isPrimary": true

          }
        },{
          "id": "5555", "account": {
            "id": "123", "fullName": "jim bean"
          },
          "position": {
            "id": "a16b0000004AxeBAAS",
            "positionTitle": "Managing Director",
            "isPrimary": true
          }
        }]
      }]
    }]

  },{

    "name": "community days",
    "engagementTypes": [{
      "name": "skyscraping",
      "engagements": []
    },{
      "name": "tennis",
      "engagements": [{
        "name": "engagement346",
        "members": [{
          "id": "34", "account": {
            "id": "0010X000048DDMsQAO", "fullName": "edy long"
          },
          "position": {
            "id": "3999434",
            "positionTitle": "Managing Director",
            "isPrimary": true
          }
        }]
      }]
    },{
      "name": "Juicing",
      "engagements": [{
        "name": "347343",
        "members": [{
          "id": "4546", "account": {
            "id": "001b000003WnPy1AAF", "fullName": "jeff bint"
          },
          "position": {
            "id": "35006",
            "positionTitle": "Senior Manager, Energy"

          }
        }]
      }]
    }]
  }]
}

Notice Jim bean has two position.
My array, whose isPrimary: true positionTItles I want to use:
IndividualData = [{
  "account": {
    "id": "23423",
    "fullName": "jim bean"
  },
  "positions": [{
    "id": "123",
    "organizationId": "001b0000005gxmlAAA",
    "organizationName": "a",
    "positionTitle": "Dalius Senior Manager, Energy",
    "positionLevel": "5-Middle Management & Advisers",
    "isPrimary": true,
    "startDate": "2016-10-07",
    "endDate": null
  }]
},{
  "account": {
    "id": "394838",
    "fullName": "jim bean"
  },
  "positions": [{
    "id": "a16b0000004AxeBAAS",
    "organizationId": "001b0000005gxmlAAA",
    "organizationName": "a",
    "positionTitle": "Head Recruiter",
    "positionLevel": "Senior Management",
    "isPrimary": false,
    "startDate": "2008-04-23",
    "endDate": null
  }]
},{
  "account": {
    "id": "001b000003WnPy1AAF",
    "fullName": "jeff bint"
  },
  "positions": [{
    "id": "a16b0000004AxeBAAS",
    "organizationId": "001b0000005gxmlAAA",
    "organizationName": "a",
    "positionTitle": "Senior Manager, Energy",
    "positionLevel": "5-Middle Management & Advisers",
    "isPrimary": true,
    "startDate": "2016-10-07",
    "endDate": null
  }]
}, {
  "account": {
    "id": "0010X000048DDMsQAO",
    "fullName": "edy long"
  },
  "positions": [{
    "id": "a160X000004nKfhQAE",
    "organizationId": "001b0000005gxmlAAA",
    "organizationName": "a",
    "positionTitle": "Managing Director",
    "positionLevel": "4-Head of Business Unit/Head of Region",
    "isPrimary": true,
    "startDate": "2018-03-05",
    "endDate": null
  }]
}, {
  "account": {
    "id": "123",
    "fullName": "john boer"
  },
  "positions": [{
    "id": "325345634634",
    "organizationId": "001b0000005gxmlAAA",
    "organizationName": "a",
    "positionTitle": "Managing Director",
    "positionLevel": "4-Head of Business Unit/Head of Region",
    "isPrimary": true,
    "startDate": "2018-03-05",
    "endDate": null
  }]
}]

Jim Bean also has two positions in the array above, but one is primary.
my code which currently does replace but doesnt take the primary from the array and update all positionTitles for the same user:
const accountIdToPositionDict = IndividualData.reduce( (current, item) => {
  current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
  return current;
}, {} );

const updatedGraphTable = { ...graphData,
  engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
    engagementTypes: area.engagementTypes.map(type => ({ ...type,
      engagements: type.engagements.map(engagement => ({ ...engagement,
        members: engagement.members.map(member => ({ ...member,
          position: { ...member.position,
            // use the found positionTitle, or the original one that was given
            positionTitle: member.account &&  accountIdToPositionDict[member.account.id] || member.position.positionTitle
          }
        }))
      }))
    }))
  }))
};

My current output:
{
  "name": "Annual meetings",
  "engagementAreas": [{
    "id": "1",
    "engagementTypes": [{
      "name": "forestry",
      "engagements": []
    }, {
      "name": "houses",
      "engagements": [{
        "name": "engagement1",
        "members": [{
          "id": "e334",
          "account": {
            "id": "123",
            "fullName": "jim bean"
          },
          "position": {
            "id": "3434",
            "positionTitle": "Managing Director",
            "isPrimary": false
          }
        }]
      }]
    }, {
      "name": "landscaping",
      "engagements": [{
        "name": "engagement1343",
        "members": [{
          "id": "e334",
          "account": {
            "id": "123",
            "fullName": "john boer"
          },
          "position": {
            "id": "4545",
            "positionTitle": "Managing Director",
            "isPrimary": true
          }
        }, {
          "id": "5555",
          "account": {
            "id": "123",
            "fullName": "jim bean"
          },
          "position": {
            "id": "a16b0000004AxeBAAS",
            "positionTitle": "Managing Director",
            "isPrimary": true
          }
        }]
      }]
    }]
  }, {
    "name": "community days",
    "engagementTypes": [{
      "name": "skyscraping",
      "engagements": []
    }, {
      "name": "tennis",
      "engagements": [{
        "name": "engagement346",
        "members": [{
          "id": "34",
          "account": {
            "id": "0010X000048DDMsQAO",
            "fullName": "edy long"
          },
          "position": {
            "id": "3999434",
            "positionTitle": "Managing Director",
            "isPrimary": true
          }
        }]
      }]
    }, {
      "name": "Juicing",
      "engagements": [{
        "name": "347343",
        "members": [{
          "id": "4546",
          "account": {
            "id": "001b000003WnPy1AAF",
            "fullName": "jeff bint"
          },
          "position": {
            "id": "35006",
            "positionTitle": "Senior Manager, Energy"
          }
        }]
      }]
    }]
  }]
}

My Expected output. look at Jim Bean's positionTitles.:
{
  "name": "Annual meetings",
  "engagementAreas": [{
    "id": "1",
    "engagementTypes": [{
      "name": "forestry",
      "engagements": []
    }, {
      "name": "houses",
      "engagements": [{
        "name": "engagement1",
        "members": [{
          "id": "e334",
          "account": {
            "id": "123",
            "fullName": "jim bean"
          },
          "position": {
            "id": "3434",
            "positionTitle": "Dalius Senior Manager, Energy",
            "isPrimary": false
          }
        }]
      }]
    }, {
      "name": "landscaping",
      "engagements": [{
        "name": "engagement1343",
        "members": [{
          "id": "e334",
          "account": {
            "id": "123",
            "fullName": "john boer"
          },
          "position": {
            "id": "4545",
            "positionTitle": "Managing Director",
            "isPrimary": true
          }
        }, {
          "id": "5555",
          "account": {
            "id": "123",
            "fullName": "jim bean"
          },
          "position": {
            "id": "a16b0000004AxeBAAS",
            "positionTitle": "Dalius Senior Manager, Energy",
            "isPrimary": true
          }
        }]
      }]
    }]
  }, {
    "name": "community days",
    "engagementTypes": [{
      "name": "skyscraping",
      "engagements": []
    }, {
      "name": "tennis",
      "engagements": [{
        "name": "engagement346",
        "members": [{
          "id": "34",
          "account": {
            "id": "0010X000048DDMsQAO",
            "fullName": "edy long"
          },
          "position": {
            "id": "3999434",
            "positionTitle": "Managing Director",
            "isPrimary": true
          }
        }]
      }]
    }, {
      "name": "Juicing",
      "engagements": [{
        "name": "347343",
        "members": [{
          "id": "4546",
          "account": {
            "id": "001b000003WnPy1AAF",
            "fullName": "jeff bint"
          },
          "position": {
            "id": "35006",
            "positionTitle": "Senior Manager, Energy"
          }
        }]
      }]
    }]
  }]
}

A: I don't fully understand your data structure, but if I assume that :

*

*IndividualData.account.id is not reliable

*IndividualData.account.fullName is reliable

*IndividualData.account.positions is an array that contains one element per IndividualData.account
The solution I came up with is to filter the IndividualData.accounts that has a primary position before using your reduce, and do the whole thing on fullName instead of Id :
const accountIdToPositionDict = IndividualData
    .filter(item => item.positions.find(p => p.isPrimary))
    .reduce( (current, item) => {
        current[item.account.fullName] = (item.positions.find( position => position.isPrimary ) || {} ).positionTitle;
        return current;
     }, {} );

const updatedGraphTable = {
    //Long stuff to get to the relevant path...
    accountIdToPositionDict[member.account.fullName] || member.position.positionTitle
}

Edit
According to your comment, if a user has no primary position in IndividualData, you have to set his position to the first position you get for this user in IndividualData. In that case, you can drop the filter part of my previous snippet and go for the following approach in your reduce:

*

*If the current item has a primary position, add it to the current[item.account.fullName] key

*Else, if there is nothing stored for the current item's fullName, add it to the current[item.account.fullName] key
const accountIdToPositionDict = IndividualData
    .reduce((current, item) => {
        const primaryPosition = item.positions.find(p => p.isPrimary);
        if(!current[item.account.fullName] || primaryPosition)
            current[item.account.fullName] =
                (primaryPosition && primaryPosition.title) ||
                item.positions[0].positionTitle;
    return current;
}, {} );


text:
Q: 'list' object has no attribute 'id' i get 'list' object has no attribute 'id' error. I dont know why.
@posts.route("/post/<int:post_id>", methods=['GET','POST'])
@login_required
def course_post(post_id):
    post=Post.query.get_or_404(post_id)
    chapters=Chapter.query.filter_by(post_id=post_id).all()
    chapter_id = chapters.id
    videos=Videos.query.filter_by(chapter_id=chapter_id).all()
    return render_template('course.html', title=post.course_name, post=post, chapters = chapters)

class Chapter(db.Model):
    id = db.Column(db.Integer, primary_key= True)
    chapter_no = db.Column(db.Integer)
    chapter_name = db.Column(db.String(50))
    chapter_desc = db.Column(db.String(50))
    chapter_date = db.Column(db.DateTime, default=datetime.utcnow)
    vi = db.relationship('Videos', backref='topic', lazy=True)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)

    def __repr__(self):
        return f"Chapter('{self.chapter_no}', '{self.chapter_name}', '{self.chapter_desc}', '{self.chapter_date}', '{self.post_id}'"

class Videos(db.Model):
    id = db.Column(db.Integer, primary_key= True)
    video_no = db.Column(db.Integer)
    video_name = db.Column(db.String(50), nullable=False, index=True)
    video_file = db.Column(db.String(200))
    yout_code = db.Column(db.String(200))
    video_description = db.Column(db.Text(100))
    uploaded_date = db.Column(db.DateTime, default=datetime.utcnow)
    rating = db.Column(db.Integer())
    chapter_id = db.Column(db.Integer, db.ForeignKey('chapter.id'), nullable=False)
    c_v = db.relationship("Chapter", foreign_keys=chapter_id)  #

    def __repr__(self):
        return f"Videos('{self.video_no}','{self.video_name}', '{self.video_file}', '{self.yout_code}', '{self.video_description}', '{self.uploaded_date}', '{self.rating}', '{self.chapter_id}'"

i am trying to get all the videos for each chapter in the Videos table using chapters.id as foreign key
Please what am i doing wrong ?

A: Try updating your function like this
@posts.route("/post/<int:post_id>", methods=['GET','POST'])
@login_required
def course_post(post_id):
    post=Post.query.get_or_404(post_id)
    chapters=Chapter.query.filter_by(post_id=post_id).all()
    chapter_id = chapters and chapters[0].id
    videos=Videos.query.filter_by(chapter_id=chapter_id).all()
    return render_template('course.html', title=post.course_name, post=post, chapters = chapters)

Now it uses first chapter ID it founds. I don't know if this is something you want though.
If you want to get list of chapter ids you can do it like this
chapter_id = [c.id for c in chapters]

But I don't know how ORM library you are using handles filtering by lists.

A: I added this to the parent class (Chapter) of the model.py
medias = db.relationship('Videos', backref='Chapter',  lazy='subquery')
The code below pulls the query and sub query of parent and child. This code does that:
chapters = db.session.query(Chapter).filter_by(post_id=post_id).all()
i.e:
@posts.route("/post/<int:post_id>", methods=['GET','POST'])
@login_required
def course_post(post_id):
    post=Post.query.get_or_404(post_id)
    #chapters=Chapter.query.filter_by(post_id=post_id).all()
    chapters = db.session.query(Chapter).filter_by(post_id=post_id).all()
    return render_template('course.html', title=post.course_name, post=post, chapters = chapters)

Then in my template, to loop the chapters and videos for each chapter in the template:
 {% for v in chapters %}
            <h7>+{{ v.chapter_name }}</h7>

                 {% for media in v.medias %}

{{  media.video_name }}

                 {% endfor %}

        {% endfor %}


text:
Q: How to access child page components from parent page router links in Angular 6 In app.component.html, I have a top menu bar which contains 3 links
named as Home, About and contactus.
If I click a home link then I should show leftmenubar of Home page(Home.component.html)
If I click about link then I should show leftmenubar of About page(About.component.html)
so my question is "How to access the Home page, about page divs i.e leftmenubar from my main page(app.component) image button click.
app.component.html

   Home
ABOUT
 CONTACTUS

<router-outlet></router-outlet>

Home.component.html

  sample1
  sample2
  sample3

aboutpage.component.html

  sample3
  sample4
  sample5

A: Create a Subject in a service myservice.service.ts as follows:
In your myservice.service.ts
public sidebar$ = new Subject<boolean>();

In your app.component.ts, import the myservice in the constructor then create a flag as follows:
public isShowMenu = true;
constructor(private myservice: MyService){}

When the user clicks the image
ShowLeftMenubar() {
  this.isShowMenu = !this.isShowMenu;
  this.myservice.sidebar$.next(this.isShowMenu);
}

In your home.component.ts and about.component.ts, you should listen for the Subject using subscribe method inside the ngOnInit
public isShowSidebar = false;
constructor(private myservice: MyService){}
ngOnInit() {
  this.myservice.sidebar$.subscribe((value) => this.isShowSidebar = value);
}

In home.component.html and about.component.html

  sample1
  sample2
  sample3


text:
Q: What is the relation of resolution with linear and angular magnification of a convex lens? 1) Linear magnification is the ratio of size of image to the size of object located at same distance. Whereas angular magnification is the ratio of Visual angle subtended by image at an aided eye to visual angle subtended by object at unaided or naked eye. which of them is related to resolution?
2) On optical devices which magnification is mentioned linear or angular?

A: Resolution is to do with an optical instrument obstructing wavefronts and hence causing diffraction effects.
For example, a telescope with diameter of lens/mirror $D$ the smallest angular separation $\theta$ which can be resolved at a wavelength $\lambda$ is given by $\theta = 1.22 \frac \lambda D$.
However for microscopes resolution is often quoted in terms is the smallest distance between two objects which can be resolved.
A lot/most? optical instruments are capable of producing a final image at infinity even though that may not produce the maximum angular magnification.
This is because when the eye is used to make observations it will not fatigue as quickly as compared with having the final image at the near point.
If the final image is at infinity then the only measure of magnification which is sensible is angular magnification.
So when a telescope manufacturer quotes the magnification as $50\times$ it is an angular magnification which is quoted with the final image at infinity.
Increasing magnification does not increase resolution, all that happens is that the diffraction patterns just get bigger and that does not improve the ability to resolve two objects.

A: In fact linear or angular magnification has nothing to do with resolution. You can have a device with large resolutions but poor magnification. To be of use resolution is increased so that the increased magnification can be useful. Resolution is related to the aperture size as given by the formula by Farcher.


text:
Q: Batch Move Data from TADOTable to MySQL TMyTable I am trying to import a table from an old database (MS Access) to MySQL server using CRBatchMove using Delphi 2007.
The program fetches data from the legacy database over an ODBC connection and stores it on the local hard drive using TADOTable.SaveToFile(). The second part of the program reads this file into another TADOTable and uses TCRBatchMove to transfer it to a MySQL server (via DevArt's TMyTable). In this process the batch move appears to be extremely slow for some reason.
Amount of data in the following trial is about 100,000 records each with about 120 fields. Most of the fields are integers and VARCHAR (each of VARCHAR less than 32 chars).
The performance figures I obtained are:
Time taken to bring data to local file over ODBC connection: 17 seconds
Time taken to load data from local file into TADOTable: 3 seconds
Time taken by TCRBatchMove to move data from TADOTable to TMyTable: > 30 minutes

MySQL server is running locally on the development machine (which is an i7-2.8GHz) and the database is otherwise very snappy).
Why is it so slow for the batch move to push data to MySQL server. Is there a way to speed up this task? Or is there a better way to accomplish this?

A: Not really an answer, but I'm running out of space in the comments.
MySQL has a function called load data infile
 see: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
You can use that to time the fastest time possible to insert data. This will give you a baseline for the insert time into MySQL and allow you to pinpoint whether the delay is in MySQL or Delphi. If you have the source for TMyTable, you can use a profiler as well.
Another option is to download ZEOS data access components at:
http://sourceforge.net/projects/zeoslib/
If there's is some snafu in the component you're using a change of toolset might fix the problem. (Devart's components are usually excellent though).
On the MySQL side you can disable index updates before the bulk-insert and enable the index after. If you have a lot of inserts that usually works out faster.
See: https://stackoverflow.com/a/9524988/650492
SET autocommit=0;
SET unique_checks=0;
SET foreign_key_checks=0;

your insert here

SET autocommit=1;
SET unique_checks=1;
SET foreign_key_checks=1;


text:
Q: Visual Studio 2013 Intellisense does not put enum type in a place of a parameter of method For example, I have the following code:
namespace VS2013_EnumTypes
{
    class Program
    {
        enum SomeEnum
        {
            One,
            Two
        }
        static void SomeMethod(SomeEnum someEnum)
        {
            //some code
        }

        static void Main(string[] args)
        {
            SomeMethod()
        }
    }
}

In Visual Studio 2010 and 2012 I can type name of the method SomeMethod and when I type parenthesis '(' then Visual Studio 2010 and 2012 offers me to select the type SomeEnum. But Visual Studio 2013 doesn't do this. It only add for me closing parenthesis and doesn't offer me select enum type, and I am forced to type name of enum type manually.
How to force VS 2013 to show me enum type, which used as parameter of method?

A: If you turn off Automatic Brace Completion (Tools->Options->Text Editor->C#) Visual Studio gives suggestions as in previous versions. Unfortunately that's just a bad workaround, but anyhow...
Hopefully this is not by design, and it might be related to this bug: http://connect.microsoft.com/VisualStudio/feedback/details/793192/vs-2013-autocompletion-of-parenthesis-breaks-intellisense.


text:
Q: Solr 5.3 Zookeeper Ensemble create_collection timeout 180s I have 3 servers running with each Solr 5.3 and Zookeeper (solr-cloud-01/zookeeper-01, solr-cloud-02/zookeeper-02 & solr-cloud-03/zookeeper-03)
Zookeeper is up and running and one of the servers is a leader, others are follower
# zkServer.sh status

If I try to create a solr collection, the config is created correctly in Zookeeper, but the core itself will not create, but timeout after 180s
# solr create_collection -c [collection_name] -d [config_name]

Connecting to ZooKeeper at zookeeper-01:2181,zookeeper-02:2181,zookeeper-03:2181 ...
Uploading /opt/solr/server/solr/configsets/[config_name]/conf for config
[collection_name] to ZooKeeper at zookeeper-01:2181,zookeeper-02:2181,zookeeper-03:2181

(or)
Re-using existing configuration directory [collection_name]

next:
Creating new collection '[collection_name]' using command:
http://localhost:8983/solr/admin/collections?action=CREATE&name=
[collection_name]&numShards=1&replicationFactor=1&maxShardsPerNode=1&
collection.configName=[collection_name]

ERROR: Failed to create collection '[collection_name]' due to:
create the collection time out:180s

The solr admin console log shows 2 identical error messages, one from SolrCore, the other from SolrDispatchFilter
null:org.apache.solr.common.SolrException: create the collection time out:180s
    at org.apache.solr.handler.admin.CollectionsHandler.handleResponse(CollectionsHandler.java:239)
    at org.apache.solr.handler.admin.CollectionsHandler.handleRequestBody(CollectionsHandler.java:170)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:143)
    at org.apache.solr.servlet.HttpSolrCall.handleAdminRequest(HttpSolrCall.java:675)
    at org.apache.solr.servlet.HttpSolrCall.call(HttpSolrCall.java:443)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:214)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:179)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:499)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
    at java.lang.Thread.run(Thread.java:745)

If I then edit /opt/zookeeper/conf/zoo.cfg and uncomment the other zookeepers (reducing the quorum to 1 server)
server.1=zookeeper-01:2888:3888
#server.2=zookeeper-02:2888:3888
#server.3=zookeeper-03:2888:3888

And change the ZK_HOSTS option in /var/solr/solr.in.sh
#ZK_HOST="zookeeper-01:2181,zookeeper-02:2181,zookeeper-03:2181"
ZK_HOST="zookeeper-01:2181"

And restart both zookeeper and solr => The core is created (it was queued somehow?). But offline becausethe quorum was down (1 of 3 zookeeper nodes)

So then I experimented with a standalone solr / zookeeper setup (solr-cloud-01 / zookeeper-01)
# zkServer.sh status
JMX enabled by default
Using config: /opt/zookeeper/bin/../conf/zoo.cfg
Mode: standalone

# zkServer.sh status
JMX enabled by default
Using config: /opt/zookeeper/bin/../conf/zoo.cfg
Mode: standalone

I executed the same command:
# solr create_collection -c [collection_name] -d [config_name]

Connecting to ZooKeeper at zookeeper-01:2181 ...
Uploading /opt/solr/server/solr/configsets/[config_name]/conf for config [collection_name]
to ZooKeeper at zookeeper-01:2181

Creating new collection '[collection_name]' using command:
http://localhost:8983/solr/admin/collections?action=CREATE
&name=[collection_name]&numShards=1&replicationFactor=1&
maxShardsPerNode=1&collection.configName=[collection_name]

{
  "responseHeader":{
    "status":0,
    "QTime":9417},
  "success":{"":{
      "responseHeader":{
        "status":0,
        "QTime":8869},
      "core":"[collection_name]_shard1_replica1"}}}

So that works!

In conclusion, I have the feeling that some routes are not correctly configured, but I can't seem to find out which... Because Zookeeper seems to work and all individual solr instances as well
Here my hosts file:
127.0.0.1 localhost
10.0.0.1 solr-cloud-01
10.0.0.2 solr-cloud-02
10.0.0.3 solr-cloud-03
10.0.0.1 zookeeper-01
10.0.0.2 zookeeper-02
10.0.0.3 zookeeper-03

A: So, I finally found the answer!
After inspecting the /clusterstate.json via the zkCli.sh I saw that when disconnected 3 'rogue' replica's were mad to the standalone cluster. All pointing to 127.0.1.1, (which is a debian specific loopback to localhost, see https://www.debian.org/doc/manuals/debian-reference/ch05.en.html#_the_hostname_resolution)
The clue was in my hosts file.
So when I changed all reference to hostnames from 127.0.1.1 to the outside IP (in my case 10.0.0.x) it started working!
My new hosts file:
127.0.0.1 localhost
10.0.0.1 solr-cloud-01
10.0.0.2 solr-cloud-02
10.0.0.3 solr-cloud-03
10.0.0.1 zookeeper-01
10.0.0.2 zookeeper-02
10.0.0.3 zookeeper-03


text:
Q: Python Tkinter how to change background color while frame is active i am having a problem with the following code:
def __init__(self):
    window = Tkinter.Tk()
    window.minsize(600,600)
    window.maxsize(600,600)
    window.title("test")

    #window.iconbitmap('sample.ico')

    menu_bar = Tkinter.Menu(window)

    change_color_option = Tkinter.Menu(menu_bar, tearoff=0)
    change_color_option.add_command(label = "Red", command = self.color_change(1, window))
    change_color_option.add_command(label = "Blue", command = self.color_change(2, window))
    change_color_option.add_command(label = "Yellow", command = self.color_change(3, window))
    change_color_option.add_command(label = "Green", command = self.color_change(4, window))
    change_color_option.add_command(label = "Purple", command = self.color_change(5, window))
    change_color_option.add_command(label = "Brown", command = self.color_change(6, window))

    file_menu_item = Tkinter.Menu(menu_bar, tearoff=0)
    file_menu_item.add_command(label = "Quit", command = window.quit)

    option_menu_item = Tkinter.Menu(menu_bar, tearoff=0)
    option_menu_item.add_cascade(label = "change color", menu = change_color_option)

    menu_bar.add_cascade(label="File", menu=file_menu_item)
    menu_bar.add_cascade(label="Options", menu=option_menu_item)

    window.config(menu=menu_bar)

    window.mainloop()

def color_change(self, color, window):
    if color == 1:
        window.configure(background = "#CC0000")
    elif color == 2:
        window.configure(background = "#0000CC")
    elif color == 3:
        window.configure(background = "#FFFF00")
    elif color == 4:
        window.configure(background = "#336600")
    elif color == 5:
        window.configure(background = "#660099")
    elif color == 6:
        window.configure(background = "#663300")

however my problem is that the window will take the last color (#663300) and it wont change even if i press the menu button to change color. I have to run mainloop again which is not something i want to do every time i change the color. Is there any way around it?

A: To pass an argument with the callback command, you need to use a lambda expression. Otherwise, Tkinter will perform the callback when the widget is made, which is why it's heading straight to the last value, as this is the last one the process flow reaches.
Format your lambda expressions like this:
    change_color_option.add_command(label = "Red", command = lambda: self.color_change(1, window))

More info: http://effbot.org/zone/tkinter-callbacks.htm


text:
Q: Failed to load the JNI shared library on starting Eclipse I downloaded the latest version of Eclipse, but I can not start it.
The error message I get is:

Failed to load the JNI shared library "C:\Program Files (x86)\Java\jdk1.6.0_20\bin..\jre\bin\client\jvm.dll".

How do I fix this?
I use 64-bit Windows, 32-bit JDK, and downloaded 64-bit Eclipse.

A: This usually happens if you have a 32- vs. 64-bit mismatch between the installed JDK and Eclipse versions!
Your version of Eclipse is trying to access a 32-bit JDK (as indicated by C:\Program Files (x86)), but either fails because Eclipse is expecting a 64-bit JDK or because the 32-bit JDK is missing - consequently you'll need to make sure to match the Eclipse and JDK versions bit wise accordingly.

A: I had installed both JDK and Eclipse 64-bit versions, but had the same issue...
Finally I discovered that my %PATH% system variable didn't include the folder. Don't forget to change it to the correct folder where your JDK\bin is installed. Worked for me.

A: -startup
plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.2.R36x_v20101222
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
-vm
C:/Program Files/Java/jdk1.6.0_32/jre/bin
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m

use eclipse and os both 64 bit or both 32 bit

A: If you have downloaded 64-bit Eclipse and a 64-bit JDK/JRE, check the availablity of javaw.exe for 64-bit.
In my case it was in C:\Program Files\Java\jre6\bin
I have extracted Eclipse to the c:\eclipse folder; within that the eclipse.ini file is available. Replace the contents of that file with the following:
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-vm
C:\Program Files\Java\jre6\bin\javaw.exe
-framework
plugins\org.eclipse.osgi_3.4.3.R34x_v20081215-1030.jar
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xmx700m
-XX:MaxPermSize=690M

Leave the new line in between the -vm flag and the value. It worked for me.

A: I had a 64 bit Eclipse and 32 bit Java and had the same issue. After installing 64 bit Java and updating system path, no issues.

A: On Windows 7 you have the chance to use symbolic links as under unix.
So with cmd (run as an admin), run the following: mklink /d jdk jdk-versionnr-etc you don't need to update your path, JAVA_JOME the next time you update Java !

A: I was facing same issue even though I had 64-bit versions of both JDK and Eclipse. I found out that the JDK path was missing in eclipse.ini.
So I added following lines in eclipse.ini file:
-vm
C:\Program Files\Java\jdk1.7.0_45\jre\bin <this might be different on your machine>

This solved the problem! :-)

A: If eclipse is 64 bit , update Java in Path to C:\Program Files\Java\jre7
or else
check the Java location being referred by eclipse and copy the content C:\Program Files\Java\jre7 to eclipse jre location.
Reference - http://www.buggybread.com/2013/01/failed-to-load-jni-shared-library.html

A: 1.Uninstall available jdk7.1 (It was 64 bit)
2. Downloaded and installed jdk7.1 32 bit.
   The jvm.dll will be in the follwing path: "C:\Program Files (x86)\Java\jdk1.7.0_75\jre\bin\client"
Hope it works.

A: To elaborate on Steffen Opel's answer the mismatch occurs between the JVM specified in eclipse.ini file and the JVM encountered and launched as a result of the entries on your Windows path environment variable.  So to fix the issue, ensure they both refer to the same JVM.
To fix this issue follow these steps:
1. Amend Eclipse Configuration So It Launches with Desired Version of JVM

Open eclipse.ini and change the line below to the java version you wish to use eg:
-Dosgi.requiredJavaVersion=1.5
2. Ensure Eclipse Can Access the JVM It Requires

Goto Control Panel --> Edit System Environment Variables --> Path.

    a) Make sure an entry exists here to your java

    b) Make sure this entry sits higher (or earlier) than any other java paths within your @path entry.
Hopefully that should fix the problem for you.

A: Although this is an old question, I thought to add some more relevant info to the Accepted answer given by @Steffen Opel.
It is possible to install any number of versions of 32-bit JDKs and 64-bit JDKs in a 64-bit Windows OS. Also it is possible to install 32-bit Eclipse and 64-bit Eclipse in the same computer as well. But to run one of those platform related Eclipse (in OPs case 64-bit Eclipse) version, the machine should have matching "Environment Variables" configured for JDK. This can be done (should be done) without modifying
eclipse.ini file.
Environment Variables
To run java without giving full path it is required to add file location for java.exe to PATH environment variable. And also for some other third party utilities, JAVA_HOME environment variable is required as well.
Normally java developers always need to have JDK installed (JRE is included in JDK). And PATH is set to "bin" folder under JDK installation folder (in OPs case C:\Program Files\Java\jdk1.6.0_40\bin) while JAVA_HOME is set to JDK installation folder (in OPs case C:\Program Files\Java\jdk1.6.0_40).
Here OP has only got 32-bit JDK but trying to use 64-bit Eclipse. So to fix the issue OP need to install 64-bit JDK.  And change JAVA_HOME & PATH "Environment Variables" to match that installation location.
Here is the more complete steps:

*

*Download and install 64-bit JDKx.x.x_xx

*Then open Windows Explorer, right click on Computer icon and select
Properties -> Advanced system settings.
It will open up
System Properties window, and in "Advanced" tab select "Environment    Variables" to open up editing window.

*Under the System variable section look for JAVA_HOME variable
name and click "Edit" button at the bottom section, if not
available click "New" and enter C:\Program Files\Java\jdk1.6.0_40
and click OK.

*Then select the PATH variable and click "Edit" and append
%JAVA_HOME%\bin; to the front or  %JAVA_HOME%\bin to the end of
the existing string. DO NOT over write the existing string, and click
OK -> OK ->OK to complete.
Now Eclipse will be open without the error.
Note:

*

*If someone needs to use 32-bit Eclipse then default JDK path will be C:\ Program Files (x86) \Java\jdkx.x.x_xx

*When changing PATH Environment variables in Windows 10 there is an additional window will comes up as shown in picture below.

A: I had faced same issue but I got the solution.
Check if Eclipse is 32 or 64 bits, then

*

*If it is 32 bit then set JAVA_HOME to the 32 bit version of jdk

*If Eclipse is 64 bit then set JAVA_HOME to the 64 bit version of jdk


text:
Q: Removing commutative pairs in a list in Python I got a list as follows:
list_1 = [[3, 0], [0, 3], [3, 4]]

I'm trying to filter out the commutative elements in this. For example, [3,0] and [0,3] are the same and I need to keep only one of them. I tried converting this into a set, and it didn't help. I also tried iterating, but it's causing real overhead. Is there any Pythonic way to do this?
Thanks.

A: For example, you can use dict comprehension:
>>> {tuple(sorted(t)): t for t in list_1}.values()
[[0, 3], [3, 4]]

A: You can use a set of frozensets for the filtering.
If order does not matter:
>>> map(list, set(frozenset(t) for t in list_1))
[[3, 4], [0, 3]]

To retain order:
list_1 = [[3, 0], [0, 3], [3, 4]]
seen = set()
filtered = []
for item in list_1:
    item_set = frozenset(item)
    if item_set not in seen:
        filtered.append(item)
        seen.add(item_set)

Result:
>>> filtered
[[3, 0], [3, 4]]


text:
Q: Getting error of not staying within study area using ArcMap Why is ArcMap giving this error of not staying within the study area?
I tried to change the coordinates and the datum and still an error occurs, follow the prints below


text:
Q: How to make a Class Diagram of a Struts 2 Web Application I would like to know what would be the way to model a Class diagram of a Struts2 Web App.
I was thinking about this:
Since Struts2 uses a MVC architecture, I would have for example, 3 classes:
CatalogueThemeController, CatalogueThemeModel, and a JSP to display the view of that Catalogue.
How do I have to make the relationships between the classes? Thanks in advance for your help.
John Smith

A:
How do I have to make the relationships between the classes?

After you wrote the classes, you can generate the UML digram using any UML generator application. There are a lot of UML generator applications, find one that suit to yourself. For me, I'm using eclipse as the Java IDE and eUML2 seem does its job in generating the class diagram.
Now you have action controller and model in your web app which reside in the java package? You can generate them easily in the UML class diagram and you can show the relationship between the classes (in your case, 3 classes). The class diagram can show dependencies, inheritances or associations. Think that is good enough to show relationship between classes in your struts webapp.
Hope it helps you and answer your question. I've generated my project which using strut and check out this diagram


text:
Q: Laravel 5.2 Class 'Collective\IronQueue\IronQueueServiceProvider' not found I am trying to use the IronMQ driver in the latest version of Laravel (5.2) and am getting the below error;

Class 'Collective\IronQueue\IronQueueServiceProvider' not found

Here is my configuration.
composer.json:
"iron-io/iron_mq": "~2.0"

config/app.php:
'providers' => [
    Collective\IronQueue\IronQueueServiceProvider::class,
],

A: Try to use version 3 :
"iron-io/iron_mq": "~3.0"

And don't forget to update your composer :
composer update

Hope this helps.

A: I managed to fix the issue by adding:
"laravelcollective/iron-queue": "5.2.*"
to composer and then running update:
composer update
It doesn't mention this step on the Laravel Collective website.


text:
Q: Rails find model with text manipulation Rails 3 environment using haml.
Scenario
we have an app whereby accounts have their own subdomain. the account may have been passed to us by a referral partner. the referral partner will also have their own account. Each account can store their own logo, including the partner. We want the end user accounts to display the partner logo on their login page.
Approach
So the way I went about this was to include a parameter with the login url, so that partners can have buttons on their own website that link to a page that displays their logo and our login form, such as
http://www.myapp.com/login?partner=bob

Then in the login form I look for the parameter, so
- if params[:partner].blank?
  = %img{src = > @our_logo}
- else
  - p = params[:partner]
  - a = Account.where(:full_domain => p}
  = %img{src = > a.logo}

Now this works great. however, the full_domain field contains what the name suggests, the full domain, so the code works as long as the login url is something like
http://www.myapp.com/login?partner=bob.myapp.com

I think this is nasty, and want something more like
http://www.myapp.com/login?partner=bob

which I think is neater.
The problem
What I need to be able to do is split out the first word of the full domain and find the account based on that. This code will certainly split it correctly...
a = Account.find(1)
a.full_domain.split('.').first

But I do not know how to use that when trying to find a record. So, for example, this failed
- a = Account.where((full_domain.split('.').first) => p).first

because full domain is not a symbol I think. This next attempt failed...
- a = Account.where((:full_domain.split('.').first) => p).first

because I don't think you can do a split on anything other than a string (sorry I am self taught and relatively new to both programming and ruby/rails!)
so finally I tried to convert it to a string like this...
- a = Account.where((:full_domain.to_s.split('.').first) => p).first

But this didn't work either, and I have a sneaky suspicion I am barking up the wrong tree.
Can anyone help point me in the right direction?
thanks in advance
G

A: I might be thinking too simple, but isn't this what you want?
p = params[:partner]
a = Account.where(:full_domain, "#{p}.myapp.com").first


text: Q: Vue.js: How to pass in data that isn't a parent / access vue methods? I'm working on a simple timer app. I'm getting 3 pieces of data from the server: timers, projects and users. I believe I'm looping through timers correctly, but I'm not sure if I should be passing in data this way. I want different parts of my app to use the same dataset for users and projects in case a project name changes for example. Here's the code so far with questions embedded. I would like to do a single call for now for all the data at once.


text:
Q: 2 iPhones, 1 computer. Why are they now both running on the same iTunes account? I have recently synced my partner's iPhone to my computer because his computer crashed. He has his own iTunes account so we backed his phone up to iCloud, wiped it a re-synced it to my computer.But when he tried to access iTunes through his iPhone (to download music or new apps) it takes him to my account and asks for my password.In settings on his iPhone under iTunes account it still has his user ID. How do we get access to his iTunes account from his iPhone back?

A: Why not log out your iTunes account so that he can log in his iTunes account?


text:
Q: Autodidactic as a Verb Is there an equivalent use of Autodidactic as a verb? Such as "John is an autodidactor". I couldn't find "autodidactor" or "Autodidact Eclipse RCP so I am better educated about how to use Eclipse RCP" as if it were a to-do item.
I am trying to express the idea of self-taught as a verb:  One can learn things on one's own, but does that mean that one can autodidact things?

A: The root word here is the adjective didactic, meaning instructive (sometimes, particularly of morals), which can be pluralised to give a noun meaning the art or science of teaching (the alternative being didacticism).
There are no verb forms associated with this root, but it can take the prefix auto- (Greek, self, same). Thus an autodidact is one who teaches [or more usually, has taught] himself.
So you don't say "John is an autodidactor" because John is an autodidactic.
A common expression used by people who don't know/like such relatively obscure words is to say "John studied at the University of Life", which gives a clue as to why we don't really need autodidact to function as a verb - the relevant verb is usually just live [every day of your life as a learning experience].
I suspect OP would like autodidactic to have more the sense of solitary home study, but since the word is more evocative of dispensing teaching than absorbing learning, I feel this extension of meaning is unlikely to catch on. A reasonable alternative for OP's context is..
Teach myself Eclipse RCP so I know better how to use it.
or perhaps Learn about..., Study..., or Bone up on... (that last is somewhat informal, but does perhaps imply "by my own efforts" more strongly).


text:
Q: How could I get this regex statment to capture just a select piece I am trying to get the regex in this loop,
my $vmsn_file = $snapshots{$snapshot_num}{"filename"};
my @current_vmsn_files = $ssh->capture("find -name $vmsn_file");
foreach my $vmsn (@current_vmsn_files) {
$vmsn =~ /(.+\.vmsn)/xm;
print "$1\n";
}

to capture the filename from this line,
./vmfs/volumes/4cbcad5b-b51efa39-c3d8-001517585013/MX01/MX01-Snapshot9.vmsn

The only part I want is the part is the actual filename, not the path.
I tried using an expression that was anchored to the end of the line using $ but that did not seem to make any difference. I also tried using 2 .+ inputs, one before the capture group and the one inside the capture group. Once again no luck, also that felt kinda messy to me so I don't want to do that unless I must.
Any idea how I can get at just the file name after the last / to the end of the line?
More can be added as needed, I am not sure what I needed to post to give enough information.
--Update--
With 5 minutes of tinkering I seemed to have figured it out. (what a surprise)
So now I am left with this, (and it works)
my $vmsn_file = $snapshots{$snapshot_num}{"filename"};
my @current_vmsn_files = $ssh->capture("find -name $vmsn_file");
foreach my $vmsn (@current_vmsn_files) {
$vmsn =~ /.+\/(\w+\-Snapshot\d+\.vmsn)/xm;
print "$1\n";
}

Is there anyway to make this better?

A: Probably the best way is using the core module File::Basename.  That will make your code most portable.
If you really want to do it with a regex and you are based on Unix, then you could use:
$vmsn =~ m%.*/([^/]+)$%;
$file = $1;

A: well, if you are going to use find command from the shell, and considering you stated that you only want the file name, why not
... $ssh->capture("find -name $vmsn_file -printf \"%f\n\" ");

If not, the simplest way is to split() your string on "/" and then get the last element. No need regular expressions that are too long or complicated.
See perldoc -f split for more information on usage


text:
Q: Expected non-nullable value for MutableLiveData private val _users = MutableLiveData<List<User>>()
val users: LiveData<List<User>> get() = _users

fun getUsers() {
    viewModelScope.launch {
        _users.value = users()
    }
}

suspend fun users(): List<User> {
    TODO("Not implemented")
}

I get following error on _users.value = users()

Expected non-nullable value. Inspection info:
This check ensures that LiveData values are not null when explicitly declared as non-nullable.

I'm using lifecycle version 2.3.1. The problem seems to be with suspend function users(). If I remove the suspend modifier it works fine.

A: Try this._users.value = users(). Adding this at the front works for me. Not sure why. In your case you might need this@yourModel._users.value = users() since you are calling it in the viewModelScope.

A: Just use
private val _users: MutableLiveData<List<User>> = MutableLiveData()

instead of
private val _users = MutableLiveData<List<User>>()


text:
Q: How do i use "if" and "and" condition in R data frame I want to update in "Remark" column using condition on other multiple columns
RBNRFinal$Remarks<- ifelse(RBNRFinal$restock_date != "NA","Restock Done"," ") # this works fine

RBNRFinal$Remarks<- ifelse(RBNRFinal$Remarks == " " & RBNRFinal$dispatched_flag == 1,"GP Done"," ") # dont get " GP Done" values

please help me in using correct "IF" and "And" or & condition in the data frame.


text:
Q: How to connect php 5.3.8.1 to MS SQL Server 2000? I need to connect a php script (running on php 5.3.8.1) to MS SQL Server 2000. I've been told that mssql_ commands are not supported anymore and sqlsrv_ ones are used now. Any help ???

A: See the manual entry. There's a bunch of good examples in the comments. In general, you'll do something like this:
$serverName = "serverName\sqlexpress";
$connectionInfo = array("Database"=>"dbName","UID"=>"userName","PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);


text:
Q: Using System.Runtime.Caching I am using System.Runtime.Caching library.
I have problem when initiating this code
private ObjectCache cache = MemoryCache.Default;

I get error

Could not load file or assembly 'System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

Before that, I use those classes and works OK. So it is not the problem accessing the assembly, as I initially thought.
    private CacheItemPolicy cacheItemPolicy;
    cacheItemPolicy = new CacheItemPolicy();
    cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(240);


text:
Q: Como faço para remover acentos em uma string? Eu tenho uma string
áéíóú

Que eu quero converter para
aeiou

Como eu removo os acentos? Preciso para guardar no banco de dados como uma URL.

A: Você pode usar esta função:
public static string RemoveAccents(this string text){
    StringBuilder sbReturn = new StringBuilder();
    var arrayText = text.Normalize(NormalizationForm.FormD).ToCharArray();
    foreach (char letter in arrayText){
        if (CharUnicodeInfo.GetUnicodeCategory(letter) != UnicodeCategory.NonSpacingMark)
            sbReturn.Append(letter);
    }
    return sbReturn.ToString();
}

Fonte: http://www.ninjacode.com.br/post/2011/08/10/Retirar-acentos-de-strings-C.aspx

A: Você também pode fazer a leitura de todos os caracteres que está na variável comAcentos, e dado um Replace no parâmetro que foi passado na função, ou seja, é substituído as letras que estão comAcentos pelas de semAcentos e retorna o novo texto.
public static string removerAcentos(string texto)
{
    string comAcentos = "ÄÅÁÂÀÃäáâàãÉÊËÈéêëèÍÎÏÌíîïìÖÓÔÒÕöóôòõÜÚÛüúûùÇç";
    string semAcentos = "AAAAAAaaaaaEEEEeeeeIIIIiiiiOOOOOoooooUUUuuuuCc";

    for (int i = 0; i < comAcentos.Length; i++)
    {
        texto = texto.Replace(comAcentos[i].ToString(), semAcentos[i].ToString());
    }
    return texto;
}

A: Usando LINQ fica bem prático:
public static string RemoverAcentuacao(this string text)
{
    return new string(text
        .Normalize(NormalizationForm.FormD)
        .Where(ch => char.GetUnicodeCategory(ch) != UnicodeCategory.NonSpacingMark)
        .ToArray());
}

O que são NormalizationForm.FormD e UnicodeCategory.NonSpacingMark
Isso é uma forma de representar a string original de forma que marcas como acentuação, cedilha, entre outras, sejam separadas em caracteres distintos: o caractere base, que é a letra, e o caractere da marcação. O caractere de acentuação, neste caso é chamado de NonSpacingMark, ou seja, marcador sem espaço, significa que é um marcador que não ocupa nenhum espaço, e será aplicado ao caractere anterior.
Usando o LINQ podemos remover estas marcações, deixando apenas os caracteres base, sem as marcações e construímos uma nova string a partir desses caracteres.

A: public static string RemoverAcentos(this string texto)
{
   if (string.IsNullOrEmpty(texto))
       return String.Empty;

   byte[] bytes = System.Text.Encoding.GetEncoding("iso-8859-8").GetBytes(texto);
   return System.Text.Encoding.UTF8.GetString(bytes);
}

string nome = "João Felipe Portela";
string nomeSemAcentos = nome.RemoverAcentos();

A: Existe esse método que utilizo para remover acentuação:
public static string RemoverAcentos(string texto){

    string s = texto.Normalize(NormalizationForm.FormD);
    StringBuilder sb = new StringBuilder();
    for (int k = 0; k < s.Length; k++)
    {
        UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(s[k]);
        if (uc != UnicodeCategory.NonSpacingMark)
        {
            sb.Append(s[k]);
        }
    }
    return sb.ToString();
}

A: Uma alternativa as respostas dadas acima é instalar o seguinte nuget:
https://www.nuget.org/packages/MMLib.Extensions/
então você podorá remover os acentos da seguinte forma:
var str = "áéíóú";
str = str.RemoveDiacritics();

A: O código de página (codepage) Greek (ISO) pode fazer isso
Informações sobre este codepage podem ser obtidos no retorno do método System.Text.Encoding.GetEncodings(). Veja mais aqui.
Greek (ISO) tem o codepage 28597 e nome iso-8859-7.
Vamos ao código... \o/
string text = "Você está numa situação lamentável";

string textEncode = System.Web.HttpUtility.UrlEncode(text, Encoding.GetEncoding("iso-8859-7"));
//result: "Voce+esta+numa+situacao+lamentavel"

string textDecode = System.Web.HttpUtility.UrlDecode(textEncode);
//result: "Voce esta numa situacao lamentavel"

Então, escreva essa função...
public string RemoverAcentuacao(string text)
{
    return
        System.Web.HttpUtility.UrlDecode(
            System.Web.HttpUtility.UrlEncode(
                text, Encoding.GetEncoding("iso-8859-7")));
}

Observe que Encoding.GetEncoding("iso-8859-7") é equivalente a Encoding.GetEncoding(28597). O primeiro busca pelo nome, o segundo pelo codepage do Encoding.
Outras opções pode ser vistas no Stackoverflow em inglês:

A: Em QTcreator
QString GerCorrida::removeAccentuation(QString text)
{
    QString with = "ÄÅÁÂÀÃäáâàãÉÊËÈéêëèÍÎÏÌíîïìÖÓÔÒÕöóôòõÜÚÛüúûùÇç";
    QString withOut = "AAAAAAaaaaaEEEEeeeeIIIIiiiiOOOOOoooooUUUuuuuCc";
    for (int i = 0; i < with.size(); i++)
    {
        text = text.replace( with[i], withOut[i] );
    }
    return text;
}


text:
Q: Can I scrape content only after a specific header? def parse_linkpage(self, response):
    hxs = HtmlXPathSelector(response)
    item = QualificationItem()
    xpath = """
            //h2[normalize-space(.)="Entry requirements for undergraduate courses"]
             /following-sibling::p
            """
    item['Qualification'] = hxs.select(xpath).extract()[1:]
    item['Country'] = response.meta['a_of_the_link']
    return item

So I was wondering if I could get my code to stop scraping after reaching the end of the
.
Here is the webpage:

Entry requirements for undergraduate courses

Example1

Example2

Postgraduate Courses

Example3

Example4

I want these results:
Example1
Example2

But I get:
Example1
Example2
Example3
Example4

I know I could change this line,
item['Qualification'] = hxs.select(xpath).extract()

to,
item['Qualification'] = hxs.select(xpath).extract()[0:2]

But this scraper looks at many different pages that might have more than 2 paragraphs in the first header meaning it would leave this information out.
I'm wondering if there is a way of just telling it to extract the exact data that follows the header I want and not everything?

A: It's not very pretty or easy to read, but you can use EXSLT extensions to XPath and use set:difference() operation:
>>> selector.xpath("""
    set:difference(//h2[normalize-space(.)="Entry requirements for undergraduate courses"]
                    /following-sibling::p,
                   //h2[normalize-space(.)="Entry requirements for undergraduate courses"]
                    /following-sibling::h2[1]
                    /following-sibling::p)""").extract()
[u'
Example1
', u'
Example2
']

The idea is to select all p following your target h2, and exclude those p that are after the next h2
In a bit easier to read version:
>>> for h2 in selector.xpath('//h2[normalize-space(.)="Entry requirements for undergraduate courses"]'):
...     paragraphs = h2.xpath("""set:difference(./following-sibling::p,
...                                             ./following-sibling::h2[1]/following-sibling::p)""").extract()
...     print paragraphs
...
[u'
Example1
', u'
Example2
']
>>>

A: Maybe you could use this xpath
//h2[normalize-space(.)="Entry requirements for undergraduate courses"]
         /following-sibling::p[not(preceding-sibling::h2[normalize-space(.)!="Entry requirements for undergraduate courses"])]

you can just add another predicate of the following-sibling::p not to include those ps whose preceding-sibling is not equal to "Entry requirements for undergraduate courses"


text:
Q: How to delete an event in Google agenda with CURL? I'm using a script that create events with something like that:
$data = "<entry xmlns='http://www.w3.org/2005/Atom' " .
            "xmlns:gd='http://schemas.google.com/g/2005'>\n" .
            "<category scheme='http://schemas.google.com/g/2005#kind' " .
            "term='http://schemas.google.com/g/2005#event'></category>\n" .
            "<title type='text'>event title</title>\n" .
            "<content type='text'>event description</content>\n" .
            "<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>" .
            "</gd:transparency>\n" .
            "<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>" .
            "</gd:eventStatus>\n" .
            "<gd:where valueString='event address'></gd:where>" .
            "<gd:when startTime='$date"."T$timestart:00.000+01:00' endTime='$date"."T$timeend:00.000+01:00'></gd:when>\n" .
            "</entry>\n";

curl_setopt($cs, CURLOPT_URL, "https://www.google.com/calendar/feeds/default/private/full");
curl_setopt($cs, CURLOPT_POST, 1);
curl_setopt($cs,CURLOPT_HTTPHEADER,array('Accept: text/html,application/xhtml+xml,application/xml'));
curl_setopt($cs, CURLOPT_HEADER, 1);
curl_setopt($cs, CURLOPT_HTTPHEADER, $httpheader);
curl_setopt($cs, CURLOPT_POSTFIELDS, $data);

I can get the event ID but I don't know how to delete it then.
Thanks

A: I assume you are using the V2 API, so according to the documentation:

To delete an event, first you retrieve the event you want to delete,
  then you send a DELETE request to the event's edit URL.

So, first perform a GET request to grab the event you want, grab the edit link from the XML e.g.
<link rel='edit' type='application/atom+xml'
      href='https://www.google.com/calendar/feeds/jo@gmail.com/private-magicCookie/full/entryID'></link>
Then use CURL to perform a DELETE request to that URL. To find out more about that, see this page which explains to use the CURLOPT_CUSTOMREQUEST option.


text:
Q: Horror movie about family driving down a country road This American horror movie came out in the mid to late 90s / early 2000s.
It centres around a family going on a vacation. Mother, father and two teenagers.
They're driving down a highway somewhere in the states and I think the father suggests taking a short cut down a long country road.
Lots of freaky stuff happens on this country road, they crash and die a few times I think but they keep waking up back in the car.
Each member of the family flips out one after another and they attack each other and everyone dies but they keep waking up back in the car.
Other weird stuff happens, at one point the mother sustains a serious blow to the back of her head, she goes insane and starts picking out her own brains and eating them. Which is nice...
I know there is a hearse following them for the entire journey though.
I can't remember the ending, but I think at least one of them survives and wakes up in a hospital and the hearse is parked outside.
I'm not sure if they ever have any interaction with the hearse driver or if you ever find out what's going on with the hearse.
This sounds like a lot of jibberish, hopefully someone can decipher it and help me out!

A: Possibly "Dead End" (2003)
Features a family who take a shortcut, hit another car, but are still alive. They die repeatedly. A hearse is featured throughout. The full description is in the Wikipedia link above.


text:
Q: "Unable to Load App, Server Error" in ExactTarget IMH/MC We've spent a few days trying to get SSO/JWT working with an app we're building for HubExchange.
We started by simply setting up the Subscriber Search Node app from https://code.exacttarget.com/api/sample-app-subscriber-search with the credentials the required credentials in App Center (Application Endpoints, Client ID, Client Secret, App Signature, etc). We followed the instructions very carefully.
We're building this on the ET sandbox and we are using https://auth-test.exacttargetapis.com/v1/requestToken by node-fuel in this example to get tokens, because there isn't information about it in request.session. We get a token back and then use that token as the session token when using node-fuel.
My understanding is that when the App loads in IMH, the application login page will receive an encoded JWT, which we then decode using the application signature of the app, but we are not getting this JWT payload from the App.
We have the app running fine on locally but when we load the app in IMH, we get a message "Unable to Load App, Server Error. We are unable to load the application you requested. Please try again later."
I think there is a clue here when tracing the console output from the browser:
 Failed to load resource https://pulse.test.exacttarget.com/pubsub/cometd/handshake
 GET https://pulse.test.exacttarget.com/pubsub/cometd/handshake?jsonp=jQuery1710…3A60000%2C%22interval%22%3A0%7D%2C%22id%22%3A%222%22%7D%5D&_=1390473712263  fuel-all.min.js?_=1.5.305:137
 send fuel-all.min.js?_=1.5.305:137
 f.extend.ajax fuel-all.min.js?_=1.5.305:137
 d.jsonpSend imh-all.min.js?_=1.5.305:6
 b.transportSend imh-all.min.js?_=1.5.305:6
 l imh-all.min.js?_=1.5.305:6
 o imh-all.min.js?_=1.5.305:6
 b.send imh-all.min.js?_=1.5.305:6
 bb imh-all.min.js?_=1.5.305:6
 bl imh-all.min.js?_=1.5.305:6
 (anonymous function) imh-all.min.js?_=1.5.305:6
 (anonymous function) imh-all.min.js?_=1.5.305:6
 INFO: Cometd Stopped

We're tailing the Node server log and IMH is not trying to load the page.
I have uploaded the Node project that we are using to GitHub at https://github.com/Aluman/SubscribersSearch
We abandoned the Subscriber Search Node example and instead tried using fuel-throttle-node which again works fine on localhost but we get the same error.
Any ideas or clues where we can look to next would be really helpful. Again, we are not trying to do anything unusual, we just want to get a demo app working at this stage!

A: I just spoke with an engineer on our Platform team who says there is a bug with the SSO flow in the Sandbox environment. He's creating a ticket for it and it is moving forward.

*

*When you say "it works locally", do you mean:
A: The application loads outside of the (Marketing Cloud/IMH) on your local machine?
B: The application loads by running it locally and clicking your app's name in the App Switcher of the (Marketing Cloud/IMH)?

A: As of yesterday's release this has been resolved.  Please verify that it is working for you now.


text:
Q: How to save innerHTML of div in a local storage? I want to save and restore data from div - that is container of other divs,
In order to make it I use local storage and JSON like this:
window.onload = restoreJason;

function makeJson(){
     var canvas = document.getElementById("canvas");
            var shapes = canvas.querySelectorAll("div[class='drag']");
            var divs = new Object();
            for(var i=0; i<shapes.length; ++i){
                divs[shapes[i].getAttribute('innerHTML')] = shapes[i].innerHTML;
            }
            localStorage.setItem("divs", JSON.stringify(divs));
        }

function restoreJason(){
        var divs = JSON.parse(localStorage.getItem("divs"));
            var canvas = document.getElementById("canvas");
            var shapes = canvas.querySelectorAll("div[class='drag']");
            for(var i = 0; i<shapes.length; i++){
                shapes[i].value = divs[shapes[i].getAttribute("innerHTML")];
            }
            console.log(divs);
    }

However, I don't know how to access the innerHTML of the elements and save it or restore it.
What do you think I shall do?
(To be more detailed - I need to save the content of the div when user click on "save", and load it when the user click "load". This is a snippest of it...)
NOTICE: the "canvas" is just the id of the main div, and not a real "canvas".

function randomizeColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * letters.length)];
    }
    return color;
}

function randomizeRectangle() {
    var width = Math.random() * 700 + 50;
    var height = Math.random() * 250 + 50;
    if (height <= 20) {
        height = 20;
    }
    var posX = Math.round(Math.random() * window.innerWidth);
    var posY = Math.round(Math.random() * window.innerHeight);

    var randomRecObj = {
        "width": width + "px",
        "height": height + "px",
        "posX": posX,
        "posY": posY
    };
    return randomRecObj;
}
function makeShape() {
    var rect = randomizeRectangle();
    var rectDOM = document.createElement("div");
    rectDOM.className = "rectangle";
    rectDOM.style.border = "1px solid black";
    rectDOM.style.width = rect.width;
    rectDOM.style.height = rect.height;
    rectDOM.style.background = randomizeColor();
    rectDOM.style.top = rect.posY + "px";
    rectDOM.style.left = rect.posX + "px";
    //rectDOM.addEventListener("click", selectShape);
    // rectDOM.style.transform =rect.rotation;
    return rectDOM;

}

function randRect() {
    var rectDOM = makeShape();
    var canvas = document.getElementById("canvas");
    canvas.appendChild(rectDOM);
}

function randOval() {
    var ovalDOM = makeShape();
    ovalDOM.style.borderRadius = "50%";
    var canvas = document.getElementById("canvas");
    canvas.appendChild(ovalDOM);
}

function changeColor(){

}

function cancelSelection() {
    var selected = document.getElementsByClassName("selected");
    while (selected) {
        selected[0].classList.remove(selected[0]);
    }
}

function removeShape(event) {
    var selectedShapes = document.getElementsByClassName("selected");
    var len = selectedShapes.length;
    while (len > 0) {
        selectedShapes[0].parentNode.removeChild(selectedShapes[0]);
        --len;
    }
}

function removeCorners(rectDom) {
    var corners = document.getElementsByClassName("corners");
    var len = corners.length;
    while (len > 0) {
        corners[0].classList.remove("corners");
        --len;
    }

}
.header{
    background: #4ABDAC;
    color: #fff;
    margin: 1px;
}

hr{
    border-top: 3px double #2a3132;

}
ul{
    list-style: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #90afc5;
}

li{
    float: left;
    border: 2px solid #336b87;
    padding: 3px;
    margin: 3px;
}

li>a{
    display: block;
    color: #2a3132;
    text-decoration: none;
    padding: 10px 14px;
}

#color{
    margin-left: 150px;
}

#rect{
    margin-left: 100px;
}

li>a:hover{
    color: #763626;
    cursor: pointer;
}

#canvas{
    background: #66a5ad;
    position: relative;
    height: 1200px;
    width: 100%;
}

.corners{
    position: absolute;
    height: 10px;
    width: 10px;
    background:#fff;
    border: 1px solid black;
    display: none;
}
.selected .corners{
    display: inline-block;
}
.cornerUpLeft{

    top: -5px;
    left: -5px;

}

.cornerUpRight{

    top: -5px;
    right: -5px;

}

.cornerBtmLeft{

    bottom: -5px;
    left: -5px;

}
.cornerBtmRight{

    bottom: -5px;
    right: -5px;

}

.rectangle{
    position: absolute;
}

.colorBox{
    border: 1px solid black;
    height: 20px;
    width: 20px;
    list-style: none;
}
<!DOCTYPE html>

        <title>Sketch Board - Eyal Segal Project</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="css/style.css" rel="stylesheet">

Sketch Board

Load

Save

Rectangle

Oval

A: All you need to do is set the .innerHTML of the div id="canvas" into localStorage. There's no need for JSON or loops at all.
Also, don't use inline HTML event attributes (onclick). Instead, do all your JavaScript separately using modern, standards based event handling.
Lastly, there is no need for  elements to be able to respond to a click event. Actually, your a elements are invalid as they don't have a name or href attribute anyway. The li elements can simply be set up for click events.
This is the code to do it but it won't execute here in the Stack Overflow snippet environment, but you can see it working here.

// Get reference to the "canvas"
var can = document.getElementById("canvas");

// Save the content of the canvas to localStorage
function saveData(){
  localStorage.setItem("canvas", can.innerHTML);
}

// Get localStorage data
function restoreData(){
  can.innerHTML = localStorage.getItem("canvas");
}

// get load and save references
var load = document.getElementById("load");
var save = document.getElementById("save");

// Set up event handlers
load.addEventListener("click", restoreData);
save.addEventListener("click", saveData);

// Get references to the rect and oval "buttons" and set their event handlers
var rect = document.getElementById("rect");
rect.addEventListener("click", randRect);

var oval = document.getElementById("oval");
oval.addEventListener("click", randOval);

function randomizeColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * letters.length)];
    }
    return color;
}

function randomizeRectangle() {
    var width = Math.random() * 700 + 50;
    var height = Math.random() * 250 + 50;
    if (height <= 20) {
        height = 20;
    }
    var posX = Math.round(Math.random() * window.innerWidth);
    var posY = Math.round(Math.random() * window.innerHeight);

    var randomRecObj = {
        "width": width + "px",
        "height": height + "px",
        "posX": posX,
        "posY": posY
    };
    return randomRecObj;
}

function makeShape() {
    var rect = randomizeRectangle();
    var rectDOM = document.createElement("div");
    rectDOM.className = "rectangle";
    rectDOM.style.border = "1px solid black";
    rectDOM.style.width = rect.width;
    rectDOM.style.height = rect.height;
    rectDOM.style.background = randomizeColor();
    rectDOM.style.top = rect.posY + "px";
    rectDOM.style.left = rect.posX + "px";
    //rectDOM.addEventListener("click", selectShape);
    // rectDOM.style.transform =rect.rotation;
    return rectDOM;

}

function randRect() {
    var rectDOM = makeShape();
    var canvas = document.getElementById("canvas");
    canvas.appendChild(rectDOM);
}

function randOval() {
    var ovalDOM = makeShape();
    ovalDOM.style.borderRadius = "50%";
    var canvas = document.getElementById("canvas");
    canvas.appendChild(ovalDOM);
}

function changeColor(){

}

function cancelSelection() {
    var selected = document.getElementsByClassName("selected");
    while (selected) {
        selected[0].classList.remove(selected[0]);
    }
}

function removeShape(event) {
    var selectedShapes = document.getElementsByClassName("selected");
    var len = selectedShapes.length;
    while (len > 0) {
        selectedShapes[0].parentNode.removeChild(selectedShapes[0]);
        --len;
    }
}

function removeCorners(rectDom) {
    var corners = document.getElementsByClassName("corners");
    var len = corners.length;
    while (len > 0) {
        corners[0].classList.remove("corners");
        --len;
    }

}
.header{
    background: #4ABDAC;
    color: #fff;
    margin: 1px;
}

hr{
    border-top: 3px double #2a3132;

}
ul{
    list-style: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #90afc5;
}

li{
    float: left;
    border: 2px solid #336b87;
    padding: 3px;
    margin: 3px;
}

li>a{
    display: block;
    color: #2a3132;
    text-decoration: none;
    padding: 10px 14px;
}

#color{
    margin-left: 150px;
}

#rect{
    margin-left: 100px;
}

li>a:hover{
    color: #763626;
    cursor: pointer;
}

#canvas{
    background: #66a5ad;
    position: relative;
    height: 1200px;
    width: 100%;
}

.corners{
    position: absolute;
    height: 10px;
    width: 10px;
    background:#fff;
    border: 1px solid black;
    display: none;
}
.selected .corners{
    display: inline-block;
}
.cornerUpLeft{

    top: -5px;
    left: -5px;

}

.cornerUpRight{

    top: -5px;
    right: -5px;

}

.cornerBtmLeft{

    bottom: -5px;
    left: -5px;

}
.cornerBtmRight{

    bottom: -5px;
    right: -5px;

}

.rectangle{
    position: absolute;
}

.colorBox{
    border: 1px solid black;
    height: 20px;
    width: 20px;
    list-style: none;
}

Sketch Board

Load

Save

Rectangle

Oval


text:
Q: Apache : Wrong hostname is checked when connecting to proxyed sever using SSL I'm trying to make this setup work :

*

*Reverse proxy : SSL enabled and facing the internet using Let's Encrypt certificate (reverse-proxy.com).

*Target : Site accessed via the reverse proxy with SSL enabled using internal certificate chain (target.internal).

So the connection should be :

*

*Client to reverse proxy TLS handshake

*Reverse proxy to target TLS handshake [failling]

What did I did good :

*

*Adding my root CA certificate to the proxy server

*Adding certificate, key and chain to the target

*trying successfully openssl s_client -connect target.internal:443 -prexit -CAfile /var/certs/root-ca.crt from the reverse-proxy

But Apache is failing because when trying to connect to "target.internal", it want to find the hostname "reverse-proxy.com" in the target certificate, while the target certificate was made for "target.internal".
I have this error in my log :
Cert does not match for name 'reverse-proxy.com'

It print this after successfully walking the certificate chain from "root-ca.crt" down to "target.internal.crt".
I don't get why Apache isn't looking for a certificate made for "target.internal".
Someone have an idea ?
Thanks you.
EDIT :
Listen 0.0.0.0:443 https

SSLPassPhraseDialog exec:/usr/libexec/httpd-ssl-pass-dialog

SSLSessionCache         shmcb:/run/httpd/sslcache(512000)
SSLSessionCacheTimeout  300

SSLRandomSeed startup file:/dev/urandom  256
SSLRandomSeed connect builtin

SSLCryptoDevice builtin

<VirtualHost _default_:443>

        ErrorLog logs/ssl_error_log
        TransferLog logs/ssl_access_log
        LogLevel trace1

        SSLEngine on
        SSLProxyEngine on
        SSLProxyCACertificateFile /var/certs/root-ca.crt

        SSLProtocol -all +TLSv1.2
        SSLCipherSuite HIGH:!SSLv3:!kRSA:!kECDH:!ADH:!DSS

        SSLCertificateFile /etc/letsencrypt/live/reverse-proxy.com/cert.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/reverse-proxy.com/privkey.pem

        <Files ~ "\.(cgi|shtml|phtml|php3?)$">
            SSLOptions +StdEnvVars
        </Files>
        <Directory "/var/www/cgi-bin">
            SSLOptions +StdEnvVars
        </Directory>

        BrowserMatch "MSIE [2-5]" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

        CustomLog logs/ssl_request_log \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

        ServerName reverse-proxy.com
        SSLCertificateChainFile /etc/letsencrypt/live/reverse-proxy.com/chain.pem

        ProxyPreserveHost On
        RewriteEngine On

        RewriteRule         ^/stuff/(.*)$     https://target.internal/$1 [P]
        ProxyPassReverse    /stuff/           https://target.internal/

</VirtualHost>