How to prevent squirrels from using electric wire as a runway

Question: Does anyone know of a way to prevent squirrels from running on electric wires?
Squirrels are using the electric wire that brings electric into our home as a runway.  I see them running both directions, both to our house and to the electric pole.
At least so far, I do not see them gaining access to the interior of my home.   However, I don't want to wait until that happens to address the problem.
The electric comes into our home about 2' below the roofline and about 10' above the ground.   We have metal siding and a metal roof.   I have seen them getting to the wire by climbing the electric pole (not on our property).  Once they get about a foot from where the electric comes into the house, they jump onto our roof.  I have walked the roof and cannot figure out why our roof would interest them.   Obviously, we don't throw food up there.  I cannot find any nest or damage caused by the squirrels.
Comment: With squirrels about the only proven way is have the wires removed.
Comment: @crip659 go off grid to avoid wildlife? How ironic!
Comment: They make their way onto your roof because their instinct is to explore. My yard is full of mature oaks and they use our roof as the runway. They're across it every day, and I've never had damage beyond some nibbling on plastic rain gutter mesh. I wouldn't make it a problem until it's a problem.
Comment: Are the squirrels causing problems? What are you doing to keep birds off your roof? How about spiders, ants, dragon flies, moths, etc.? Your house exists in nature and until nature invades the house, I don't see a problem. Now, I had a momma racoon climb our tree, cross to the roof and go down the unused chimney to give birth. Listening to all the scratching in the chimney kept us awake at night. I chased them out with a chimney sweep brush, and once we had a couple of nights with no noise, I went back to the roof & capped the chimney, but I was solving a known problem, not a potential one.
Comment: It's that sort of proactive interference with nature that has us where we are today, with a sterilized ecosystem and a shredded climate. Well, that and plain apathy. Our comeuppance is due. Yes, even squirrels are part of the equation. You likely have Cooper's hawks and owls in your neighborhood, too, which depend on the squirrels. Everything's connected. Our survival depends on theirs.
Comment: Can see this and then learn to love squirrels.  https://www.youtube.com/watch?v=DTvS9lvRxZ8
Comment: If squirrels are recognised as vermin where you live, get the exterminator. Slotted plastic wastepipe, 5-6' long, smeared with something unsavoury, slid along the wire, taped so it won't slip off?
Comment: Never underestimate a squirrel...especially red squirrels.  I had one chew through my screen and enter the home, even with a dog barking at it the whole time it was chewing just 10 feet away.  This was 5am...by the time I got up to see what the dog was barking at it was already inside.
Comment: Be glad they are not using the feeder for lunch!
Comment: Have the tower tell them to go around?
Comment: Remove the insulation?
Answer: That wire belongs to the power company. And you can't put anything there without their permission.
That said, the key to preventing squirrel home invasions is not the power company line.  That is positively in their territory. You can and should expect their activity there.  If your weatherhead is terminated properly, this will only give them access to your roof (also their territory).
The key is to maintain the integrity of your home's walls.  Don't be sloppy. Secure openings.  Put filler in the hole for the A/C line-sets. Put gratings across the vents for bathroom, range hood and dryer, soffit vents, etc. . If you're not interested or able to do this type of home-crafting, bring in a handyman who can.
You really need to do this.  If squirrels can get in, then so can much worse vermin, like rats or birds.  Ever hear of the squirrel flu?  Nope.
Answer: There are many types of animal baffles that can prevent this like the one shown below. You would need the plastic/PVC version and install it where the power company wires attach to your wires. Check with your power company since many will install them at your house or at the pole.

Here's one very similar to the ones we installed, not affiliated in any way
https://www.critterguard.org/products/line-guard
Comment: That particular baffle is 16 inch diameter.  It forms a cone and is meant to be installed on a pole to prevent squirrels from approaching from above or underneath.   On a horizontal wire it would present only an 8 inch obstruction.  Determined squirrels would  jump over it! Although, if the roof is not a good food source they may not be that determined.    It also has to be held in place, and comes with metal hardware.  Not sure how I would safely mount it on a high voltage wire.
Comment: @jay613 I didn't personally, I sent crews out to do it.  The baffles had a rubber sleeve that fit over the cable and the baffle fit over that... a pretty snug fit.
Comment: As it turns out, your comment was the solution.   I called the electric company (First Energy), and they put an orange ball - about the size of a basketball, on the wire leading to my home.   They also surrounded the base of the pole they were climbing with a skirt to make climbing the pole just about impossible.  Now, if they get past the skirt (so far, they have not), the round ball stops them.   Turns out that squirrels cause most power outages, so the company is very quick to respond to nuisance squirrel complaints.  They actually found & removed a squirrel's nest on the pole.
Comment: @jay613 If it's fitted over the wires and attached together, the metal hardware wouldn't be needed... That's all we did with the ones at the power company.
Comment: You installed these professionally?  That is pretty cool.  If they are not attached to the wire, couldn't the animal just push them along towards the house then jump over?  Or the wind could blow them towards the pole where the animal could easily bypass them?
Comment: today it would, in a year perhaps not.
Comment: The product aimed at utilities is very nice.  Well designed and robust. For homeowner use, a little on the expensive side but it's a great product for OP's specific situation.   For use on other than high voltage lines I'd say it's just very expensive coke bottles. :)
Comment: That company's "pole guard" is a nice telephone-pole adaptation of the simple conical baffle which works well on bird feeder poles.
Comment: It never occurred to me that I could call the power company to ask them to put up a squirrel guard.   I will do so on Monday.   Thank you for the suggestion.
Answer: some sort of rat guard perhaps
Answer: Relocate the squirrels.
I had a problem with red squirrels chewing through the trash can outside, and eventually chewed through my screen and entered the house.  I trapped them with a small animal trap, and would release them in a wooded area somewhere between home and work which was 40 miles away.  I caught 4 and they never came back after relocating them.  I also caught a skunk, which wasn't as bad as it sounds.  A few people walked past it without even noticing it was there, it looked like it was sleeping when I opened the trap.
Answer:
I don't know if or how you could safely do this on a high voltage wire but the best way to keep squirrels from passing a horizontal wire is a string of 2 liter drink bottles drilled through the top and bottom.  You need at least 5 or 6 of them or squirrels can just jump over.  They don't need to be held in place.  They drift towards the sagging part of the wire and they stay together there.  Squirrels try to jump over but when they land on the bottles the bottles flip over and there's nowhere for the squirrels to grip.
Sometimes a squirrel can get a grip on the wire between bottles.  You can prevent that by cutting off the bottoms of all the intermediate bottles so they ride over the conical part of the next bottle, and tape or staple them in place that way.
Again, I've never seen this done on high voltage wires and I cannot imagine how I would go about that myself.
I think the baffle idea from @JACK is more promising but for horizontal use I think you'd need to find one that is bigger than 8 inches in radius, it doesn't need to be conical, and you'd need to figure out a safe way to clamp them to the live wires, probably not with sharp metal hardware.
EDIT: the issue of safe installation of bottles is addressed by the fit-for-purpose product in the other answer.  That product combines baffles and rollers that are assembled over existing wires and that product is more robust than drink bottles, hopefully will last longer.
Comment: if search "rat guard" you will see similar products  but the rollers are split and clip over the wire,
Comment: I haven't seen those before.  Nice.  I think the way they use built-in plastic compression fittings to attach to the wire is clever and probably is a good way to attach to power lines.   I'm still not convinced that a determined squirrel would be deterred by these.  They are 15 to 17 inches.  Easy for a squirrel to jump over an 8 inch radius.  Also if clamped firmly to a high tension overhead cable, the squirrel could probably jump ONTO the top of it and have enough stability to then proceed happily onwards.   My quick search of youtube for any proof of this found nothing.
Comment: Also those rat guards are expensive.   If they work, great solution for putting just one on your incoming power lines.   My own interest is keeping them away from bird feeders, so I'm looking to make something similar from thin plexiglass for much less $.


Can't Json parse Array BACK after Json stringify it to cookie

Question: When i save json to the cookie i can't parse it back :(
var checkoutArray = [{"id":"1021397549","prod-name":"2015 новый шик! горячая распродажа бесплатная доставка сексуальные женщины красочные птицы шифон рубашка форме крыла летучей мыши широкий блузки свободного покроя топы","cost":134,"sku":"14:200001438#8;5:361385","pcs":"1","ship-num":"2","ship-name":"e-EMS","ship-cost":796,"img":"http:\/\/i01.i.aliimg.com\/wsphoto\/v15\/1021397549_1\/2015-новый-шик-горячая-распродажа-бесплатная-доставка-сексуальные-женщины-красочные-птицы-шифон-рубашка-форме-крыла-летучей.jpg","aviable":"990","sku-html":"<img class=\"color\" height=\"26\" width=\"26\" src=\"http:\/\/i01.i.aliimg.com\/wsphoto\/sku\/v12\/1021397549\/1021397549_200001438\/Хаки-2015-новый-шик-горячая-распродажа-бесплатная-доставка-сексуальные-женщины-красочные-птицы-шифон-рубашка-форме-крыла-летучей.jpg_50x50.jpg\" title=\"8\" bigpic=\"http:\/\/i01.i.aliimg.com\/wsphoto\/sku\/v12\/1021397549\/1021397549_200001438\/Хаки-2015-новый-шик-горячая-распродажа-бесплатная-доставка-сексуальные-женщины-красочные-птицы-шифон-рубашка-форме-крыла-летучей.jpg\"\/>L<\/span>"},{"id":"2028047220","prod-name":"2015 новый шик! горячая распродажа бесплатная доставка сексуальные женщины красочные птицы шифон рубашка форме крыла летучей мыши широкий блузки свободного покроя топы 14003","cost":135,"sku":"","pcs":"2","ship-num":"2","ship-name":"China Post Registered Air Mail","ship-cost":110,"img":"http:\/\/i00.i.aliimg.com\/wsphoto\/v0\/2028047220_1\/2015-новый-шик-горячая-распродажа-бесплатная-доставка-сексуальные-женщины-красочные-птицы-шифон-рубашка-форме-крыла-летучей.jpg","aviable":"998","sku-html":""},{"id":"802048809","prod-name":"Дизайнер искусственного из двух частей кружева шифон блузка рубашка с кардиган для женщин 2015 весна мода дамы свободного покроя топы","cost":582,"sku":"","pcs":"1","ship-num":"3","ship-name":"Fedex IE","ship-cost":3865,"img":"http:\/\/i01.i.aliimg.com\/wsphoto\/v0\/802048809\/Дизайнер-искусственного-из-двух-частей-кружева-шифон-блузка-рубашка-с-кардиган-для-женщин-2015-весна-мода.jpg","aviable":"918","sku-html":""}];

