Deleting column/field in PyQGIS

Question: How to remove or delete column fields in a shapefile using PyQGIS?
Answer: If you get no joy with QGSVectorLayer::deleteAttribute as they docs say: delete an attribute field (but does not commit it) have a look at the data provider. As QGIS deals with lots of feature types with different drivers I suspect that it's left up to the driver as to whether or not a field can be deleted.
Here's some code that I dredged up that may help:
fields = vlayer.dataProvider().fields()

count = 0
for name, field in fields.iteritems():
    if field.name() == fieldName:
        return count
    count += 1

To get the index of the field from the name. In this case I'm not using .upper() but I would recommend it.
After getting the index of the field you (might) delete it using the dataprovider.
fList = list()
fList.append(count)
vlayer.dataProvider().deleteAttributes(fList)

It's expecting a list so the integer needs to be put into a list. I have not used this method; normally I would use ArcMap to delete the field.
As pointed out by RogerHuang, the fields of the layer may need to be updated now that they have been changed to refresh the layers' fields definition:
vlayer.updateFields()

Comment: vLayer.fieldNameIndex('YourFieldName') might be a easier way to get index
Comment: layer.updateFields() seems to be needed, in order to regenerate fields from data provider. https://qgis.org/api/classQgsVectorLayer.html
Comment: Thanks @vinayan, I have overlooked that one. The code I took this from is quite old, that function may be newer than my code.
Comment: Thanks, It worked well  Is there way to get max. index number ? I have an error "return outside function" Thanks for answers
Comment: Thanks for answers all of my problems solved and I combined ideas to find max. field index by following ways            count = layer.dataProvider().attributeIndexes()
print count
maxindex = count[-1]
print maxindex
Answer: For PyQGIS 3 this might be the easiest way to delete a single field:
# Get a layer object and enter edit mode:
my_vectorlayer = iface.activeLayer()
with edit(my_vectorlayer):
    # Get the field index by its name:
    my_field = my_vectorlayer.fields().indexFromName('name of field you want to delete')
    # Delete the field by its index, note that it has to be in a list:
    my_vectorlayer.dataProvider().deleteAttributes([my_field])
# Update the fields, so the changes are recognized:
my_vectorlayer.updateFields()

Or if you want to delete multiple fields at once, you can go for this slightly modified:
# Get a layer object:
my_vectorlayer = iface.activeLayer()
# Create a list of the fieldnames you want to delete:
fieldnames_to_delete = ['field_a','field_c']
# Enter Edit mode
with edit(my_vectorlayer):
    # Create empty list we will fill with the fieldindexes
    fields_to_delete = []
    # Iterate over the list of fieldnames and get the indexes
    for fieldname_to_delete in fieldnames_to_delete:
        # Get the field index by its name:
        fieldindex_to_delete = my_vectorlayer.fields().indexFromName(fieldname_to_delete)
        # You can also check if the field exists
        if fieldindex_to_delete == -1:
            # If it does not exist, just skip it and go to the next one. This may prevent a crash or error :)
            continue
        # Append the index to the list
        fields_to_delete.append(fieldindex_to_delete)
    # Delete the fields by their indexes, note that it has to be a list:
    my_vectorlayer.dataProvider().deleteAttributes(fields_to_delete)
# Update the fields, so the changes are recognized:
my_vectorlayer.updateFields()

Comment: what do i need to do if i want to delete multiple fields by name?
Comment: thank you very much!!
Answer: There's several methods but I will mention the ones I normally use, both using the Python Console.

For SINGLE shapefiles:

Method 1 - Using a method utilising the QGIS algorithm - Delete Column:
output_0=processing.runalg('qgis:deletecolumn', myshapefile.shp, "myFirstField", None)
output_1=processing.runalg('qgis:deletecolumn', output_0['OUTPUT'], "mySecondField", None)
output_2=processing.runalg('qgis:deletecolumn', output_1['OUTOUT'], "myThirdField", myoutput.shp)

Method 2 - Deleting the fields directly by selecting the layer from the Layers window (Table of Contents) and using the following code:
layer = qgis.utils.iface.activeLayer()              # Sets the selected layer as the active layer
res = layer.dataProvider().deleteAttributes([0])    # The [0] represents the 1st field, so [1] is the 2nd field etc. To delete multiple fields, use the comma to separate. Eg. [0, 2, 4]
layer.updateFields()                                # Updates the layer with the changes

For MULTIPLE shapefiles:

Following on from Method 1, you can use the following script which was tested with 2 folders on the Desktop - "Testing" (which contained the shapefiles) and "Results" (which will contain the output shapefiles of the script):
import processing, os, glob

from os.path import expanduser
home = expanduser("~")

result_path = home + "\Desktop\Results\\"
os.chdir(home + "\Desktop\Testing\\")

for fname in glob.glob("*.shp"):
    output_0=processing.runalg('qgis:deletecolumn', fname, "myFirstField", None)
    output_1=processing.runalg('qgis:deletecolumn', output_0['OUTPUT'], "mySecondField", None)
    output_2=processing.runalg('qgis:deletecolumn', output_1['OUTPUT'], "myThirdField", result_path + fname)

print "All done!"

Following on from Method 2, you can use the following code if you have multiple shapefiles loaded in your Layers window without having to select them individually.
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    res = layer.dataProvider().deleteAttributes([0])
    layer.updateFields()

Hope this helps!
Comment: I've done as you suggested in the 1st method but appeared this comment: "Error: Wrong parameter value: None". I can´t use the 2nd method because I have to do the same for a large number of shapefiles, about 8000. Any idea?

Deleting column/field in PyQGIS


If planet orbits are in the shape of an ellipse and the sun is at one focus, what is at the other focus?

Question: I've studied ellipses. I've studied physics. But when it comes down to the elliptical orbits of the planets is where I get confused.
Ellipses contain two foci — and in the orbits of our solar system the sun is consistently stated as one of them. Okay. What about the second focus point? Why is it never brought up? And if there is no second focus — then how do we even move in an elliptical orbit?
Comment: http://physics.stackexchange.com/q/4731/
Answer: There is no physical object at the location of the second focus.
Newton showed that an elliptical path was the consequence of an inverse square radial force from a fixed point.  While you can identify the point that is the second focus, nothing associated with that point is required to create the elliptical motion.
Deriving Kepler's Laws from Inverse-Square Law
Answer: Due to the force of gravity, which goes as the inverse of the square, planets trace out an ellipse in space as they orbit around the sun, which is located at a single focus. The other focus is unphysical.
Actually, given two massive bodies, their "difference" vector will trace out an ellipse with the center of mass at the focus. Because the sun is so much more massive than most of the planets, we can usually disregard this since the center of mass is located within the sun itself.
Without going into more complicated effects such as orbit precession, here is an image depicting a planet's motion about an approximately stationary sun:
Comment: IIRC the mass of Jupiter means the Sun-Jupiter barycenter is just above the surface of the sun
Comment: This does not answer the question. *Why* is the 2nd focus "unphysical"? What do you mean by this?


MouseMoveEvent in QGraphicsView

Question: I need to get a move event in my main widget but the QGraphicsView catches the event, so I can't get it in my main widget. is there any way to turn this off, so i can catch the event like i would catch any mousemoveevent in my widget. Note: The problem is NOT that i have mousetracking disabled. I know about that and catching this event outside the graphicsview is working
Comment: To with installing an event filter on the QGraphicsView and intercept the move event.
Answer: Here are two possible solutions among dozens of them:
Ignore
From documentation:

You should call ignore() if the mouse event is not handled by your
  widget. A mouse event is propagated up the parent widget chain until a
  widget accepts it with accept(), or an event filter consumes it.

<code>// view.cpp

mouseMoveEvent(QMouseEvent *event){
event.ignore(); // propagated to parent
}
</code>
Double event
Try emitting a signal with mouse position from QGraphicsView, when a move event occurs, and catch it in main widget.
<code>// view.cpp

mouseMoveEvent (QMouseEvent *event){
    emit mouseMoveSignal(event.pos());
    }

// mainwindow.cpp

mainWindow::mainWindow (QWidget * parent = 0){
    connect(view, SIGNAL(mouseMoveSignal(QPointF)), this, SLOT(mouseMoveSlot(QPointF)));
}
</code>
Comment: Event filters seem to be more convenient solution. Passing mouse events data through signal-slot system could be too slow and cannot be recommended. I don't understand why you wrote "double event" because signals are not events and should not be confused with them.
Comment: double event: IN CASE you need to catch the event in BOTH widgets. I know the question is NOT asking that; he wants to ignore the event. I just like to express as many approaches I can. Just being curious, is there easier, an obvious way of doing that? Of course, one can also apply an event filter to child, and invoke mouseMoveEvent of the parent widget (I think dynamic casts needed here), when move event of child occurs. I thought signals are easier to handle.

MouseMoveEvent in QGraphicsView


Does Deathtrap get my Shock Damage boosts?

Question: Thanks to Make It Sparkle I can turn Deathtrap's melee attacks into Shock elemental. Does he get my shock damage boost from Wires Don't Talk? Further, does he also get shock damage boosts from other sources like elemental relics?
Answer: The folks over at Wikia speculate that Wires Don't Talk? does add to Make It Sparkle.

If you set Deathtrap's element to Electrical through the use of Make
  it Sparkle, then Wires Don't Talk may also increase his damage.

However looking at the actual skill description for Wires Don't Talk.

Increases all Shock and Electrocute Damage that you inflict.
  Shock and Electrocute Damage: +3% per skill rank.

It mentions you specifically, so that you lead me to surmise that it won't apply to anything else.
There doesn't seem to be much chatter on the Gearbox forums about these skills.
Comment: I just need to test it manually, from casual observation it does'nt seem to though (Fire deathtrap still deals more elemental damage to flesh targets than Shock, but with all of my shock boosts they should be equal)


change ownership of all files from root to user

Question: i'm new to Ubuntu and was wondering if there is a way to remove the ownership of all files and scripts from root to user even if i have to re-install Ubuntu?
i do know about the command 'chown -v username foldername', although it doesn't work on all files.
Comment: If you take away root ownership of some files, Ubuntu will stop working. Why would you want to do this?
Comment: Really bad things will happen if you do this.
Answer: Just go to the directory you want to change:
cd /opt/lampp/htdocs

and change the permission using the chown command:
sudo chown userName -R codeigniter

