Wiring a fluorescent T8 fixture to a standard plug

Question: I am looking to connect a T8 fluorescent light fixture (that holds 4 bulbs) to a cord with a plug at the end so I can plug the fixture directly into a standard wall socket (or in my case a light socket adapter like this one.)
Here is an image of the connector, I'm not sure the exact name of the connector part, but how would I connect that to a cord with a plug at the end?
Notice the connector has 2 holes for white and 2 holes for black, I'm not sure what those are for.

It seems the ballast is grounded to the fixture, would I need a 2 or 3 pronged cord?
Comment: Note: your light socket adapter will *not* provide a ground and should not be used. You could perhaps replace the light fixture with something like [this (Amazon)](http://www.amazon.com/dp/B00002N5FR)
Comment: As long as you actually use the screw to ground the adapter, yes.
Comment: There are lots of plug-in fluorescent fixtures. Even better, there are lots of plug-in LED fixtures that are fairly direct replacements for T4/T8 fixtures. Might be easier to buy those, and donate the old fixture to a Habitat Re/Store or some similar architectural-reuse-for-the-needy service.
Comment: @DoxyLover I will connect a 3 pronged power cord to my light fixture. The socket I will be plugging the light fixture into is a 2 pronged socket with an adapter that makes it 3 pronged (it has a grounded screw) something like [this](http://www.amazon.com/Coleman-Cable-3-Prong-Grounding-Converter/dp/B002HGUQYK) will that be OK?
Answer: The extra holes in the connector are for wire chaining the fixture to the next fixture.  One pair goes to power, the other pair to the next fixture.
You can cut off the connector and strip the two wires (black and white) and connect them directly to the cord with wire twist connectors.  These are color coded for the total size of wires in them.  Yours plus a cord is likely to be the smallest (blue).

Black goes to black and white to white.
Be sure to use a three prong cord with a ground wire, like this:

Secure the green wire to the fixture's metal with a screw (maybe one already in place), or cut the end of the wire, strip it, and use a twist connector to tie it to a ground wire in the fixture.
The clamp is a great idea if the edge of the hole in the fixture is sharp.
Comment: Look at the edges of the cord assembly very carefully.  One of them has a molded stripe (raised or texture along its length) and the other side doesn't.  The striped side is equivalent to the black; the non-striped side is white.
Comment: The cord you linked to doesn't have white or black colored wires. Can I attach white to any end and black to the other? (and ground to the ground screw)?
Answer: The fluorescent fixture you have is intended to be hard-wired, so I'm not sure you'll be able to find an adapter for that quick-connect fitting you show, which are designed to wire several fixtures together. If you want to add a plug I think you'll have to cut the wire and splice in a new replacement cord. There should be a circular knock-out at the top of the fixture that you can use to get the wiring into the fixture. Make sure you use an appropriate cable clamp connector.
As for the number of conductors: The fixture should be grounded. Usually this is done by a ground wire attached to the fixture (you can actually see the green grounding screw in your photo). In your case you should use a 3-prong cable and use the ground.
One more comment: if you're setting up a makeshift fixture from an existing Edison socket, make sure you don't overload the capacity of the socket. A 4-lamp T8 fixture is probably going to draw 150 watts or so.
Answer: The yellow connector can be used for connecting to power cord. If hard wiring, you would simply strip the proper amount of insulation from the solid conductors and push in the holes to connect. If the connector is like the Ideal #102 (same idea, different mfg) you can even use the stranded wires from the power cord, just twist them and tin them with solder. Look up the specific yellow connector that came with the fixture to be sure it is approved for stranded wire first.


Upgrading From 11.04 (32bit) to 12.04 (64bit)

Question: I'm upgrading from 11.04 i386 to 12.4 64x. What I mean is I've installed the 12.4 64x server and I want to get all the settings from the 11.04 to set up the 12.4, the settings I'd like to get are for apache / PHP / phpmyadmin etc. Any and all settings that have to do with the web server. What files should I get or what path should I take here? Any suggestions would be great.
Answer: Depending on your configurations, your PHP settings should be in /etc/php5/*.
I do not know where phpmyadmin stores its data on the system.
I also do not know where your website files are.  but your Apache settings should be in either /etc/httpd/* or /etc/apache2/*, where * is a wildcard meaning everything within that folder.
Those folders contain the files for your configurations, and should be saved.  As well, any relevant user data should be saved as well (/home/user/* for example, where user is your username.)
Comment: Would I just copy the folders over to the new system and restart it?
Comment: You would not just "restart", you'd need to save your data onto some type of external media, and then *clean install* 12.04 64bit, since you cannot go directly from 32bit to 64bit.  Then you would need to manually go through and restore your data from the external storage.  As well, you'd need to reinstall all the packages again, some of which have had name changes since 11.04.
Comment: "clean install" means a brand new installation from the installation media, a 12.04 DVD or USB stick with the installation software image on it.
Comment: BTW these are both VMs. I have a fresh install of the 12.4 so now I just install/update all the services/programs I need. Then get the "etc/" folders for each and copy those over?
Comment: No, you first clean-install each service/program you need (`sudo apt-get install apache2 mysql-server php5 ...` depending on what you need, of course), then you copy your configs over.  Then you copy your files over.  Then you restart each service accordingly, and hope that it doesnt blow up.  If it blows up, there's something wrong.  but that'll be a different question.
Comment: Understood. I'll get on that and see how it goes. Thanks!
Comment: Everything worked out fine. Thanks for the tips.


Haystack-django SyntaxError: 'return' outside function

Question: My Search_Indexes
from datetime import datetime
from haystack import indexes
import json
from dezign.models import dezign

class dezignIndex(indexes.SearchIndex,indexes.Indexable):
    text=indexes.CharField(document=True,use_template=True)
    post_date=indexes.DateTimeField(model_attr='post_date')
    like=indexes.IntegerField(model_attr='like',indexed=False)
    #content_auto=indexes.EdgeNgramField(model_attr='title')
    #r= indexes.CharField(indexed=False)

    def get_model(self):
        return dezign

    def index_queryset(self,using=None):
        return self.get_model().objects.filter(like__exact=0)

# Error in prepare method
    def prepare(self, object):
        self.prepared_data = super(dezignIndex, self).prepare(object)
        self.dezign_jsonformat=[]
        select_dezign = dezign.objects.filter(like=self.prepared_data['like'])
        for i in select_dezign:
            dezign_jsonformat.append({'title':i.title,'body':i.body,'like':i.like,'date':i.post_date})
        self.prepared_data['list']=json.dumps(dezign_jsonformat)
        return self.prepared_data

When i run in command prompt
I am using Haystack with Whoosh
python .\manage.py rebuild_index
Error
PS C:\Python27\Scripts\dezignup_django> python .\manage.py rebuild_index

WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'.
Your choices after this are to restore from backups or rebuild via the `rebuild_index` command.
Are you sure you wish to continue? [y/N] y
Removing all documents from your index because you said so.
Traceback (most recent call last):
  File ".\manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\haystack\management\commands\rebuild_index.py", line 15, in handle
    call_command('clear_index', **options)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 159, in call_command
    return klass.execute(*args, **defaults)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\haystack\management\commands\clear_index.py", line 50, in handle
    backend.clear()
  File "C:\Python27\lib\site-packages\haystack\backends\whoosh_backend.py", line 239, in clear
    self.setup()
  File "C:\Python27\lib\site-packages\haystack\backends\whoosh_backend.py", line 126, in setup
    self.content_field_name, self.schema = self.build_schema(connections[self.connection_alias].get_unified_index().all_
searchfields())
  File "C:\Python27\lib\site-packages\haystack\utils\loading.py", line 316, in all_searchfields
    self.build()
  File "C:\Python27\lib\site-packages\haystack\utils\loading.py", line 200, in build
    indexes = self.collect_indexes()
  File "C:\Python27\lib\site-packages\haystack\utils\loading.py", line 169, in collect_indexes
    search_index_module = importlib.import_module("%s.search_indexes" % app)
  File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 40, in import_module
    __import__(name)
  File "C:\Python27\Scripts\dezignup_django\dezign\search_indexes.py", line 28
    return self.prepared_data
SyntaxError: 'return' outside function

I am doing a small web search project where we need data in json format
please help
I will be very thankful to you
Comment: Check your indentation. Mixing tab and spaces? Don't do that.
Answer: Make sure you're not mixing spaces and tabs for indentation.
One possible reason for the error is that the line containing the return statement is indented with tab, while other statements are indented with spaces.
Choose spaces (preferred) or tab only for indentation.


BeautifulSoup 4 parsing attribute error

Question: i am trying to parse an HTML document, but bs4 fail to parse attribute in a specific tag:
<select class="inputNormal" id="TipoImmobileDaNonImportare" name="TipoImmobileDaNonImportare" style="width:100%">
            <option value=""></option>
            <option value="unità immobiliare urbana">unità immobiliare urbana</option>
            <option value="particella terreni">particella terreni</option>
</select>

when i print, the error
AttributeError: 'tuple' object has no attribute 'items'`
the tag and attribute i print:`select: (u'style', u'class', u'name')`
instead of (for example):  `input: {u'type': u'hidden', u'name': u'Immobile_Note', u'value': u'Ubicazione occupazione', u'id': u'Immobile_Note'}`

UPDATE:
 if i try soup.find_all( attrs= {'id' : 'somevalue' } ) it fail because try access all attributes of tree!
If i try:
s = BeautifulSoup( """<select class="inputNormal" id="TipoImmobileDaNonImportare" name="TipoImmobileDaNonImportare" style="width:100%">
<option value=""></option>
<option value="unità immobiliare urbana">unità immobiliare urbana</option>
<option value="particella terreni">particella terreni</option>
</select>""")

The parser detect it correctly:
select: {'id': 'TipoImmobileDaNonImportare', 'style': 'width:100%', 'class': ['inputNormal'], 'name': 'TipoImmobileDaNonImportare'}

i try to parse it with lxml parser and html5lib parser, but the result is the same.
Thanks for any replies.
EDIT:
thanks to Amanda, but there was an error in my code, i try to store in tag.attrs a touple object because this code is porting from bs3 to bs4!
Thanks.
Comment: What are you trying to parse or access in this case?
Answer: I'm not entirely sure what you're trying to access with Beautiful Soup here, but if you want to get at the attributes for the select or the options, you can do something like:
html = """<select class="inputNormal" id="TipoImmobileDaNonImportare" name="TipoImmobileDaNonImportare" style="width:100%">
        <option value=""></option>
        <option value="unità immobiliare urbana">unità immobiliare urbana</option>
        <option value="particella terreni">particella terreni</option></select>"""

soup = BeautifulSoup(html)

You can show the attributes of the first "select" with:
print soup.find('select').attrs

Or show the attributes of all the options with:
for option in soup.find_all('option'):
    print option.attrs

Or, if you're looking for the names of available items, use:
for option in soup.find_all('option'):
    print option.text

or if you want the option value rather than the displayed text, use:
for option in soup.find_all('option'):
    print option['value']

If that doesn't help, maybe you could give an example of the output you're expecting

BeautifulSoup 4 parsing attribute error


mysql query ask 2nd table only if !=""

Question: I have a table customers:
id, firstname, lastname, companyname,title_id,salutation_id
1,Peter,Pan,1,1
2,Cindy,Crawfort,Tinysoft,0,1
3,,,Amaton,,,
..

and a table title
id, name
1. Dr.
2. Dr. Prof.
...

and a table salutation
id name
1, Mrs.
2,Mr.
3,none

What I'd like to do is, to make a query that gives me the correct salutation if it is not empty.
I tried:
select *
from customers
 where if(customer.name!="",customer.title_id=titles.id) and
       if(customer.name!="",customer.salutation_id=salutations.id) ;

That means in a header should be the correct Name if exists. But sometimes, like Amazon you don't have a name, just the companys name to adress. In this case the companys name should only be put out.
An output should look like this:
Mr. Peter Pan
Dear Dr. Peter Pan or
Mrs. Crawfort
Dear Mrs Crawfort
or
Amazon
Dear sirs or madams,
The mentioned query is empty. Any idea? Thank you!
tsunami
Answer: You need to use left join and some logic in the select clause:
select c.*,
       (case when s.id is not null and s.id <> '' then s.name
             else t.name
        end) as CorrectSalutation
from customers c left join
     title t
     on c.title_id = t.id left join
     salutation s
     on c.salutation_id = s.id;

mysql query ask 2nd table only if !=""


What is wrong with this vb wfa code?

Question: What is wrong with this code for multiple checkboxes in vb wfa, it says it can't be converted to a boolean:
If ch1.Checked & ch2.Checked = True Then
        score = score + 1
End If

Comment: @KenWhite No it´s not. The And Operator in VB .NET is `And`  not `&`
Comment: & is the string concatenation operator.  It doesn't care much for `If "FalseTrue" Then`.  Nobody does, that's truetrue.  Use And or AndAlso.  And do favor Option Strict On for a while so the compiler can tell about typos like this.
Answer: In vb, the operator is And:
If (ch1.Checked And ch2.Checked) Then
    score = score + 1
End If

Comment: how can i have 2 radio buttons in 1 program with out one overwriting the outer
Answer: If you want compare that both checkboxes are checked then AndAlso will be little bid better, because it will not evaluate second checkbox value if first is false
If ch1.Checked AndAlso ch2.Checked Then
    score = score + 1
End If

In c# it is same as && operator

What is wrong with this vb wfa code?


Google Plus1 on mobiles. - How to disable annotation

Question: I can't seem to disable annotations for the plus1 button on iPhone and Android. I tried:
<g:plusone size='tall' data-annotation='none'></g:plusone>"

as well as just
"annotation='none' "

Both work fine on desktops, but both show annotations on mobiles. Is this just me or are other having the same issues?
Example Link: http://filmandmusic.mobi/song/101
Answer: Change it back to <g:plusone size="tall" annotation="none"></g:plusone>. I see the annotation on the desktop with data-annotation. If it still shows with annotations on mobile create a bug report. http://bugpl.us/new
Comment: Changed it back - makes no difference as per my initial post. Thanks for the bug report link.


N56VZ: Subwoofer not working anymore

Question: I use Ubuntu 12.04 on Asus N56VZ, the subwoofer used to work doing the following trick advised by Sami:

a. Add to rc.local
echo 0x1e 0x99130112 > /sys/class/sound/hwC0D0/user_pin_configs
echo 1 > /sys/class/sound/hwC0D0/reconfig
b. Add options snd-hda-intel model=asus-mode4 in /etc/modprobe.d/alsa-base.conf
c. Reboot
d. Set the mode to "Analog Surround 5.1 output" in the sound settings panel

But a few weeks ago, the "Analog Surround 5.1 output" box does not appear anymore on the sound setting panel
I tride to install this driver: https://wiki.ubuntu.com/Audio/UpgradingAlsa/DKMS
But no result.
Here is my /etc/rc.local:
<code>#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
fstrim -v /
fstrim -v /home
echo 0x1e 0x99130112 > /sys/class/sound/hwC0D0/user_pin_configs
echo 1 > /sys/class/sound/hwC0D0/reconfig

exit 0
</code>
and my /etc/modprobe.d/alsa-base.conf:
<code># autoloader aliases
install sound-slot-0 /sbin/modprobe snd-card-0
install sound-slot-1 /sbin/modprobe snd-card-1
install sound-slot-2 /sbin/modprobe snd-card-2
install sound-slot-3 /sbin/modprobe snd-card-3
install sound-slot-4 /sbin/modprobe snd-card-4
install sound-slot-5 /sbin/modprobe snd-card-5
install sound-slot-6 /sbin/modprobe snd-card-6
install sound-slot-7 /sbin/modprobe snd-card-7

# Cause optional modules to be loaded above generic modules

install snd-rawmidi /sbin/modprobe --ignore-install snd-rawmidi $CMDLINE_OPTS && { /sbin/modprobe --quiet --use-blacklist snd-seq-midi ; : ; }
# Cause optional modules to be loaded above sound card driver modules

install snd-emu10k1 /sbin/modprobe --ignore-install snd-emu10k1 $CMDLINE_OPTS && {     /sbin/modprobe --quiet --use-blacklist snd-emu10k1-synth ; }
install snd-via82xx /sbin/modprobe --ignore-install snd-via82xx $CMDLINE_OPTS && {     /sbin/modprobe --quiet --use-blacklist snd-seq ; }

# Load saa7134-alsa instead of saa7134 (which gets dragged in by it anyway)
install saa7134 /sbin/modprobe --ignore-install saa7134 $CMDLINE_OPTS && {     /sbin/modprobe --quiet --use-blacklist saa7134-alsa ; : ; }
# Prevent abnormal drivers from grabbing index 0
options bt87x index=-2
options cx88_alsa index=-2
options saa7134-alsa index=-2
options snd-atiixp-modem index=-2
options snd-intel8x0m index=-2
options snd-via82xx-modem index=-2
options snd-usb-audio index=-2
options snd-usb-caiaq index=-2
options snd-usb-ua101 index=-2
options snd-usb-us122l index=-2
options snd-usb-usx2y index=-2
# Ubuntu #62691, enable MPU for snd-cmipci
options snd-cmipci mpu_port=0x330 fm_port=0x388
# Keep snd-pcsp from being loaded as first soundcard
options snd-pcsp index=-2
# Keep snd-usb-audio from beeing loaded as first soundcard
options snd-usb-audio index=-2
options snd-hda-intel model=asus-mode4"
</code>
Thanks a lot for your help.
Answer: after suspending computer sound card stops working. I can use headphones, but subwoofer and computer speakers doesn't work, after restarting it works. Any idea how to solve this? Without changes in /etc/modprobe.d/alsa-base.conf subwoofer doesnt work, but computers speakers works fine after several suspendings

N56VZ: Subwoofer not working anymore


Run MongoDB service as daemon of SystemD on Ubuntu 15.10

Question: MongoDB just supports versions of Ubuntu Long Term Support (LTS). The last is Ubuntu 14.04 LTS, where the init process is managed by Upstart proprietary of Canonical. However I'm using Ubuntu 15.10 with the Linux standard SystemD init process. So I can't start the MongoDB service on boot.
When I read the service status or try start it, show the message "failed to load":
> systemctl status mongod
Loaded: not-found (Reason: No such file or directory)
Active: inactive (dead)
> sudo systemctl start mongod
Failed to start mongod.service: Unit mongod.service failed to load: No such file or directory.

I'm running the official MongoDB 3.2 Community Edition (mongodb-org) from https://docs.mongodb.org/master/tutorial/install-mongodb-on-ubuntu/ not the MongoDB 2.6 meta-package (mongodb) from Ubuntu repository.
> sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
> echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
> sudo apt-get update
> sudo apt-get install -y mongodb-org

Someone knows how to start the MongoDB with SystemD?
Comment: my problem was a custom config file that was not forking mongod, here is the snippet from the default mongod conf that I was missing,

    processManagement:
      fork: true
      pidFilePath: /var/run/mongod.pid
Answer: I managed start the MongoDB service with SystemD on boot:
I uninstalled the official meta-package (mongodb-org) v3.2, then I installed the meta-package (mongodb) v2.6 from Ubuntu repository:
> sudo apt-get remove mongodb-org
> sudo apt-get install mongodb

Create the service config file as shown below:
> cd /lib/systemd/system
> sudo touch mongodb.service
> sudo nano mongodb.service
[Unit]
Description=An object/document-oriented database
Documentation=man:mongod(1)
After=network.target

[Service]
User=mongodb
Group=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongodb.conf

[Install]
WantedBy=multi-user.target

Verify in the list if the service is enabled or disabled using the command below:
> systemctl list-unit-files --type=service
...
mongodb.service             disabled
...

If it is disabled or not in the list, enable it:
> sudo systemctl enable mongodb.service

Check again:
> systemctl list-unit-files --type=service
...
mongodb.service             enabled
...

Now you can managing the service on SystemD init process:
> systemctl status mongodb
> sudo systemctl stop mongodb
> sudo systemctl start mongodb
> sudo systemctl restart mongodb

Enjoy!
Comment: That service unit was written by Canonical, not by a local administrator, then they **must reside** in the `/lib`. The parts of the service definition are good enough to start the service, the additional settings do not take significant effect, so they are considered complementary. If you add the `PIDFile=/var/run/mongodb/mongod.pid` line and the `run` instruction on `ExecStart=` line, you get an error, because I'm using (mongodb) meta-package 2.6, not the (mongodb-org) meta-package 3.2.
Comment: Why down voted, I upvoted. I also faced a similar issue and this answer helped, thanks.
Comment: See http://askubuntu.com/a/617869/43344 for a pointer to the parts of the service definition that you missed.  Also note that service units supplied and written by the local administrator **should not** go in `/lib`.
Comment: This was super helpful moving from Ubuntu 14 to 18, my only addition would be that I had to recreate the data and log directories and `chown` them before mongod would start via systemctl. Nothing the install docs wouldn't have told me but in case it's helpful!
Answer: On default install from MongoDB repository, in order to have automatic startup of mongod service, all you need to do is enable system.d service:
systemctl enable mongod.service (pay attention to mongod service name, not mongodb)
NOTE: this is tested on both Debian/GNU Jessie 8.x with systemd and Ubuntu Xerus 16.04 LTS.
Comment: The file is present in `/lib/systemd/system/mongod.service` in my Ubuntu 16.04
Comment: This stands true for Ubuntu Xerus 16.04 LTS as well. After installing from official repo, you need to enable systemd service unit! I just confirmed it with another instance installation... :)
Comment: Yes, systemd unit definition is there but it's disabled, so you need to enable it in order to have it automatically started each time you reboot your instance.


In nautilus how can I hide file types

Question: Like on windows? There doesn't seem to be an option for this? Is this possible? it's annoying looking at the .xxx all the time.
Comment: @JacobVlijm Windows Explorer (the default file manager for Windows) used to hide the file extenstion (the 3 characters following the [.], in XP and Windows 7 by default. I don't know about 8 and later. Those who are from that world got used to seeing file names without the extension.
Answer: In nautilus you can not hide a certain file extension.
File extensions can be deceiving!
But I wrote a for loop in shell for you:
<code>for file in *.xxx; do mv $file .${file%%}; done
</code>
This will hide all files with .xxx extension in your current working directory.
Answer: A simple way to use a "." as the first symbol of the name.  Or you can put the file inside a folder and rename the folder by having a "." as the first symbol of the folder's name.
Examples:
.hidden
.folder
.hiddenfolder
.file
.title
Automatically, the folders/files will be hidden.  Then, when you want to see the hidden items again, you'll have to press Ctrl + h on your keyboard every time you want to see whatever's hidden.

In nautilus how can I hide file types


Store variable in Session

Question: I want to store the user_level from my mysql db of the user who submits the form in the $_SESSION
My code currently is this:
    <form id='login' action='<?php echo $fgmembersite->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'>
    <fieldset >
    <?php
    if(isset($_POST['submitted']))
    {
 session_start();
    if($fgmembersite->Login())
       {

        $mysqli = new mysqli('host', 'name', 'psw', 'db');
                if ($result = $mysqli->query("SELECT user_level FROM users WHERE username='$username'")) {

                 $_SESSION['user_level'] = $result;
            }
            $fgmembersite->RedirectToURL("loginhome.php");

       }

    }
    ?>

    <legend>Login</legend>

    <input type='hidden' name='submitted' id='submitted' value='1'/>

* benötigte Felder

<?php echo $fgmembersite->GetErrorMessage(); ?>

        Benutzername*:

        <input type='text' name='username' id='username' value='<?php echo $fgmembersite->SafeDisplay('username') ?>' maxlength="50" />

Now I checked it on the site, where you got redirected with print_r($_SESSION); and I get this result:
[user_level] => mysqli_result Object ( [current_field] => [field_count] => [lengths] => [num_rows] => [type] => )

Can anyone explain to me what happens there? Or what went wrong?
Comment: You need to use mysql_fetch_assoc to extract the data from object which is $result
Comment: `$mysqli = new mysqli('host', 'name', 'psw', 'db');
 $data = array();
 if ($result = $mysqli->query("SELECT user_level FROM users WHERE username='$username'")) {
  while($res = $result->fetchAll(MYSQLI_ASSOC)){
  $data[] = $res;

  }

    }
    $_SESSION['user_level'] = $data;`
Comment: Sadly, with this my loginform disappears
Answer: This probably will not fix your issue but a session should always be started at the utmost top of your script.
<?php
if (!isset($_SESSION)) {
    session_start();
}

// ... Other code ...

There is also an issue with your query. You should use it like:
$conn = new mysqli('host', 'username', 'password', 'database');
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("s", $editID);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

print_r($row);

Comment: Hm, my loginform disappears. But I can't print the `$row` as the loginform is not yet submitted? because there is no value for `'$username'`.
Comment: @pr0cz  when you have this `$fgmembersite->Login()` then why not in that function only save the data to session, again one more query and result fetching? that is unnecessary
Answer: Try this
1) Start session at top of page
2) you should fetch data in associative array and then assign value in session variable
 if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $_SESSION['user_level'] =  $row['user_level'];
    }

Comment: instead of  `$_SESSION['user_level'] = $result;` ?
Comment: Okay, now it doesn't show the `user_level` in the `print_r` tag anymore.
Comment: try to print $row and check what it contains
Comment: it doesn't get printed on the redirected page

Store variable in Session


How to get the desktop back to normal size and actually fit screen

Question: For some reason (probably me accidentally pressing "secret" key combo) my desktop no longer fits screen. Only a portion of it (perhaps 90%) is shown at a time and it scrolls when I move the mouse. That annoys me a lot.
How do I get the screen back to normal again? I'm using xfce 4.12
Answer: It turned out that I accidentally pressed Alt+Scroll Wheel which acts as zoom. Using it again turned the desktop back to normal.


How can I run an additional electrical circuit to a wall mounted TV?

Question: I am in the in the planning phase of mounting my 50" plasma in my living room.  The wall the TV is going on is an exterior wall (it should have insulation) and the interior side is already finished so I don't have full access for running new electrical.  I am thinking of running the wires behind the wall from the tv down to the bottom of the wall and having them come out at the bottom and running them outside the wall along the baseboard to the reciever/cable box/etc.  This way I don't need to punch holes in the drywall and run the wires through the studs.
For running the low voltage wires I will get two face plates that allow me to run the HDMI cables through the wall.  But running the electrical to behind the TV is trickier.  I found a kit (Recessed Pro Power Kit w/Straight Blade Inlet White) that seems to be designed for this situation.  Is there a way to get this myself without buying the whole kit?  I don't need the low voltage lines to run next to the electrical, and I would like to actually have a normal outlet behind the TV (so I can plug 2 devices into it) instead of just one like in the kit.
For the outlet behind the TV I can just use a normal outlet but I don't know how or what to use for the other "outlet" the gets the power initially.  I don't want to buy the $50 kit above just for that piece.
EDIT: While there are other eletrical outlets on this wall, none are below were I want to mount the TV so I can't reach them without going through studs.  However this is an exterior wall on the first floor, I can get to the bottom of the wall from my unfinished basement.  Initially I liked the product I linked from Monoprice because it would still allow me to run my TV through me APC surge protector.  However I have found some in wall surge protectors (like this) so if I run power from the basement I could install one of those.
Comment: possible duplicate of [Best option for hiding wires to wall mounted TV](http://diy.stackexchange.com/questions/2507/best-option-for-hiding-wires-to-wall-mounted-tv)
Comment: I've just found a better duplicate - http://diy.stackexchange.com/questions/742/how-to-run-wires-for-a-wall-mount-flatscreen-tv
Comment: I actually saw the second one and it is close.  However my question is more specifically is there a way for me to "DIY" my own kit like the one I linked.  Really I just don't know how to run the power over to this outlet without wiring it into the existing in-wall eletrical.
Answer: See my previous answer to a similar question.  (It's kind of funny.  I even mention that that same kit you found seems a bit pricey.)
I used a single, recessed, dual-voltage wall plate that lets you do your media and power cables all in one plate.  You just buy an "old work" electrical box, wire it up, and attach it to this plate instead of to the drywall.

I used 6-port keystone plates for the media ports, so I could put just the ports that I wanted back there, and even customize it easily later, if needed.
Comment: But how do I get power to this outlet without wiring it into another in wall eletrical outlet.  I relly just want to "feeder" part of the linked kit, the power cable and the "male" eletrical outlet.  Once I get that I know what to do behind the TV.
Comment: I'm not sure where you would get power from, if not from another outlet, switch, or junction box.  I believe most municipalities would have codes against running extension cords through the walls, if that's what you're thinking about.  I'm guessing that they're not rated for use under enclosed, insulated conditions.  To do this right, I would definitely tie into an existing outlet.  I recommend this recessed box because I think it ends up looking cleaner and more professional than having 3 separate plates behind the TV.
Answer: If you're just using a regular outlet as you suggest behind the TV, then my suggestion would be to supply it like a regular outlet.
If there is another outlet nearby (directly below would be ideal), fish a wire to it, and attach it to that circuit.
If there is unfinished space below, you can get a wire down there (use a long "installer's drill bit") and then it should be relatively easy to find a circuit to attach it to (or just run it back to the panel).
I'd be nervous about any contraptions that attempt to get power to this circuit otherwise. You absolutely need to have a male end in the wall, as a male-to-male extension cable is dangerous to have.

The best thing I can think up totally as a DIY without requiring real hard-wiring would be to get a blank faceplate, and put a square hole in it, and then mount an IEC 320-C14 connector in it (eg. from digikey).

Then you can just use a standard C13 cord (like the kind used to connect most computers, TVs, etc) and plug it into a surge protector or UPS or whatever.
Comment: I do have access to the underside of this wall as my basement is unfinished. Is there anything wrong with drilling through the sill plate and running a wire up from the basement?
Comment: No, but using an installer bit to drill down is much easier (I have a post on my blog about doing this: http://gregmaclellan.com/blog/running-network-cables/). With careful measuring you can drill up from the basement. You only need a 1/2 or 3/4" hole (Romex 14-2 fits fine in 1/2") so it doesn't affect the structural integrity in any measurable way (all your existing wiring will be run this way anyways).
Comment: Great good to know.  My concern was more related to fire and if that sill plate was supposed to act as a firestop.  However you are right, all the wires going upstairs must be doing that :)
Comment: It does technically provide a route for fire. If you are concerned, there are companies that make expanding foam that is designed as a fire block (like this: http://www.homedepot.com/h_d1/N-5yc1vZ1xg1/R-202023037/h_d2/ProductDisplay?langId=-1&storeId=10051&catalogId=10053).
Comment: I'm pretty sure cutting holes in a faceplate violates its Listing. Wiremold is a better route if you don't want the hassle of fishing cable through a finished wall.
Answer: At the home stores in the electrical aisles you can get some surface mount cable hiding channels of various sizes.  It looks kind of like molding, but opens to mount cables in it.  While it's not as nice as running things in the wall, my wife was happy with the lack of cable visual clutter and I was very happy with how easy it was to run and make changes for new wiring.  I have one running up to drive a projector, and another running down from a wall-mounted flat-panel to the baseboard, over to the UPS.
It's cheap, easy to install, and easy to change out cables for things like when you replace the TV with one that needs Ethernet, you decide to run more HDMI cables directly to the TV instead of through a receiver, or we switch from HDMI to Display Port or whatever the next thing is (or from HDMI 1.3 to 1.4 or beyond).


How to simulate sys.argv[1:] on web based python

Question: I have a Python program where the initiation script looks like this:
if __name__ == "__main__":
    main(sys.argv[1:])

To run this, I have to use Shell or Terminal like this:
myscript somefile.xml

The script accepts a file and then does all the rest of the work.
Now, I am trying to run this program on a web server.
SO I use a HTML Form to submit the file to this script.
In my Python script, I am doing like this:
....
elif req.form.has_key("filename"):
    item=req.form["filename"]
    if item.file:
        req.write("I GO HERE")
        myscript.main(item)
....

As you can see here, I am trying to send the file directly to the "main" function.
Is this the right way to do?
I dont get any script error, but the Python script is not producing the expected results.
Any help?
Thanks
Comment: What framework are you using? Or is it a CGI script? And what actually does happen?
Answer: Write the uploaded file contents to a temporary file (using tempfile.mkstemp()) and pass the filename of the temporary file into main() wrapped in a list.
For example (untested):
import os
import tempfile

fd, temp_filename = tempfile.mkstemp()
try:
    with os.fdopen(fd, "wb") as f:
        # Copy file data to temp file
        while True:
            chunk = item.file.read(100000)
            if not chunk: break
            f.write(chunk)

        # Call script's main() function
        myscript.main([temp_filename])
finally:
    os.remove(temp_filename)

Comment: You need to use `f.flush()` after the copying loop to ensure, that internal IO buffers are flushed, and all data is really written to the file.  Moreover the code could be simplified by using `tempfile.NamedTemporaryFile` and `shutil.copyfileobj`.
Comment: Thanks for your reply,
But I get an Syntax error here:
    with os.fdopen(fd, "wb") as f:
Comment: What version of Python?  You might need to add `from __future__ import with_statement` at the top of the file.


Scrapy CrawlSpider output with spaces and functions

Question: I'm currently writing a scraper with scrapy. I want to crawl all the text that is shown on the website, not a single page, but all the subpages aswell. I#m using CrawlSpider, because I think it's made for scraping the other pages aswell. Here is the code I wrote so far:
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.exporters import XmlItemExporter

class MySpider(CrawlSpider):
    name = 'eship2'
    allowed_domains = ['tlk-energy.com']
    start_urls = ['http://www.tlk-energy.com']

    rules = [Rule(LinkExtractor(), callback='parse_item', follow=True)] # Follow any link scrapy finds (that is allowed).

    def parse_item(self, response):
        item = dict()
        item['url'] = response.url
        item['title'] = response.meta['link_text']
        item['body'] = '\n'.join(response.xpath('//text()').extract())
        return item

I get an output which suits my wishes very well but I still have a lot of tabs and spaces like this one:
> Wärmepumpen- Klimakreislauf E-Fahrzeug
>
>
>
>
>
>
>
>
>
>
>
>
>
> Projektbeschreibung
>
> Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet
> egestas purus in blandit. Curabitur vulputate, ligula lacinia
> scelerisque tempor, lacus lacus ornare ante, ac egestas est urna sit
> amet arcu.

and also some text like this one:
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-77796939-1', 'auto');
  ga('send', 'pageview');

I just want a file, for example xml where the text of the website is shown and maybe the url where the text was found.
Answer: You need to add some postprocessing to clear you results:

To remove javascript and css text from your results use this:
results = response.xpath(
   '//*[not(self::script or self::style)]/text()'
).extract()
Then apply strip and if to remove empty lines:
text = " ".join([x.strip() for x in results if x.strip()])
Comment: i adjusted the code you suggested, and now it works! Thanks so much for the help!
Comment: one last question. now i get a text without any paragraphs, what I wanted. But is there a option to get a paragraph when there is one in the text? Then it will be easier to read the text. If not, it's okay how it is now.
Comment: That depends on how the HTML is structured. If the text you want is inside a `` tag, you can use selectors to just get that specified tag and avoid getting the rest.  You will need to know some css or xpath to select only what you want from the website.


What do I get if my Directrix and Focus are the same?

Question: In my calculus class today we had a discussion about whether you'd get a vertical line or just a point when your directrix and focus become the same point. What would happen?
Comment: That sounds like a deep question about mathematics. I highly encourage you to ask it on the Mathematics SE. My initial gut feeling is that the Parabola becomes pointier and pointier as the point and the directrix merge. I suspect : LINE
Comment: A directrix is a *line*, while a focus is a *point*. (Check your definitions again!) How, then, can they be the same?
Comment: J.M., I think the OP intends to ask: what if the focus were to lie on the directrix? That is to say, they share an x- or a y- coordinate
Comment: @Αδριανός, in that case, if the OP can derive the equation of the general conic whose directrix is the $y$-axis, and whose focus is a point on the $x$ axis, he can then study what happens if the movable point becomes the origin.
Comment: Hi John! I tried to ask the question on Mathematics SE but it got redirected to here it would seem. Perhaps I'll try again?
Answer: You have everything zoomed out.At the nearest point the distance between focus and directrix is $ d(1+\epsilon)$ where d is distance to focus which when itself shrinks to zero entire scene goes to a point by uniform scaling. If length of feet of a person is 6 inches for his height 6 feet then those of an ant by same proportion would be 6 mm and 0.5  mm respectively.


How to use preact using html and script tag?

Question: I have a very simple react program that imports react using a script command and a cdn.
How do I covert it to preact while keeping the same structure?
I tried to follow these instruction, but they weren't very clear
<!DOCTYPE html>

    <title></title>

Answer: As per this github issue you have a couple of different options for using Preact with a script tag. You can directly call h- Preact's version of React.createElement or you can use babel standalone to transform your JSX as you were in your original React example. Here is a Preact conversion of your original example.
<!DOCTYPE html>

  <title></title>


Rendering over 1000 markers using React Map GL

Question: I am experiencing a problem with rendering large amount of markers. Each marker is displayed as a SVG. Everything is fine until the number of markers increases to more than 1000. The map start lagging and there is delay when zoom in or zoom out, even moving the map. As I saw from this post: Stylable marker/feature in react-mapbox-gl?
Is there any other methods that I can render and interact smoothly without changing from react-map-gl to react-mapbox-gl? Because Feature component does not exist in react-map-gl.
Thanks for answering my question.
Answer: There are optimizations described here for rendering large numbers of markers and zooming/panning: https://github.com/visgl/react-map-gl/issues/750
Answer: You will need to cluster your markers, there are different ways to accomplish this depending on your setup, for react-mapbox-gl there is a really good tutorial here using a custom hook for Supercluster


Where can I find ASROCK E350M1 Integrated AMD Radeon HD 6310 graphics driver?

Question: I just built a desktop computer using an ASRock E350M1 board, powered by an AMD Fusion E-350 APU (AMD Radeon HD 6310 GPU Model). I installed Ubuntu 10.04. Did all the updates. Almost everything works great: I can see movies (DVD), surf, etc., but I cannot play games --screen frames are very, very slow. I have not installed any hardware drivers. When I search (in Ubuntu) for the hardware drivers, none are found.
I found here, http://wiki.cchtml.com/index.php/Hardware that the graphics card is officially supported: PALM | Radeon HD 6250/6310
If this is of any help, this is what I entered on the terminal:

lspci -nn | grep VGA

00:01.0 VGA compatible controller [0300]: ATI Technologies Inc Device
  [1002:9802]
^C
sudo apt-get install build-essential cdbs fakeroot dh-make debhelper debconf libstdc++6 dkms libqtgui4 wget execstack libelfg0 dh-modaliases

[sudo] password for pat:
  Reading package
  lists...
  Done Building dependency tree
  Reading state
  information...
  Done debconf is already the newest version. libstdc++6
  is already the newest version. libqtgui4 is already the newest
  version. libqtgui4 set to manually installed. wget is already the
  newest version. E: Couldn't find package dh-modaliases

I do not know what to do from here.
Questions:

Where can I locate the drivers?
How do I install the drivers?
Answer: I think you would have to download and install AMDs proprietary driver from their website.
For 32 and 64-bit: http://support.amd.com/us/gpudownload/linux/Pages/radeon_linux.aspx?type=2.4.1&product=220.127.116.11.42&lang=English
after downloading right click on the file and mark it as executable under properties. Now open a terminal and type in
sudo sh /home/your_username/Downloads/amd-driver-installer-12-2-x86.x86_64.run

the installer will guide you through the installation.
After the installation was succesful, type into the terminal
sudo aticonfig --initial -f

and finally
sudo reboot

Comment: FYI, I got the drivers at AMDs driver page looking under 'Desktop Graphics' -> 'E-Series APU' -> 'E-350 APU' -> 'Linux x86_64'
Comment: Daniel, your instructions were concise, clear and exactly what I needed. Thanks also for telling me how you located the driver. please note that, for whatever reason, I was not able to use,"sudo sh /home/your_username/Downloads/amd-driver-installer-12-2-x86.x86_64.run" I received the following message, "Can't open /home/your_username/Downloads/amd-driver-installer-12-2-x86.x86_64.run
pat@pat-desktop:~$"
Comment: oh sorry, you have to put the actual username of your ubuntu account where I put 'your_username' it was just a placeholder. Alternatively you can type sudo sh $HOME/Downloads/amd-driver-installer-12-2-x86.x86_64.run
Comment: Thanks again Daniel! Thanks also for showing me where to locate the driver. I should have figured out to put my username in place of 'your_username' but I am totally new to Linux...
Comment: My next step is to locate and install the Realtek drivers. Is the proper protocol to ask a new questions since it has nothing to do with graphics drivers?
Comment: please close this question first by accepting my answer and then open a new question with specific details for the issue you're having
Answer: I've had good success with that exact board, which I have, with the 3.2 kernel in precise and the open-source radeon driver. (I am using the non-free firmware) I recommend installing the backport kernel and xserver-xorg-video-radeon.
I succeeded in installing Coreboot onto my ASROCK E350M1.


Greater Rift Keystone drop rate and requirements?

Question: The Greater Rift Keystone drop rate is 100% for T6 and maybe 75% for T1, lower for lower difficulties and chance of 2 dropping in higher difficulties. Is there any empirical data that confirms rates?
Edit: drop rates were changed in a hotfix on Sept 3, 2014:

The drop rate for Key of Trials has been significantly increased (9/3)

Edit: difficulty requirement was removed in patch 2.3 on Aug 25, 2015:

Generic Greater Rift Keystones now drop and can drop at any difficulty level

Confirmed level 70 required.
I'd still like to know approximate drop rates on all difficulties if anyone has data/insight.
Comment: There are no posts on this as of yet. T1 and 70 are required. You can see the psuedo rates I posted here: http://gaming.stackexchange.com/a/182521/25404 and I will update them when there is more actual information released or available.
Comment: I'd recommend removing the request for blue/green posts.  Those requests are off-topic.  We can test and give empirical evidence, so it's objective, but specifically asking us to hunt down what developers have said isn't something we do.
Comment: Possible duplicate of [What are Greater Nephalem Rifts and how do they work?](http://gaming.stackexchange.com/questions/182501/what-are-greater-nephalem-rifts-and-how-do-they-work)
Comment: Aren't these drop rates the same as keys for infernal machine?
Comment: @BenLefebvre - They are not, because for example the keys drop at a 50% rate on T6 and the keystone drops at a 100% rate on T6.
Answer: This may be just an approximate answer. But as far as I tested it, I've checked it on my game.
You reference that T6 will provide a 100% drop chance. As far as I tested it, this won't be true. I have played some T6 portals and I gt some keys, which is great, but also some runs without any key.
There is a reference on the net which says it could be 100%. But in my experience they are much lower. As everytime were a percentage chance exists, it won't be possible to pin it down to an exact value without viewing the code. But regarding my drop chance experiences the drop chance base seems to be like the drop rate for the infernal machine which is described below.

Torment I: 25%
Torment II: 28%
Torment III: 33%
Torment IV: 38%
Torment V: 43%
Torment VI: 50%


main function not waiting for channel read before exiting?

Question: Consider the following attempt to implement Dining Philosophers with Go routines and channels.
package main

import "fmt"

func philos(id int, left, right, plate chan bool) {
    fmt.Printf("Philosopher # %d wants to eat\n", id)
    <-left
    <-right
    plate <- true
    left <- true
    right <- true
    fmt.Printf("Philosopher # %d finished eating\n", id)
}

func main() {
    const numPhilos = 5
    var forks [numPhilos]chan bool
    for i := 0; i < numPhilos; i++ {
        forks[i] = make(chan bool, 1)
        forks[i] <- true
    }
    plates := make(chan bool)
    for i := 0; i < numPhilos; i++ {
        go philos(i, forks[(i-1+numPhilos)%numPhilos], forks[(i+numPhilos)%numPhilos], plates)
    }
    for i := 0; i < numPhilos; i++ {
        <-plates
    }
}

Sometimes this works as expected, i.e. all philosophers eat, e.g.:
Philosopher # 4 wants to eat
Philosopher # 3 wants to eat
Philosopher # 2 wants to eat
Philosopher # 1 wants to eat
Philosopher # 4 finished eating
Philosopher # 3 finished eating
Philosopher # 2 finished eating
Philosopher # 1 finished eating
Philosopher # 0 wants to eat
Philosopher # 0 finished eating

However, sometimes, one (or more) philosophers are missed (e.g. Philosopher #0, did not eat in the following case):
Philosopher # 4 wants to eat
Philosopher # 1 wants to eat
Philosopher # 3 wants to eat
Philosopher # 2 wants to eat
Philosopher # 4 finished eating
Philosopher # 0 wants to eat
Philosopher # 2 finished eating
Philosopher # 1 finished eating
Philosopher # 3 finished eating

Question is: why does this happen?
What I already know:

The program will exit if the main go routine finished (even if some other routines are still running).
A go routine will block if it tries to read from a channel, and that channel is empty (i.e. no-one wrote to it previously).

Now, main tries to read 5 times from the channel plates, therefore it should not terminate until the philos routine has run five times. But it seems it somehow still manages to terminate before doing that. Am I missing something? (It seems that plates was read only 4 times.)
EDIT: Ok, after thinking about it a bit more, I came to the conclusion, that maybe the philos routine does always run 5 times, however, it can be interrupted before having the time to print that the philosopher ate. Indeed, if I change the order as follows, it seems to be working always:
func philos(id int, left, right, plate chan bool) {
    fmt.Printf("Philosopher # %d wants to eat\n", id)
    <-left
    <-right
    left <- true
    right <- true
    fmt.Printf("Philosopher # %d finished eating\n", id)
    plate <- true
}

Still, it would be great if someone could validate this explanation :)
Comment: @downvoter: care to elaborate what is the problem with this question? Maybe I can try to improve it.
Answer: What you see in stdout isn't the same as what's happening. Sometimes, main receives from plates and then returns before the print statement happens. So:
plate <- true
left <- true    // On this line or on
right <- true   // this line, main receives from plate and then returns before
fmt.Printf("Philosopher # %d finished eating\n", id) // this line executes

Because concurrency isn't deterministic, this doesn't happen every time. Sometimes the print happens before main returns, sometimes it doesn't. That doesn't mean the channel read isn't happening.
Comment: Thanks, I just arrived to this conclusion too after looking at the code again :)
Answer: Actually, the channel is read 5 times, but since the main function is only waiting for the channel to be read for the 5th time, it exits before the philos function gets to this line:
fmt.Printf("Philosopher # %d finished eating\n", id)`

In order for it to print this correctly, you would need to run this line before you write to the plate channel.


PHP Performance wrapped if statment

Question: I saw this is a code where is loop for payment, there are 5 type of payment 1,2,3,4,5 for 3 of them is generated custom span element. My question is there any point to wrap them in one if statment and if is true only then to check other statment or it is same ?
if ($value['payment_code'] == '1' || $value['payment_code'] == '2' || $value['payment_code'] == '3') {

  if ($value['payment_code'] == '1') {
    $order_type = '  Payment - PP';
  }elseif ($value['payment_code'] == '2') {
    $order_type = '  Payment PL';
  }elseif ($value['payment_code'] == '3') {
    $order_type = '  Payment PR';
  }

}

OR
  if ($value['payment_code'] == '1') {
    $order_type = '  Payment - PP';
  }elseif ($value['payment_code'] == '2') {
    $order_type = '  Payment PL';
  }elseif ($value['payment_code'] == '3') {
    $order_type = '  Payment PR';
  }

Comment: You could in the first case factor out the boiler plate html and after all the `if/else` have something like `$order_type = '  '.$order_type.'';`
Comment: No, there is no point in wrapping it (with current code). Unless there is some code that is performed when code is one of `1`/`2`/`3`
Comment: If this is the only content in the outer `if` then I see no point in it. Only if there's something else in there which you haven't shown, then it depends on what that is
Comment: a switch case statement looks better for this one.
Answer: If anything, something like this would make sense:
$codes = ['1' => 'Payment - PP', '2' => 'Payment PL', '3' => 'Payment PR'];

if (isset($codes[$value['payment_code']])) {
    $order_type = "{$codes[$value['payment_code']]}";
}

Your first approach with the redundant if checks is certainly no improvement and only makes things even more repetitive. Performance is of extremely little concern here; worry about it when you have proven that something is a bottleneck. This kind of comparison statement will almost certainly never be a bottleneck worth worrying about.

PHP Performance wrapped if statment


A creative Eco-friendly Underlayment for a metal roof?

Question: I am building an octagonal cabin with a 200 sq ft metal roof (Grandrib 3) at a 30 degree pitch; the roof will sit on wooden strapping and will eventually have insulation below it contained by a ceiling.
It was only recently brought to my attention that because I am including insulation (type yet to be determined) I should have an underlayment - if this is indeed the case? My friend told me the cold air should flow between the roof and the underlayment, underneath the ribs essentially. This is to keep out moist air.
However, I am trying to make this cabin as eco-friendly as possible: so far I have used no plastic or asphalt materials, no plastic wrap, I expect the 100 sq ft cabin to dry out when I use its wood stove. By this I mean the underlayment would decompose over time if it got wet. So, if this cabin were left in the woods and no one tended to it eventually it would disappear. I don't necessarily need shopping guidance but maybe a creative solution with another material - can floor underlayment be used in my situation, for example? Can I combine materials in some way? I have searched for eco-friendly underlayments and they are either for floors or are not really that eco-friendly, i.e. they include plastics.
So, my question is has anyone come up with a creative solution for an eco-friendly roofing underlayment? I am not worried about water getting in from above, just moist air. I would be happy to hear about solutions that didn't require an underlayment too.
Comment: "Eco-friendly" is a vague and subjective term. Some consider long-lasting solutions eco-friendly for their small average annual footprint. Also, some plastics are plant-based. You'll have to specify your criteria, and even then we're verging on a shopping assistance question.
Comment: Plastic vapor barriers that use waste oil products keep that material from going into landfills so this is really an opinion type shopping question (wood rot is natural and you want to stop that?)
Comment: Please put all that in your question post. It doesn't belong down here.
Comment: where is the cabin?  Ecofriendly means local materials if possible.
Comment: It's in Massachusetts.
Comment: " they tend to become obsolete quickly" - that doesn't seem to be the case here, bad call on closing this question
Answer: Red Rosin Paper (which is a bit old-school, but can still be found) would fill the bill, I believe. It's plant based. Seems to be getting sold for floors now, but was the thing people used before housewrap on exterior walls under siding.
However, depending on type and installation of insulation, all you really need is an airspace between the insulation and the roof. You need a vapor barrier between the ceiling and the insulation.
Some sort of cloth could also work, just to contain the top of the insulation and maintain an airspace. Boards also work, but may cost more than you want to spend.
You will want metal screening on the vent openings to discourage rodents (and perhaps other things) from nesting in the insulation.


PKCS#11 and application identification

Question: In Cryptoki, all sessions that an application has with a token must have the same login/logout status. but how a token in a Network HSM can identify sessions related to an application? is there an application Id for this purpose? for example, by sending application id to each application after calling C_initailze and sending back id? There isn't anything about this in pkcs#11 spec. I want to implement pkcs11 for a network HSM. but i don't know how identify different applications in my cryptoki token.
Any advice will be greatly appreciated
Answer: PKCS#11 defines an API usually implemented via the dynamically linked library. In run-time (when loaded) the library becomes the part of the process and gets requests from that process. So the library knows the ID of the process that it serves. Now it's up to you how your PKCS#11 library and your hardware communicates. Possibly you can store the process ID somewhere along the data passed to and from the hardware.

PKCS#11 and application identification


Is there a way to power on remotely via SSH?

Question: I'm new to Linux and get by with a few basic commands (SSH). I run minimserver on a raspberry pi running Ubuntu server. It works great!
Every night I use sudo poweroff (using an iOS app called Terminus). I do this more because I want to preserve the mounted USB HDD that stores my music. After Ubuntu power off, the HDD also switches off automatically which is my desired result. The problem is the server is in another part of the house and the next day I have to go to the server and restart it (I unplug the power from the Rpi and plug in again). This also starts up and mounts the USB HDD (as I successfully managed to configure auto mount at start up).
What I would like to achieve is to simply unmount and switch the HDD off remotely so that the next day I can just run sudo reboot (again remotely) to get the HDD powered up and running again. I tried using umount /mnt/music but this command doesn't switch the HDD off. Or if there is a remote way to switch on the Rpi but this doesn't seem technically possible.
Any help would be greatly appreciated. Apologies for the long post. I hope I've made sense.
Answer: If there is power to the Raspberry Pi then it is on, even if you have gone to "shutdown" in the OS - at which point it merely puts the OS into a state where it is ready to be turned off.  Remember old IBM computers where you'd go to shutdown in Windows and then you'd see this?  There is no way I know of to remotely reboot the device from that state as the OS has unloaded all support for networking, etc.
HDDs can cope with running 24/7.  If you do not like the idea of running it 24/7 though, you can enable auto spindown after a delay using hdparm.  Note the warning about causing increased wear on the drive by spinning it down when it's not in use and spinning it up when it is.  At some point, spinning it down and then up against a certain number of times can be worse for it than the additional time you'd leave it spinning.
You can even manually spin down the HDD at any time with hdparm -y.  There is no need to manually spin it up then, as it will do so when something needs to read or write to it.
Caveat: support for spin down via hdparm can vary, and this is especially true for USB hard drives and enclosures.  Some support it, but there are even some USB hard drives that ignore all spin down commands and have their own in-built idle spindown.
Comment: also smartctl via smartmontools... I believe I was bitten by the same above-mentioned caveat once. If i remember correctly, you have to run it and see if the desired features are supported by your drive. `apt-get install smartmontools` and check the smartctl man pages. With that said, all of these suggestions and even the OP's goal is "considered" aggressive power management, which is thought to be worse-off for the drive.... there will likely be a sooner point of diminishing returns.
Comment: Thank you for taking the time to help me with this. I realise now my question was not really a linux question. I think I will just leave the server running with the HDD attached since they can cope with that. Thanls again
Answer: As mentioned in this answer, when the raspberry pi is off, it is not in a state to accept any instructions, so you can't use SSH to turn the device on.
One workaround for this is to connect the raspberry pi's power supply to a RF or smart outlet.
Comment: Wake-on-LAN, perhaps?
Comment: @chili555: No, Raspberry Pi doesn't support WOL.
Answer: I see two possibilities:

Wake-on-Lan: in this case, you have to configure the raspberry to accept WOL requests.  This is merely a question of BIOS. Afterwards, you have to install a specific program on the computer you use to send a so-called 'magic packet' to your Raspberry.  Watch out: both devices must be connected on the same subnetwork because the protocol is not routable.
Wake at: Use a script (eventually a cronjob) to instruct your raspberry to wake-up at a certain date/time, before turning it off.

Some details:
For WOL:
on Ubuntu, use etherwake:
sudo apt-get install etherwake

To send a magic packet:
etherwake  AA:BB:CC:DD:EE:FF

where AA:BB:CC:DD:EE:FF is the MAC adress of your raspberry. It can be obtained as:
ping -c 4 server3 && arp -n

More details here
For Scripting
First you need to go into BIOS and make sure that the computer alarm is enabled to start at a given time.  For more info, please, see e.g. this.
Afterwards, it a a mere question of scripting.  Here is the script I use:
#!/bin/bash
# This program shuts down the PC and set a start time for next wake up
# Wake up is scheduled on next weekday at 6:00

# Setting wake-up alarm
springtime="+1 days 06:00"
echo 0 > /sys/class/rtc/rtc0/wakealarm
echo `date +%s -d "$springtime"`   > /sys/class/rtc/rtc0/wakealarm

/sbin/shutdown now


Is it possible to intercept a save or load event in spring-data-elasticsearch?

Question: In spring-data-jpa, we can use JPA's annotations like @PrePersist and friends to intercept save/load events.
In spring-data-mongodb, for the same purpose we can use lifecycle events.
Is there anything similar in spring-data-elasticsearch?
Answer: At the moment there are no lifecycle hooks in spring-data-elasticsearch like they exist in spring-data-mongodb. It sure would be nice to have them.
I opened issue for this.
Edit:
As Roman wrote in his answer, this has been implemented in  version 4.0
Answer: To be honest I don't know elasticsearch but as it is Spring Data I would suggest you use an EventHandler like this:
@Component
@RepositoryEventHandler(YourDomainClass.class)
public class YourDomainClassEventHandler {

    @HandleBeforeCreate
    public void handleYourDomainClassCreate(YourDomainClass yourDomainClass) {
        //do some action
    }
}

There are also annotations like @HandleBeforeSave, @HandleAfterSave and a few more. It's part of spring-data-rest-core library.
Comment: Thank you @Mirko, but `@HandleBeforeSave` and friends are not core Spring Data annotations, they are specific to spring-data-rest, so they are not available in spring-data-elasticsearch. So we have one more example of how it can be done in other spring-data-* modules :)
Comment: @RomanPuchkovskiy Ok sorry I couldn't help. Hope someone else might know an answer to this. Good luck
Answer: EntityCallback support was implemented a few months ago, see https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#entity-callbacks
Currently, after-save, after-convert, before-convert entity callbacks are supported, both reactive and blocking.


Deleted Ubuntu folder and emptied the trash

Question: Well, that was stupid. I put in an old USB and wanted to delete all the files on it. I believed it was an old Ubuntu install USB, so without further thought I clicked on something that said Ubuntu on the left side of the File Manager, deleted all the files there and promptly emptied the trash. What could ever go wrong, right? Well, the music immediately stopped playing, alerting me to what I'd done.
I've been searching around for a guide - someone else out there must have been this exact kind of stupid before - but I can't seem to find the specific phrase that captures this tragedy. Could anyone help me out? There's a lot of music on that drive I'd love to keep.
Comment: An "*old Ubuntu install USB*," if properly made, is read-only. Files cannot be removed using that method anyway.
Answer: It seems likely that you have clicked on "Other Locations", and then selected your system partition, labelled "Ubuntu".
If that is what you did, then you have deleted your OS.
If you wish to recover your data, then boot a LiveUSB, enter the "Try Ubuntu" environment, and install Testdisk or Photorec into that Live environment to begin the process of data recovery. Data recovery can be slow and tedious. Do a bit of research on "data recovery" using those applications before starting. The entire system cannot be recovered this way.
After you have recovered your valuable data to some other media, use the LiveUSB to reinstall Ubuntu.
Comment: Thank you, that's very helpful, will do that! I can restart the computer fine, it just won't find folders like Music. Hoping that working from a LiveUSB might reduce the risk of old files getting overwritten. Will read up on Testdisk and Photorec. Thanks again, that's exactly the starter I needed.


Multi criterion search across time

Question: I'm looking for a elegant and scalable way of searching through meta informations of some entities across time.
Let's take the following meta changing over time for entity A and B
[{
    "idEntity": "A",
    "name": "Name of A",
    "rating": 0.5,
    "description": "Some short description of A",
    "createdAtWeek": 1
}, {
    "idEntity": "B",
    "name": "Name of B",
    "rating": 0.2,
    "description": "Some short description of B",
    "createdAtWeek": 1
}, {
    "idEntity": "A",
    "name": "Name of A improved",
    "rating": 0.5,
    "description": "Some longer description of A",
    "createdAtWeek": 2
}, {
    "idEntity": "A",
    "name": "Name of A improved",
    "rating": 0.6,
    "description": "Some longer description of A",
    "createdAtWeek": 3
}]

I want to be able to find entities (unique) for which the last meta matches rating >= 0.2 and that contain the word of in their description. I also want to be able to go in the past a look for these same criterion but that would need to give me different result.
The most easy way to do this through Mongo would be to make an aggregation pipeline but that's too slow if the collection is getting big.
Hence I went and duplicated all the documents so that each week (1-3) gets it's full data which allows me to include the createdAtWeek in the query straightly and be sure I have consistent results across time.
But you can see where this leads, huge duplication making the collection enormous for nothing.
Hence I tried to look at storing these documents in Solr, but when looking at the documentation there doesn't seem to be a way to first group the results by entity and date and then search within the grouping.
Is there another way to achieve the same results as the duplication without actually duplicating?
Comment: Rather than write a novel for a question, it would be better if you could show by example in **"one"** chosen technology what you actually want to achieve. Tagging to the interest of "two competing" technolgies and simply asking the "does Coke or Pepsi taste better?" question is not really useful to anyone. Way too broad and opinion based a question for here.
Comment: I thought that abstracting the question would make lot of sense in this case rather than obtaining an answer that would be too focus on one technology. But I'm going to rephrase it as you seem to have some experience here.
Answer: Solr Block Join Query Parser can handle this kind of operations.
The data structure is changed toward a hierarchical system and the createdAtWeek is replaced with validSince_i and validUntil_i.
/* Entity A */
{
  "path_s": "1.entity",
  "id": "A",
  "_childDocuments_": [
    {
      "path_s": "2.metadata.rating",
      "id": "2.metadata.rating.1",
      "_childDocuments_": [
        {
          "path_s": "3.metadata.rating.timeValidity",
          "id": "2.metadata.rating.timeValidity.1",
          "validSince_i": -1,
          "validUntil_i": 2,
          "value_f": 0.5
        },
        {
          "path_s": "3.metadata.rating.timeValidity",
          "id": "2.metadata.rating.timeValidity.2",
          "validSince_i": 3,
          "validUntil_i": 9999999,
          "value_f": 0.6
        }
      ]
    },
    {
      "path_s": "2.metadata.description",
      "id": "2.metadata.description.1",
      "_childDocuments_": [
        {
          "path_s": "3.metadata.description.timeValidity",
          "id": "2.metadata.description.timeValidity.1",
          "validSince_i": -1,
          "validUntil_i": 1,
          "value_txt_en": "Some short description of A"
        },
        {
          "path_s": "3.metadata.description.timeValidity",
          "id": "2.metadata.description.timeValidity.2",
          "validSince_i": 2,
          "validUntil_i": 9999999,
          "value_txt_en": "Some longer description of A"
        }
      ]
    }
  ]
}
/* Entity B */
{
  "path_s": "1.entity",
  "id": "B",
  "_childDocuments_": [
    {
      "path_s": "2.metadata.rating",
      "id": "2.metadata.rating.2",
      "_childDocuments_": [
        {
          "path_s": "3.metadata.rating.timeValidity",
          "id": "2.metadata.rating.timeValidity.3",
          "validSince_i": -1,
          "validUntil_i": 9999999,
          "value_f": 0.2
        }
      ]
    }
  ]
}

BlockJoin can now be leveraged with faceting as long as the timeValidities are not overlapping each other like so:
fq={!parent which="path_s:1.entity"}(path_s:3.metadata.rating.timeValidity AND validUntil_i:[2 TO *] AND value_f:[0.3 TO *])&fq={!parent which="path_s:1.entity"}(path_s:3.metadata.description.timeValidity AND validUntil_i:[2 TO *] AND value_txt_en:short)&q=*:*

Which returns no entities as there are no entities later than week 2 that have a rating >= 0.3 with a description containing short
Running the following works fine too
fq={!parent which="path_s:1.entity"}(path_s:3.metadata.rating.timeValidity AND validUntil_i:[2 TO *] AND value_f:[0.3 TO *])&fq={!parent which="path_s:1.entity"}(path_s:3.metadata.description.timeValidity AND validUntil_i:[2 TO *] AND value_txt_en:longer)&q=*:*

As you can see entity A shows up as its rating is >= 0.3 after week >= 2 with the description containing longer.
Performance aspect needs to be asserted but it does the job and avoids duplicates.

Multi criterion search across time


jQuery reference to (this) does not work?

Question: I have this href link with text either "attivo" or "non attivo"
User can set the item to 'active' or 'closed' in the database with an ajax request $.post()
I have 2 questions for these:

I can't get the reference to $(this) to work.. I tried it with a normal link and it works, but not wrapped in if/else??
How can I prevent the user from clicking more than one time on the link and submitting several request? Is this a valid concern? Do I need some sort of a small timer or something?
First I was thinking about a javascript confirm message, but that's pretty annoying for this function..

HTML:

some title

    some description

status: non attivo

test

JS:
        $('dd a.toggle-active').click(function() {
            var a_ref = $(this);
            var id = a_ref.parent().parent().attr('id').substring(3);
            if (a_ref.text() == "non attivo") {
                var new_active = "active"; // for db in english
                $.post("ajax-aa.php", {album_id:id, album_active:new_active},
                function(data) {
                    // alert("success");
                    a_ref.text("non attivo"); // change href text
                });
            } else {
                var new_active = "closed"; // for db in english
                $.post("ajax-aa.php", {album_id:id, album_active:new_active},
                function(data) {
                    // alert("success");
                    a_ref.text("attivo"); // change href text
                });
            }
            return false;
        });

        $('a.test').click(function() {
            var a_ref = $(this);
            $.post("ajax-aa.php", {album_id:2, album_active:"active"},
            function(data) {
                a_ref.text("changed");
            });
            return false;
        })

Comment: Insert `console.log(this)` in some places in your code, and look at the console in Firebug, then you will understand what `this` is pointing to at each point.
Comment: Is there any chance that your Ajax request is failing? The callback function is run when the request is successful.
Comment: it was working fine, after the successfull ajaxcall I set my text back to what it already was.. grr. Thanks for the tip about console and Firebug!
Answer: $(this) should refer to your a element inside the if/else, but not inside the callback function. The callback function is run in a different context, so inside the callback function
    function(date) { }

this does not refer to the a element. this inside the callback function is not the same as this outside the callback function.
Because the callback function is a closure though, it will keep a reference to your local variable a_ref.
To prevent the user from clicking twice, add a class to the element
  $(this).addClass("hasbeenclicked")

and in the click handler check whether this has been set and not do anything when it has:
  if ( ! $(this).is(".hasbeenclicked") ) {
  ....
  }

Comment: ok understand for this inside the callback fnc, but why does it work in the test link example than?
Comment: because in the callback function for click this does refer to the element that was clicked on
Comment: ok, cheers. How can I reference the href without using the $('dd a.toggle-active') selector than?
Comment: I don't think you need to change anything - what your are doing is what I would do: select it using the selector first, then store it in a local variable that you reference from further callback functions.
Comment: I agree the code should work. You are doing it right. The callback function is executed when the Ajax request is successful. You might be failing if the code doesn't work. Your usage of `a_ref` is correct.
Comment: I see the error!! everything worked fine.. I only changed the text "non attivo" to "non attivo" etc. That's why I thought it didn't work..
Comment: sorry where and when do I add the class and check if it is clicked?
Answer: The easiest way to stop the user clicking the link multiple times, will be to add a class or something to the link when the user clicks it.
a_ref.addClass('in-progress');

and then remove the class when the AJAX request has completed.
a_ref.removeClass('in-progress');

When the user first clicks the link, check to see whether a request is in progress;
if (a_ref.hasClass('in-progress')) {
    return'
};

Edit: A more detailed example:
$('a.test').click(function() {
    var a_ref = $(this);

    if (a_ref.hasClass('in-progress')) {
        return false;
    } else {
        a_ref.addClass('in-progress');
    }

    $.post("ajax-aa.php", {album_id:2, album_active:"active"},
    function(data) {
        a_ref.text("changed").removeClass('in-progress');
    });

    return false;
})

Comment: I am having trouble figuring out how to use this.. Can you tell me where exactly I add the class and where to check for the class? return will prevent further execution of the click functions?
Comment: See my edit. The return will prevent that single click making a request; and will keep preventing the requests as long as the current request is in progress. If you want to stop the AJAX request ever happening, do `a_ref.unbind('click');` in the callback of the AJAX request.


How do you say "no" if you don't want to continue co-op in freeplay?

Question: I played co-op a few times. There is an option if you want to continue playing in free play mode as well. I can see a "Yes" button but there is no "no". How do reject the offer?
Comment: Reject kinda seems harsh :)
Answer: You don't technically say "No". You can just go back to the main menu and start another game.
There is no option to start a new map or anything either. You would have to create a separate new game.


array_walk only partially removes matches

Question: Ran into a weird situation were using array_walk() will only partially remove matches from my method, not certain exactly what is going on. I am currently using PHP v5.6.4. The issue almost seems to be that it is only removing every secondary match.
The kerning function
private function strip(array $exceptions)
{
    array_walk($this->hosts, function($v, $k) USE ($exceptions)
    {
        foreach ($exceptions AS $exception)
        {
            if (preg_match("/{$exception}/i", strtolower($k)))
            {
                unset($this->hosts[$k]); break;
            }
        }
    });
    print_r($this->hosts); die;
}

Comment: Why not use array_filter() instead?
Comment: array_filter() is fine as well, this was just the way I knew how to do it.
Answer: Quoting from the PHP docs

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

my emphasis
Comment: Well with array_filter() you shouldn't be unsetting within the closure, simply returning a boolean true/false to indicate whether the record should be unset or not
Comment: Agreed, the array_filter implementation doesn't seem to work much better though http://pastebin.com/iztTJpjT
Comment: Awesome, worked amazingly, +1 and accepted. Will also publish code to show anyone else searching for this the answer.
Answer: This worked in conjunction with the information provided by Mark Baker, thanks Mark.
private function strip(array $exceptions)
{
    $this->hosts = array_filter($this->hosts, function ($k) USE ($exceptions)
    {
        foreach ($exceptions AS $exception)
        {
            if (preg_match("/{$exception}/i", strtolower($k)))

                return false;
        }
        return true;
    }, ARRAY_FILTER_USE_KEY);

    return $this;
}


Is the series $\sum_{n=1}^\infty\frac{n^n}{n!e^n}$ divergent?

Question: How I can show that the following series is divergent $$\sum_{n=1}^\infty\frac{n^n}{n!e^n}?$$
thank in advance.
Comment: Stirling's formula.
Answer: Following Stirling, $$ n!\approx n^ne^{-n}\sqrt{2\pi n}$$
hence your series is comparable to $\sum\frac1{\sqrt n}$, which is divergent.

Without Stirling available, we consider
$$e^n=\sum_{k=0}^\infty\underbrace{\frac{n^k}{k!}}_{=:a_k}$$
(where all summands are positive). For $k\ge n$, we have
$ \frac{a_{k+1}}{a_k}=\frac{n}{k+1}\le \frac n{n+1}=:q$. As $q<1$, we can estimate the tail of the series by a geometric series:
$$\sum_{k=n}^\infty a_n\le a_n\cdot\left(1+q+q^2+q^3+\ldots \right)=a_n\cdot\frac1{1-q}=(n+1)a_n.$$
On the other hand, for $k<n$ we have $\frac{a_{k+1}}{a_k}=\frac{n}{k+1}\ge1$, so that
$$\begin{align}e_n&=\sum_{k=0}^{n-1}a_k+\sum_{k=n}^\infty a_k\\&\le na_n+(n+1)a_n \end{align}$$
We conclude
$$\frac{n^n}{n!e^n} =\frac{a_n}{e^n}\ge \frac1{2n+1}$$
and hence
$\sum_{n=0}^\infty\frac{n^n}{n!e^n}$ is divergent by comparison with the harmonic series.
Comment: Nice approach; I would have expected this to be too blunt, but it just barely isn't.


Where is Steady Hand McDuff?

Question: I can't find Steady Hand McDuff. I have not looked in Iron Keep because I don't know where it is ether.
Can you help?
Answer: He is in Lost Bastille. Not so far from entrance via flying bird - there are several dogs and barrel near stairs in that area.

 You can either found Bastille Key to open the door or push the barrel down the stairs and then detonate it (via torch or firebomb or flame enchanted weapon).

See also this wiki page.

Where is Steady Hand McDuff?


How to create a Custom GUI?

Question: I am creating a Minecraft vanilla mini games server and I want to create a custom GUI, but as far as I know there is no way to do this without a Bukkit server. I want to make it so it will /testfor a compass in a player's hand. When the player has a compass, it will /summon a donkey without a saddle, and with a chest on the player's head. When the player left clicks with the compass, it will open the donkey's chest GUI. Then, I want to make it so there is already items in the chest, but an unsure how.
Comment: Have you made any attempt to solve this yourself? Arqade works better when askers show effort to solve their own problems; we see that you have a problem you've worked on, and answerers respond to that. You also get a more specific answer that's tailored exactly to the part you're stuck, and Arqade gets a very specific question. Everybody wins!
Comment: I tried doing it on my own and than looking it up but i found no answer to my problem
Answer: Use /replaceitem. It will allow you to set items in the donkey's chest. Then, give each item a custom name. testfor it being in a player's inventory, then perform the necessary action

How to create a Custom GUI?


cannot convert MethodHandle(Dates)JodaCompatibleZonedDateTime to (Object)double

Question: I am trying to add conditions if field exist, then sort according to it otherwise use another field. Since one of either will exist.
Here is my query:
GET /my_index/_search
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "type":"number",
      "script": "if(doc['contextDates.event.date'].value != 0){ return doc['contextDates.event.date'].value} else { return doc['contextDates.start.date'].value}",
    "order": "asc"
    }
  }
}