$.cookie("wishlist", JSON.stringify(checkoutArray));
console.log( $.cookie("wishlist") );
var checkoutArray = JSON.parse($.cookie("wishlist"));

var checkoutArray = JSON.parse($.cookie("wishlist"));
jQuery.each(checkoutArray, function (i, wishlistID) {
checkoutArrayDom += '
'+ wishlistID + '
';
});

In Chrome console i get this

"[{\"id\":\"1021397549\",\"prod-name\":\"2015 новый шик! горячая
  распродажа бесплатная доставка сексуальные женщины красочные птицы
  шифон рубашка форме крыла летучей мыши широкий блузки свободного
  покроя
  топы\",\"cost\":134,\"sku\":\"14:200001438#8;5:361385\",\"pcs\":\"1\",\"ship-num\":\"2\",\"ship-name\":\"e-EMS\",\"ship-cost\":796,\"img\":\"http://i01.i.aliimg.com/wsphoto/v15/1021397549_1/2015-новый-шик-горячая-распродажа-бесплатная-доставка-сексуальные-женщины-красочные-птицы-шифон-рубашка-форме-крыла-летучей.jpg\",\"aviable\":\"990\",\"sku-html\":\"\"},{\"id\":\"802048809\",\"prod-name\":\"Дизайнер
  искусственного из двух частей кружева шифон блузка рубашка с кардиган
  для женщин 2015 весна мода дамы свободного покроя
  топы\",\"cost\":582,\"sku\":\"\",\"pcs\":\"1\",\"ship-num\":\"3\",\"ship-name\":\"Fedex
  IE\",\"ship-cost\":3865,\"img\":\"http://i01.i.aliimg.com/wsphoto/v0/802048809/Дизайнер-искусственного-из-двух-частей-кружева-шифон-блузка-рубашка-с-кардиган-для-женщин-2015-весна-мода.jpg\",\"aviable\":\"918\",\"sku-html\":\"\"}]"
jquery-latest.min.js:2

Uncaught TypeError: Cannot use 'in' operator to
    search for '966' in [{"id":"1021397549","prod-name":"2015 новый шик!
    горячая распродажа бесплатная доставка сексуальные женщины красочные
    птицы шифон рубашка форме крыла летучей мыши широкий блузки свободного
    покроя
    топы","cost":134,"sku":"14:200001438#8;5:361385","pcs":"1","ship-num":"2","ship-name":"e-EMS","ship-cost":796,"img":"http://i01.i.aliimg.com/wsphoto/v15/1021397549_1/2015-новый-шик-горячая-распродажа-бесплатная-доставка-сексуальные-женщины-красочные-птицы-шифон-рубашка-форме-крыла-летучей.jpg","aviable":"990","sku-html":""},{"id":"802048809","prod-name":"Дизайнер
    искусственного из двух частей кружева шифон блузка рубашка с кардиган
    для женщин 2015 весна мода дамы свободного покроя
    топы","cost":582,"sku":"","pcs":"1","ship-num":"3","ship-name":"Fedex
    IE","ship-cost":3865,"img":"http://i01.i.aliimg.com/wsphoto/v0/802048809/Дизайнер-искусственного-из-двух-частей-кружева-шифон-блузка-рубашка-с-кардиган-для-женщин-2015-весна-мода.jpg","aviable":"918","sku-html":""}]

But when i do same thing without saving cookie $.cookie("wishlist", JSON.stringify(checkoutArray)); checkoutArray = JSON.parse($.cookie("wishlist"));, just using checkoutArray = JSON.parse(JSON.stringify(checkoutArray)); everything works fine!
Comment: that is too much data for cookies, think about using localStorage
Comment: are you sure you aren't exceeding cookie size limit?
Answer: Well, It sincerely depends on which browser is executing this code because a browser has its specification about what length of cookie it can store.
I sincerely feel that you are crossing that limit.
Here is table which gives you the details about most of the browsers.

and check out this Link, to know more about your browser..
Comment: solution in my hands, i am looking for local storage now)

`Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}`


Ensure a windows service is started from Visual Basic .Net

Question: I have a WCF service being hosted in a Windows Service (using techniques discussed here) and it works great. I'm now writing a (VB.Net) frontend app that needs to call that service, but I don't want my users having to fiddle around with the services snap-in and starting the service manually.
Can I write some code to ensure the Windows Service is started, or start it if it isn't?
Edit: OF course, I can ensure the Service startup is set to automatic, but it doesn't need to be running all the time, and even then the frontend app still needs to be sure the service is running and start it if it isn't.
Answer: You can use the ServiceController class to manipulate a service as needed.
Example from MSDN using the Status property to check if a service needs to be started:
<code>' Toggle the Telnet service -
' If it is started (running, paused, etc), stop the service.
' If it is stopped, start the service.
Dim sc As New ServiceController("Telnet")
Console.WriteLine("The Telnet service status is currently set to {0}", sc.Status)

If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then
   ' Start the service if the current status is stopped.
   Console.WriteLine("Starting the Telnet service...")
   sc.Start()
Else
   ' Stop the service if its status is not set to "Stopped".
   Console.WriteLine("Stopping the Telnet service...")
   sc.Stop()
End If

' Refresh and display the current service status.
sc.Refresh()
Console.WriteLine("The Telnet service status is now set to {0}.", sc.Status)
</code>
Answer: You can do something like
<code>    Dim controller As New ServiceController("ServiceNameHere")
    If controller.Status = ServiceControllerStatus.Stopped Then
        controller.Start()
    End If
</code>
Remember to add reference to and import System.ServiceProcess


buildozer: crashed with 'env': env must be a dict

Question: The error is that 'env':env must be a dict. I believe I have upgraded buildozer and my env. My buildozer was installed using pip3, and my code is for python 3. Also, I used the module plyer in my source code, I don't know if that's the case, but if I just build kivy, then there's no error.
Please give some suggestions, solutions, or feedbacks!
Below is my main.py, buildozer.spec, and log (I deleted some because of the body size limit).
main.py:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.properties import StringProperty

from plyer import sms

Builder.load_string('''
<SmsInterface>:
    orientation: 'vertical'
    BoxLayout:
        size_hint_y: None
        height: sp(30)
        Label:
            text: 'Recipient:'
        TextInput:
            id: recipient
            multiline: False
            on_text_validate: message.focus = True
    BoxLayout:
        Label:
            text: 'Message:'
        TextInput:
            id: message
    IntentButton:
        sms_recipient: recipient.text
        sms_message: message.text
        text: 'Send SMS'
        size_hint_y: None
        height: sp(40)
        on_release: self.send_sms()
''')

class SmsInterface(BoxLayout):
    pass

class IntentButton(Button):
    sms_recipient = StringProperty()
    sms_message = StringProperty()

    def send_sms(self, *args):
        sms.send(recipient=self.sms_recipient, message=self.sms_message)

class SmsApp(App):
    def build(self):
        return SmsInterface()

    def on_pause(self):
        return True

if __name__ == "__main__":
    SmsApp().run()

buildozer.spec:
[app]

# (str) Title of your application
title = Plyer sms Test

# (str) Package name
package.name = plyersms

# (str) Package domain (needed for android/ios packaging)
package.domain = org.test

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
#version.regex = __version__ = '(.*)'
#version.filename = %(source.dir)s/main.py

# (str) Application versioning (method 2)
version = 0.1

# (list) Application requirements
requirements = plyer,kivy

# (list) Garden requirements
#garden_requirements =

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png

# (str) Supported orientation (one of landscape, portrait or all)
orientation = portrait

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 0

#
# Android specific
#

# (list) Permissions
android.permissions = SEND_SMS

# (int) Android API to use
#android.api = 14

# (int) Minimum API required (8 = Android 2.2 devices)
#android.minapi = 8

# (int) Android SDK version to use
#android.sdk = 21

# (str) Android NDK version to use
#android.ndk = 9c

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path =

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#android.p4a_dir =

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (str) python-for-android branch to use, if not master, useful to try
# not yet merged features.
#android.branch = master

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (list) Android additionnal libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

#
# iOS specific
#

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# -----------------------------------------------------------------------------
# List as sections
#
# You can define all the "list" as [section:key].
# Each line will be considered as a option to the list.
# Let's take [app] / source.exclude_patterns.
# Instead of doing:
#
#     [app]
#     source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
# This can be translated into:
#
#     [app:source.exclude_patterns]
#     license
#     data/audio/*.wav
#     data/images/original/*
#

# -----------------------------------------------------------------------------
# Profiles
#
# You can extend section / key with a profile
# For example, you want to deploy a demo version of your application without
# HD content. You could first change the title to add "(demo)" in the name
# and extend the excluded directories to remove the HD content.
#
#     [app@demo]
#     title = My Application (demo)
#
#     [app:source.exclude_patterns@demo]
#     images/hd/*
#
# Then, invoke the command line with the "demo" profile:
#
#     buildozer --profile demo android debug

log:
buildozer android debug deploy run

[INFO]:    Copying pyjnius java class to classes build dir
[INFO]:    -> directory context /home/yd/Desktop/test/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/pyjnius-python3-sdl2/armeabi-v7a__ndk_target_21/pyjnius
[INFO]:    -> running cp -a jnius/src/org /home/yd/D...(and 84 more)
[INFO]:    <- directory context /home/yd/Desktop/test/.buildozer/android/platform/python-for-android
[INFO]:    Postbuilding android for armeabi-v7a
[INFO]:    Postbuilding kivy for armeabi-v7a
[INFO]:    # Installing pure Python modules
[INFO]:    *** PYTHON PACKAGE / PROJECT INSTALL STAGE ***
[INFO]:    The requirements (certifi, plyer) don't have recipes, attempting to install them with pip
[INFO]:    If this fails, it may mean that the module has compiled components and needs a recipe.
[INFO]:    -> directory context /home/yd/Desktop/test/.buildozer/android/platform/build-armeabi-v7a/build
[INFO]:    -> running virtualenv --python=python3 venv
[INFO]:    Upgrade pip to latest version
[INFO]:    -> running bash -c source venv/bin/activat...(and 23 more)
Traceback (most recent call last):
  File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/yd/Desktop/test/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 1199, in <module>
    main()
  File "/home/yd/Desktop/test/.buildozer/android/platform/python-for-android/pythonforandroid/entrypoints.py", line 18, in main
    ToolchainCL()
  File "/home/yd/Desktop/test/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 671, in __init__
    getattr(self, args.subparser_name.replace('-', '_'))(args)
  File "/home/yd/Desktop/test/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 155, in wrapper_func
    build_dist_from_args(ctx, dist, args)
  File "/home/yd/Desktop/test/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 209, in build_dist_from_args
    args, "ignore_setup_py", False
  File "/home/yd/Desktop/test/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 605, in build_recipes
    ignore_setup_py=ignore_project_setup_py
  File "/home/yd/Desktop/test/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 791, in run_pymodules_install
    ), _env=copy.copy(base_env))
  File "/home/yd/Desktop/test/.buildozer/android/platform/python-for-android/pythonforandroid/logger.py", line 179, in shprint
    output = command(*args, **kwargs)
  File "/home/yd/.local/lib/python3.6/site-packages/sh.py", line 1474, in __call__
    extracted_call_args, kwargs = self._extract_call_args(kwargs)
  File "/home/yd/.local/lib/python3.6/site-packages/sh.py", line 1377, in _extract_call_args
    raise TypeError("Invalid special arguments:\n\n%s\n" % exc_msg)