Where userName is the username and codeigniter is the folder's name.
Comment: @spasSpasov: Could you please review my [edits](http://askubuntu.com/posts/874432/revisions) and also review the [editing help](http://askubuntu.com/editing-help) to improve the readability of your own edits in the future... **;-)**
Comment: @Fabby Yes of course, I will.
Comment: Sure.But the Answer will not be helpfull for new users.
Answer: When you do an install you have several directories.  Everything in /home/user/ can be changed to your user.  If you chown the others your system will break.  And when you chown you need to make sure you chown to the user and NOT just some name you choose.  It will be the same name as the folder under /home/. Do not change either permissions or ownership of anything but files under /home/user/.
sudo chown -v -R user:user /home/user/

The command will change the user and the group to the same at the same time.
Comment: And all files become executable permissions? sorry, that's a -1
Answer: The below is for individual file:
sudo chown user:user filename

For an entire directory it will be:
sudo chown user:user dirName

For recursive (i.e files and folders inside a folder):
sudo chown -R user:user dirName

Note: user is, if you do pwd under any Documents, you will see the path: /home/jhon/Documents. Here user is jhon.


Default account in Twitter app

Question: I have two Twitter accounts in my Twitter app, one personal and one for work. I added the personal one first, and it appears first in the Android Accounts settings. I want the Twitter app to use the personal account when it first opens, but it always defaults to the other one - can I change this?
Answer: I would suggest logging out of both and signing into your personal account first. Then the work account. This should then default to the first account you signed up with...
-edit (sorry for being so stupid)-
Try another twitter client such as twiddle (free) or talon (Paid). These may have the feature your looking for...
I can't comment as I don't have enough rep yet.
Comment: Unfortunately I've tried that on both my current and previous phones, adding the accounts both ways round. It might be alphabetical or something.
Comment: He stated clearly in the original post:  "I added the personal one first"
Comment: Updated answer to make it a bit better

Default account in Twitter app


Breaker feeding sub-panel causes other breakers to trip

Question: I have a 40 amp circuit feeding a sub-panel in the garage. Sub-panel has 5 breakers (GFCI/AFCI combo breakers) feeding outlets for holiday lights. Our AC compressor breaker started tripping last week, as did two other circuits in our basement.  The garage circuit was also tripping (in the sub panel, not the main), with nothing but a lamp and desk fan as far as a load on it.  I found that by shutting off the 40amp to the garage feed in the main panel, the AC unit and basement breakers were no longer tripping.  Coincidence?  Could the 40amp breaker be bad and causing issues within the main panel?  Or would it be more beneficial to start looking at the garage circuits themselves?  I have not yet tried to recreate the issue, but my plan is to go one circuit at a time in the garage, to see if I can get the AC breaker to fail again. (when it's not 95 degrees outside)
Comment: What kind of bulb is in the lamp?
Comment: Are the breakers tripping in the house GFCI? If the sub panel ground and Neutral are not isolated this could be a cause. Is this a new install (the sub) .
Comment: What make/model of breakers do you have (both main and sub)?
Answer: Wow, very mysterious.
First of all, if the AC unit trips a breaker, it may be the compressor is intermittantly having a hard start.  Mine was doing this in cooler weather, or at night.  Adding a hard-start capacitor to the compressor fixed it.
But your event looks more troublesom than that, as you have unrelated circuits tripping together.  What I would first guess is that you are having brown outs.  The brown outs could be caused by the AC compressor having a hard-start.  Or the brown-out could be caused by the grid voltage being low.
When a AC compressor starts, it acts like a dead-short for a brief moment, until the motor is spinning.  The unit starts in the "locked rotor" condition, and the locked-rotor current is usually many times that of the breaker, so a unit that has a 40 amp breaker might have an locked rotor amp  (LRA) rating of over 100amps.  Most breakers trip on heat, so they can take a load 3 or 4 times higher than they are rated, for a few miliseconds.
So if your AC is slow to start, it might hit your house with a 100+ amp load for a second, causing your house voltage to drop.  If the voltage drops, then many things you have plugged in with reactive loads will increase in current as the voltage drops out.  The breakers run off current only, and don't care that the current is caused by a brown out, so if the brown-out causes current to exceed ratings, breakers trip.
So the first thing I would do is tell your AC repairman you are popping the AC breaker from time to time, and ask him to investigate putting a hard-start kit on your compressor.  What the hard-start kit does it ads a little extra boost of start-up power to the compressor, so a tired old compressor can start easier, and avoid tripping the breaker.
Replacing the AC bereaker may be called for, but don't put one in that is larger than the name plate rating on the compressor.  The compressor will say on the nameplate how large a breaker you should use.  Don't put a larger one in, a larger breaker will not make a hard-start compressor better, it will make it burn-up quicker.  The only fix is a new compressor or a hard-start kit, never a larger breaker.  Of course that assumes it is your compressor.  It could be something else entirely, like a power grid brownout.
In my case, the compressor hard-start was only when it was cool outside, but that is just one odd case, most of the time a hard start compressor will hard start all the time, or only when hot, or only when the unit is short cycles, or only when it's been off for a while.  Your AC guy should know to look for hard-start when you mention the breaker tripping intermittently.  You should hear him talk about trying a hard-start kit even if you don't mention it to him, but that doesn't mean you can't suggest it to him anyway... if he thinks you know what is going on, he is less inclined to give you B.S...  If he is unscrupulous, he may suggest a compressor replacement first, but really a hard start kit is a better first move if a hard-start condition is suspected.


How do I get review for my first short story?

Question: I have wrote an initial draft of a short story.This is my first time. How do I get a review for it?
Comment: Hi, and welcome to Writers. Are you asking about finding a *beta reader* or an *editor*, someone who will critique your work to help make it better?
Comment: I had great luck with critters.org
Comment: @LaurenIpsum- yes
Answer: I'm going to assume you are looking for someone to critique your story, since you say this is your initial draft. I have two suggestions. Look in your area for a writing critique group (meetup.com may list one in your area or check your library bulletin board). The other is to check out scribophile.com -- you will need to critique other people's work first, to earn karma, and then you can post your work for feedback. You will actually learn from  trying to critique other writing, so this is actually a benefit. Good luck.
Comment: I also recommend that you go through your story on your own first, if you haven't already, and give it a sanity check and edits yourself. I don't recommend sending your actual first draft out to anyone. You may not wind up changing much, but that check for sore thumbs will serve you well.


Restart Galera Cluster - all nodes with same sequence number

Question: I have a 3 node Galera cluster running MariaDB on Ubuntu 18. I ran a few batch files to add data to the database, then shut down each node as this cluster is being relocated to a different subnet at a new location. After trying to bring the cluster back up, each node fails. Examining /var/lib/mysql/grastate.dat for ALL nodes show seqno = -1, safe_to_bootstrap = 0. I ran mysqld --wsrep-recover and ALL nodes report WSREP: Recovered position :100344, which is expected since the nodes were idle for sometime before shutdown.
The question is how to bring up the cluster again, I keep getting "Failed to start MariaDB 10.1.38 database server" when checking status. I set safe_to_bootstrap: 1 but that did not work.
Answer: The working fix for this was executing sudo galera_new_clusteron any node. I had the other pair shutdown when executing this, then started each in turn and the cluster was back up.
Comment: Better would have been to shutdown-move-restart each one, one at a time.


Remove gpkg delated QGIS

Question: I accidentally deleted a gpkg file from QGIS browser… I thought it was to delete the connection and the file was deleted… does anyone know any way to recover it? Does QGIS save deleted files somewhere?
Comment: Have a look at the recycle bin of your system. Normally, this is more of a question on the level of the operating system than the application you use. Files are hardly deleted at all, only intentionally overwriting them with random data really comes close to delete. So there are high chances you can recover your file(s). Search for "recover deleted files" for your Operating system.
Comment: My QGIS browser GeoPackage section lists geopackages with right-click options: "Remove Connection" and "Delete FOO.gpkg...".  The delete option asks if I'm sure I want to "delete /the/path/to/FOO.gpkg". If you deleted the file without it being clear it was the file being deleted, I'd file an issue with QGIS to clarify. Was it a poorly translated text? Personally I'm not sure something as dangerous as "delete" should be there.
Answer: I don't think QGIS saves a backup copy. If you are on a windows system you could try using the Recuva software, it's pretty straightforward.

Remove gpkg delated QGIS


Heating aioli as part of cooking or not

Question: Just learned how to make aioli a while back and I'm curious if it can be heated while cooking or if it is something intended for the end while plating.
Answer: It's generally presented in a small bowl or container at the table. I've tried using it for cooking, but not with great success. It just separates...
While it can make an emergency substitute for raw garlic or garlic powder in cooking I guess, I'd not call it a satisfactory alternative for either.

Generally in Spain I've seen it served mostly as a dip or spread with bread or toast (though it can also be used at the table like you'd use garlic butter, but again it separates rapidly when heated so is less than ideal).
Comment: Thank you.  I wanted to make a garlic aioli to put on Hasselbeck potatoes but perhaps I'll top them at the end.
Comment: In Valencia it's commonly served instead of mayonnaise with patatas bravas (although I suppose that's covered by your reference to dips) and as an accompaniment to paella.

Heating aioli as part of cooking or not


Spot pops after wudu

Question: Salam, I have acne on my face and after doing wudu some spots burst. Today I was doing wudu and when drying I avoided the spot but it burst and I wasn't sure whether my wudu was valid so I waited and wiped away the pus and blood. After that another one burst whilst doing wudu and I got fed up so I tried washing out the blood and only a very small amount was on the surface of it but it was dripping down. Is my wudu valid?
Comment: The prophet didn't renew ablution after a single point cupping, recorded by muhaddith darukatni. In cupping blood flows from cut.
Comment: So my wudu is still valid? Because it's annoying when it happens and I can't always prevent them popping even when I'm extremely careful
Comment: As per shaafae, hambali, salafi and shia pus and blood other than from 2 excrement openings doesnt invalidate Ablution
Comment: @Abdurrehman Salafi isn't a fiqh school of thought It's an aqeeda/madhab school of thought, sufis also follow shaafae, hanbali, and maliki, and hanafi fiqhs. Also, there are 2 major different fiqhs in shia and you just stated "shias" please tell the different opinions of both of them and the sunni hanafi fiqh as well. Also, add some evidence to your claims like Quran, Hadith, etc.
Answer: Salam,
In my opinion, your wudu is valid. Remember Allah (swt) made wudu simple for us, and we aren't supposed to feel frustrated doing it. Some of the scholars said that if water (pus) from wounds is a small amount, it does not invalidate wudoo, but if it is a large amount then it does invalidate wudoo'.
Hope that helps.
MuslimGap
Comment: This helps, jazakallah khair.