When I execute this query, I get following error:
"failed_shards" : [
      {
        "shard" : 0,
        "index" : "my_inedx",
        "node" : "UxKwS8SIR-uIbzo5_0IbcQ",
        "reason" : {
          "type" : "script_exception",
          "reason" : "runtime error",
          "script_stack" : [
            "return doc['contextDates.event.date'].value} else { ",
            "                                     ^---- HERE"
          ],
          "script" : "if(doc['contextDates.event.date'].value != 0){ return doc['contextDates.event.date'].value} else { return doc['contextDates.start.date'].value}",
          "lang" : "painless",
          "position" : {
            "offset" : 84,
            "start" : 47,
            "end" : 99
          },
          "caused_by" : {
            "type" : "wrong_method_type_exception",
            "reason" : "cannot convert MethodHandle(Dates)JodaCompatibleZonedDateTime to (Object)double"
          }
        }
      }
    ]

I have tried Double.parseDouble method as well but it doesn't work. This is what I have inside document for contextDates
"contextDates" : {
        "event" : {
         "date" : "2020-06-26T00:00:00.000Z",
         "resolution" : "day",
         "score" : 0,
         "type" : "event"
       }
     }

Answer: The doc value you're getting is of type JodaCompatibleZonedDateTime which you're trying to compare to a double value, so you need to modify your script like this
if(doc['contextDates.event.date'].value.getMillis() != 0){ return doc['contextDates.event.date'].value.getMillis()} else { return doc['contextDates.start.date'].value.getMillis()}