TypeError: Invalid special arguments:

  'env': env must be a dict. Got environ({'GJS_DEBUG_TOPICS': 'JS ERROR;JS LOG', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'USER': 'yd', 'TEXTDOMAIN': 'im-config', 'XDG_SEAT': 'seat0', 'SSH_AGENT_PID': '1163', 'XDG_SESSION_TYPE': 'x11', 'SHLVL': '1', 'QT4_IM_MODULE': 'xim', 'HOME': '/home/yd', 'OLDPWD': '/home/yd/Desktop', 'DESKTOP_SESSION': 'ubuntu', 'GNOME_SHELL_SESSION_MODE': 'ubuntu', 'GTK_MODULES': 'gail:atk-bridge', 'ANDROIDMINAPI': '21', 'DBUS_SESSION_BUS_ADDRESS': 'unix:path=/run/user/1000/bus', 'COLORTERM': 'truecolor', 'IM_CONFIG_PHASE': '2', 'LOGNAME': 'yd', 'GTK_IM_MODULE': 'ibus', '_': '/home/yd/.local/bin/buildozer', 'ANDROIDAPI': '27', 'USERNAME': 'yd', 'XDG_SESSION_ID': '1', 'TERM': 'xterm-256color', 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated', 'ANDROIDNDK': '/home/yd/.buildozer/android/platform/android-ndk-r19b', 'WINDOWPATH': '1', 'PATH': '/home/yd/.buildozer/android/platform/android-ndk-r19b/toolchains/llvm/prebuilt/linux-x86_64/bin:/home/yd/.buildozer/android/platform/android-ndk-r19b/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86/bin/:/home/yd/.buildozer/android/platform/android-ndk-r19b/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/:/home/yd/.buildozer/android/platform/android-ndk-r19b:/home/yd/.buildozer/android/platform/android-sdk/tools:/home/yd/.buildozer/android/platform/apache-ant-1.9.4/bin:/home/yd/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin', 'SESSION_MANAGER': 'local/COMPUTER:@/tmp/.ICE-unix/1027,unix/COMPUTER:/tmp/.ICE-unix/1027', 'XDG_MENU_PREFIX': 'gnome-', 'GNOME_TERMINAL_SCREEN': '/org/gnome/Terminal/screen/32290487_4474_4053_b800_c94f4e7d0d39', 'XDG_RUNTIME_DIR': '/run/user/1000', 'DISPLAY': ':0', 'LANG': 'en_US.UTF-8', 'XDG_CURRENT_DESKTOP': 'ubuntu:GNOME', 'ANDROIDSDK': '/home/yd/.buildozer/android/platform/android-sdk', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:', 'XDG_SESSION_DESKTOP': 'ubuntu', 'XMODIFIERS': '@im=ibus', 'GNOME_TERMINAL_SERVICE': ':1.62', 'XAUTHORITY': '/run/user/1000/gdm/Xauthority', 'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh', 'SHELL': '/bin/bash', 'QT_ACCESSIBILITY': '1', 'GDMSESSION': 'ubuntu', 'PACKAGES_PATH': '/home/yd/.buildozer/android/packages', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'TEXTDOMAINDIR': '/usr/share/locale/', 'GJS_DEBUG_OUTPUT': 'stderr', 'GPG_AGENT_INFO': '/run/user/1000/gnupg/S.gpg-agent:0:1', 'XDG_VTNR': '1', 'QT_IM_MODULE': 'xim', 'PWD': '/home/yd/Desktop/test/.buildozer/android/platform/python-for-android', 'CLUTTER_IM_MODULE': 'xim', 'XDG_DATA_DIRS': '/usr/share/ubuntu:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop', 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/etc/xdg', 'VTE_VERSION': '5202', 'PYTHONPATH': '/home/yd/Desktop/test/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/plyersms'})

# Command failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=plyersms --bootstrap=sdl2 --requirements=plyer,kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir="/home/yd/Desktop/test/.buildozer/android/platform/build-armeabi-v7a" --ndk-api=21
# ENVIRONMENT:
#     CLUTTER_IM_MODULE = 'xim'
#     LS_COLORS = 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:'
#     LESSCLOSE = '/usr/bin/lesspipe %s %s'
#     XDG_MENU_PREFIX = 'gnome-'
#     LANG = 'en_US.UTF-8'
#     DISPLAY = ':0'
#     GNOME_SHELL_SESSION_MODE = 'ubuntu'
#     COLORTERM = 'truecolor'
#     USERNAME = 'yd'
#     XDG_VTNR = '1'
#     SSH_AUTH_SOCK = '/run/user/1000/keyring/ssh'
#     XDG_SESSION_ID = '1'
#     USER = 'yd'
#     DESKTOP_SESSION = 'ubuntu'
#     QT4_IM_MODULE = 'xim'
#     TEXTDOMAINDIR = '/usr/share/locale/'
#     GNOME_TERMINAL_SCREEN = '/org/gnome/Terminal/screen/32290487_4474_4053_b800_c94f4e7d0d39'
#     PWD = '/home/yd/Desktop/test'
#     HOME = '/home/yd'
#     TEXTDOMAIN = 'im-config'
#     SSH_AGENT_PID = '1163'
#     QT_ACCESSIBILITY = '1'
#     XDG_SESSION_TYPE = 'x11'
#     XDG_DATA_DIRS = '/usr/share/ubuntu:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop'
#     XDG_SESSION_DESKTOP = 'ubuntu'
#     GJS_DEBUG_OUTPUT = 'stderr'
#     GTK_MODULES = 'gail:atk-bridge'
#     WINDOWPATH = '1'
#     TERM = 'xterm-256color'
#     SHELL = '/bin/bash'
#     VTE_VERSION = '5202'
#     QT_IM_MODULE = 'xim'
#     XMODIFIERS = '@im=ibus'
#     IM_CONFIG_PHASE = '2'
#     XDG_CURRENT_DESKTOP = 'ubuntu:GNOME'
#     GPG_AGENT_INFO = '/run/user/1000/gnupg/S.gpg-agent:0:1'
#     GNOME_TERMINAL_SERVICE = ':1.62'
#     XDG_SEAT = 'seat0'
#     SHLVL = '1'
#     GDMSESSION = 'ubuntu'
#     GNOME_DESKTOP_SESSION_ID = 'this-is-deprecated'
#     LOGNAME = 'yd'
#     DBUS_SESSION_BUS_ADDRESS = 'unix:path=/run/user/1000/bus'
#     XDG_RUNTIME_DIR = '/run/user/1000'
#     XAUTHORITY = '/run/user/1000/gdm/Xauthority'
#     XDG_CONFIG_DIRS = '/etc/xdg/xdg-ubuntu:/etc/xdg'
#     PATH = '/home/yd/.buildozer/android/platform/apache-ant-1.9.4/bin:/home/yd/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin'
#     GJS_DEBUG_TOPICS = 'JS ERROR;JS LOG'
#     SESSION_MANAGER = 'local/COMPUTER:@/tmp/.ICE-unix/1027,unix/COMPUTER:/tmp/.ICE-unix/1027'
#     LESSOPEN = '| /usr/bin/lesspipe %s'
#     GTK_IM_MODULE = 'ibus'
#     OLDPWD = '/home/yd/Desktop'
#     _ = '/home/yd/.local/bin/buildozer'
#     PACKAGES_PATH = '/home/yd/.buildozer/android/packages'
#     ANDROIDSDK = '/home/yd/.buildozer/android/platform/android-sdk'
#     ANDROIDNDK = '/home/yd/.buildozer/android/platform/android-ndk-r19b'
#     ANDROIDAPI = '27'
#     ANDROIDMINAPI = '21'
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2

Comment: Hey, I am assuming you are running this on a virtual machine? Have you installed kivmb on that machine?
Comment: Yes, I am running this on Virtual Box. Can you explain kivmb more? Is there anything I need to do after installing kvm? Thanks!
Comment: Sorry, that's a typo. I meant kivmob. Have you installed kivmob onto your virtual box?
Comment: No, but can you explain how kivmob is related to this issue? I searched it up a bit, it's just putting ads inside a kivy application.
Answer: I had this same issue, and was able to resolve it with some minor tweaks to some buildozer code:

Navigate to your app directory
CD to: .buildozer/android/platform/python-for-android/pythonforandroid
Open up build.py
On lines 791, 797, and 841, you should see _env=copy.copy(base_env).
Replace all instances of that with _env=dict(copy.copy(base_env))

So, it should look about like this:
Image 1
Image 2
Then, save and rebuild as normal. Good luck!
Comment: It worked! I'm glad that you looked through the build.py and found its errors; it saved me a lot of time.Thank you!
Comment: @Camden Senneff - Thank you! It turns out this has been fixed in the p4a develop branch ([more info](https://github.com/kivy/python-for-android/issues/2170#issuecomment-623664851)) but the fix has not yet been released.


Get Facebook access token from Social.framework(iOS6)

Question: I need to retrieve Facebook access token of my system account, which I set in Settings application.
I know that Social.framework(iOS6) knows all my FB account information & I can perform API calls to Graph API using SLRequest class, like in this post http://blogs.captechconsulting.com/blog/eric-stroh/ios-6-tutorial-integrating-facebook-your-applications
But, my question is - how can I retrieve my Facebook system account's access token?
I found solution for Twitter https://dev.twitter.com/docs/ios/using-reverse-auth , but could you help me with Facebook
Answer: If you already know how to get the account store set up, here's code around it showing how to get the access token:
<code>@property (strong, nonatomic) ACAccountStore *accountStore;
@property (strong, nonatomic) ACAccount *fbAccount;

...

@synthesize accountStore = _accountStore;
@synthesize fbAccount = _fbAccount;

...

// Initialize the account store
self.accountStore = [[ACAccountStore alloc] init];

// Get the Facebook account type for the access request
ACAccountType *fbAccountType = [self.accountStore
    accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

// Request access to the Facebook account with the access info
[self.accountStore requestAccessToAccountsWithType:fbAccountType
                                           options:fbInfo
                                        completion:^(BOOL granted, NSError *error) {
    if (granted) {
        // If access granted, then get the Facebook account info
        NSArray *accounts = [self.accountStore
                             accountsWithAccountType:fbAccountType];
        self.fbAccount = [accounts lastObject];

        // Get the access token, could be used in other scenarios
        ACAccountCredential *fbCredential = [self.fbAccount credential];
        NSString *accessToken = [fbCredential oauthToken];
        NSLog(@"Facebook Access Token: %@", accessToken);

        // Add code here to make an API request using the SLRequest class

    } else {
        NSLog(@"Access not granted");
    }
}];
</code>
Comment: Unfortunately we can't use [self.fbAccount credential]; - this method return null - just look at docs - http://developer.apple.com/library/ios/#documentation/Accounts/Reference/ACAccountClassRef/Reference/Reference.html#//apple_ref/doc/uid/TP40011019 -  For privacy reasons, this property is inaccessible after the account is saved.
Comment: is this same for twitter acess token
Comment: Interesting, I was able to print it out both on simulator and real device but I'm not saving it explicitly and it seems it may not be happening implicitly. Are you saving it and if so, why do you need to save?
Comment: I would like to use it in the Facebook iOS SDK. For example, if I logged in in system, I don't want to login again using Facebook iOS SDK, I just need to retrieve system access token and save it into Facebook iOS SDK to future requests.
Comment: How to save it to Facebook iOS SDK?


I am facing this problem in pyppeteer in simply login to page and logout by clicking on div anchor tag

Question: Where i am going wrong?
I just want to go on some URL fill login file fields and click on submit button and select logout div click on it and exit..
pyppeteer.errors.NetworkError: Execution context was destroyed, most likely because of a navigation.

import asyncio
from pyppeteer import launch
import time
async def main(user , password):
    browser = await launch(headless=False)
    page = await browser.newPage()
    await page.setViewport({ 'width': 1280, 'height': 800 })
    await page.goto('someurl')
    await page.type('[ id = userName ]', user)
    await page.type('[ id = password ]', password)
    await page.click('[type = submit]')
    time.sleep(5)
    await page.screenshot({
        'path' : 'next2.png'
    })
    element = await page.querySelectorAll('div[class = pull-right]')
    await page.evaluate('(element) => element.click', element)

    await browser.close()

asyncio.get_event_loop().run_until_complete(main('username , 'password@123'))

Comment: `(element) => element.click` looks wrong -- you probably want to call the function, `(element) => element.click()`. Also, you're missing a closing quote after `username, `.
Answer: This error usually comes when the page is in a navigation state.
You just need to use page.waitForNavigation:
await page.waitForNavigation()

See docs for more information about it. Make sure the official docs are for Node.js so you need to use a dictionary instead of object.


How to select by non-direct child condition in Xpath?

Question: I would like to show an example.
This how the page looks:

        Hello

        Pick Delivery Location

I want to select anchor tags that have a child (direct or non-direct) span that has the text 'Hello'.
Right now, I do something like this:
//a[@class='aclass'][div/span[text() = 'Hello']]

I want to be able to select without having to select direct children (div in this case), like this:
//a[@class='aclass'][//span[text() = 'Hello']]

However, the second one finds all the anchor tags with the class 'aclass' rather than the one with the span with 'Hello' text.
I hope I worded my question clearly. Please feel free to edit if necessary.
Answer: In your attempt, // goes back to the root of the document - effectively you are saying "Give me the as for which there is a span anywhere in the document", which is why you get them all.
What you need is the descendant axis :
//a[@class='aclass' and descendant::span[text() = 'Hello']]

Note I have joined the conditions with and, but two separate conditions would also work.


Batch txt to excel delimited using vba question

Question: I was trying to batch convert text files to excel using VBA and found this code in this web. This is how my text looks like:
ABC|123|DEF
ZZZ|233|YTU
Sub LoopAllFiles()
    Dim sPath As String, sDir As String
    sPath = "C:\work\"
    If Right(sPath, 1) <> "\" Then sPath = sPath & "\"
    sDir = Dir$(sPath & "*.txt", vbNormal)
    Do Until Len(sDir) = 0
        Workbooks.Open (sPath & sDir)
        With ActiveWorkbook
            Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
                TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
                Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
                :="|", FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
            .SaveAs Filename:=Left(.FullName, InStrRev(.FullName, ".")) & "xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
            .Close
        End With
        sDir = Dir$
    Loop
End Sub

After using the code, the exported excel looks like this:
ABC 123 DEF (3 separated cell)
ZZZ|233|YTU (1 single cell)
Anyone have idea why the code only convert the first row and stop afterwards?
Thanks a lot.
Comment: Instead of `Selection.TextToColumns...` try `Cells.TextToColumns`, or even better would be to provide a specific range.
Comment: That does not work for me. A runtime error 1004 appeared saying that Microsoft excel can convert only one column at a time
Comment: D'oh, then do `Range("A1:A100").TextToColumns` (or whatever range you need).
Answer: In this case, TextToColumns will work on the selected text, which by default is a single cell, but you need it to be the range of cells of the imported data. Try expanding the selection before doing the TextToColumns, for example, insert the following code line:
    Selection.CurrentRegion.Select
after
    With ActiveWorkbook


jinja2 cannot import name 'select_autoescape'

Question: i am going crazy with an import problem. It should be 'simple' because i have a script (test2.py) with this import inside:
from jinja2 import Environment, FileSystemLoader, PackageLoader,select_autoescape

    def myfun(arg1)
       ...

       env = Environment(loader=FileSystemLoader('/var/www/html/templates'),autoescape=select_autoescape(['html', 'xml']))
       ...

Note that this script test2.py is called by test1.py (called by a CGI scripr) like that :
import test2
test2.myfun(arg1)
then i get the error:
from jinja2 import Environment, FileSystemLoader, PackageLoader, select_autoescape
ImportError: cannot import name 'select_autoescape'

the crazy thing is that if i call (directly) another script with these imports:
    from jinja2 import Environment, FileSystemLoader, PackageLoader,select_autoescape
it goes fine! it does import the select_autoescape thing ...
So my question is why does it not import it when i call it from another function/module?
Answer: Try reinstalling jinja2:
sudo pip3 install --upgrade jinja2

It worked for me.


Images are rotated in PictureBox

Question: As the question implies, when I load an image into a pictureBox (using dialog box), it doesn't appear as its original look. in this screen shoot, the image on the left is the one I loaded into the pictureBox (on the right).
Trying to know what causes this I draw an image using Paint app and rotated it using Windows Photo Viewer, the rotated image loaded as it is (rotated), that is it, some pictures are just fine loaded, and others are rotated! and I can't figure out why?!
Comment: Photo-viewer rotates JPGs by tweaking the EXIF data - it doesn't actually change the pixel data. I guess the picture-box doesn't check the EXIF orientation of JPGs. Other formats like BMP and PNG don't have EXIF, so photo-viewer actually modifies the pixel-data when rotating them.
Answer: When you view an image in Windows Photo Viewer, it automatically corrects image orientation if it has an Exif orientation data. PictureBox doesn't have built-in support for such functionality. You can create a custom PictureBox which shows images correctly even if they have orientation data:
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;

public class MyPictureBox : PictureBox
{
    private void CorrectExifOrientation(Image image)
    {
        if (image == null) return;
        int orientationId = 0x0112;
        if (image.PropertyIdList.Contains(orientationId))
        {
            var orientation = (int)image.GetPropertyItem(orientationId).Value[0];
            var rotateFlip = RotateFlipType.RotateNoneFlipNone;
            switch (orientation)
            {
                case 1: rotateFlip = RotateFlipType.RotateNoneFlipNone; break;
                case 2: rotateFlip = RotateFlipType.RotateNoneFlipX; break;
                case 3: rotateFlip = RotateFlipType.Rotate180FlipNone; break;
                case 4: rotateFlip = RotateFlipType.Rotate180FlipX; break;
                case 5: rotateFlip = RotateFlipType.Rotate90FlipX; break;
                case 6: rotateFlip = RotateFlipType.Rotate90FlipNone; break;
                case 7: rotateFlip = RotateFlipType.Rotate270FlipX; break;
                case 8: rotateFlip = RotateFlipType.Rotate270FlipNone; break;
                default: rotateFlip = RotateFlipType.RotateNoneFlipNone; break;
            }
            if (rotateFlip != RotateFlipType.RotateNoneFlipNone)
            {
                image.RotateFlip(rotateFlip);
                image.RemovePropertyItem(orientationId);
            }
        }
    }
    [Localizable(true)]
    [Bindable(true)]
    public new Image Image
    {
        get { return base.Image; }
        set { base.Image = value; CorrectExifOrientation(value); }
    }
}

Comment: If you use `MyPictureBox` instead of `PictureBox` the rotation will be fixed automatically. Also you can manually use `CorrectExifOrientation` method on an image and put the image in a `PictureBox`. Let me know if you have any question about the answer :)
Answer: Without the original image data, it's impossible to say for sure what going on. But it's clear that at some point, some software involved in the processing of the image has used the EXIF orientation property to rotate the image, rather than actually modifying the image data itself. This may be Photo Viewer or some other tool that handled the photo at some point.
Here is code you can use to detect the orientation of the image, as recorded in the EXIF data by the camera that took the picture:
static ImageOrientation GetOrientation(this Image image)
{
    PropertyItem pi = SafeGetPropertyItem(image, 0x112);

    if (pi == null || pi.Type != 3)
    {
        return ImageOrientation.Original;
    }

    return (ImageOrientation)BitConverter.ToInt16(pi.Value, 0);
}

// A file without the desired EXIF property record will throw ArgumentException.
static PropertyItem SafeGetPropertyItem(Image image, int propid)
{
    try
    {
        return image.GetPropertyItem(propid);
    }
    catch (ArgumentException)
    {
        return null;
    }
}

where:
///
/// Possible EXIF orientation values describing clockwise
/// rotation of the captured image due to camera orientation.
///
/// <remarks>Reverse/undo these transformations to display an image correctly</remarks>
public enum ImageOrientation
{
    ///
    /// Image is correctly oriented
    ///
    Original = 1,
    ///
    /// Image has been mirrored horizontally
    ///
    MirrorOriginal = 2,
    ///
    /// Image has been rotated 180 degrees
    ///
    Half = 3,
    ///
    /// Image has been mirrored horizontally and rotated 180 degrees
    ///
    MirrorHalf = 4,
    ///
    /// Image has been mirrored horizontally and rotated 270 degrees clockwise
    ///
    MirrorThreeQuarter = 5,
    ///
    /// Image has been rotated 270 degrees clockwise
    ///
    ThreeQuarter = 6,
    ///
    /// Image has been mirrored horizontally and rotated 90 degrees clockwise.
    ///
    MirrorOneQuarter = 7,
    ///
    /// Image has been rotated 90 degrees clockwise.
    ///
    OneQuarter = 8
}

The GetOrientation() method above is written as an extension method, but of course you can call it as a plain static method. Either way, just pass it the Bitmap object you've just opened from a file, and it will return the EXIF orientation stored in the file, if any.
With that in hand, you can rotate the image according to your needs.
Answer: I load my image from the file explorer to the pictureBox like this:
private void btnBrowse_Click ( object sender, EventArgs e ) {
    using( OpenFileDialog openFile = new OpenFileDialog() ) {
        openFile.Title = "Select image for [user]";
        openFile.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png)|*.jpg; *.jpeg; *.jpe; *.jfif; *.png|All files (*.*)|*.*";

        if( openFile.ShowDialog() == DialogResult.OK ) {
            //image validation
            try {
                Bitmap bmp = new Bitmap( openFile.FileName );//to validate the image
                if( bmp != null ) {//if image is valid
                    pictureBox1.Load( openFile.FileName );//display selected image file
                    pictureBox1.Image.RotateFlip( Rotate( bmp ) );//display image in proper orientation
                    bmp.Dispose();
                }
            } catch( ArgumentException ) {
                MessageBox.Show( "The specified image file is invalid." );
            } catch( FileNotFoundException ) {
                MessageBox.Show( "The path to image is invalid." );
            }
        }
    }
}

This is the method for displaying the images proper orientation:
//Change Image to Correct Orientation When displaying to PictureBox
public static RotateFlipType Rotate ( Image bmp ) {
    const int OrientationId = 0x0112;
    PropertyItem pi = bmp.PropertyItems.Select( x => x )
                                .FirstOrDefault( x => x.Id == OrientationId );
    if( pi == null )
        return RotateFlipType.RotateNoneFlipNone;

    byte o = pi.Value[ 0 ];

    //Orientations
    if( o == 2 ) //TopRight
        return RotateFlipType.RotateNoneFlipX;
    if( o == 3 ) //BottomRight
        return RotateFlipType.RotateNoneFlipXY;
    if( o == 4 ) //BottomLeft
        return RotateFlipType.RotateNoneFlipY;
    if( o == 5 ) //LeftTop
        return RotateFlipType.Rotate90FlipX;
    if( o == 6 ) //RightTop
        return RotateFlipType.Rotate90FlipNone;
    if( o == 7 ) //RightBottom
        return RotateFlipType.Rotate90FlipY;
    if( o == 8 ) //LeftBottom
        return RotateFlipType.Rotate90FlipXY;

    return RotateFlipType.RotateNoneFlipNone; //TopLeft (what the image looks by default) [or] Unknown
}

These are my references:
Code reference (I modified the accepted answer): https://stackoverflow.com/a/42972969/11565087
Visual reference (found in the comments[I don't know how to link a comment here]) : http://csharphelper.com/blog/2016/07/read-an-image-files-exif-orientation-data-in-c/

Images are rotated in PictureBox


How to determine wrong data type

Question: I use the following to see if the data is an integer, if not it tells me. Is there a way to determine which one is incorrect so can change it or would i have to create the same loop for every item?
while i_input == True:
    try:
        i_pointstarget=int(pointstarget.get())
        i_ap1=int(ap1.get())
        i_ap2=int(ap2.get())
        i_ap3=int(ap3.get())
        i_ap4=int(ap4.get())
        i_ap5=int(ap5.get())
        i_ap6=int(ap6.get())
    except ValueError:
        i_input=False
        continue
    else:
        break

Thanks for any help :)
Comment: ... Have you considered writing a separate function to convert?
Comment: @IgnacioVazquez-Abrams I don't need to convert it i just need to locate which one is wrong
Comment: If you don't need to convert it then how come you keep calling `int()` each time?
Comment: @IgnacioVazquez-Abrams Because I want the variable to be a int, i was using this to then detect if it's not an int however it doesn't tell you which one isn't an int. At least I think that's what it is doing - i'm new and not very good :)
Comment: Add some sample input and out.
Answer: Instead of trying to convert to int (btw int(1.23) works, returning 1) you can also use numbers like
import numbers
def is_integral(n): # actually not checking for int but also other int-equivalents
    return isinstance(n,numbers.Integral)

if you want to check if you have a number which can loslessy be converted to an integral number (like int) you can do
import numbers
def exact_integral(n): # check if n can be exactly represented as an integer
    return isinstance(n,numbers.Complex) and n==round(n.real)

Answer: To know the type of a variable you can use isinstance(variable_name, int), this will return the Boolean value.

How to determine wrong data type


How to calculate IVs properly

Question: I have been using different IV raters and calculator in web and application. And mose of them require to put the informacion about CP, HP and dust needed for power up. However, some of them also require to put your trainer level like the following:
https://thesilphroad.com/research
Does this mean whenever i check the IV of a pokemon what matters is the level of when i catched it? Or my current level?
Comment: Procedurally casting close vote per Chris' comment.
Answer: Your current level. Because the max CP of a pokemon is a product of your current level times a multiplier.
See: https://gist.github.com/KazWolfe/68e10ebf1ed41ae1ae6de2350d5de884 line:574
Answer: Once caught a pokemon's IV will never change. The reason your trainer level may make a difference is that the pokemon's level is limited by your trainer level. When working out IVs it is something of a trial and error effort so knowing the upper limit of the possible pokemon level by knowing your trainer level can help them narrow down your pokemon's stats.

How to calculate IVs properly


Do we approve suggested edit robo?

Question: This user only doing Suggested edit (only editing the title spelling mistake), Is this valid editing behavior ?
Answer: I agree with MPD that titles are important, but I would rather prefer a suggested edit that changes most of the things that can be changed. For example, this suggested edit doesn't touch the question text, which is the following.

Have anyone measured the difference between preloading all changes in $node object and then do node_save () vs. injecting changes in node fields directly by doing db_insert ?

If you see the same user doing consecutive suggested edits like that, you could decline it. Once the declined suggested edits are higher than X, the user would not be allowed to suggest edits for 7 days.
Comment: @KrishnaMohan you can check your suggested edits here http://drupal.stackexchange.com/users/25879/krishna-mohan?tab=activity
Comment: @KrishnaMohan click the suggested edit link in http://drupal.stackexchange.com/users/25879/krishna-mohan?tab=activity
Comment: And that's why I rejected some of his edits, and improved other ones... When I did much more in my improvement than he in original edit, I unchecked "helpful". I approved when I believed title was the only thing that needed changes.
Comment: And you are doing well. That is what I would do too.
Comment: @Mołot - My intention was, corrected spelling mistakes helps with search.Thanks for giving clear idea on this.I'll be cautious
Comment: @kiamlaluno - Thanks, I'll be cautious.I thought that the 'title' plays major role in search. (even though the title text doesn't touch the question text).
How can a user know his rejected edits?
Comment: @Bala - Thanks bala,it shows all of my suggested edits.how could I know my rejected edits? If every user know his rejected edits, that helps to improve his editing behaviour.
Answer: I'm not sure quite what you mean; that user has contributed both questions and answers as well as edits.
I would say the usual advice applies: concentrate on the content of the edit rather than the person proposing it - if it's a good edit, accept it, if not, reject it.
Editing is an important part of the site; if a user feels they can help out more by cleaning up other questions/answers than they can by providing new content, I say let them at it, and a big thank you to them at the same time
Comment: If you feel the edit is to minor, reject it as such :)
Comment: @Bala Titles should be impeccable.  Correcting spelling mistakes here is important, as it helps with search.  I will post more info about this when I get a chance.
Comment: @Bala I would have approved that.  I am searching for a particular post I remember to support the "titles should be impeccable" statement.  Having trouble finding it.
Comment: only concern about the edit is, he is only editing the title spelling mistake and not sure to accept or reject ?
Comment: @MPD I already approved many suggested edit from him and raised the question because of this http://drupal.stackexchange.com/review/suggested-edits/27177 hope you understand.
Comment: @MPD thanks for sharing your opinion and now I'm clear about this!

Do we approve suggested edit robo?


Have I missed anything from my list of web form best practices?

Question: So I have been putting together a list of best practices to apply to forms recently and there is a lot of conflicting research out there. I have been combing everything from blogs through to HCI conference reports. So the question is have I missed something or included anything that has since clearly been refuted through research?
Field labels
The following should be a table but UX doesn't seem to render them properly.
Label placement
Short form with simple/short labels  =  On top or to the left, but right aligned
Short form and complex/long labels   =  To the left and left aligned
Long form and simple labels          =  To the left, but right aligned
Long form and complex labels         =  To left and left aligned

Labels should use sentence case and not title case as it is much easier for the human eye to read
Bold text should also not be used for form labels for similar reasons

Required fields

Legend describing meaning of required indicator at the top of the form
Asterisks (standard indicator) to appear after the form fields label
Asterisks should ideally be highlighted by a colour - red by convention
Do not rely on colour alone to indicate an error as this can be easy to miss, difficult for colour blind people etc
Do not confuse the meaning of the asterisks by using it to denote optional fields

Firstly fields marked optional should generally be avoided
Secondly they should have the full word after the field label e.g. (optional)

Buttons

Submit button should appear at the base of the form and be right aligned
Avoid reset buttons as they have no use to real people and just annoy when accidentally clicked
Make the path to completion as visible as possible - one button equals less load as there is no choice to be made

Grouping

Relevant fields should be logically grouped together
Consider using a fieldset to group more than two fields

Errors

Never rely on colour alone - all errors should be accompanied by a text explanation
There should be a message at the top of the form stating that there are errors in the form that need to be corrected
Individual error messages for each field describing the issue for that particular field should appear above the label and field
Messages where possible should be vanquished by client side validation as the user resolves them
Messages can also appear to the right of a label and field if error messages are of a suitable length and the form is not too wide

Select lists

Should be used for 3 or more options - less than this and radio buttons should be used
Anything more than 15 options should always make use of the Chosen progressive enhancement script
If Chosen is used the other select lists in the form should maintain its style
Use them sparingly as they are very heavy and eye catching
The first option in the select list must be a place holder
Place holder should reflect the label rewritten as an action

Place holders as labels (ala Apple store)

These should be avoided as it makes it hard to review a form before submitting it
They should fade slightly when the fields is given focus
Place holder to disappear only when the user enters some text and triggers keyup

Date fields

Should be enhanced by the use of a calendar date picker

Form success

Redirect the user to a confirmation page on successful completion of the form

The redirect on success stops the user from seeing messages like "Resend submitted information or cancel?" It also stops users from the refreshing the page and triggering a re-post.
Comment: I am really tempted to post the single answer "No" :-)
Comment: +1 for a very useful post. Should I dare suggest that this be made into a community wiki?
Comment: I wouldn't want to make this a wiki, as I don't agree this should be a list of best practices. See my [answer](http://ux.stackexchange.com/questions/9898/have-i-missed-anything-from-my-list-of-web-form-best-practices/10143#10143) below.
Comment: Google has posted a [blogpost about internationalization](http://googlewebmastercentral.blogspot.com/2011/09/internationalization.html) where they advice to always place labels *on top* of the input fields, instead of left to it.
Comment: @Lode I think the issue shown in that blog isn't so much about labels being to the left, but about the absurd amount of whitespace between label and field.
Comment: Four years has passed since this post was made. Is there any notable changes in the UX best practices now ?
Comment: @PixelSnader the example may be a bit exaggerating, but the point is still valid, and is exactly that: too much white space. Google is not alone in this by the way, see http://ux.stackexchange.com/questions/8480/input-form-label-alignment-top-or-left and http://uxmovement.com/forms/faster-with-top-aligned-labels/ for example. Also note that frontend frameworks like [Bootstrap](http://getbootstrap.com/css/#forms) and [Foundation](http://foundation.zurb.com/docs/components/forms.html) both have it as their default.
Answer: Accessibility

Provide a logical tab order for keyboard only users.
Provide labels for all controls for screen reader users.

You can get more info at these links:
http://www.jimthatcher.com/webcourse8.htm
http://www.afb.org/section.asp?SectionID=57&TopicID=167&DocumentID=2375
http://webaim.org/techniques/forms/
Answer: User interaction

Forgiving Format: Permit users to enter text in a variety of formats and syntaxes, and make the application interpret it intelligently. (Jenifer Tidwell)
Input Hints: Beside an empty text field, place a sentence or example that explains what is required. (Jenifer Tidwell)
Good Defaults: Wherever appropriate, prefill form fields with your best guesses at the values the user wants. (Jenifer Tidwell)

Organizing the form

Split the form into several pages and use a wizard (with a progress bar) if the form is very long or if it is natural to go form step by step or i a particular order.
Responsive disclosure or Responsive_Enabling: If some part of form should is rarely done, you could hide/disable this part until it is needed.

Testing

Perform some user tests on the form.  Measure how long it'll take to complete, measure the dropout and remove ambiguities.
Check how the form looks and behaves in different browsers and on different devices (ex. touch devices).
Answer: Nice list. All I can think to add is to detail how the form will need to work for Non JavaScript users.
Non JavaScript users

Place holders as labels, date picker, in-line errors for example would all need specific no-script alternatives.
Answer: There is not one answer to all questions
As you say, research conflicts here. To me there is no one-way answer to these issues. I would say that a lot of these things depend more on the situation in which they are used. It can be better to apply a set of generic ideas (like Pau Giner answered), instead of checking all items on the list and thinking you're done.
Be friendly
I would add one generic rule: Be friendly to the user.
For example in not giving them the fault saying that there are errors in the form, instead say something like almost there! can you fill in that field as well?. Another example is to remember filled in fields after the form said there are problems.
But again, these are just examples. To me it is better to keep such generic rules in mind.
A little nuance to giving examples

Firstly fields marked optional should generally be avoided

Sometimes it can be very good to both mark required and optional fields, especially when used in combination with sets of fields. And you can for example hide all optional fields in a > Advanced options section.

Submit button should appear at the base of the form and be right aligned

That depends on the looks of the whole form, and how the labels, fields, and rest of the page is aligned. As Daniel Newman also said.

There should be a message at the top of the form stating that there are errors in the form that need to be corrected
Individual error messages for each field describing the issue for that particular field should appear above the label and field

When there is only one 'error', name that error in detail directly at the top instead of leaving the user with a general "there are errors in the form".

[Select] Place holder should reflect the label rewritten as an action

There are more elaborate answers about that subject, see What should be the default option of a required dropdown list?

[Place holders as labels] These should be avoided as it makes it hard to review a form before submitting it

In short forms (up to say 5 fields) that doesn't have to be a problem and can create a much more clean form. Also when there is constant feedback about the fields you're filling in, there is less need to check everything before submitting.

[Date fields] Should be enhanced by the use of a calendar date picker

Depends on what kind date you want. Do you really need that precision of a single day? For example when asking people when in the future to remind them of something, a list with tomorrow, Saturday, next week could also be enough.

Redirect the user to a confirmation page on successful completion of the form

Could be a bit more subtle, the confirmation page isn't always thing successfully added, but could also show the thing added (like when posting an answer here). The redirect part (preventing a refresh warning) is a good thing though.

I hope it helps.
Comment: +1, but this may be true where you have the budget to create a very nice bespoke form. Unfortunately I need to come up with a good set of standard practices for staff tick off of against to ensure that forms are as good as they can be within budget. My list is likely to be used mainly in contact us forms in reality so this is why my list has cut out some of the try it and see approach.
Comment: @Treffynnon, thanks, and welcome here. It could be good to add those context variables (low budget and contact-us forms) to your question, to give a better understanding to readers.
Answer: Very, very helpful post.  Just one change that I would recommend:

Buttons
Submit button should appear at the base of the form and be right aligned

I would argue that the placement of a submit button depends on the form style.  In a multi-stage "wizard", I absolutely agree that next/continue/submit should be right-aligned.  However, for more simple forms (especially when there is only one button; no back/previous button), I believe that the button should be left-aligned with the input fields, to minimize visual fixations and follow the user's visual path (Sources: "How you should align your form buttons" & "The best way to align buttons on forms").
Also, to add to this section, Submit buttons should never just be labeled "Submit"; rather, they should be task-specific... e.g. "Create Account", "Subscribe Now", etc. (Source: "Why your form buttons should never say submit")
Comment: I disagree about left-aligning the submit button even for simple forms - it is intuitive for the final action to be on the right side because we read left to right, and the cursor naturally spends more time on the right side of the screen.  Look at Facebook, twitter, and even StackExchange - the submit button is always on the right, and I wouldn't have it any other way.  In fact I find the submit button distracting if it is aligned left - it looks like another label.
Comment: Nice resources! I linked you in [my answer](http://ux.stackexchange.com/questions/9898/have-i-missed-anything-from-my-list-of-web-form-best-practices/10143#10143) about the submit-alignment.
Answer: Some design principles that can be general but apply to form design:

Avoid the unnecesary. Avoid asking information that is unrelated to the purpose of the form. Use flexible input, structured input or the fill-in the blanks approach instead of asking for specific formats.
Organize the information. Most principles regarding layout have been already commented.
Provide guidance to the user. The user needs explanations that clarify what, why and how to answer.
Don't make things difficult on purpose. Don't hide options or force the selection of the user (e.g. newsletter subscription). Explain the benefits instead.

Months ago I posted about those principles. You can obtain more detail and examples at http://pauginer.tumblr.com/post/7080830292/form-design
Comment: Good ones! I like the more generic principles as opposed to the very specific check marks. See also [my answer](http://ux.stackexchange.com/questions/9898/have-i-missed-anything-from-my-list-of-web-form-best-practices/10143#10143) about that point.
Answer: Personally I don't use asterisks to denote required fields. All fields are required by default. I put '(optional)' next to the additional, optional fields.
Answer: I can add a few things, more about what data you collect than how you design the form:
If there's only one thing to know about a user, ask about that
Many web pages and services demand a full gamut of information about a user, when there's often only one of two things about a user that they need to know. If you're serving content that's inappropriate for minors, for example, all you really need to ask is "Are you over 16?" - not demand my name, email, telephone number and full date of birth.
If the user has already submitted some data, never ask for it again
It's not just annoying for the user to enter data several times - when you make a user submit more than once, there's always the chance they create a duplicate record by entering the same data slightly differently. Think John Smith submitting 'John William Smith' on one form, 'John W Smith' on the next. These duplicate records create major headaches for both you and your users further down the line.
If you can guess data from heuristics, try that
If there's any other information about the user which suggests certain data, try and default your form's options appropriately. For instance, if your user is connecting from a French IP address, set 'Country' to 'France'. If you're offering a user a software download, and their user agent suggests they're using Linux, offer them a Linux version by default.
Answer: Buttons
I would say that input:reset elements can and should be used with the label of "cancel"; they should also look distinctly different from the input:submit button. Quite often the cancel button should perform additional functionality (e.x. kick the user back to the previous page/step/state/whatever), but part of the functionality should also be to clear the form of all data.
Comment: Have you come across any research suggesting that users actually need the reset button? All anecdotal evidence I have seen suggests it just inhibits conversion.
Comment: @Treffynnon, I've seen a number of good UI designs that include `cancel` buttons. They may or may not be `input:reset` (sometimes they are `input:submit`). It's a necessary feature when you have multiple actions that may be completed with web forms. Take for instance, editing a post in StackExchange. There is a second button next to "save edits" that looks like a link named "cancel".
Comment: The purpose of my post was not to say that `cancel` buttons *must* be `input:reset`, but that using an `input:reset` as a cancel button would be acceptable semantically as well as work within the UI.
Answer: validate on both sides:
client-side, for ux; ideally you can accomplish this via html5 attributes alones.
server-side, for validation; validate all form controls to ensure successful, and secure form submission.


recreates @ViewScoped bean on every request

Question: I am using Primefaces fileUpload component in advanced mode to upload multiple         images. When i select few files and press upload button, my @ViewScoped managed bean recreates multiple times. That is a problem for me, because i want to store all files uploaded within one view interaction in separate folder, but I'm getting multiple folders - one for each file. When I made my managed bean @SessionScoped the problem is gone, also i found that this bug appears only after server restart for the first uploading, so when i reload view and upload data second time everything is ok.
I am using Tomcat 7, jsf 2.2 and prime faces 5.1
Here is jsf page:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <f:facet name="first">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    </f:facet>

    <title>Jsf Upload</title>
</h:head>

<h:body>
    <h:form id="growlForm">

    </h:form>

    <h:form id="uploadForm" enctype="multipart/form-data">

    </h:form>
</h:body>

Managed Bean:

@ManagedBean
@ViewScoped
public class UploadController implements Serializable {

    private static final long serialVersionUID = 5711090879027971547L;

    private static final Logger logger = LoggerFactory
            .getLogger(UploadController.class);

    private List<UploadedFile> files;

    public UploadController() {
        logger.info("UploadController constructor call");
        files = new ArrayList<UploadedFile>();
    }

    @PostConstruct
    public void init() {
        logger.info("Post Construct init() method call");
    }

    public void upload(FileUploadEvent event) {
        logger.info("upload() method call, file = {}", event.getFile()
                .getFileName());
        files.add(event.getFile());
        logger.info("Added file = {}", event.getFile().getFileName());
    }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <display-name>JsfUpload</display-name>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>bootstrap</param-value>
    </context-param>

    <context-param>
        <param-name>primefaces.UPLOADER</param-name>
        <param-value>commons</param-value>
    </context-param>
    <filter>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>

    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
</web-app>

Here is my logging output, showing that constructor and @PostConstruct method called multiple times:
2014-12-08 18:57:24,629 [http-bio-8380-exec-7] INFO  ru.duytsev.test.upload.UploadController - UploadController constructor call
2014-12-08 18:57:24,629 [http-bio-8380-exec-7] INFO  ru.duytsev.test.upload.UploadController - Post Construct init() method
2014-12-08 18:57:24,645 [http-bio-8380-exec-7] INFO  ru.duytsev.test.upload.UploadController - upload() method call, file = brick-yellow.png
2014-12-08 18:57:24,645 [http-bio-8380-exec-7] INFO  ru.duytsev.test.upload.UploadController - Added file = brick-yellow.png
2014-12-08 18:57:24,666 [http-bio-8380-exec-6] INFO  ru.duytsev.test.upload.UploadController - UploadController constructor call
2014-12-08 18:57:24,666 [http-bio-8380-exec-6] INFO  ru.duytsev.test.upload.UploadController - Post Construct init() method
2014-12-08 18:57:24,666 [http-bio-8380-exec-6] INFO  ru.duytsev.test.upload.UploadController - upload() method call, file = brick-purple.png
2014-12-08 18:57:24,666 [http-bio-8380-exec-6] INFO  ru.duytsev.test.upload.UploadController - Added file = brick-purple.png
2014-12-08 18:57:24,678 [http-bio-8380-exec-4] INFO  ru.duytsev.test.upload.UploadController - UploadController constructor call
2014-12-08 18:57:24,679 [http-bio-8380-exec-4] INFO  ru.duytsev.test.upload.UploadController - Post Construct init() method
2014-12-08 18:57:24,679 [http-bio-8380-exec-4] INFO  ru.duytsev.test.upload.UploadController - upload() method call, file = brick-green.png
2014-12-08 18:57:24,679 [http-bio-8380-exec-4] INFO  ru.duytsev.test.upload.UploadController - Added file = brick-green.png
2014-12-08 18:57:24,693 [http-bio-8380-exec-5] INFO  ru.duytsev.test.upload.UploadController - upload() method call, file = brick-orange.png
2014-12-08 18:57:24,694 [http-bio-8380-exec-5] INFO  ru.duytsev.test.upload.UploadController - Added file = brick-orange.png
2014-12-08 18:57:24,715 [http-bio-8380-exec-8] INFO  ru.duytsev.test.upload.UploadController - upload() method call, file = brick-blue.png
2014-12-08 18:57:24,715 [http-bio-8380-exec-8] INFO  ru.duytsev.test.upload.UploadController - Added file = brick-blue.png

My pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ru.duytsev.test.upload</groupId>
    <artifactId>JsfUpload</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>5.1</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.extensions</groupId>
            <artifactId>all-themes</artifactId>
            <version>1.0.8</version>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.8-02</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.8-02</version>
        </dependency>

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>el-impl</artifactId>
            <version>2.2.1-b05</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.7</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${pom.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Answer: Change to @ViewScoped.
This causes the constructor to be called only once
Comment: Please give the OP information about where to put that.
Comment: Try reading question from top to bottom before posting an answer.


Write to log in Azure Function

Question: This is the guts of the code I have. I want to write to the log to troubleshoot. It does not like it in the other methods. I saw some examples where they discussed how to achieve this but no real code I could find to try.
I'm writing an Azure function from within the portal.
Any assistance most appreciated.
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

   bool isGood = Verify(myKey, myInput;

   return code != null
        ? (ActionResult)new OkObjectResult($"Request Successful")
        : new BadRequestObjectResult("Bad Request");

} // End Main

public static bool Verify(String key, String input)

    {

        log.LogInformation("Write something here");

    return;

    }

    private static string CreateToken(string message, string secret)

    {
        log.LogInformation("Write something here");
        return;
    }

Comment: what exactly do you want to log? It's not clear in your question, and there are samples in your code (log.LogInformation("Write something here");
Comment: Sorry. The last two do not work. It only works in the main part where it is handling the http request. The function is to handle a github webhook. If I don't have the log statement in Verify or CreateToken it works fine. If I have a log statement like the one in the code it fails and sends back a 500. Not sure where else to check for the possible problem.
Answer: you need to pass ILogger to your methods assign it to a static variable in the Run method:
option 1:
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

   bool isGood = Verify(myKey, myInput, log);
   var token = CreateToken("abc","def",log);

   return code != null
        ? (ActionResult)new OkObjectResult($"Request Successful")
        : new BadRequestObjectResult("Bad Request");

} // End Main

public static bool Verify(String key, String input, ILogger log)

    {

        log.LogInformation("Write something here");

    return true;

    }

    private static string CreateToken(string message, string secret, ILogger log)

    {
        log.LogInformation("Write something here");
        return "";
    }

option 2:
public static class Function1
{
   private static ILogger _log = null;
   public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
   {
    _log = log;
    log.LogInformation("C# HTTP trigger function processed a request.");

   bool isGood = Verify(myKey, myInput;

   return code != null
        ? (ActionResult)new OkObjectResult($"Request Successful")
        : new BadRequestObjectResult("Bad Request");

} // End Main

public static bool Verify(String key, String input)

    {

        _log.LogInformation("Write something here");

    return true;

    }

    private static string CreateToken(string message, string secret)

    {
        _log.LogInformation("Write something here");
        return "";
    }
}

Answer: Create a static ILogger at the class level, assign it in one of the Azure Functions invoked methods, and then use it in your other classes.
public static class LogTest
{
    static ILogger _log;

    [FunctionName("LogTest")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        _log = log;
        log.LogInformation("C# HTTP trigger function processed a request.");

        LogIt("Log this");

        return (ActionResult)new OkObjectResult($"Done logging");
    }

    private static void LogIt(string s)
    {
        _log.LogInformation(s);
    }
}

Write to log in Azure Function


How does the game determine where a Resonator is deployed?

Question: When I deploy Resonators, they usually appear at locations similar to other Resonators -- they are far from the Portal. However, sometimes, my Resonators appear at a place that is not my current location, and they are close to the Portal, meaning all of them can be easily destroyed in a few blows.
What affects the final location of a Resonator? How does the game determine where to deploy it?
Answer: Distance of a resonator to the portal center depends on how much close you are to the portal center.
Also if you don't select a slot, the first deploy will show your location. It starts deploying from the slot that is closest to your location and keep deploying accordingly in a clockwise fashion.
Answer: So far my observations say it's dependent on your distance from the portal. The further you are, the further the resonator will be deployed. I recommend having the portal just on the border of your action ring when deploying.
Answer: The answers are right. This is based on your distance from portal when deploying.
What the others did not says, why is it important, and how should to build your portal to be the most effective.
Here is a site, when you can simulate an attack, and you can set the distance where from you fire: http://ipas.graphracer.com/
When all the resonators are close to the center, a little (eg. lv5) XMP can be damage more, if the attacker stands center.
But if the resonators are far from center, if you check the heatmap, lv5 damages very little, because of it range. So you can imagine, that if you build it far as you can, portal will be "stronger", harder to destroy.
Ok, but what else? Here is a trick: experienced players deploys one resonator really close to the center. But why, if it will destroy soon? Because of Ultra strikes. Ultra strikes are really really strong weapons, but focused on a very little area. If you have an important portal, what your faction needs to hold, and there are 4 AXA shields in it, but an attacker stands to very center of the portal and starts with ultra strikes to destroy AXA shields, you won't get notification about attack, because US does not reach any resonators.
But if one resonators close to the portal, you get the notification.
Is there any more? Yes. How to build a portal? When it is empty, the best way (usual), if you deploy a lvl8 into a slot, the lvl7 the opposite side, and so on.
For example: 8 to north, 7 to south, 6 to east, 6 west, 5 north east, 5 south west, 4-4 into the rest. This is because of heatmap. If 8766 are close to each ohther, attacker won't stand to the center of portal, but to the center where the most damage caused for these higher level resonators, and the "wind of attack" will care about little ones. So you have more chance to hold a portal with recharge, if you build as I mentioned.


Enable a button after open jquery dialog with modal true

Question: I want to enable a button after that i have opened a jquery dialog with option modal set to true.The button obviously is outside the dialog. I already know that this seems to be a strange request but i need this behaviour because I have a form in the dialog so after click on the button to submit the data I have to append the dialog at the end of the form and then click agin on the button that now is outside of the dialog.
Thank you in advance.
Comment: @FlorianMargaine hahaha good for seo :)
Answer: Use te open event that is fired whenever the dialog is opened
<code>$( ".selector" ).dialog({
   open: function(event, ui) {
        $('#yourhiddenbutton').show();
    }
});
</code>
EDIT - you could do it like this
<code>$(function() {
    $("#dialogRifiuto").dialog({
        width: 'auto',
        autoOpen: true,
        closeOnEscape: true,
        modal: true,
        resizable: false,
        open: function(){
            //change the z-index and position the div where you want
            $('#a').css({'z-index':  1005, 'position': 'absolute', 'top': 0 });
        },
        close: function(){
            //go back to normal
            $('#a').css({'z-index':  1, 'position': 'static' });
        }

    })

});
</code>
Comment: He may also need to change the `z-index` because it will be below and useless
Comment: what I need is enable a button blocked by modal jquery dialog (the button isn't in the dialog). With that code i can only show a button in dialog.
Comment: @RobertodeSantis i was just suggesting you to use the open event, the code was just to point out that you should do something, i didn't really got what is your use case, but i think you should change the z-index of the button or something like that
Comment: @NicolaPeluchetti http://jsfiddle.net/XXG3t/ here you can find a snippet of code. I need to enable the input text that contains value pippo without close the dialog or set the dialog modal to false. I have tryed z-index with no success.
Comment: Sorry for the up vote but you have forgotten a dot in $('#a')removeProp('disabled');
Comment: @RobertodeSantis sorry if i don't get this, but you want to have the field with pippo that is modifiable when the dialog is open?Remember that the input field that is inside the dialog will not be sent to the server because the dialog takes that outside of the form
Comment: Yes I want that. I know that the input field inside the dialog will not be sent to the server, infact I'm trying to append the dialog to the form and then click again on the button dialog that now is in the form. The problem is that the modal dialog prevent the click on the button and so nothing happen. For this reasons i need to enable an input field or button disabled by the modal dialog.
Comment: Ok it work. However 'top': 0 isn't necessary.
I'have tried to modify the html and remove manually all the layer build by jquery dialog but without z-index and position it doesn't work. A little strange no?
Comment: @RobertodeSantis no it's normal that you need to set position: absolute to work because the overlay div covers everything otherwise and the only way  around this is absolute positioning
Comment: it work even if set position to relative. Only with static position it doesn't work. However i delete from the html code the overlay div.
Answer: You can enable the button using
$('#myButton').removeAttr('disabled');
Comment: wow, You really need to work with your questions. you can also use `$('#button').attr('disabled',false);`


Javascript only affects one element

Question: I don't understand, the border is only visible on the first item, why?
HTML

Content 1

Content 2

JavaScript
document.getElementById('item').style.borderTop = '1px solid #0ea2c7';

JsFiddle: here
Comment: `id` is supposed to be unique within the document. You may want to use class instead.
Comment: Are you sure about javascript support borderTop method of css ?
Comment: well, why don't you use this in a css property like this one http://jsfiddle.net/SbNKa/53/ ! no need of js!
Comment: It's likely that there are better approaches to what you are trying to do than style elements explicitly using script. One obvious one is to define a class with the `border-top: 1px solid #0ea2c7` property and add that class to the elements. Better yet, make a CSS declaration such as `#theContainer.border-items .item { border-top: 1px solid #0ea2c7; }` and then you'll  just need to add the `border-items` class to the single `#theContainer` element.
Comment: Hope this may work :

[reference](http://stackoverflow.com/questions/3349332/getelementsbyclassname-not-working)
Answer: You can use document.getElementsByClassName
JavaScript
var elements = document.getElementsByClassName('item');
for (i =0; i < ele.length; i++)    {
    elements[i].style.borderTop = '1px solid #000';
}

HTML

Content 1

Content 2

CSS
#theContainer {
    height: 100px;
    width: 500px;
    position: relative;
    border: 1px solid #900;
    padding: 10px;
}
.item {
    height: 50px;
    width: 100%;
}

Answer: "document.getElementById" means "Returns a reference to the element by its ID", see here; and id means identity, you should have only one element in your dom tree per id.
If you want to style multiple elements, try to use class.
HTML

Content 1

Content 2

CSS
.item { border-top: 1px solid #0ea2c7; }

Javascript only affects one element