Spot pops after wudu


Footer Link or Site Map

Question: I am creating a site map for a website.I have recently come to know that instead of site map I can give footer links.So I am confused whether to have a site map or footer links or both.Can anyone suggest me? (considering both Search engine optimization and users navigation)
Answer: When you submit sitemap to google - googlebot will visit your site more frequenly, and when you create new site it will index it sooner.
Answer: Adding a sitemap will not damage your website. Even with a good set of footer links it's good practice to submit your sitemap to Google et al.
Considering user navigation though I must say a good footer can prove a real good tool to show users what's what and how to find it. A footer isn't a sitemap though, just a summary usually. So why not add both?

Footer Link or Site Map


Enabling Jumbo Packet support on Hyper-V internal network NIC

Question: I have a Hyper-V setup where guest OS'es accesses the host/parent OS via an Internal Network. I've noticed that "Microsoft Virtual Machine Bus Network Adapter" has support for Jumbo Packets and disabled by default. Does enabling this setting, both on host and the guests, makes any performance boost of network activity? Thanks!
Comment: AND ALSO: Is there any possibility of data corruption/loss if the software  doesn't expect that large packet size for network transfers?
Answer: It depends greatly on the kind of I/O you're doing. It works great for iSCSI and FCoE because those protocols rely on a data frame size larger than the standard 1500b MTU for Ethernet. For regular old file transfers, the improvement isn't always apparent. And for databasy stuff that tends to be smaller than 1500b anyway, it doesn't do a thing. It's generally kept off by default because it minimizes things that can go wrong.
Where jumbo packets really do help is that it allows the TCP conversation to start at a higher base throughput when dealing with larger transfers. No need to negotiate window size, when what you're passing can fit in a 4Kb packet.
Comment: The type of I/O I'm doing in this case is database (MS SQL Server) and file transfer over a Windows share.
Comment: In that case, the database isn't likely to notice any difference in performance. The file transfers might, but it depends on how large the files are.
Comment: I enabled 9K jumbo frames on a Hyper-V host's virtual adapter and now I cannot RDP into it.  Hmmn.
Answer: It would increase your network performance, if everything on your network is configured for it and your switches can handle it. It's mostly used if you're running iSCSI.
Good explanation: http://blog.allanglesit.com/Blog/tabid/66/EntryId/55/Enabling-Jumbo-Frames-on-Hyper-V-2008-R2-Virtual-Switches.aspx


How to add super admin to all sites

Question: Is there a way to add super admins to ALL sites without having to add them to each site individually? My group of super admins needs access to all sites.
Answer: Super admins do have access to all sites, but they don't show up in "My Sites" by default, which I imagine is where you're looking. They'll want to go to the network admin (/wp-admin/network/, then go to all sites from there, then find the site they want to edit and click "Dashboard" (which appears on hover).
I like to think of "My Sites" almost as favorites, and only add myself to a site when I'll be accessing it frequently, as it reduces the list I have to pick through.
Does that make sense and clear up your question?
Answer: Or For adding your sites on "My Sites" if you've missed them, then you can add them by go to
Network Admin > Dashboard > All Sites > Edit Your Desired Site > Users (Tab) > Add Existing User > Add your desired existing username and role it as "Admin"
Regards.
Comment: I hate when important UI is below the fold.
Answer: I manage multisites with 50+ subsites.
I have multiple super admins and editors.
I installed and activated this plugin:
https://wordpress.org/plugins/wp-multisite-user-sync/
Went to a user at the network level,
clicked the Sync All box,
all subsites instantly became automatically checked in a list.
When I saved the user and
went back to Users the
user had access to all subsites.
I love it when something (esp. plugins) do what they say they will do OOTB.
Chris

How to add super admin to all sites


Continue to read iPhone accelerometer data while screen is locked (manually)

Question: I know this issue has been discussed before as in: Enable iPhone accelerometer while screen is locked
I tried the solution mentioned in the post, including adding the   DeepSleepPreventer module, as well as enabling proximity sensor as suggested in the answer Enable iPhone accelerometer while screen is locked by adding:
<code>UIDevice *device = [UIDevice currentDevice];
device.proximityMonitoringEnabled = YES;
</code>
However, as soon as I manually lock the screen on my iPhone touch, the accelerometer stops sending data. I'm using iOS SDK 4.3. Did I miss anything?  Any help would be greatly appreciated.
Answer: It's impossible to get accelerometer events on locked ios devices via SDK


How long was my flight delayed

Question: What was the take off time of west jet flight number ws2 on June 23 2016 from Gatwick airport. I want to claim compensation and can't remember what time we departed.
Answer: According to FlightAware, the flight departed at 2:44PM and arrived at 4:31PM. It was scheduled to depart at 10:55AM and land at 10:31AM.

How long was my flight delayed


Salesforce Mobile return to account details

Question: I have a custom button that will update a field in the account detail page which will input the long and lat but when I tried it in Salesforce1 mobile,it goes to a blank page. How can I set the page to redirect to view the account in mobile.
It seems to work in a desktop.
public with sharing class GetGeolocationController {

    ApexPages.StandardController sc;

    Public decimal longT{get;set;}
    Public decimal latT{get;set;}

    public GetGeolocationController(ApexPages.StandardController sc){
        this.sc = sc;
    }

    public PageReference savePositionMethod(){
        Account acc = (Account)sc.getRecord();
        acc.Longitude__c = longT;
        acc.Latitude__c = latT;
        update acc;

        return null;
    }

}

Answer: Your page is not redirecting, so it's probably best if you changed:
update acc;
return null;

To:
return sc.save();

This will allow you to redirect to the account page after a successful save.


is it possible to get next_post_link

Question: I have come across a problem whilst using the next_post_link() function.
It seems that this function automatically echo's, for position reasons I need this to just return the link. Is there any available function or workaround that I can use to achieve this result?
Answer: try to work with http://codex.wordpress.org/Function_Reference/get_adjacent_post;
example:
$next_post_link_url = get_permalink( get_adjacent_post(false,'',false)->ID );
$prev_post_link_url = get_permalink( get_adjacent_post(false,'',true)->ID );

Comment: Bear in mind this will only get the adjacent *URL* - you'll have to generate the HTML like `next_post_link` does yourself.
Answer: If you take a look at the source, next_post_link is just a wrapper for adjacent_post_link.
Unfortunately, this function doesn't take any form of 'echo' parameter, so you'll either need to replicate the code in your own function & return the value, or catch it in an output buffer;
ob_start();
next_post_link();
$next_post_link = ob_get_clean();

Answer: Actually, yes: just use get_next_posts_link(), using the same arguments.
The next_posts_lin() function simply echoes the returned value of get_next_posts_link().
EDIT
Erm, nevermind. I mis-read the function name.
You could use get_next_post(), which returns a post object; then you could get the permalink from the returned ID object parameter:
$nextpost = `get_next_post( $args )`;
$nextpostid = $nextpost->ID;
$nextpostlink = get_permalink( $nextpostid );

is it possible to get next_post_link


Can I create pbr textures from blender and export it to Unreal or Unity?

Question: I would like to experiment with pbr on blender, using the pbr feature, I know people who export from substance painter  as albedo map, normal map, specular ,etc from substance to another engine such as unity or even unreal, I noticed that "whatever happens in cycles dies in cycles", but can my luck change ?
if I create Pbr maps and export in from blender cycles-Pbr to an engine?
pd : Cycles nodes does not exist in another engine! ,but pbr is an exception?
Answer: "PBR" is a buzzword that refers to some shader design conventions, such as respecting energy conservation, using fresnel reflections, and such. "PBR Textures" are merely textures intended for some shader that follows these conventions. As Cycles is a render engine itself and not a texture authoring tool, it won't be helpful in authoring textures. You can certainly paint textures using Blender's texture painting function that target a PBR shader, but as Blender doesn't have a PBR viewport shader you will won't have the instant viewport feedback of how your textures are looking. You have to export them out to your game engine, doing some "guess and check" with the values.
Comment: it is like guess and check? it means I should create some texture maps and export it to another software , apply the textures to the slot and check them in real time?
Comment: Yep. Once HP can see what they look like, you can go back and paint more, or adjust them with an image editor such as GIMP or Photoshop. It's not as efficient as working in dedicated texturing tools like Substance, but it gets the job done
Comment: but can I create an albedo, spec map ,normal map ,height map, oclution map in cycles? and then bake every slot of this textures and save it and expor them? I like photoshop or gimp to create every map , but prefer to make them in cycles and search the way to make more realistic a Spainter.
Comment: You could, but it won't be very easy or intuitive, again, you won't have any preview for what you're doing. These textures are just images (and with the exception of normals and occlusion, are usually not baked, btw). You can create them in any tool that creates images, it's just a lot harder without a dedicated tool like Substance. Cycles is a render engine  With the exception of baking, it does not create textures.


basics of charging a Lead Acid battery?