Ubuntu fails to install on HP zbook 15 G2

Question: This is after 4 days of hell, trying to find a solution for a thing that I anticipated would take 30 minutes. Kindly help me.
I have a project on ROS (robot operating system). ROS works only with trusty Ubuntu, and its indigo version is best suitable for Ubuntu 14.04. I have a HP zbook 15 G2 with core i7, 64 bit, 512GB SSD and 16 GB RAM. It had windows 7 pre-installed.
I tried to first do a dual boot with Ubuntu 14 64 bit amd, but I got an error that ext4 cant be mounted.Then it gave an fsyncing error.
I then tried to run as VM in windows 7. That gave issues too.
Upon contact with my IT team at work, they told me that UEFI could be causing the problem. I decided to start from the scratch and get ubuntu installed on a clean PC
Therefore I formatted everything. I tried to install Ubuntu 14 and ubsequently Ubuntu 16. Both failed. The file system ext4, 3, 2 all fail to mount. Then they give the fsyncing error.
I started googling about the problem. Someone suggested, that I should try another distribution of Ubuntu. So I went for Ubuntu mate and it installed seamlessly. Later on Windows 7 installed seamlessly too. My hard disk has no errors. But sadly both of the above dont support ROS.
So I am back to zero. I have tried everything I could to run ubuntu 14 or 16 on this PC. The ubuntu website says that this computer model has even an option of pre-installed ubuntu. Someone in my IT team, emailed me that he was able to install ubuntu 14 on the same model of the PC without a problem.
Can someone help me in perhaps identifying a ubuntu version that can be installed on this PC. I have seen some posts of guys with the same computer model having issues that I am having right now. None of them were solved. I would highly appreciate any help.
Comment: Why isn't MATE compatible? Did you actually try it? It's just Ubuntu with a different skin.
Comment: Oh. You need to try installing 14.04 then. ROS won't work even if you get normal 16.04 installed.
Comment: This is very strange for me as well. As MATE is just a different skin. However, no package of ROS is found when I try to install it. Here is something from the ROS wiki.

"Setup your computer to accept software from packages.ros.org. ROS Indigo ONLY supports Saucy (13.10) and Trusty (14.04) for debian packages. "
Comment: That is what I am trying to do for the last four days but I have never encountered a PC so powerful that can do so less. I spent a big buck on getting my hands on something with so much power. And I am surprised that installing ubuntu has taken me so much time.

There is a ROS version for ubuntu 16. I am thinking of installing ubuntu mate 16 and see if the new version works with Mate. Is the mate not just a skin for trusty dist?
Comment: MATE is a different flavor of Ubuntu. It's just a DE and a few packages and themes.
Comment: Can we say that mate is just a skin for Ubuntu 14.04 "Trusty" LTS. Since ROS indigo is supported only for TRUSTY.

And lasty, why the hell is this machine not installing ubuntu 14.04 when it says on their website that if requested it ships with ubuntu pre-installed?
Comment: Trusty is the codename for Ubuntu 14.04. 14.04 == Trusty. 14.04 can be running Unity, MATE, XFCE, LXDE, etc. Trusty isn't a version of 14.04, it is 14.04, just like 12.04 is Precise, and 16.04 is Xenial.
Comment: @ViperMaverick MATE is just example of desktop environment aka graphic shell. The reality is that any OS has text console ( even Windows ).
Comment: @ViperMaverick We need the exact `fsync` error to help.
Comment: Thank you Zacharee, this is useful information. Kaz here is the error tree
It start with ext4 file system failed to mount. This happens even if you create a new partition tree or try to install on the existing one. Then it asks if you want to continue, which after a long try by installer lead to.
Error fsyncing/closing/dev/sda1: Input/Output error.
multiple try again options lead to nothing. pressing ignore many times lead to:
Input/output error during read on /dev/sda
Answer: It appears that packages.ros.org covers all currently supported Ubuntu Operating systems. You should be able to install the appropriate version of these packages on virtually any flavor of currently supported Ubuntu you desire. You don't mention any details, but I would not be surprised to discover that your installations that failed were due to a corrupt ISO. I base this theory on the fact that you were able to successfully install Mate (which would indicate hardware is unlikely to be the issue)