Question: I want to build a poor man's portable power station. There are only two things I need to run off of it: a 240watt fan to blow up my mattress and a CPAP machine all night that is rated at 12v 3 amp. I am pretty sure a mid-size 12v lead acid battery will get the job down, the only question is the recharging. I would hook it back up to my car each day and recharge as I drive around. I just don't want to overcharge the battery, so I am looking for some way to monitor the charge and stop the charge once it is topped off. How do I do that?
Comment: It is very dangerous to keep this battery in your sleeping space especially if it's being used. An AGM battery would be safer but still not recommended.
Comment: So what do you recommend?
Comment: I would recommend finding an AGM battery To do what your intending to do. It is extremely safer than lead acid battery.
Answer: While the answer by wilkvolk is accurate for recharging a battery, I'm pretty sure you won't need to go through all of that to do what you need it to do. If the battery is hooked up to your vehicle and is being recharged by your on board charging system (ie: alternator), and the on board charging system is functioning correctly, you shouldn't have to worry about when to take it off the system. The system has a built in regulator which won't allow your battery to be overcharged.
If you are hooking a separate charging system to your secondary battery, then you'd want a charger which is a maintainer (ie: Battery Tender) as a maintainer will charge it to capacity, then keep it topped off as long as you're not using the battery, without overcharging.
Another consideration is you'll want to use a deep cycle battery for your needs. These provide a continuous amount of power which allow for a long duration. These will stand up to the abuses you plan on submitting it to. From this website, I deduced you'll need one of 64AH (flooded style battery) size or bigger to supply a 3 Amp load for eight hours. AGM or Gel (which would be better suited to your needs because they do not emit gasses when recharging or discharging) could be smaller.
Answer: Step 1
Wear protective gloves and goggles before you rebuild the cell structure of your 12- volt battery. You need to access the cell reservoirs that contain highly toxic sulfuric acid that immediately burns on contact with skin.
Step 2
Place your 12-volt lead-acid battery in a battery tray on a stable work surface. Remove the six battery cell caps on top of the battery. Either unscrew the caps using your fingers, or if the caps have slots, use a screwdriver. Each cell produces 2 volts and is linked in series to produce 12 volts. Put the caps to one side.
Step 3
Check the fluid level inside the six cells. It's likely you find the fluid level is below the minimum mark on the inside of the cells. This means the process of the electrons flowing from one lead plate to the other inside the cell has stopped. The fluid, called electrolyte, is sulfuric acid and enables a chemical reaction to take place between the positive and negative plates when the battery gets a flow of electricity from the car's alternator or battery charger. If the fluid level drops below the minimum marker, the plates would be exposed, and they would corrode over time.
Step 4
Rebuild the chemical cell structure by replacing the fluid. Use distilled water and top each cell up to the maximum marker inside the cell. It's important that you don't overfill the cell as during the charging process the cells get warm and the fluid expands. The distilled water will mix with any existing sulfuric acid in the cell and start to rebuild the chemical structure. However, for the process to begin the battery needs electrons to flow between the plates created by a small electric current from a battery charger.
Step 5
Replace the cell caps using your fingers or a screwdriver. Don't over-tighten.
Step 6
Put the spring clamp on the end of the black battery charger cable onto the negative battery terminal. It's clearly labeled "Neg," "-" or may have a black plastic ring around the terminal pole. Put the spring clamp on the end of the red battery charger cable onto the other battery terminal. It's clearly labeled "Pos," "+" or may have a red plastic ring around the terminal pole.
Step 7
Set your battery on the lowest setting possible; often called "trickle charge." Rebuilding the chemical structure inside the cells takes time and it's important the process is done slowly so the distilled water gets more acidic. As acidity increases so electron flow increases between the lead plates. Any corrosion on the plates caused by lack of electrolyte dissipates rebuilding the structure.
Step 8
Plug in your battery charger and turn it on. Check the setting again to make certain it's on the lowest possible. Leave the 12-volt lead-acid battery to charge slowly for 36 hours. During this time, the energy retention of the plates increases as chemical activity changes. You can check if the rebuilding process is working by touching the side of the battery after about 12 hours. You would find it's getting warm indicating that the battery is taking a charge.
Turn off the battery charger after about 36 hours. Disconnect the battery cable clamps from the battery terminals. Place your hand on the side of the 12-volt lead-acid battery, and you find it's fairly warm to the touch meaning the chemical cell structure is rebuilt, and your battery has retained a charge.
Tip
If you find the battery is cold, or only part of it is warm, after the charging period you probably have to resign yourself to buying a replacement as the plates in the cells were too corroded and couldn't rebuild.
Warning
Only use distilled water to top up the battery cells. Regular tap water contained minerals and other impurities that prevent electron flow, reduce acidity and attach to the lead plates causing corrosion.
More on here--->https://itstillruns.com/rebuild-12-volt-leadacid-batteries-7841854.html

basics of charging a Lead Acid battery?


Keyboard lag, lost keystrokes, and high fan speed in Filevault's EFI pre-boot unlock/login screen (MacBook Pro 2017)

Question: I have a MacBook Pro (15-inch, 2017) with macOS 10.15.4 and FileVault enabled.
When I boot the machine, the Filevault's pre-boot unlock screen appears as normal, prompting me for my password.
Now, while the system remains on this screen, and all the way until the correct password is recognized, the following symptoms occur:

Built-in fans start spinning at top speed within seconds from boot (which, I assume, indicate high CPU use).
Built-in keyboard very noticeably lags: key inputs are buffered before actually appearing in the password text field and some of them are disregarded altogether.

Now, this presents a very practical problem: sometimes it takes me more than 10 attempts to actually get my password to be recognized.
Even worse, with each mangled password the screen almost seem to work slower and slower, all very reminiscent of high-CPU-load situations.
I usually type my password fairly quickly, but any other password prompt within the OS takes it without a hiccup. And even when I slow down, lost keystrokes are still a problem and are hard to detect in a password field, where actual characters are not shown.
The problem repeats itself between macOS installations, and is definitely not caused by system still booting up in the background: as I said, the apparent high CPU load always continues until the password is recognized and stops immediately after.
What exactly does Filevault do on that screen? Is it some sort of deterrence against hacking attempts? Can this behavior be tweaked?
Comment: That's not normal behavior and sounds like a hardware issue given that it still exists *after* reinstalls. Try installing with FV turned off to see what's going on
Comment: @Allan Just to be clear, you are suggesting re-installing macOS with FV turned off? A month ago I did a clean install from a USB stick, completely wiping the previous HD in the process. Would that count?
Answer: I would try resetting  NVRAM: https://support.apple.com/en-us/HT204063
Comment: I'll take a poke at that as soon as I can, will post the results. Thanks for the suggestion.


Best NFS scenario to both read and write at certain times?

Question: The problem that I'm facing is that I have an NFS NAS that I use to store and export a home directory, media files like music, movies, etc.
The critical things are backed up, so spare the comments about "If you can't afford to lose it back it up rule of 3-2-1." Got it. But that's not happening for little ol' me and 7TB of data, so I backup what I need to.
So here's the thing, I like being able to export those directories to other computers so that I can read, and sometimes write, but I recently rm -rf . /'d a bunch of stuff on my laptop and thankfully at the time they weren't mounted. I also realized, and tested recently, that doing something like that with the way I had NFS mounted, would have resulted in wiping everything out remotely, as well. (again spare me the lessons about rm, I got it I just have some really old bad habits to get rid of)
The ways that you can secure it are obvious. Only use the anon user, or export as ro, or mount as ro on the client computer. I don't like the latter option because it gives control to an attacker should they gain access to my network.
I need a way to satisfy the following conditions:

Directories can be mounted by the client system, but are not normally writable, but are readable.
At a later point, the user decides that they need to edit something and they do something to make that possible from the client computer.*

* meaning that I don't want to SSH in unless I absolutely have to
The only thing that seems to work functionally the way I'm thinking is to use no_root_squash and mount the filesystem ro on the client system, then -o remount,rw when I need to change something, but like I said earlier I feel that has serious security implications.
Answer: IIUC, you want to normally be disabled from deleting or writing to the media files, but occasionally want to add a file, whether or not over the NFS link.
For that purpose, why putz with mount options?  Why not set the media directories to mode 555?  As owner, use chmod u+w dirname && cp filename dirname/; chmod u-w dirname to update the directory as needed.


Please check the sentence

Question: The sentence is "The application of this capability range from - , - , and -, among others." Is the sentence grammatically correct.
Comment: "ranges"; *application* is singular.
Answer: While this sentence is grammatically correct, I'm not sure what you would be referring to and it feels quite unnatural.
As I understand the sentence, you are talking about how one would apply certain capabilities.
However, the word choices make me think that you are intending to talk about the way someone might use a computer application. In which case, I would rephrase the sentence as: "The capabilities of this application consist of _, _, and ___, among others."
Here I use the plural, 'capabilities' because the application has more than one of those.

Please check the sentence


How to set default value in catalog category add products to categories in position column

Question: I have attached screenshot, I want to add default values in position, for example when I add product in category position should show 100.
Thanks in advance
Answer: I have set my default position for products to 100 by using this patch. This sets it to 100 when a product is added to a new category.
<code>    @package magento/module-catalog

diff --git a/Controller/Adminhtml/Product/Initialization/Helper.php b/Controller/Adminhtml/Product/Initialization/Helper.php
--- a/Controller/Adminhtml/Product/Initialization/Helper.php
+++ b/Controller/Adminhtml/Product/Initialization/Helper.php    (date 1666682384544)
@@ -513,7 +513,7 @@
             $categoryLink = $categoryLinks[$categoryId] ??
                 $this->categoryLinkFactory->create()
                     ->setCategoryId($categoryId)
-                    ->setPosition(0);
+                    ->setPosition(100);
             $newCategoryLinks[] = $categoryLink;
         }

</code>
Comment: Thanks, but I had done this I was overriden some magento core functionalities.


Keyframes selectable, can't move or delete them

Question:
I am relatively new to Blender animation.
I find myself unable to move or delete keyframes in the Dopesheet Editor.
I also see that they have a ghosted appearance.  How do I change these keyframes (back?) to an editable state once more?
Comment: hello, could you please share your file (the object itself, not the rest of your scene)? upload and copy paste the URL it will create: https://pasteall.org/blend/
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: The question was specific.  I can't edit these keyframes and -don't know- why. Help me to  learn possible actions that could have led to the problem.  It's as concise as you would expect in this kind of new-user question.

That said, I figured out what was happening and will post the answer to the question as-stated:  "How do I change these back to an editable state?"
Answer:
I figured it out.  I had Appended the character Armature from a different .blend scene file.  Whether by accident or design, this Action (highlighted in the sample image) came in as "linked".  This means it is "linked" to the data in that other file and would only change if the action were changed in the source file and then re-evaluated here, locally.  The benefit of this is that the animation could be stored in an Action, re-used in multiple other scenes and then updated in one place, with the change then propagating out to the Linked scenes.

In my case, looking at the list of Actions revealed one that had a small icon next to it of a small chain (see image).  In the second image, I have selected that Action and hovering on the chain icon revealed that I could "click to make local".  I did so and can now edit the keyframes as-expected.
Less than one year into my transition to Blender, I see that I have a lot to learn.


A person who uses a dog for hunting

Question: Is there a specific name for a person who uses dogs for hunting or other practical means such as tracking? Something like falconer for people using birds of prey?
Comment: It's not a 'dog hunter' because that would imply that they hunt for the dogs, not using them. I've heard fox hunting (hunting for foxes) called 'beagling' because beagles are used. But I've never heard the people following the beagles on horseback called 'beaglers'.
Comment: There might be an obscure term, but I don't recall any sort of common one.  "Tracking" would usually imply a dog, and knowing what sort of hunting is being done might suggest whether a dog is used or not, but nothing certain.
Comment: According to Joe Bruchac, the Iroquois term is "[Two Legs and Four Legs](http://rednation.org/index.php?topic=298.0)."
Answer: If you are talking about hunting, then a person in charge is a Master of Hounds.
This is a term usually used in the field of hunting to hounds which usually means fox hunting or drag hunting.  A pack of dogs follows the scent of the animal or a deliberately laid scent (a "drag").  The dogs are followed by the hunters, often on horseback.  The Master trains and looks after the pack.
If you are talking about using a trained dog for other tasks, the term is simply a Dog Handler.
This is used for sniffer dogs, police dogs, guide dogs and other forms of working.
Comment: "If you are talking about hunting": 'hunting' has a far wider meaning than just fox-hunting with a pack of hounds, and I doubt that @Fenisko had this in mind at all.
Comment: Yeah, keep in mind that a dog might be used in duck hunting, racoon hunting, and several other common forms of hunting (in the US).  In most cases these are one hunter/one dog, so terms such as "master of hounds",  "dog handler", or "houndsman" place the emphasis inappropriately.
Answer: There seems to be a term that some people who hunt with dogs use among themselves; Houndsman.
The term isn't quite a simple as being a person who hunts with dogs, so much as a person who hunts with dogs in a way that purist hunters-with-dogs approve of.
This quote is from a forum for Big Game Houndsmen

I know this may be a bitter pill to many: a lion hunter does not make
  you a houndsman, and bear hunter or a cat hunter or a coon hunter does
  not make you a houndsmen. You are a hunter a possibly a hound
  enthusiast. You will know when you are a houndsmen. No longer is it a
  hobby, no longers is it a sport, it is a way of life. And it is not
  for everybody.

This quote clearly suggests that the author isn't familiar with any other generic words for 'hunter-with-dog' as he classes anyone who hunts-with-dogs but isn't a houndsman as a mere hunter or hound enthusiast.
I can't find this term defined in any dictionaries I can access, and there is the added confusion that there might be a more nudge-nudge-wink-wink type definition of a houndsman being one who enjoys the chase of cougars but doesn't want to be tied down.
Answer: There is some debate in the USA but in Europe and the UK these things have been decided already. The use of dogs to track, flush out, chase, and take down deer, fox, rabbit, or other game animals is considered "hunting". Whereas the use of firearms to take down game fowl or smaller game animals is considered "shooting".
The difference and implications are quite clear. If your weapon of choice is a canine, you are considered as a "hunter". Sansguns. If you are using a pistol or rifle you are considered as.... A hunter also. lol
The houndsman is the man responsible for the care, upkeep, housing, and feeding of the hunting dogs. So, no. No specific term comes down from the old country.
Comment: This would benefit from a cited source.  Please take a moment to see the [help] and take the site [tour].

A person who uses a dog for hunting


How can I get a list of all owners of an ERC1155 NFT by using a web3 call?