How to update mysql data with event and remove the event after

Question: I have a mysql table that looks like this
| begintime  | endtime  | begindate  | enddate  | state |
+------------+----------+------------+----------+-------+
|  TIME      | TIME     |    DATE    |   DATE   | string|
+------------+----------+------------+----------+-------+

I have this code
CREATE EVENT Update
ON SCHEDULE
  EVERY 1 SECOND
DO
  UPDATE tablename SET tablename.state = CASE
   WHEN (SELECT CURRENT_TIME() FROM DUAL)>=tablename.begintime AND (SELECT CURDATE()>= tablename.begindate) THEN "Available"
   WHEN (SELECT CURRENT_TIME() FROM DUAL)>tablename.endtime AND (SELECT CURDATE()= tablename.enddate) THEN "Finished"
   ELSE "Not Available"
   END

I want the server to be always checking if any of those statements is true, and I dont know how to remove the event when:
WHEN (SELECT CURRENT_TIME() FROM DUAL)>tablename.endtime AND (SELECT CURDATE()= tablename.enddate) THEN "Finished

Thanks for your help.
Answer: please try this one.
SET GLOBAL event_scheduler = ON;
DROP EVENT IF EXISTS Update1;
CREATE EVENT Update1
ON SCHEDULE
  EVERY 1 SECOND