Question: With ERC721, there's the 'ownerOf' function that takes a non-fungible token's id and returns the owner address, but ERC1155 doesn't officially require that a function like that be implemented. I made an ERC1155 contract through rarible.com, and I can't find a function implemented there either. Both rarible.com and Opensea.io marketplaces show the owners of ERC1155 NFTs, so I know it's possible, but I can't figure it out.
Answer: UPDATE: Now you can use the Moralis API <code>/nft/{token_address}/owners</code> endpoint to get this directly.
This is quite difficult, as Anupam pointed out you would have to go through all the transfer events and save them to some sort of database. And this takes a lot of effort when you want to do it with a lot of big NFTs. I've never found an easy solution myself.
Full disclosure: I work at Moralis, and we've gotten a lot of these requests. And we're currently building this functionality, so hopefully in a few weeks you will be able to get this with only one line of code through the moralis SDK.
I'll edit this post once I know the full specification of this.
TheGraph is also an option, but it's a little bit cumbersome.
Comment: Moralis is dead :(.

What TheGraph subgraph are you talking about specfically? Also, how to do this during development on truffle?
Comment: Moralis is not dead. But the API endpoint changed in the latest update to API version 2.0. The new endpoint for this is /nft/{address}/owners. I will update my original answer.
Comment: lol moralis is dead; It broke on mint day for 20 concurrent users...
Comment: Please reach out to our suppor team if you need any assistance with your specific application.
Answer: If you want an ownerOf in ERC1155 youll have to implement it yourself.
rarible and opensea use indexing services like thegraph.com to keep track of transfers and who currently owns the token.
Comment: Is there a particular subgraph from thegraph.com that tracks the nft transfer? I'm not sure which particular subgraph to use
Comment: @lampbottle create your own https://thegraph.com/docs/developer/quick-start
Answer: @Dylan pointed it out correctly.
The openzeppelin implementation doesn't have any function for this.
One other way to do this is parsing events, as they are emitted on each transfer. This may get computationally expensive, so you can use TheGraph for indexing purposes.


Could the price drop between July and September 2011 have been caused by a bot?

Question: In July 2011, 1 BTC was trading at above $10 USD. By September, the price of 1 BTC had fallen over 50%, and at the time of writing (October 2011) 1 BTC is trading around $2.50 - $3.00 USD.
In a forum thread one of the pool operators for bitcoinpool claims this is due to some bot forcing the prices down:

Fairuser detected a buy/sell bot on the better portion of exchanges
  (currently, only Bitmarket (EUR) seems unaffected) that is
  consistently keeping the value of BTC low while it's generating tens
  of thousands of dollars worth of transactions across the exchanges at
  a profit of 2 - 40 cents per transaction. We're still unsure if it's
  intentionally dropping the price, or if it's just a side-effect of the
  way the bot is designed.
Either way, the bot is entirely responsible for the price drop from
  $10 USD to $5 USD.

Is there any evidence of such a phenomenon, and if so, what could be done to stop it?
Comment: Is a bot illegal to be used in a stock market?
Comment: Also, see this question: [Why have prices fallen so drastically around October 2011?](http://bitcoin.stackexchange.com/questions/1659/why-have-prices-fallen-so-drastically-around-october-2011)
Answer: Since the bot exists, and the people who wrote it presumably wish it to perform every transaction it performs, it reflects real supply and real demand. Why would you want to stop it? There is nothing inherently good about a high price.
Personally, I think the drop in value was due to the bursting of a speculative bubble. The price was previously kept high due to press attention that made people think Bitcoins might be a good investment. As soon as everyone who was going to be brought in by the hype was brought in, the demand started to drop. This caused a small price slide, which induced a lot of panic selling from people who thought the speculative rise would continue forever. Once the price starts dropping at the end of such a bubble, more and more people try to sell out to minimize their losses. Once everyone who expected a short-term profit sells out, the price stabilizes.
We're now back at that relatively stable floor, waiting for the next hype cycle to start another speculative bubble. Until Bitcoin's price is driven by its use as a real medium of exchange, this pattern is likely to repeat over and over.
Comment: Unfortunately I was caught up in that bubble and bough a bunch of BTC at ~$8-$10 each. So yes, you're right, there's nothing inherently good about a high price, but this does little to make me feel better about my foolish investment LOL ;-)
Answer: I've heard this mentioned so many times by so many different people- but the only real cause is supply and demand.  If a "bot", or "manipulator", or whoever you want to call it, was selling off so many coins that it has the effect of lowering the price... then there is not enough demand to satisfy the supply, and so the price drops.
Answer: A bot can hardly cause a noticable long-term price decrease. To do this, it would have to use an algorithm. The algorithm has to operate along the goal of the bot. Normally, the goal will be maximum profit. If the bot tries to bring the price down, it has to buy high and to sell low; this does cost money. Worse, if someone else suspects a but doing this, he could write a bot which buys low and sells high, making a lot of profit. The net effect would be that a hughe amount of money is transferred from the owner of the first bot to the owner of the second bot.
This isn't to say that prices cannot be influenced or even manipulated. But this has a lot to do with psychology, and apart from that this works only at specific times, bots are not good at this.
Answer: A bot has one advantage over humans: speed. Other than that, it is not that different from a human.
That said, it is not very relevant whether a bot or human sold coins at a low price. Someone accepts selling this low, thus the price is this low.
The decline of the price was a classic economic bubble. The process started in May at the latest, from there up until October the market was dominated by the dynamics of inexperienced masses speculating wildly. If you want to understand why things happened the way they did, read on economic bubbles.
Answer: If there is a bot running a lot of transactions on the system, one could find it out by analysing all the transactions and looking for some emerging patterns. This, however, is very difficult. One interesting example I can think of that is related to that is a TED talk about the stock exchange (I recommend seeing it).
A sure way to stop that would be to disable bot operations on the exchanges, but that might do more damage than the bot. Alternatively, one could make a second bot to counter the first one and hopefully bankrupt it, but that would also be bad. Probably the best thing one can do is not trade on websites that are botted and organically shift the business to exchanges that are not facilitating automatic transactions. But as that isn't too likely to happen, things will probably stay this way.
As it was mentioned in the other answer - having a bot on the exchange is not a bad thing in itself.
Answer: I think the single biggest event that triggered the downward spiral of the price was the theft of all coins from MyBitcoin.com. Whether it was "Hackers" that took the coins or the site operator himself is as yet unknown, but they were certainly stolen.
MyBitcoin attempted to solve the two main issues of Bitcoin in its current form:
1 - You need to be logged on to the computer containing your wallet if you want to spend your coins
2 - The time taken for a transaction to "confirm" is much too slow for most types of internet transaction.
MyBitcoin represented a real hope of solving both issues by offering users an online "E-Wallet", coins from which could be transferred instantly to other MyBitcoin users.
When the site was taken down it had just under 500'000 Bitcoins in its vaults, more than 5% of all the bitcoins in the world, which at the time was worth around $5m. The thieves got away with the single biggest online theft in history.
This had two effects:
1 - Many users lost all confidence in the Bitcoin project. If a site so big and seemingly officail as MyBitcoin could be taken down, what hope is there for anyone?
2 - The theives had to sell the coins they stole, selling quickly for well under market value and setting off a domino effect which led to a big a price drop.
Personally, I don't think Bitcoin will ever be worth more than $5 again, even $4 seems a bit too much to hope for. With many alternative cryptocoins available with better security, more features and stronger support from developers than Bitcoin, it seems like it has no real future.
Bitcoin will be remembered as the coin that started it all, but another coin will surely take its place soon.


How do you get p5.js into a website?

Question: I have searched nearly all over the internet, and i've gotten pretty close to an answer, but I still can't figure out how to use p5.js in a website. To be more specific, i want to be able to perhaps create a weebly, and have it display p5 code. i know it involves the website loading the p5.js through a file or the online file, and the sketch.js. If there is no way to use p5.js on the web, is there any way to use processing code in general(or something similar) on the internet? Thanks
Answer: Follow these instructions: http://p5js.org/get-started/
Or these instructions: https://github.com/processing/p5.js/wiki/Embedding-p5.js
In other words, you need to create an html file that uses p5.js, which you should already have.
Then you need to upload that html file, along with any resources you're using, to some kind of web host.
You might also want to check out Processing.js, which comes with the standard Processing editor.
Answer: creat html file and a sketch.js file
in your html file you can put in a starter template and then add p5js in the sketch.js
check the docs here

// All the paths
var paths = [];
// Are we painting?
var painting = false;
// How long until the next circle
var next = 0;
// Where are we now and where were we?
var current;
var previous;

function setup() {
  createCanvas(720, 400);
  current = createVector(0,0);
  previous = createVector(0,0);
};

function draw() {
  background(200);

  // If it's time for a new point
  if (millis() > next && painting) {

    // Grab mouse position
    current.x = mouseX;
    current.y = mouseY;

    // New particle's force is based on mouse movement
    var force = p5.Vector.sub(current, previous);
    force.mult(0.05);

    // Add new particle
    paths[paths.length - 1].add(current, force);

    // Schedule next circle
    next = millis() + random(100);

    // Store mouse values
    previous.x = current.x;
    previous.y = current.y;
  }

  // Draw all paths
  for( var i = 0; i < paths.length; i++) {
    paths[i].update();
    paths[i].display();
  }
}

// Start it up
function mousePressed() {
  next = 0;
  painting = true;
  previous.x = mouseX;
  previous.y = mouseY;
  paths.push(new Path());
}

// Stop
function mouseReleased() {
  painting = false;
}

// A Path is a list of particles
function Path() {
  this.particles = [];
  this.hue = random(100);
}

Path.prototype.add = function(position, force) {
  // Add a new particle with a position, force, and hue
  this.particles.push(new Particle(position, force, this.hue));
}

// Display plath
Path.prototype.update = function() {
  for (var i = 0; i < this.particles.length; i++) {
    this.particles[i].update();
  }
}

// Display plath
Path.prototype.display = function() {

  // Loop through backwards
  for (var i = this.particles.length - 1; i >= 0; i--) {
    // If we shold remove it
    if (this.particles[i].lifespan <= 0) {
      this.particles.splice(i, 1);
    // Otherwise, display it
    } else {
      this.particles[i].display(this.particles[i+1]);
    }
  }

}

// Particles along the path
function Particle(position, force, hue) {
  this.position = createVector(position.x, position.y);
  this.velocity = createVector(force.x, force.y);
  this.drag = 0.95;
  this.lifespan = 255;
}

Particle.prototype.update = function() {
  // Move it
  this.position.add(this.velocity);
  // Slow it down
  this.velocity.mult(this.drag);
  // Fade it out
  this.lifespan--;
}

// Draw particle and connect it with a line
// Draw a line to another
Particle.prototype.display = function(other) {
  stroke(0, this.lifespan);
  fill(0, this.lifespan/2);
  ellipse(this.position.x,this.position.y, 8, 8);
  // If we need to draw a line
  if (other) {
    line(this.position.x, this.position.y, other.position.x, other.position.y);
  }
}

Answer: If you are creating your sketch using the editor for Mac or Windows (Version 0.5.7 (0.5.7) as of this writing), go to "Save As" and the editor will export your "web ready" files.
Your saved file will have the same name as your sketch and will include an index.html and sketch.js file along with a "libraries" folder.   You can post the .html and .js files as-is and inspect the .html for links to the p5 .js libraries.

How do you get p5.js into a website?


Is a diopter recommended for a 56mm lens?

Question: I have a Sigma 56mm f/1.4 and Sony a6400.
I'm looking into buying a diopter because it seems to be relatively cheap and can reduce the minimum focus distance while also zooming in, which I both want.
Which diopter specs should I look for? I want <25cm focus distance if that's realistic.
Comment: Whatever the solution (close-up or extension tube), remember that your camera becomes myopic and won' t be able to focus at "normal" distances making it hard to to "close in" when shooting outdoors.  A true macro lens is a lot more usable.
Comment: @xenoid The OP mentioned "relatively cheap", and typical macro lenses, while of course delivering superior results, don't fall into that category.
Comment: @RalfKleberhoff I know, this is why it's a comment and not an answer. The OP should know what s/he loses by not going the more expensive way. This said, 2nd-hand off-brand lenses (Sigma, Tamron, Tokina) are good and quite cheap.
Comment: Related: [How do I choose a camera for macro photography without considering special lens?](https://photo.stackexchange.com/q/47116/15871) and [How can I take a macro shot without a macro lens?](https://photo.stackexchange.com/q/4741/15871) and [What are the biggest differences between Reversal Rings, Extension Tubes and Macro Lenses?](https://photo.stackexchange.com/q/19009/15871) and [What am I losing when using extension tubes instead of a macro lens?](https://photo.stackexchange.com/q/9169/15871)
Answer: Because of the very simple optical design of the diopter (or, technically more correct: close-up lens), the image quality will suffer a lot, e.g. from heavy chromatic aberration. The results will be like using the cheapest, crappiest lens instead of your quality Sigma one.
Instead, I'd recommend an extension tube. IMHO, they are a much better value for the price: better image quality and much more flexibility.
An extension tube will not interfere with the optics of your lens, just use it a bit outside of its designed distance range. From my experience with other lenses, I'd expect quite decent results from your 56mm prime.
A 10mm extension tube, used with your 56mm prime, will give you a focus distance range of roughly 20 to 30cm. And they often come in pairs or sets, so you can achieve various extension values, meaning even closer distances possible.
And they only have to match your body mount, and can thus be combined with whatever lens matches your body. The close-up lens, on the other hand, can only be used on lenses with the same filter diameter.
When shopping for extension tubes, just make sure that they are "automatic" ones, connecting the camera signals to the lens, and that they have a decent mechanical quality (e.g. looking at user ratings in online stores). My set for a Canon EOS-M was in the $20 price range, and I'm completely satisfied with them.
Comment: Good close-up lenses are not that bad but get very expensive quickly for large filter sizes. Extension tubes are a better solution (unless of course you have a compact/superzoom camera).
Answer: You can mount a close-up lens (diopter) on a lens of any focal length. These supplemental close-up lenses work exactly like reading glass spectacles that allow older people to read with the book or newspaper close at hand. In fact, you can go to the drugstore and handhold one lens of a reading glass before your camera. This will allow you to preview the effect. The power engraved on the reading glass is the diopter measure of the lens, same as the power of the one you buy for your camera.
The diopter is a unit of power (focal length), is used by eye doctors when they write prescriptions for corrective lenses. 1 diopter = 1000mm, 2 diopters = 500mm, 3 diopters = 333mm, 4 diopters = 250mm, 5 diopters=200mm.
If you mount a +3 close-up (333mm supplemental before your lens, you grant the ability to focus closer to your subject. With a +3 mounted and the camera set to infinity focus (∞), objects will be in focus 333mm forward of the lens. Using the camera's focus knob, you can focus even closer. Your revised focus range is likely 1 diopter = 333mm to 250mm.
Close-up supplemental lenses can be a cheap single element or a good quality two element achromatic (without color error) lens.
Mounting a drugstore reading lens is an inexpensive way to preview what a close-up does. After you decide the power you need, buy a good two element, I suggest a +3 for your first purchase.


Stacked IFs Google Sheets Apps Script

Question: New to Google Apps Script. Could someone tell me to to write stacked IFs in Apps Script.
I want to create a custom function that calculates the total sixteenths in a custom feet-inches-sixteens format.
The format is different depending on the length of the string. 1=1', 12=12',508 = 5 1/2", 1604 = 16 1/4", etc...and in order to convert to feet-inches-sixteen I have to calculate the total 16ths first.
Any help is appreciated.
Comment: What research did you do till now? Do you have a code you're working on? Can you provide a copy of the spreadsheet you are working on, free of sensitive information, clearly indicating the desired outcome?
Comment: Sorry for not being more clear in my question, but the format itself is a bit confusing. Here's a link to a spreadsheet that might explain things better.  https://docs.google.com/spreadsheets/d/1BU9X8w_KVJ00-zTmXPxZ0qvUUEhjszZFG_YuU2jwGyc/edit?usp=sharing
Answer: Your question is a little hard to understand, but I think you have values in sheets represented as 1' 3 1/2" (1 ft, 3.5 in) which you'd like to convert to sixteenth-inch units.
The following function should do what you want:
<code>function SIXTEENTHS(string) {
  var regex = /^\s*([0-9]*(?=\'))?\'?\s*([0-9]+(?![0-9]))?\s*([0-9]+\/[0-9]+)?\"?\s*$/;
  var parsed = string.match(regex);
  if (!parsed) {
    return 'Bad input';
  }
  var inches = (parsed[1] | 0) * 12; // Parse feet
  inches += (parsed[2] | 0); // Parse inches
  if (parsed[3]) {
    inches += (parsed[3].split('/').reduce((a, b) => a/b)); // Parse fractions
  }
  return inches*16;
}

</code>
Parsing the string is a little tricky, but you can see what the regex is doing and test it at Regex 101.
Comment: Sorry for not being more clear in my question, but the format itself is a bit confusing. Here's a link to a spreadsheet that might explain things better.  https://docs.google.com/spreadsheets/d/1BU9X8w_KVJ00-zTmXPxZ0qvUUEhjszZFG_YuU2jwGyc/edit?usp=sharing
Comment: The reason I want to convert to 16ths first is so I can do calculations with my measurements like adding or multiplying.
Comment: The input format you're using leaves some ambiguity. How do I tell the difference between 5 ft 8 in and 5 8/16 in? Both would be written as 508. The function could easily be tweaked to return the desired format (or you could do this in sheets with the QUOTIENT and MOD functions). But first you need a consistent unambiguous format for the input data.
Comment: 5'8" would be written as 50800, 5-1/2" (or 5-8/16") would be 508. Like I said, the format is a bit confusing but it works. I updated the spreadsheet to clarify how the function works.
Comment: I've made in work in Excel with a couple of helper columns, but I want to get away from that.
Comment: Here is my rudimentary spreadsheet. All measurement conversions are on the Calculations page. https://docs.google.com/spreadsheets/d/1Gjx7c4xW2uztLB3uhw91E8TmtMRjCHB9uIZZlM9UoRo/edit?usp=sharing

Stacked IFs Google Sheets Apps Script


insufficient gas funds error on rinkeby infura using brownie

Question: I have sufficient ether in my testnet account but still the code is showing error. What to do next? I have attached multiple screenshots of my code and metamask rinkeby wallet.. Kindly guide me

enter image description here
Answer: Adding on to @Majd TL's helpful observation there, if you'd like to see the various ethereum addresses that get generated from your mnemonic (aka seed phrase) take a look at the answer to this post on how to "Create ethereum  address from seed".
Please pay special attention to the Warning in the answer because you should not share the seed phrase for your ethereum wallet as anyone can access your funds.
Answer: Your mnemonic does not generate your metamask account that start with 0x76B...


Formatting idea for 2 rows table

Question: Hey im looking for a solution to format this table in a good looking way. I like the booktabs formatting for tables that read vertically but i want this one to be read horizontally. This is what i came up with but i found it not looking solid and sharp enough. Do you have an idea?
Answer: well it is a two steps process, it visually makes more sense to go with a horizontal line between the spaces as for the redundant text you can use it as header of a third row (before step1). Furthermore the same text is present for your concentration c, time t and temperature T. For clarity I'd use an explanation in the caption of the table for the redundant details and in parentheses the units. In addition, maybe changing from t to i as a notation for time points. This would look like this:
Steps \ Variables  |    c(mM)     i(min)    T(°C)
-------------------------------------------------
1                  |     1         2880      25
-------------------------------------------------
2                  |     1           30      70

caption including an explanation of immic1m2. Which experiment, condition, etc?
Hope this helps!
Comment: thanks for the Idea thats good! My concern is that the concentration is given for one species, but it could be for e.g step 3 that the concentration is a mixture of lets say c12/c8 at ratios 5:1... may i ask you for another idea how to implement that? i dont want to bloat the infos, just clear and sharp. B
Comment: glad to help! Regarding the ratios to explicit some concentrations i assume you are referring to steps 12 and 8 when you write `c12`and `c8`, respectively. so how about just using that as a fraction followed by the ratio in brackets [5:1]? :-)
Comment: you have to define at some point `c_s` with `s` steps if you use the notation `\frac{c_{12}}{c_{8}}`

Formatting idea for 2 rows table


Using Tornado and mysql with Python 3x

Question: Tornado framework is compatible with Python 3, but it uses the mysqldb package which from what I've read is not compatible with Python 3.
Will this present any issues when working with my mysql database? If so, is there a workaround? I'd be open to using another framework that is more friendly to Python 3, but I'm committed to sticking with Python 3.
Thanks
Answer: There are no issues, as Tornado has no dependencies on a particular client; the wrapper is included for your convenience. You can get a working py3 version of python-mysqldb on Golhke's site. Since you can use any valid Python code in the handlers, you can also use any other library (like PyMySQL), you just won't be able to use Tornado's wrapper functions.

Using Tornado and mysql with Python 3x


Amazon Ec2 Automatically Create New Instance On Event

Question: How could I do this on Amazon AWS: Automatically create a new instance on a certain Elastic IP and close another when X happens, in a database?
Answer: You may want to investigate CloudWatch, the AWS auto-scaling service.
Answer: You need 2 things, Simple bash script command + Amazon AMI API to launch new instance.
Let me give you the algorithm that how it will work then you can write it in bash+API commands.
if DB Event
then
Create ami
Associate Elastic IP with AMI
Turn on AMI


Why are inverse transformations applied to rays rather than forward transformations to objects?

Question: When computing ray-object intersections against a transformed object, most raytracers apply the inverse transform to each ray and compute the intersection against a non-transformed object.  Wouldn't applying the forward transform, putting the object into a flat world-space, be faster and more efficient, because you only need to compute the transform once?
Comment: I think the assumption is that all primitives would be transformed to a flat world-space position during scene preparation. (Which does dramatically increase memory usage.) Then rays would be directly intersected against the primitives without a preceding transformation between spaces, since they're now both in world-space.
Comment: What do you mean by "only compute the transform once"? Meaning you don't have to compute the inverse transform, or you only ever need to transform an object once? Computing the inverse transform is cheap compared to a geometry intersection, and you definitely would need to transform an object multiple times (into the space of each different ray).
Answer: Most raytracers do both!
Have you ever seen a ray-triangle intersection test where the triangle is transformed so that one vertex is at the origin and the triangle is flat along one of the axes? That would simplify the test, but storing the inverse transformation to apply it to the ray takes more space than the triangle itself. So you could say that almost all ray-triangle tests do apply the forward transformation to the object.
And yet most of the time you are rendering a mesh of many triangles, and "most raytracers" don't transform every vertex in the mesh by the object's transform matrix, they inverse transform the ray into object space. There isn't necessarily a good reason for this—it can definitely be more performant in some cases to preprocess the mesh and put every vertex in world space.
But then say you're doing animation studio-scale path tracing. Now your scene geometry might not all fit in RAM at once. It's no longer a performance win to pre-transform all your vertices/control points, because (a) you need one copy of the object per instance, and (b) you need to transform it each time you read it into RAM. When data bound, the cost of two matrix multiplies per ray is insignificant anyway.
Floating point precision is a potential reason as well: when you have an object a long way from the origin, you get more error from floating point positions, and if you pre-transform the object you apply that error in different directions to each vertex, whereas if you inverse transform the ray you have one fixed error amount from the imprecise position of the ray, but your vertices have less error relative to each other.
Although I suspect the real answer to "why do most raytracers inverse transform the ray" is that most raytracers with public source code implement a wide range of geometric primitives, either for educational purposes or as a proof-of-concept, and it's easier to implement one cheap ray inverse transform than N shape forward transforms. (Plus, as has been mentioned, some intersection algorithms are much simpler if the object is in its canonical space.)
Answer: Most ray intersection algorithms can be greatly simplified if you can assume the shape you're intersecting is at the origin, unrotated and with unit size. There are a few exceptions (Like spheres, which have rotational symmetry.) but the more general versions of the algorithms mathematically usually end up basically translating both the shape and ray to the origin before calculating the intersection. With that in mind it's simpler and more consistent to simply transform rays so that the intersection always happens in object-space.
Comment: @AlanWolfe, wouldn't the same resolution issues show up when computing the inverse transformation and applying it to the ray, though?
Comment: It can be more accurate too.  The farther you get away from zero, the less resolution there is between integers, when using floating point numbers.


How can I override a broken Haskell package in nix?

Question: I use NixOS, and I'm trying to set up a Nix Haskell environment for my Haskell project. I have this Haskell package written in Nix that I'm trying to get working via nix-shell, but the dependent Haskell package Clay won't build, as described in this bug report I just opened. How can I override this package with a different (older or newer, I guess it doesn't matter) version of this Haskell package that works?
Comment: This might be useful: https://stackoverflow.com/questions/56414329/how-do-i-override-a-haskell-package-with-a-git-local-package-with-nix-when-usi/56416694#56416694
Answer: Not completely relevant, however I needed to modify an existing package that failed to build. I ended up with:
nixpkgs.config.packageOverrides = pkgs: {
    haskellPackages = pkgs.haskellPackages.override {
      overrides = hsSelf: hsSuper: {
        greenclip  = pkgs.haskell.lib.overrideCabal hsSuper.greenclip  (oa: {
          version = "3.1.1";
          sha256 = "1axh1q7kcvcnhn4rl704i4gcix5yn5v0sb3bdgjk4vgkd7fv8chw";
          executablePkgconfigDepends = oa.executablePkgconfigDepends ++ [pkgs.xorg.libXdmcp];
        });

        wordexp  = pkgs.haskell.lib.overrideCabal hsSuper.wordexp  (oa: {
          version = "0.2.2";
          sha256 = "1mbcrq89jz0dcibw66w0jdy4f4bfpx4zwjfs98rm3jjgdikwdzb4";
        });
      };
    };
  };

The above went in my configuration.nix
Answer: For others looking, you can use override on the haskellPackages and provide an overlay in the overrides attribute, this will create your own version of the package set containing the overridden packages.
Example, removing version constraints on beam-core package and disabling tests on beam-postgres package.
myHaskellPackages = nixpkgs.haskellPackages.override {
    overrides = hself: hsuper: {
      # Can add/override packages here
      beam-core = nixpkgs.haskell.lib.doJailbreak hsuper.beam-core;
      beam-postgres = nixpkgs.haskell.lib.dontCheck hsuper.beam-postgres;
    };
  };

Then you use that modified package set to build your project:
myHaskellPackages.callCabal2nix "my-project" ./. { }

It's possible to build a derivation for a specific version of the package with nixpkgs.haskellPackages.callHackage as long as it exists on Hackage, or use callCabal2nix on a modified local repo, or fetchFromGitHub and alike to refer to a remote repo.
More details on fixing broken Haskell packages can be found here, and tips in general about Haskell development with Nix here, you'll find there an example on how to override dependencies of a dependency.


Video Shortcode & Video Poster Question

Question: Totally new to WP, need help with WP Video Short Code.  I got my video on my webpage, got it the right size, got it to play, and it resets to the beginning when it finishes playing.  My problem is, after it plays, I want it to reset to the "Video Poster" it's on when the page first loads.  Does anyone know how I can make it do that?  (Please explain in beginner terms because I don't know hardly anything about WP or writing code or placing code... again, total beginner, so tell me FULL DETAIL as if I'm stupid!  Thanks!)
Comment: Please include the shortcode that you've used.
Comment: Is this what you mean?  (Sorry I am new to all this):  https://codex.wordpress.org/Video_Shortcode

Then I used this for the video poster:
[video poster="http://yeswolfcopywriters.com/wp-content/uploads/2017/01/YC-Video-Poster.png" width="1525" height="850"][/video]

It all works but when the video finishes playing, it resets to the top of the video without putting the video poster back up.  I want it to go back to the video poster.  Any help greatly appreciated.
Answer: There's no straight forward way of doing this but we can achieve this with a small JS snippet. You can add the following JS snippet in your footer to make it work with all videos in your content.
var videos = document.getElementsByTagName('video');
for (var i = 0; i < videos.length; i++) {
    videos[i].addEventListener('ended', function(e) {
        e.target.load();
    });
}

What does this code do?
The above snippet register ended event on all videos it can find and just loads the video when it ends.
To make it more seamless, we can filter the_content if any [video][/video] shortcode is used, if so, then include this code, otherwise not.
Add the following code to your functions.php or in a custom plugin:
function ja_video_shortcode_check( $content ) {

    if ( has_shortcode( $content, 'video' ) ) {
        add_action( 'wp_footer', function(){
            echo "";
        } );
    }

    return $content;
}
add_filter( 'the_content', 'ja_video_shortcode_check' );

Tested in fresh WP instance using TwentySeventeen theme with no plugins activated.
To add this code in a widget, add a Text widget, toggle to the Text view and paste the following code:

Comment: Thank you so much for this -- but I am so new to this, I am not sure  how to use what you have sent me.  Can you explain it to me step by step, please?  Exactly where do I put this?  This is what it says on the page now... [video poster="http://yeswolfcopywriters.com/wp-content/uploads/2017/01/YC-Video-Poster.png" width="1525" height="850"][/video]
Comment: Sorry, it didn't show you the whole string.  I have 3 footer boxes across the bottom that appear on every page of the website.  Does it matter which one i put the top string you sent in? And the string does use [/video], so how do I use the bottom section you sent.  Again, sorry to be so stupid, just new to all this and need help.  Seems like it should be fairly easy but I guess not.
Comment: Add the second code snippet to your theme's `functions.php` file, a tutorial on how to do this, [click here](https://www.youtube.com/watch?v=N9VNXh506ys)
Comment: Can it be placed in one of my Footer Widgets?
Comment: I updated the answer. Check the code at bottom.
Comment: I greatly appreciate your help but still do not understand how to use what you have sent me.  Can you PLEASE explain all of this step by step like I am a dummy?  That is the only way I will understand it.

Video Shortcode & Video Poster Question


How old was Sarah when God first promised that she would bear a son for Abraham?

Question: How old was Sarah when God first made the promise that she would bear a son for Abraham?
Answer: It seems that she was 90 yrs old:

Genesis 17:17 (NWT)
  At this Abraham fell facedown and began to laugh and to say in his heart: "Will a man 100 years old have a child born to him, and will Sarah, a woman 90 years old, give birth?"
Comment: When quoting other sources, begin a new paragraph (after a blank line) with a ">" character, and finish with another blank line, and don't forget to include the version of the Bible you have used.
Answer: I heard that at the age of 90 sarah did give birth and in the torah this was called a miracle and when this happened abraham was 100 years old.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Which Buddhist schools give importance to cultivation of Jhanas?

Question: Which schools/lineages in Buddhism give importance to the cultivation of Jhanas before entering Vipassana, and which schools focus entirely on Vipassana?
Comment: I have not 50 reputations yet to comment here. Hence answer here.
I have personal experience in Goenka's 10 day retreats. Their first 3 days practice samatha - anapanasathi and the next 6 days use for vipassana and the final day is for Metta - loving kindness.
Answer: This is not an exhaustive or scholarly answer, but:
Lineages or traditions don't necessarily predict how this is taught. I believe Ajahn Brahmavamso, who teaches that it's very important to master jhanas first, comes from the Thai Forest Tradition, but not all Thai Forest teachers emphasize that as strongly. Pa Auk Sayadaw in Burma is also a proponent of jhana mastery before vipassana.
On the other side of things, the Mahasi Sayadaw lineage in Burma emphasizes vipassana from the outset.
All traditions would agree (I think) that a certain degree of samatha is a prerequisite for attaining vipassana knowledges. The difference is in how one teaches the practice, and how strictly one defines 'jhana'. There is always a dynamic interplay between samatha and vipassana, so jhana factors can emerge in formal vipassana practices, and insight wisdom can develop during formal samatha practices.
Comment: Ajahn Brahm tends to discount talk of Vipassana as a method and his position as I understand it is that vipassana was not a technique taught by the Buddha, that vipassana (insight) is inseperable from jhana, and that the practices that have come to be under the heading 'vipassana' are dangerous insofar as one may be deluded into thinking they have insight (which is not possible outside of a clear, calm mind).

http://www.theravada-dhamma.org/blog/?p=3466

http://www.dhammatalks.net/Books9/Ajahn_Brahm_Samatha_Meditation.htm

http://media.bswa.org/sutta_study/Brahmavamso_2013_06_30.mp3
Comment: If you're thinking about the Goenka-tradition 10-day retreats, I believe they focus entirely on vipassana. (Take my answer with a grain of salt- I have no personal experience of them- but I think when you see a '10-day vipassana retreat', it's often the Goenka organization).
Comment: Thanks! Not directly related, but just in case you know the answer,
Comment: Sorry, the previous comment got submitted because I pressed newline:-) Thanks for your answer. I had one more question, not directly related, but just in case you know the answer, do the 10 day Vipassana retreats discuss Jhanas, or do they focus entirely on Vipassana (Insight)?


Record a webcam video using HTML5 and then store it on a remote server

Question: I need to record a video on the client's machine using HTML5 with permissions and then store them on a remote server.
I am new to HTML5. Please help me with the steps I should take care of, in order to do this.
Thanks in Advance!
Comment: Below is a tutorial from html5rocks which might help you get started.

http://www.html5rocks.com/en/tutorials/getusermedia/intro/
Answer: Html5 rocks is a very good tutorial. So, if you need a flash plugin or to be sure that works in all browser (I use it because my app must run in IE<10) use Scriptcam, easy to use. Link


How can I use machine learning with smart contract?

Question: I'm new in programming Blockchain. I want to make a smart contract with machine learning, a simple case. I know how to create a solidity contract, but I do not know how to add learning to the contract. Does anyone have any ideas?
Answer: I'll throw the question back at you. Why would you implement "machine learning" in a smart contract?
The majority of the machine learning models right now have a pipeline that looks like the following:

Preprocess the data. This operation is unsuitable to do in a smart contract due to the high transaction costs and speed. One could consider adding the final dataset to the blockchain, but there is no benefit from that. Let alone the transaction costs for uploading the data to the blockchain. It would be much more suitable to store it on IPFS if you want free distribution of data that are immutable.
Train the model: Again it would be crazy to train using a smart contract given the lack of support for linear algebra. Imagine that our local computers run high performant linear algebra libraries in Fortran or C that have been developed and maintained for decades. You could consider storing the model on the blockchain and save other people the effort and the time to train it again.
Run the model: This depending on the model could be viable, but again the lack of Linear-Algebra libraries would probably make it prohibitively costly to develop.

Take my answer with a grain of salt as the area is developing at a fast pace. Personally, I dont see the reason to use blockchain in machine learning right now. Hopefully, someone smarter than me will come to prove me wrong.
P.S. Check Open Minded that do privacy enhancing decentralized machine learning using differential privacy and secure MPC. However, this is a different beast
Comment: @ElvisSuarez again you need to elaborate on that. Since a server exists which is a point of centralization (centralization is not an inherently bad thing ), why not let the users contact the server directly. What you say is technically possible with [Oraclize](http://www.oraclize.it/). Deep down my point is similar to [this](https://twitter.com/socrates1024/status/902649363943612416).
Comment: Thanks for answering! My idea is to use Artificial Intelligence in Ethereum, and I had opted for machine learning. Possibly, if the contract is only responsible for making requests to a server would be more feasible and would leave all the logical process to the server.
Comment: Thanks again, it would be more convenient to centralize everything in a server and ready, but for a subject of the faculty I must mix both concepts, although I understand that I must delve into the subject, greetings
Answer: Machine Learning usually takes a lot of processing power and memory. Blockchain costs a lot for any processing power or memory. I would create smart contracts that do minimal processing and data collection from the blockchain and offload everything CPU and memory intensive via web3, web3j or some other off-chain API to a traditional server.
Answer: You would have to define the smart contracts yourself. While Solidity or Smart Contracts were not meant to used for Machine Learning, here is an interesting incentive for using smart contracts- they let you easily assess the efficiency of a process. But given the fact that we have Python for Machine learning, a language which boast of such a powerful library like Scikit-Learn, one would be hard-pressed to do it.
That being said, Using Solidity and Smart Contracts to test out Machine Learning Concepts isn't a bad idea.


Best practice suggestions for iPhone application with multiple NIBs

Question: I am developing an application with seven NIBs.  The TabController is throwing a bunch of these into the ..More tab, which spoils the user experience.  Does anyone have advice on a better approach?
I am wondering if I should detect swipes and switch out each NIB in turn (with an eye to creating a circular experience i.e NIb 1 -> Nib 2... Nib 7 -> Nib1 etc.
Failing this, I could use a Navigation controller and switch NIBs with "Forward" & "Back" buttons.
I have tried the first idea.  I can switch NIBs after detecting a swipe, but the previous NIB won't release for some reason (and can be seen underneath the new NIB).   The second idea takes up screen space with the nav bar, and I would rather use this for the tables etc in the NIB.
Sample code and thoughts are appreciated.
Answer: My sugestion would be to build your own custom "tabBar" as a scroll view with paging enabled. And try to use lazy loading for the NIBs.
Anyway you must find a way to recycle your resources (in a similar way that tableViews reuses the cells)


Getting to Mexico City Airport early in the morning

Question: I was thinking of booking a flight that leaves at 6.15am in the morning from MEX, which means that I'll have to get there at 4.15am or so. What are my options for getting there so early in the morning, since I read that the metros run beginning at 5am?
Comment: Welcome to travel.SE.  Can you clarify where you're starting from? And how much are you willing to spend on a trip?
Comment: I was looking for the easiest way to get to the airport from somewhere within Mexico City. I don't speak Spanish, so it also needs to be a reliable way, so I don't mind paying slightly more, for that convenience.
Comment: Get to a hotel at the airport and stay overnight would be easiest IMHO.
Answer: Since you haven't told us where you are, I'll assume you're somewhere else within or near by Mexico City.  Your best bet will be a taxi.
Public transport (buses and trains) don't start until 4:30am or later:

Metro (trains)
Monday thru Friday from 5:00 to 24:00 hrs.
Saturdays 6:00 to 24:00 hrs.
Sundays and Holidays 7:00 to 24:00 hrs.
Metrobus
Monday thru Friday from 4:30 to 24:00 hrs.
Saturdays and Sundays 5:00 to 24:00 hrs.
source; in Spanish
Comment: @chinmayn: You can call for a taxi 24/7 in Mexico City. If you follow the link in my answer, it provides costs for taxis as well.
Comment: Thank you. Can I call for a taxi that early in the morning? Approximately how much does it cost (say from the city center)?