DO
  UPDATE tablename SET tablename.state =
  CASE
   WHEN NOW() BETWEEN CONCAT(tablename.begindate,' ',tablename.begintime) AND CONCAT(tablename.enddate,' ',tablename.endtime) THEN "Available"
   WHEN NOW() > CONCAT(tablename.enddate,' ',tablename.endtime) THEN "Finished"
   ELSE "Not Available"
  END;

To drop the event after setting to "Finished" try using something like this
SET GLOBAL event_scheduler = ON;
DROP EVENT IF EXISTS Update1;
DELIMITER //
CREATE EVENT Update1
ON SCHEDULE
  EVERY 1 SECOND
DO BEGIN
    SELECT @begindate := begindate,
           @begintime:= begintime,
           @enddate := enddate,
           @endtime := endtime FROM tablename;
    IF (NOW() BETWEEN CONCAT(@begindate,' ',@begintime) AND CONCAT(@enddate,' ',@endtime)) THEN
        UPDATE tablename SET state = 'Available';
    ELSEIF (NOW() < CONCAT(@begindate,' ',@begintime)) THEN
        UPDATE tablename SET state = 'Not Available';
    ELSEIF (NOW() > CONCAT(@enddate,' ',@endtime)) THEN
        UPDATE tablename SET state = 'Finished';
        DROP EVENT IF EXISTS Update1;
    END IF;
END//
DELIMITER ;


ffmpeg fix video orientation

Question: A video can contain a meta info about the camera orientation. For example iPhone and other phones set this flag if you turn the device. Problem is while some player read this info and rotate the video accordingly, other players do not.
To fix this the video has to be rotated and the meta info needs to be set correctly.
Does ffmpeg provide a fix for this or do I have to go the hard way (Read rotation, rotate, set meta data)
Answer: I did go the hard way:
<code>$ffmpeg == "path/to/ffmpeg";
$output_file_full = "file/after/normal/conversion";

// get rotation of the video
ob_start();
passthru($ffmpeg . " -i " . $output_file_full . " 2>&1");
$duration_output = ob_get_contents();
ob_end_clean();

// rotate?
if (preg_match('/rotate *: (.*?)\n/', $duration_output, $matches))
{
    $rotation = $matches[1];
    if ($rotation == "90")
    {
        echo shell_exec($ffmpeg . ' -i ' . $output_file_full . ' -metadata:s:v:0 rotate=0 -vf "transpose=1" ' . $output_file_full . ".rot.mp4 2>&1") . "\n";
        echo shell_exec("mv $output_file_full.rot.mp4 $output_file_full") . "\n";
    }
    else if ($rotation == "180")
    {
        echo shell_exec($ffmpeg . ' -i ' . $output_file_full . ' -metadata:s:v:0 rotate=0 -vf "transpose=1,transpose=1" ' . $output_file_full . ".rot.mp4 2>&1") . "\n";
        echo shell_exec("mv $output_file_full.rot.mp4 $output_file_full") . "\n";
    }
    else if ($rotation == "270")
    {
        echo shell_exec($ffmpeg . ' -i ' . $output_file_full . ' -metadata:s:v:0 rotate=0 -vf "transpose=2" ' . $output_file_full . ".rot.mp4 2>&1") . "\n";
        echo shell_exec("mv $output_file_full.rot.mp4 $output_file_full") . "\n";
    }
}
</code>
I used some ugly temp files. Sorry about that.
Comment: eeeeshhhh this sure is hacky.  Consider the following instead to get the meta data as json:  ffprobe -of json  -show_streams your_video.file  2>/dev/null
Comment: I know I'm coming very late, but instead of rotating it twice, you might as well "transpose=2,transpose=2"
Comment: @ZioCain Do you mean $rotation == "180"? Maybe like this: `echo shell_exec($ffmpeg . ' -i ' . $output_file_full . ' -metadata:s:v:0 rotate=0 -vf "transpose=1,transpose=1" ' . $output_file_full . ".rot.mp4 2>&1") . "\n";` ?
Comment: @PiTheNumber The `ffmpeg` output is not meant to be machine parsed. Use [`ffprobe` instead to get the rotation](https://stackoverflow.com/a/41306388/) (and it will simplify your code).
Comment: @PiTheNumber yeah, that's what I actually meant! thank you for providing again the full working code!

ffmpeg fix video orientation


Python: Calculate 5-year rolling CAGR of values that need to be grouped from a dataframe

Question: I have a dataframe with historical market caps for which I need to compute their 5-year compound annual growth rates (CAGRs). However, the dataframe has hundreds of companies with 20 years of values each, so I need to be able to isolate each company's data to compute their CAGRs. How do I go about doing this?
The function to calculate a CAGR is: (end/start)^(1/# years)-1. I have never used .groupby() or .apply(), so I don't know how to implement the CAGR equation for rolling values.
Here is a screenshot of part of the dataframe so you have a visual representation of what I am trying to use:
Screeshot of dataframe.
Any guidance would be greatly appreciated!
Comment: I'm assuming there is 1 value per company per year? Is it safe to reduce date to only year?
Answer: Assuming there is 1 value per company per year. You can reduce the date to year. This is a lot simpler. No need for groupby or apply.
Say your dataframe is name df. First, reduce date to year:
df['year'] = df['Date'].dt.year

Second, add year+5
df['year+5'] = df['year'] + 5

Third, merge the 'df' with itself:
df_new = pandas.merge(df, df, how='inner', left_on=['Instrument', 'year'], right_on=['Instrument','year+5'], suffixes=['_start', '_end'])

Finally, calculate rolling CAGR
df_new['CAGR'] = (df_new['Company Market Cap_end']/df_new['Company Market Cap_start'])**(0.2)-1

Answer: Setting up a toy example:
import numpy as np
import pandas as pd

idx_level_0 = np.repeat(["company1", "company2", "company3"], 5)
idx_level_1 = np.tile([2015, 2016, 2017, 2018, 2019], 3)
values = np.random.randint(low=1, high=100, size=15)

df = pd.DataFrame({"values": values}, index=[idx_level_0, idx_level_1])
df.index.names = ["company", "year"]
print(df)

               values
company  year
company1 2015      19
         2016      61
         2017      87
         2018      55
         2019      46
company2 2015       1
         2016      68
         2017      50
         2018      93
         2019      84
company3 2015      11
         2016      84
         2017      54
         2018      21
         2019      55

I suggest to use groupby to group by individual companies. You then could apply your computation via a lambda function. The result is basically a one-liner.
# actual computation for a two-year period
cagr_period = 2
df["cagr"] = df.groupby("company").apply(lambda x, period: ((x.pct_change(period) + 1) ** (1/period)) - 1, cagr_period)
print(df)

               values      cagr
company  year
company1 2015      19       NaN
         2016      61       NaN
         2017      87  1.139848
         2018      55 -0.050453
         2019      46 -0.272858
company2 2015       1       NaN
         2016      68       NaN
         2017      50  6.071068
         2018      93  0.169464
         2019      84  0.296148
company3 2015      11       NaN
         2016      84       NaN
         2017      54  1.215647
         2018      21 -0.500000
         2019      55  0.009217