Convergence of sequences in $\mathbb{C}$

Question: I am currently getting into the field of complex numbers, with the imaginary unit $i^2 = -1$ and stuff. At the moment i am looking onto a few sequences in $\mathbb{C}$, regarding convergence.
I have the feeling that $\mathbb{C}$ still is thin ice for me, so:
Can somebody please just give me a feedback weather the following proof is correct?
I want to prove
$a_n = \frac{1+i}{n+i}$ convergent. I am using the quotient criteria. Also i am using the fact that $i^2 = -1$. $0<\theta<1$
$$|\frac{\frac{1+i}{(n+1)+i}}{\frac{1+i}{n+i}}|=$$
$$|\frac{(1+i)(n+i)}{((n+1)+i)(1+i)}|=  |\frac{n+i+in-1}{(n+1)+(n+1)i +i-1}|=$$
$$|\frac{n+in+i-1}{(n+1)+in+2i-1}|<\theta$$
$$because:$$
$$n+in+i-1<n+in+2i$$
$$q.e.d.$$
If that is correct, can somebody please just give me a hint for the sequence:
$$a_n=(e^{i\frac{\pi}{4}})^n$$
Which criterion would you suggest looking on?
Thanks for any help.
P.S: If you are cool you can also tell me how get these || to cover the whole fraction ;) Sorry for this formatting.
Comment: `$\left| \frac{blah}{blah} \right|$` produces $\left|\frac{blah}{blah} \right|$.
Comment: A sequence $a_n = e^{\mathbb{i}na}$ converge only if $a \equiv 0\pmod{2\pi}$
Comment: Damn, i added the explanation for $\theta$ and now your suggested edit is gone cause it conflicts :/
Answer: I can't quite grasp the argument you present for $\frac{1+i}{n+i}$. It looks like you're applying the ratio test, but what is the $\theta$ that appears amid all of the algebra?
It would be easier just to do
$$|a_n|=\left|\frac{1+i}{n+i}\right|=\frac{|1+i|}{|n+i|}<\frac{|1+i|}{n} \to 0 $$
For $(e^{i\pi/4})^n = e^{ni\pi/4}$ you'll need to know Euler's formula for $e^{ix}$. Compare the values for $n=0,8,16,24,\ldots$ with those for $n=4,12,20,\ldots$.
Comment: @FalcoWinkler: But you're never saying what $\theta$ is. Note that just because you have a sequence with every $b_n<1$ it is not necessarily true that there is a $\theta<1$ such that every $b_n<\theta$ -- (for a counterexample consider $b_n=\frac{n}{n+1}$).
Comment: @FalcoWinkler: In any case, your proof definitely goes wrong when you write "$n+in+i−1\sqrt{n^2}=n$.
Comment: Thanks again Henning. @servabat : What rule did you use there? Sorry i am a bit new to complex numbers.
Comment: @Falco: It's just $|z/w|=|z|/|w|$, combined with $|a+bi|=\sqrt{a^2+b^2}$ above and below the fraction bar.
Comment: Ah yeah okay. Wow thats fancy. Complex numbers are really interesting as it seems. Thanks @everyone, i think i am good to carry on now :)
Comment: @HenningMakholm, right but I meant, just taking $\sqrt{n^2+1}$ was sufficient as it converge to $+\infty$ (without transformations). But I'm agree, and yes it's probably best practice.
Answer: For your second sequence, the best way in my opinion is to show that :
$$\lim\left(\mathbb{e}^{ina}\right)_{n \geq0}=L, L \in \mathbb{C} \iff a \equiv 0\pmod{2\pi}.$$
($\implies$ is sufficient, but the other way is quite easy as $a \equiv 0\pmod{2\pi}$ means the sequence is a constant)


set up 2 networks card with different gateways

Question: I have a VMs Ubuntu server 20.04 with two network cards, I would like to set up a different vlan with different gateway in each one. I made my routing table in the file yaml but when I assign gateway to each interface when I apply netplan I am getting the error: Conflicting default route declaration for ipv4
here is my yaml file
enter image description here
here is my rt_table file
enter image description here
What I am doing wrong?
Answer: In later releases of netplan, the gateway4 field is being deprecated altogether precisely because of this kind of confusion.
You should only include your default route for each interface under routes instead.  I see you are already doing this for one interface:
  routes:
    - to: 0.0.0.0/0
      via: 10.150.250.1
      table: 800

Note that gateway4 is equivalent to setting a default route under routes, except, that you cannot declare a routing table when using gateway4!  This is why only one is allowed, because if you define gateway4 twice you get incoherent routes in the default routing table.


Fixing a broken bios lenovo

Question: I am a little bit stuck. Since I've installed Ubuntu 17.10 on my laptop.
It corrupted my bios from my laptop (I have a Lenovo Y50).
This means that I cannot

Change my bios
Boot using USB
And EFI entries read-only

So I installed Windows using another laptop and put the disk in the laptop. So I can work with it. The problem now is that there is a fix for the bios (using Ubuntu). But I can't boot Ubuntu from USB or hard disk.
When I use the same way to install Ubuntu on a hard disk and connect it to the laptop, it won't boot at all.
Is there a way to fix this :)
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1734147
Comment: According to this thread a fix is possible https://askubuntu.com/questions/1013832/ubuntu-17-10-corrupted-bios-lenovo-with-usb-boot-device.
Answer: If you are able to boot in Windows the BIOS can be re-flashed with the Y50-70 Laptop BIOS Update If you are not able to boot then you will not be able to run the BIOS update. You will have to send the laptop to Lenovo to re-flash the BIOS.
A clip From Phoronix - Ubuntu 17.10 Temporarily Pulled Due To A BIOS Corrupting Problem:
Should your BIOS be corrupted, you may need to replace your motherboard if there is not a removable flash chip. There are some reports that resetting the BIOS does work, but it's too early to know if that works for everyone. This issue has been confirmed for several different lines of Lenovo laptops including the Yoga and IdeaPad products. There is also the reports of it affecting a few Acer, Toshiba and Dell laptops.
When the BIOS is corrupted by the Intel SPI kernel driver, the effects range from being unable to save BIOS settings to no longer being able to boot from USB devices.
The Intel SPI kernel driver is responsible for reading/writing to SPI serial flash. Due to the SPI serial flash holding the BIOS and other platform specific data, Intel's driver is supposed to make the contents read-only, but clearly something is going awry with the driver in 17.10.
Comment: first of all thank you for your answer.  the problem is if I cannot boot Ubuntu format hard disk.  yesterday I connect a a hard drive with Ubuntu on it. Internal harddrive, Didn't load. I have the same issue with one USB stick I have only the possibility to boot something using a pxe server.
Comment: The second problem that I have is that I cannot flash  my bios  using Windows. If you download program to Flash your laptop  it does not work. It will reboot your computer and nothing is changed
Comment: I would send a email to Lenovo tech support.
Comment: Please report back any findings.  The same happened with me.  I have a Lenovo B50-80.
Comment: @stumblebee I've already asked this on the Lenovo forum. But I get less information than on 'askubuntu'.
Answer: Sup Guys (and girls),
One of my friends connected a usb 2.0 on it (UEFI) (on a usb 2.0 port).
This with a disconnected HDD. So It loaded (took us one hour to find out).
After that we installed Ubuntu and installed the patch. So my laptop is working again.
(after the install, I downloaded http://people.canonical.com/~ypwong/lp1734147/linux-image-4.15.0-041500rc6-generic_4.15.0-041500rc6.201712312330+20170103+1_amd64.deb package and installed it)

Fixing a broken bios lenovo


How do I show an external file creation date on website using just JavaScript?

Question: I don't even know if this is posible.
I'm using straight HTML.  It's really my only option.  No PHP, No .Net, No Java, YES JAVASCRIPT.
I have URL, and I'm trying to display the last modified date.
I came across this code, but it displasy the file, not the last modified date.  Is there something wrong with the code, or is there another way to do this using just HTML and JavaScript?
I'm not able to share the real URL here.

Thanks!
Lee
Answer: This solution is not possible with just HTML (HTML is static), and if you're doing any interaction with files using JavaScript you'll need to be hosted on a web-server. If that's the case, you certainly have a reason to use PHP.
Comment: Good News.  I can use Javascript.  I've updated the posting to include this fact and the partial script I've found that seems to get me in the right direction.  But it doesn't display last modified date. ugh.
Answer: If you are parsing your files via a server and you really can't use PHP, you might be able to use a Server Side Include (SSI); try including the following code in your HTML file:

you'll probably need to change the file extension to .shtml tho, so that the server knows it has to do something special with it.
Comment: Sadly, I don't control the naming convention of the html file.
Comment: It'll depend on the server environment - you might not have to


RRule and iCal Complex recurrence

Question: I need to be able to create events based on weekdays regardless of year. A good example would be Thanksgiving, the 4th Thursday in November:
RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=11;BYDAY=Th;
BYMONTHDAY=22,23,24,25,26,27,28

But suppose I want the Sunday after Thanksgiving? It would be much the same, except when Thanksgiving falls on the 28th the following Sunday is in December. I tried:
RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=11,**12**;BYDAY=Su;
BYMONTHDAY=25,26,27,28,29,30,**01**

And this does not work, because it'll flag Sunday 11/1s and Sunday 12/25-30 as well.
Comment: The only solution I can come up with is to create a second event that handles dates that cross month boundaries. But that's not a very satisfying solution.
Comment: Another example of a complex recurrence I have to generate. The town's parade is always on the 2nd Saturday of December. The tree lighting and open house are on the preceding Fri and Sat, respectively. Fri and Saturday are not necessarily the first Fri and Sat of the month, they could be the last Fri in Nov and the first Sat of Dec.
Answer: These kinds of rules imply calculations that haven't been built into the iCal format, so it might not be possible for all rules of the mentioned kind to be modeled in iCal. Nevertheless it's often possible to find some 'workarounds' for specific cases, which is the case for the examples you mentioned:
The Sunday after the 4th Thursday of November:
FREQ=YEARLY;BYYEARDAY=-37,-36,-35,-34,-33,-32,-31;BYDAY=SU

The Saturday preceding the 2nd Saturday of December (i.e. the 1st Saturday of December):
FREQ=YEARLY;BYMONTH=12;BYDAY=1SA

The Friday preceding the 1st Saturday of December:
FREQ=YEARLY;BYYEARDAY=-32,-31,-30,-29,-28,-27,-26;BYDAY=FR

The 1st Saturday of December AND the preceding Friday:
FREQ=YEARLY;BYYEARDAY=-32,-31,-30,-29,-28,-27,-26,-25;BYMONTH=11,12;BYDAY=-1FR,1FR,1SA;BYSETPOS=1,2

RRule and iCal Complex recurrence


SVG - Background size not resizing SVG image, instead its changing it's position

Question: I am trying to use the background size property to scale my background image like this
<code>.myDiv
  background-image url('background-fill.svg')
  background-repeat no-repeat
  background-size 100% 336px
</code>
But changing the 336px does not rescale the image's height, instead the image is always proportional (adding to 336px moves the image down, and subtracting from 336px moves the image up, it does not change the size of the image)
For example, if I do
<code>  background-size 100% 536px
</code>
The image moves lower, and displays the same size as before
If I change for a png, or a jpg, it works as expected
Comment: Questions seeking code help must include the shortest code necessary to reproduce it **in the question itself** preferably in a [**Stack Snippet**](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/).  See [**How to create a Minimal, Reproducible Example**](http://stackoverflow.com/help/reprex)
Comment: In addition to providing your HTML and CSS per the previous comment, can you provide the SVG/XML too? At the very least, we'll need to see what your SVG has set for width, height, viewBox, and preserveAspectRatio in the SVG file itself. Those can have an effect on how the SVG is resized/scaled.
Comment: @HBlackorby I found the problem , I posted it as an answer to my own question. Needed to set preserveAspectRatio="none" to my svg. Thank you
Answer: I found the problem, I had to set
<code>preserveAspectRatio="none"
</code>
in my .svg, inside the svg tag


Ubuntu Kylin Artful Aardvark (17.10)

Question: Hello my name is Tyler T. I'm wondering, when will "Ubuntu Kylin 17.10" be officially available to download? Please reply whenever you can, please and thank you.
Answer: It is already available. Please visit official site - http://www.ubuntukylin.com.

Ubuntu Kylin Artful Aardvark (17.10)


Why did Ubuntu fail, given that the installation was successful?

Question: I just tried installing Ubuntu 12.04 on my new laptop, dual-booting alongside windows 8, i burnt the iso to a CD-R and installed it. The installation went fine, I got up to the part where it told me to take the disk out and press enter to restart my PC. But now when it has started, it simply says "repairing disk errors. this might take over an hour to complete." I followed the installation instructions exactly, and yet I know cannot access my laptop. Can anyone give me some idea of how to repair this.
Just in case it is helpful, the laptops specs are 8G ram, AMD 10 Quad Core processor, 750G Hard Drive.
Comment: Where and when does it say "repairing disk errors"?
Comment: Just after I power on the laptop. There is the HP icon, underneath that it says "repairing disk errors."
Answer: "repairing disk errors" does not mean the installation failed, it means on startup,  there are problems with your HDD.
Just let it run the repair which may take a while and then it should boot.
Comment: Okay then it sounds like Grub did not properly configure itself.  You can just run a reinstall of Ubuntu using the live CD, it will give you the option as you run through the install wizard when it gets to partitioning.  Grub will probably install properly the second time.
Comment: Okay, thanks :) , I will wait it out for the night, and if need be, for the rest of the day tomorrow. I was just worried that I had ruined a brand new laptop. Ill come back if there are any other problems.
Comment: Hmm, i waited it out, and that stopped. But now when i boot i just get a black screen. I have tried booting again from the live CD i used to install, is there anyway I can remove Ubuntu from within that?


Uniform convergence in closed segment

Question: Let $f_n(x)=\frac{2nx+1}{n+nx^2}$. I want to prove that it is uniform converging in $[0,3]$.
The pointwise limit function is $f(x)=\frac{2x}{1+x^2}$.
I was able to find a supremun to $|f_n(x)-f(x)|$ which is $\frac {1}{n} \rightarrow 0$.
Does this prove that $f_n(x)$ converges in $[0,3]$?
Comment: I haven't checked if what you said is right, but if the supremum is indeed $\frac{1}{n}$, then yes, this is enough.
Comment: So if I'm asked about a closed segment and able to show there is a supremum that is not depending on $x$ that is tending to 0 then it's enough?
Comment: You don't even need a closed domain for that. (The supremum does never depend on $x$ btw.)
Answer: The fact $\sup_{x\in[0,3]}|f_n(x)-f(x)|$ converges to $0$ is indeed enough, and actually equivalent to the uniform convergence on $[0,3]$. This is an instructive exercise to show it with $\varepsilon$'s.
And indeed, in your context, the supremum is equal to $1/n$ (reached at $0$).

Uniform convergence in closed segment


Making common function in cakephp

Question: I am new in cakephp, i want to know  how to create a common function.
That means i have some code which will be repeated in multiple controllers at multiple time.
So i want to make this codes into a function and us in different controllers.
How can i do this?
Answer: Put the function in AppController.php because every controller extends this class. So you can access that function using <code>$this->yourFunction();</code>

Making common function in cakephp


Vertical bars on screen

Question: I have just bought Lenovo Z570 and installed ubuntu 11.10 on it. I normally work on the machine with a distance of almost 1.5 feet but I can see vertical bars all over the screen. I have shown my laptop to friends but they couldn't see the bars. I on the other hand cannot un-see them even though the pixel bars are small.
My resolution is set to 1366x768.
lshw returns:
<code>*-display
             description: VGA compatible controller
             product: 2nd Generation Core Processor Family Integrated Graphics Controller
             vendor: Intel Corporation
             physical id: 2
             bus info: pci@0000:00:02.0
             version: 09
             width: 64 bits
             clock: 33MHz
             capabilities: vga_controller bus_master cap_list rom
             configuration: driver=i915 latency=0
             resources: irq:42 memory:d0000000-d03fffff memory:c0000000-cfffffff ioport:3000(size=64)
</code>
I was thinking if its a driver problem because I saw a similar machine on display running windows and I found its display just fine. That machine had:

Name: AMD Radeon(TM) HD 6620G
Chipset Type: ATI display adapter
Approx. Total Memory: 3046 MB
Display mode: 1366x768 (32-bit) (60/Hz)

I guess my display device is Intel based. Any idea if the problem can be solved or should I return my laptop?
Comment: Do you have contact lenses or astigmatism? Can you get some camera photos, focused with macro if you know how to do it, at various distances? Please don;t use a phone camera; use a real digital camera(point-and-shoot is OK)
Comment: That's weird I have a Z570, use ubuntu 12.04 and have no problems, I'll compare my display output
Comment: capabilities: msi pm vga_controller bus_master cap_list rom
Comment: Joshua do you have same display device? where did you take this info from: msi pm vga_controller bus_master cap_list rom
Comment: you could try installing

    sudo apt-get install mesa-utils
 my graphics always worked but this installed the details...
Comment: Joshua, I mean do you have Intel's graphic card or AMD's?
Comment: Obsessive, I don't wear contact lenses and I don't have astigmatism for I have faced this problem with only this laptop. My other laptop and my friend's laptops don't have the same problem. I don't have a point-and-shoot camera right now but as soon as i get one i will share it. However, I took picture of my screen and the windows based lenove z570 in shop with iphone's camera and found that pixels of my laptop are more distance between them as compare to the distance between pixels on the Windows based lenove z570.
Comment: @JoshuaSiret What does Graphics say in your Dash Home > Settings > System Info > Overview? Mine says Intel SandyBridge Mobile.
Comment: yes it does, I have intel HD too. you could try upgrading to 12.04?
Answer: My system settings for baltusaj:

The Graphics section was updated from:
<code>sudo apt-get install mesa-utils
</code>
But it should work anyway as per default

Vertical bars on screen


How do I patch a large hole in plaster and lath?

Question: I am having some plumbing repaired in my 1913 house that will result in a large access hole (2' x 16") on the first floor.  The wall is currently plaster and lath and I'm trying to get a handle on the best way to repair the damage after the plaster and lath are removed.  From what I've read so far, plaster of Paris hardens too fast, making it difficult to work with so I'm leaning towards DAP® Plaster Wall Patch (Dry Mix).  I know I need to provide some backing material either metal or wooden lath but I'm not sure what else is needed.  Do I need to use any fiberglass mesh to put over the lathe or can I just start with the plaster.  Does anyone have any experience with the Plaster Wall Patch?  Is there something better that would work?  When applying plaster it sounds like I need at least two layers, once base and another finishing. Should I build up a first layer, let it dry and then another layer level with the existing surface or is there a technique that would be better. Do you think I can paint over the Plaster Wall Patch or is something else needed to prepare the surface for painting?
I can't wait to get started, I just need a little help in putting a plan together.
Comment: thanks for the suggestion but I think i'm going to give replastering a shot with the mix i have and some metal lath. i'm looking at getting into a bunch of plaster work as i go room by room and i might as well dig in and see how it turns out.
Answer: What I have done on my 1909 house (I am in the U.S.) in the same exact situation is clear a wider area of the lath and plaster and replace it with drywall.  To do that, you will need to add some padding over the studs because the lath&plaster is thicker than 1/2" -- what I did was pad it with 3/8" plywood, then drywall over plywood to achieve approximately an even joint between the new drywall and the old plaster.  Then you tape and sand the joints like you would with regular drywall, prime and paint it later.
Comment: If you are trying to blend drywall with plaster, you will probably have to put a skimcoat of mud (joint cmpound) over the patch, and then sand to get a surface as smooth as old plaster.
Answer: I am a drywall and plaster contractor in Va. The guy above told you correctly. The problem with wood lath is: once you start to cut it or re-screw it back up where cracks are, the lath pulls away from the studs, causing the cracks to get worse. If you are determined to use plaster, you must use a bonding agent, plaster weld, for the new plaster to adhere to the old. Your best bet would be to use a product called easy sand. It is a drywall product that works the same as plaster (no bonding agent needed).
If you are going from room to room remodeling your house, you will be much better off gutting the entire room, hanging new wallboard and finishing it. Smooth plaster is very difficult especially for a home owner. With wood lath, it can never guarantee the cracks will not return. Gouging them out and mesh taping will not stop the cracks. Cracks are caused by movement, where the lath nails have pulled out from the studs.
Good luck.
Comment: Great first post, but you might want to remove your phone number unless you want to start getting a ton of calls for free wall repair advice. Note the number of views for this question and that it is already working its way up in the Google search results.
Answer: I am a homeowner/hobbyist that loves fixing up old houses.  Lath and plaster was a special challenge towards my endeavor to perfection. Many attempts at trial and error before this solution.
Clean all loose plaster from the damaged area and secure the exposed lath with small ring shank nails.  If the depth of existing plaster is greater than (on hand) drywall, then add a piece of drywall to the exposed lath with drywall screws,  ensure you pre drill all screw holes to avoid cracking the lath.  Leaving a 2" space between the existing plaster and the repair piece of drywall.  Most doityourself stores carry cutdown pieces of drywall.  When you purchase your patch, ensure you buy a piece that is narrower than the lowest spot of your patch.  The final coat of joint compound should be at least 1/8 inch above any taped areas.
Feather edge the plaster and drywall with a orbital sander using 40 grit sandpaper.  Do NOT break the bond of plaster that has adhered to the back side of the "good" plaster.  Clean all surfaces with a vacuum cleaner.
Spray lath and feathered plaster with a light coat of water and apply a thin coat (1/8 in.) of joint compound to all exposed surfaces.
Apply 1 layer of drywall tape.  Nylon tape works best, however, I have used both paper and nylon.  Apply nylon directly to the feathered plaster, lath and feathered drywall, overlapping all strips.  (Spray paper tape with water prior to applying to surface.)
Apply a second light coat of joint compound to all exposed surfaces.  Allow this step to set, but not cure.
Apply buildup layers, as needed, until all surfaces are smooth and even.
Allow this process to dry until cured.  Usually overnight.  Joint compound shrinks as it drys so additional build ups may be needed to achieve a smooth, even final patch. Remember to keep all paper/nylon tape at least 1/8 in. below the final surface of your patch.
Sand patch and surrounding plaster smooth.  Fill and smooth as needed.
Texture to blend with surrounding plaster.
Joe from Yuma
Answer: While the most common answer is "patch it with drywall", it can be done in lathe.
Save the lathe during the demolition.  Be very gentle, and use a fine tooth blade on any saw (preferably use a handsaw).  Don't stress the old lathe.  Now nail the lathe back in place.  If you come up short on wood, check a garden store for a cheap trellis to disassemble.  You can nail metal lathe over the wood lath, but it's really not needed.
Coat the plaster edges with a concrete bonding agent, or at least spritz them with water (else they'll draw water out of your new plaster and create cracks). Do two coats of "structalite", or another lightweight plaster.  Your top coat need not be fully even, because your existing plaster is not fully even.
Now prime.  Wait.  Prime.  Paint.


How do I get active contracts?

Question: My contracts won't work. It always says "There is no campaign active campaign.  Contracts are unavailable". Every day I check my contracts and I never get one.
Comment: At this point and time there are no active campaigns for you to complete contracts.  It is speculated that the next major update (the Pyro update not the smissmas update we just had) will bring a return to campaigns,  which will give you active contracts.
Answer: Contracts are part of the limited time campaigns such as Gun Mettle Campaign or Scream Fortress 2015. Joining a campaign may require an item, such as Gun Mettle Campaign Pass, to enter. Per the FAQ you are not able to do contracts when the campaign is over.

How do I get active contracts?


How to finding a zip dependency path?

Question: In my SBT build, I'm fetching a zip dependency (previously built with the sbt-native-packager plugin), published in my local Ivy repo with a bundle classifier.
But I need the dependency path in the Ivy repo, in order to unzip it (with IO.unzip), put some files in it and repackage it with sbt-native-packager.
I'm using the artifacts(...) method to find the artifact and add it as a dependency :
"foo" % "bar" % "1.0-SNAPSHOT" artifacts(Artifact("bar-bundle", "zip", "zip", "bundle"))

But after that, I'm a bit lost...
I tried to filter out the dependencyClasspath to find it :
val bundleFile = taskKey[File]("bundle's path")

val settings = Seq(bundleFile <<= dependencyClasspath map { _ filter (_.endsWith(".zip"))})

Trouble is : I can't find the zip dependency in any classpath...
What I'm doing wrong ?
I'm using sbt 0.13.
Answer: Zip files aren't on the classpath by default.  The types of artifacts that are included are configured by classpathTypes.  You can add "zip" to it with:
classpathTypes += "zip"

It will then appear on dependencyClasspath.
However, if it isn't really supposed to go on the classpath, you might pull it out of the update report directly.
bundleFile := {
   val report: UpdateReport = update.value
   val filter = artifactFilter(name = "bar-bundle", extension = "zip")
   val all: Seq[File] = report.matching(filter)
   all.headOption getOrElse error("Could not find bar-bundle")
}

See the documentation on UpdateReport for details.

How to finding a zip dependency path?


Reading output from yahoofinancials

Question: How to read the output from yahoofinancials 1.5 ref. [https://pypi.org/project/yahoofinancials/]
I'm new to Python, and need help to address the returned JSON Data output from:
from yahoofinancials import YahooFinancials
yahoo_financials = YahooFinancials('AAPL')
print(yahoo_financials.get_financial_stmts('annual', 'income'))**

first few lines of non ordered output:
{'incomeStatementHistory': {'AAPL': [{'2019-09-28': {'researchDevelopment': 16217000000, 'effectOfAccountingCharges': None, 'incomeBeforeTax': 65737000000, 'minorityInterest': None, 'netIncome': 55256000000, 'sellingGeneralAdministrative': 18245000000, 'grossProfit': 98392000000, 'ebit': 63930000000, 'operatingIncome': 63930000000, 'otherOperatingExpenses': None, 'incomeBeforeTax': 65737000000, 'minorityInterest': None, 'netIncome': 55256000000, . . .  . .}

My output is with single quotes and not double quotes as expected, but contain all 4 year, OK.
I can address a single year by:
data = yahoofinancials.getfinancial_stmts('annual', 'income')
data['incomeStatementHistory']['DSV.CO'][0]

get ordered output key value in each line:
{'2018-12-31': {'researchDevelopment': None'effectOfAccountingCharges': None,
  'incomeBeforeTax': 5201000000,
  'minorityInterest': -29000000,
  'netIncome': 4000000000,
  'sellingGeneralAdministrative': 11301000000,
  'grossProfit': 17489000000,
'ebit': 5426000000,
'operatingIncome': 5426000000,
'otherOperatingExpenses': None,
'interestExpense': -355000000,
'extraordinaryItems': None,
'nonRecurring': None,
'otherItems': None,
'incomeTaxExpense': 1213000000,
'totalRevenue': 79053000000,
'totalOperatingExpenses': 73627000000,
'costOfRevenue': 61564000000,
'totalOtherIncomeExpenseNet': -225000000,
'discontinuedOperations': None,
'netIncomeFromContinuingOps': 3988000000,
'netIncomeApplicableToCommonShares': 4000000000}}

Here I want to adress a few single data items, but nothing works for me. Please help.
When I try to address 'ebit':
    data['incomeStatementHistory']['DSV.CO'][0]['ebit']

I get the following error:
---------------------------------------------------------------------------
KeyError                          Traceback (most recent call last)
ipython-input-12-66fa46d51257> in module>

-----> 1 data['incomeStatementHistory']['DSV.CO'][0]['ebit']

KeyError: 'ebit'

I also want to get EBITDA, where do I get it?   It is included from Yahoo.
I can get a few single data-items by: get_total_revenue() and get_net_income(), but only from the last year.  Can it be made to take year and or quorter as a parameter.
I'm using Windows 10 and Python 3.7
Any help will be much appreciated.
Comment: how could you get `'DSV.CO'` if there is only `AAPL` ?
Comment: Thank you furas. DSV.CO is my favorit and I have called its data like AAPL. Problem solved. Your answer is accepted.
Answer: As you get in @PaulLo deleted answer - you can't get directly ebit because there is date like
 data['incomeStatementHistory']['AAPL'][0]['2019-09-28']['ebit']
 data['incomeStatementHistory']['AAPL'][1]['2019-09-29']['ebit']
 data['incomeStatementHistory']['AAPL'][2]['2019-09-30']['ebit']

But there can be different dates which you can see with .keys()
 print( data['incomeStatementHistory']['AAPL'][0].keys() ) # ['2019-09-28']
 print( data['incomeStatementHistory']['AAPL'][1].keys() ) # ['2019-09-29']
 print( data['incomeStatementHistory']['AAPL'][2].keys() ) # ['2019-09-30']

To resolve this problem you can use dates from .keys() or use .items() or .values()
from yahoofinancials import YahooFinancials

yahoo_financials = YahooFinancials('AAPL')
data = yahoo_financials.get_financial_stmts('annual', 'income')

#print( data['incomeStatementHistory']['AAPL'][0].keys() ) # ['2019-09-28']
#print( data['incomeStatementHistory']['AAPL'][1].keys() ) # ['2019-09-29']
#print( data['incomeStatementHistory']['AAPL'][2].keys() ) # ['2019-09-30']

for item in data['incomeStatementHistory']['AAPL']:
    for key, val in item.items():
        print(key, val['ebit'])

Result:
2019-09-28 63930000000
2018-09-29 70898000000
2017-09-30 61344000000
2016-09-24 60024000000

Answer: How about this?
from datetime import datetime
import lxml
from lxml import html
import requests
import numpy as np
import pandas as pd

symbol = 'AAPL'

url = 'https://finance.yahoo.com/quote/' + symbol + '/financials?p=' + symbol

# Set up the request headers that we're going to use, to simulate
# a request by the Chrome browser. Simulating a request from a browser
# is generally good practice when building a scraper
headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9',
    'Cache-Control': 'max-age=0',
    'Pragma': 'no-cache',
    'Referrer': 'https://google.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
}

# Fetch the page that we're going to parse, using the request headers
# defined above
page = requests.get(url, headers)

# Parse the page with LXML, so that we can start doing some XPATH queries
# to extract the data that we want
tree = html.fromstring(page.content)

# Smoke test that we fetched the page by fetching and displaying the H1 element
tree.xpath("//h1/text()")

table_rows = tree.xpath("//div[contains(@class, 'D(tbr)')]")

# Ensure that some table rows are found; if none are found, then it's possible
# that Yahoo Finance has changed their page layout, or have detected
# that you're scraping the page.
assert len(table_rows) > 0

parsed_rows = []

for table_row in table_rows:
    parsed_row = []
    el = table_row.xpath("./div")

    none_count = 0

    for rs in el:
        try:
            (text,) = rs.xpath('.//span/text()[1]')
            parsed_row.append(text)
        except ValueError:
            parsed_row.append(np.NaN)
            none_count += 1

    if (none_count < 4):
        parsed_rows.append(parsed_row)

df = pd.DataFrame(parsed_rows)
df

Result:
                                              0  ...            5
0                                     Breakdown  ...    9/29/2016
1                                 Total Revenue  ...  215,639,000
2                               Cost of Revenue  ...  131,376,000
3                                  Gross Profit  ...   84,263,000
4                          Research Development  ...   10,045,000
5            Selling General and Administrative  ...   14,194,000
6                      Total Operating Expenses  ...   24,239,000
7                      Operating Income or Loss  ...   60,024,000
8                              Interest Expense  ...    1,456,000
9               Total Other Income/Expenses Net  ...   -1,195,000
10                            Income Before Tax  ...   61,372,000
11                           Income Tax Expense  ...   15,685,000
12            Income from Continuing Operations  ...   45,687,000
13                                   Net Income  ...   45,687,000
14  Net Income available to common shareholders  ...   45,687,000
15                                       EBITDA  ...   73,333,000

Reading output from yahoofinancials


Creating Joomla Accounts outside of a web interface

Question: Is it possible to create a Joomla account outside the web interface.  I want to create one from my Java application.  If so can you give me an idea about the best way to do this?
These are my thoughts so far:
1.  Create a php page that inserts the data directly into the database (but is there more to an account than simply the users table).
2.  Posting the data to the register page (but will it then detect that I am not using the web interface)
Answer: Yes, it's possible. You can:

Use php to achieve it, inheriting from JUser class like explained in this thread;
Create a component using JUser in you Joomla installation, and use xml-rpc to register users using this component by calling a service from you Java application.


How does the prototype chain work?

Question: var A = {};
var B = Object.create(A);
var C = Object.create(B);
A.isPrototypeOf(C);//returns true
C.isPrototypeOf(A);//returns false

In the above code I'm not understanding the reason behind the result of being false in C.isPrototypeOf(A);
Answer: var A = {}; // A inherits Object
var B = Object.create(A); // B inherits A inherits Object
var C = Object.create(B); // C inherits B inherits A inherits Object

// Does C inherit A?
A.isPrototypeOf(C); // true, yes
// C inherits A because    B inherits A    and    C inherits B

// Does A inherit C?
C.isPrototypeOf(A); // false, no
// A only inherits Object

Answer: C is "descended" from B which is "descended" from A. How could C be the prototype of A?
As C is ultimately inheriting from A, and A gets nothing from C, then it is false that "C is the prototype of A"

How does the prototype chain work?


Updating php Session variable on image toggle

Question: I am trying to allow users to add/remove items from a shopping cart by simply clicking an image. I also want the image to change on click to show how many of this item has been purchased.
Finally, I want the cart to exist on a separate tab of the same page.
What I have so far is:
<?php session_start(); ?>
...
...

...
...

Name
Price
Quantity
Total

<?php
    if($_SESSION['cart']) {
        foreach($_SESSION['cart'] as $itemname => $quantity)
        {
            if($quantity == 0) continue;
            $price = $_SESSION['items'][$itemname];
            $prod = $price*$quantity;
            $_SESSION['total'] += $prod;
            echo "
";
            echo "" . $itemname . "	";
            echo "" . $price . "	";
            echo "" . $quantity . "	";
            echo "" . $prod . "	";
            echo "
";
        }
        echo "
";
        echo "	";
        echo "	";
        echo "	";
        echo "" . $_SESSION['total'] . "	";
        echo "
";
        echo "
";
    }
?>

Continue Shopping

The problem I'm having is that the image changes correctly (only changes when I click it and toggles through the four different images), but when I view the contents of the cart, it doesn't change. It executes all 4 php statements immediately. I know because if I remove the final toggle switch(where I reset the quantity to 0) and view the cart, it already shows that I have 3 items to be purchased before I even click once.
Any help would be appreciated. I am guessing I could also have constructed the images as form inputs, or hyperlinks that execute a script on click, but I have tried both approaches with no luck.
Thank you in advance.
Comment: You can't do that. You need to post that number you're setting it to (via AJAX) to a server side script that assigns it. Read a tutorial on AJAX - all you're doing here is redefining your session variable four times (sorry, three times - one is commented out)
Comment: Also you might want to consider getting to understand the difference between client and server side technologies altogther
Answer: Javascript is executed in the browser, and php is executed on the server, before the page is served to the user.
Your PHP snippets are not executed when the javascript is called, rather they are executed on the server before the user even sees the page.
Instead of putting the PHP code directly in the javascript functions you need to use an AJAX call there that sends a request to the server.
That said, it looks like in this particular case it might be better to store the cart information in cookies rather than the session.
Comment: you should put them in the click handler if you want them to be called whenever the images are clicked on (you can use the .click() jQuery method).
Comment: I have moved the php code into a separate file, and now I've tried both
    XMLHttpRequest.open("GET","updatecart.php?action=add&id=1",true)
and
    $.ajax({ url: "updatecart.php?action=add&id=1", data: "", dataType: 'json' })

as drop-in replacements at the toggle point, but neither one seems to execute at all. Am I still missing something? Where should these calls go if I want them to execute on every click?? The toggle function seems only able to update the attributes of the image you are toggling, and can't really understand anything else.


How do I heal in Minecraft Beta 1.8?

Question: I'm eating a load of cooked pork chops but my health isn't increasing, what do I do?
Comment: Related question: [How does food work in Minecraft?](http://gaming.stackexchange.com/questions/30036/how-does-food-work-in-minecraft)
Answer: here is the article on the minecraft wiki on Food and Health

As of 1.8, health is not restored by consuming food, but rather slowly regenerates when the player's "Food Bar" is full.

and here

In the 1.8 update, the food mechanic was changed-- No longer does eating food regain health, but instead fills the Hunger Meter, which goes down when the player does things like running, sprinting, and mining. When the player has 9 or more meat bones on the hunger meter, their health will slowly regenerate.
Comment: So theres no outside way to heal your health anymore, ei maybe a potion, you just gotta keep your health at or about 80% x.x
Comment: @RokonOrichiami As of 1.9 you can make a instant health potion see: http://www.minecraftwiki.net/wiki/Brewing
Answer: You (should) auto regen health when your food bar is full. Food no longer directly heals you.
Answer: Always eat a golden apple or eat something normal such as a apple. When you eat your hunger bar refills and your health will slowly regenerate!
Comment: Additionally most of your answer was covered by the previous two answers nearly two years ago and doesn't contribute much else. Golden apples might have been something worth expanding upon, as they do provide some additional health-related bonuses beyond the hunger bar.
Comment: Welcome to Arqade! You might want to visit the [about](http://gaming.stackexchange.com/about) and [help](http://gaming.stackexchange.com/help) pages to better understand how our site functions, particularly the "[How do I write a good answer](http://gaming.stackexchange.com/help/how-to-answer)" section.
Comment: This answer is too short and vague. you didn't even explain how to get a golden apple.

How do I heal in Minecraft Beta 1.8?


How to stream videos over local network to TV from PC

Question: I have quite a bit of hardware already (A Wii U, an Xbox 360, a Chromecast, a Raspberry Pi etc) but I still can't find a good way to watch the videos saved on my Ubuntu computer, on my TV downstairs. Is this possible? Do I need to buy something else to play them? I thought the Chromecast was going to be the answer but I can't find any working software.
Comment: I believe Google is still working on adding the ability to cast the desktop to Chrome. I would instead try connecting the Raspberry Pi to the TV, using `sshfs` to have the folders in your laptop accessible to the Raspberry Pi through SSH, and then playing the video in Pi.
Comment: @saiarcot895 could you add this as an answer so I can follow your steps and see if they work for me?
Comment: I second the Raspberry Pi solution with sshfs. For a nice media player interface for your Raspberry, take a look at [XBMC](http://xbmc.org/).
Comment: @Jos this looks like the exact solution I was looking for. I think the HDMI out is broken on my pi atm so I'm going to order a new one I think, unless there's something better/cheaper that you (or anyone) can recommend.
Comment: @captainjamie: I added the `sshfs` version as an answer below.
Comment: No, HDMI should work really well on the Pi. Notice also the XBMC apps that turn your smartphone into a remote control, and the tons of plugins.
Comment: @Jos Oh no, it is working now. Just a broken HDMI cable apparently. Wow, I wish I'd have asked this sooner, this stuff is awesome!
Answer: While there isn't any support for casting the desktop to Chromecast (yet), you could instead try playing the video files on the Raspberry Pi itself. This could be achieved by using sshfs, which displays the contents of a folder on your computer on the Raspberry Pi by using SSH.

Make sure that you have openssh-client and sshfs installed on the Raspberry Pi, and openssh-server installed on your computer. The following steps will be on the Raspberry Pi only.
Run sudo usermod -aG fuse pi, where pi is the username on your Raspberry Pi, and log in and out of your account for the changes to take effect.
Create a folder that will display the files in your computer. (For example, mkdir computerVideos).
Run sshfs email@example.com:/home/captainjamie/Videos computerVideos, where captainjamie is the username on your computer, 192.168.1.101 is the local IP address of your computer, /home/captainjamie/Videos is the folder on your computer containing the videos, and computerVideos is the folder you created in the previous step.
The files in your computer will display in the computerVideos folder. Run any videos you want.

Note that this could be extended to any other files as well.
As noted by @Jos above in the comments, you can use XBMC to get a nice media player interface with support for plugins.
Comment: I can get ssh to work but not sshfs. It says: `failed to open /dev/fuse` or if I run with sudo: `device not found, try 'modprobe fuse' first`
Comment: I've sort of worked around it. I changed some permissions and rebooted and now if I run `sudo -i` in the terminal I can run the command and it all works. Sort of. Still need to be root though, can't seem to get on without that
Comment: Strange. Did you try `sudo modprobe fuse`?
Comment: You also shouldn't have to be root to do this, and being root will mess up access through public-key authentication (if you were using this method).
Comment: Right, I just needed to run `sudo usermod -aG fuse pi` (where `pi` is the username on my raspberry pi) and also `exec su -l $USER`. This has fixed everything. (Perhaps add that to your answer)
Comment: Added a slight variation to my answer.


Don't understand the inner function in python

Question: I have this problem:

cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
Given this implementation of cons:
def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair

Implement car and cdr.

I don't get the function.
It has an inner function and calls an other function in the return. As far as I understood the inner functions is that these functions should depend on the functions above them.  In this case on cons(..).
But the function is not using a or b. And why is the function f there? The task is to implement car and cdr, and function f should be given.
So could someone explain me this function? And how could I start with the task?
Comment: IMO, `cons` should return a tuple, not a function
Comment: @cricket_007: but `cons()` is part of their assignment. So `cdr()` and `car()` will have to pass in a function that takes either the first or last argument passed.
Comment: @Martijn Right, just having a hard time thinking about how you would call this other than `cons(a, b)(func)`
Comment: @cricket_007 That's *exactly* how you would call it; it's an implementation of lambda calculus, and functions are the *only* kind of value you have. There *is* no tuple data structure, only functions that are defined to obey laws like `car(cons(a, b)) == a` and `cons(car(f), cdr(f)) == f`.
Answer: First of all: Python function objects are first class objects. A def statement results in a new function object, and you can retrieve that object by using the function name:
>>> def foo():
...     return 'foo was called'
...
>>> foo
<function foo at 0x11b3d8ae8>

What this means is that you can assign that object to other names too, and you can pass them as parameters to function calls. You can then later on call the function object by adding (...) to the reference:
>>> bar = foo
>>> bar()
'foo was called'

The function name is assigned to in the current namespace. In a module, that's the globals, but in a function such as cons, the name is added as a local. return pair in the cons function then returns the function object pair to the caller.
And function parameters such as f and a and b are also variables; if you pass in a function object as a parameter, then parameter_name(...) will call paramater_name and pass in any arguments in the ... part. f(a, b) calls f and passes in a and b.
The next item to understand are closures; closures are an extra namespace attached to function objects, for variables from a surrounding scope.
In the following example, spam is a name in the closure of the bar function:
>>> def foo():
...     spam = 'Vikings'
...     def bar():
...         return spam
...     return bar
...
>>> foo()
<function foo.<locals>.bar at 0x11b44bf28>
>>> foo()()
'Vikings'

Calling foo() returns a new function object; the bar() function inside of foo(). Calling that returned function object produces 'Vikings', the value of the spam variable in the foo function. How did bar() get access to that? Via the closure:
>>> foo().__closure__
(<cell at 0x11b3c05b8: str object at 0x11b469180>,)
>>> foo().__closure__[0].cell_contents
'Vikings'

So nested functions can have access to names from the surrounding scope via closures. (Side note: it's not the value that's stored in a closure, it's the variable. The variable can change over time, and just like other variables accessing the name later will reflect the new value; if spam was changed later on, calling bar() again would return the new value).
Now to your function: cons() creates an inner function pair(), and pair() has access to the parameters a and b via its closure:
>>> def cons(a, b):
...     def pair(f):
...         return f(a, b)
...     return pair
...
>>> cons(42, 81)
<function cons.<locals>.pair at 0x11b46f048>
>>> pair_42_81 = cons(42, 81)
>>> pair_42_81.__closure__
(<cell at 0x11b3c02b8: int object at 0x10f59a750>, <cell at 0x11b3c05b8: int object at 0x10f59ac30>)
>>> pair_42_81.__closure__[0].cell_contents
42
>>> pair_42_81.__closure__[1].cell_contents
81

The pair() function takes a parameter f, and calls that parameter, passing in a and b. Lets see what happens when we pass in print.
print is a function too, it is an object that you can call, and it writes the arguments to the console with spaces in between:
>>> print
<built-in function print>
>>> print('arg1', 'arg2')
arg1 arg2

If you passed that to the pair() function that cons() returns, you can see what f(a, b) does:
>>> pair_42_81(print)
42 81

print, passed to pair(), is assigned to f, and f(a, b) is exactly the same thing as print(a, b).
We can see that print() was called because the values are written out to the console. But you could also create a function that returns a new value. Say you have a function that adds up two numbers, and returns that value:
>>> def add(first, second):
...     return first + second
...
>>> add(42, 81)
123
>>> pair_42_81(add)
123

We can call the function directly, and 123 is returned, or we can have pair_42_81() do it for us, and the same result is returned to us. Simple!
All this works because functions are objects and can be passed around like other variables, and because pair_42_81 has a = 42 and c = 81 stored in a closure, and will use those to call a given object f with those two arguments.
Next up are cdr() and car(), which will return either the first or last element of a pair. If cons(a, b) produces pair(f) returning f(a, b), then cdr() and car() must each create a function to pass to pair() that'll extract either a or b.
So create a nested function in each, and have cdr() and car() call pair() with that function. The nested function does the work of picking either a or b, and returns that value. Then return the result of the call to the outside world:
def car(pair):
    def return_first(a, b):
        return a
    return pair(return_first)

def cdr(pair):
    def return_last(a, b):
        return b
    return pair(return_last)

pair(return_first) calls return_first(a, b), a is returned, and car() can return that to the caller:
>>> car(cons(42, 81))
42

and the same applies to pair(return_last), only now b is returned:
>>> cdr(cons(42, 81))
81

You may be interested in the background of these operations; car, cdr and cons come from LISP, where cons a b Constructs a cell with two pointers (explaining the name), and car (meaning Contents of the Address part of the Register number in the IBM 704 instruction set LISP was created on) and cdr (meaning Contents of the Decrement part of the Register number in 704 language) take the first and remainder parts of such a cell. See this Wikipedia article on the names.
Comment: Thanks for the detailed explanation. I think it's easier to get `cons(3,4)(lambda a, b: a)` but it's pretty hard for me to actually write the proper nested function which allow inner function get to access the original parameter like (3,4) within car and cdr
Comment: Great explanation! Much easier to understand than just having a solution.
Answer: cons is a function which takes two arguments, a and b and returns a function pair.
The function pair takes a function f as an argument which consumes two arguments.
def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair

f = lambda n, m: n**2 + m**3
car = lambda n, m: n
cdr = lambda n, m: m
print(cons(2, 3)(f))
print(cons(2, 3)(car))
print(cons(2, 3)(cdr))

f returns 31 = 2**2 + 3**3
Note how cons has two times the parenthesis (...) - once, for its own call and another time for the returned functions call.
Please note this answer to be able to call car(cons(2, 3)). You might also be interested in Why would a program use a closure?
Comment: In the context of the assignment, though, you would never actually call `cons(2,3)` on a function like `f`; its purpose is to take either `car` or `cdr` as an argument to retrieve the appropriate value from the tuple.
Comment: (You do still want to be able to call `car(cons(2,3))`, though; `car` and `cdr` need an additional level of indirection to allow that.)
Comment: @chepner I've added a comment to Martijn Pieters answer
Answer: This is called a closure. Two basic elements

the pair function knows the values of a and b. They are just like local variables in that respect
the cons function returns a function, not a value. You have to call the result again

So, when you call cons(a, b) you get a function that does something to a and b, only it doesn't know what yet. You have to pass another function for that. Eg
 my_f = cons(1, 2)
 result = my_f(lambda x, y: x + y)
 print(result) # 3

How this is related to your assignment is not very clear. I would only assume that for car, you only want the element a (the head), and for cdr you want the element b  (the rest of the list). So, the functions would just return the one argument and ignore the other. Eg
car_f = lambda x, y: x
cdr_f = lambda x, y: y

Comment: It's an implementation tuples in lambda calculus; `cons` returns a functional encoding of a tuple, where you retrieve the first or second element of the tuple by calling the tuple on the appropriate accessor. It's a reversal of the usual data-centric implementation. You don't call `car(some_tuple)`; you call `some_tuple(car)` instead.
Comment: @chepner: aa, ok then, makes more sense that way.
Answer: I manually converted cons function the Javascript version and then implemented the quiz:

cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.Given this implementation of cons:

def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair

Implement car and cdr.

Here is the solution

function cons(a, b) {
  function pair(f) {
    return f(a, b);
  }
  return pair;
}

function car(pair) {
 return pair((a, b) => a);
};

function cdr(pair) {
 return pair((a, b) => b);
};

console.log(car(cons(3,4)));
console.log(cdr(cons(3,4)));
Answer: Use lambda expressions
def cons(a, b):
    def pair(f):
        return f(a, b)

    return pair

def car(pair):
    return pair(lambda a, b: a)

def cdr(pair):
    return pair(lambda a, b: b)


How to copy file from etc to home?

Question: I need to make a copy of /etc/default/grub file and put it in ~/backup/config/ directory In Gnome files.
Comment: Can you provide more information on what problem you are having?  Are you receiving an error message?
Answer: This is the command. If you met with an error comment the error.
<code>sudo cp -R /etc/default/grub /backup/config/grub
</code>

How to copy file from etc to home?


Select phenotypes to use for empires

Question: Is there a way to limit what phenotypes an empire will use for the pops/leaders?
Phenotype is what the game calls the different coloured pops.
Example: I want to set up a game with USA/China/Russia based space empires all using human as race (or 3 separate race definitions using the human model) but still have them look slightly different this way.
Answer: The Separate Human Phenotypes mod allows this.
This mod splits humans into difference portraits, allowing you to make a species entirely of one race.
Unmodded, there is no way to do this.
Comment: This answer seems correct, but beware, answers like these are close to falling under the category of spam! Please read our [guide](https://gaming.stackexchange.com/help/promotion) so you don't accidentally post an answer that will be flagged as spam and deleted.
Comment: @ExpertCoder14 I added a description of the mod. Not sure what else I can do here.
Comment: The last line basically saying "no" technically answers the question. The info about the mod also solves my problem. As the asker I also don't see how it could be answered much better. Maybe pointing towards mods as a general solution since there could potentially be others also solving this in different ways? Anyway, thanks!
Comment: @ComicSansSeraphim I do agree that that's about as good as it'll get. Thanks for improving your answer! Every contribution helps.

Select phenotypes to use for empires


Prove that $\mathcal{O}_3$ and $\mathcal{O}_7$ are euclidean domains

Question:
For a non-square integer $d$ such that $d \equiv 1 \mod 4,$ we define the set $$\mathcal{O}_d := \left\{\frac{a + b\sqrt{d}}{2}:a,b \in \mathbb{Z}, a \equiv b \mod 2 \right\}.$$
Prove that $\mathcal{O}_3$ and $\mathcal{O}_7$ are euclidean domains (draw their lattices in the complex plane).

In my class we drew a general lattice for $\mathbb{Z}[i]$:

and then proved $\mathbb{Z}[i]$ is a euclidean domain:
Consider $\dfrac{b}{a} \in \mathbb{C}.$ Let $q \in \mathbb{Z}[i]$ be the closest Gaussian integer to $\dfrac{b}{a}.$ Then the norm function $N \left(\dfrac{b} {a}-q \right) \leqslant \left(\dfrac{1}{\sqrt{2}}\right)^2 = \dfrac{1}{2}.$ Set $r := b -aq \in \mathbb{Z}[i].$ Then $N(r) = N(b - aq) = N \left(a \left(\dfrac{b}{a} -q \right) \right) = N(a)N \left(\dfrac{b}{a} - q \right) \leqslant \dfrac{1}{2} N(a) < N(a).$
First off, how do we draw these lattices? I am not entirely sure how to draw $\mathbb{Z}[\sqrt{-2}]$ or $\mathbb{Z}[\sqrt{3}]$ since I don't fully understand how the values $\dfrac{1}{\sqrt{2}}$ and $1$ are chosen in the example above. Would the same methods work for drawing $\mathcal{O}_3$ and $\mathcal{O}_7$ in the complex plane? I'm not really sure where to start proving that they are both euclidean domains.
Comment: Really need help on this one, commenting to make it active
Answer: I'm sorry, I didn't notice that $O_3$ and $O_7$ are no domains, less Euclidean domains. We need $d\equiv 1\mod 4$, which is  not true for $3$ and $7$. In fact,
for any $p=4k+3$ we have
$$
\left(\frac{1+\sqrt{p}}{2}\right)^2=\frac{1}{4}(p+1+2 \sqrt{p})=k+1+\frac 12\sqrt{p}\notin O_p.
$$
so the question about $O_3$ and $O_7$ is settled. If you take $p=5$ or $p=13$, then the following works:
Let $p=5$.
Your lattice consists of the points $(a/2,b/2)$ in $\Bbb{R}^2$ with $a,b$ integer and $a\equiv b\mod 2$. Then you can show that for any point $(x,y)$ in $\Bbb{R}^2$, (hence the same holds for points in $\Bbb{Q}^2$), you can find a point in the lattice with $|x-a/2|\le 1/2$ and $|y-b/2|\le 1/4$ (Draw the picture).
Now, if you are working in $O_5$, you take the multiplicative function
$$
N((a+b\sqrt{5})/2):=|a^2-5b^2|/4,
$$
defined in all $\Bbb{Q}[\sqrt{5}]$. If you divide $(a+b\sqrt{5})/2$ by $(c+d\sqrt{5})/2$, then you find
$$
\frac{a+b\sqrt{5}}{c+d\sqrt{5}}=\frac{ac+5bd}{c^2-5d^2}+\frac{bc-ad}{c^2-5d^2}\sqrt{5}=x+y\sqrt{5}
$$
in $\Bbb{Q}[\sqrt{5}]$. Now you take $(e/2,f/2)$ in your lattice with $|x-e/2|\le 1/2$ and $|y-f/2|\le 1/4$.
Then
$$
N(x-e/2+(y-f/2)\sqrt{5})=|(x-e/2)^2-5(y-f/2)^2|\le (x-e/2)^2+5(y-f/2)^2
$$
$$
\le 1/4+5/16<1.
$$
Hence, you can write
$$
(a+b\sqrt{5})/2=((c+d\sqrt{5})/2)((e+f\sqrt{5})/2)+r,
$$
with $r=(a+b\sqrt{5})/2-((c+d\sqrt{5})/2)((e+f\sqrt{5})/2)$ and
$$
N(r)=N\left(\frac{(a+b\sqrt{5})/2}{(c+d\sqrt{5})/2}-(e+f\sqrt{5})/2\right)N((c+d\sqrt{5})/2).
$$
But
$$
N\left(\frac{(a+b\sqrt{5})/2}{(c+d\sqrt{5})/2}-(e+f\sqrt{5})/2\right)=
N(x-e/2+(y-f/2)\sqrt{5})<1,
$$
hence $N(r)<N((c+d\sqrt{5})/2)$. This shows that $O_5$ is an Euclidean domain with Euclidean function $N$.
For $O_{13}$ the lattice is exactly the same, the Euclidean function is
$$
N((a+b\sqrt{13})/2):=|a^2-13b^2|/4,
$$
and all works exactly the same way, once you have established that for any point $(x,y)$ in $\Bbb{R}^2$, (hence the same holds for points in $\Bbb{Q}^2$), you can find a point $(e/2,f/2)$ in the lattice with
$$
N(x-e/2+(y-f/2)\sqrt{13})=|(x-e/2)^2-13(y-f/2)^2|<1.
$$
For this it suffices to show that the translations of the elipse $x^2+13y^2<1$ to every point of the lattice cover all of $\Bbb{R}^2$. For this you need to know that $\frac{\sqrt{3}}{2\sqrt{13}}+\frac{1}{\sqrt{13}}>\frac 12.$
${\bf{Edit:}}$ I'just noticed that $O_3$ and $O_7$ are not closed ounder multiplication, so I rewrote it for $O_5$ and $O_{13}$.
Answer: Using the norm $N((a+b\sqrt{3})/2):= \frac{1}{4}|a^2-3b^2|$  I drew the fundamental domain $N(z) < 1$ and the corresponding hexagonal lattice.  These look like Eisenstein integers $\mathbb{Z}[e^{2\pi i /3}]$ except the discriminant is positive instead of negative.
Your goal is to show any of the blue dots can be translated onto the green area using lattice vectors.  The fact is you get infinitely many as you go up the tentacles of the hyperbola, but they are all related by a factor of units in this ring.
To the compute the units in this ring note that $\sqrt{3} = [1, \overline{1,2}] $ is the continued fraction expansion and from you compute the units by solving Pell's equation.

The corresponding situation for $\sqrt{7}$ is a bit more tricky.  The diagram suggests you get a Euclidean norm  as before - $N((a+b\sqrt{7})/2):= \frac{1}{4}|a^2-7b^2|$ -  by a narrower margin.
This trick works for discriminants up to around $13$ and there are norm Euclidean rings up to $d = 51$ and $73$.  The proof is not obvious.
Comment: See also: Keith Conrad [Euclidean Domains](http://www.math.uconn.edu/~kconrad/blurbs/ringtheory/euclideanrk.pdf)


Column data types changing during Replication

Question: We have a set of MSSQL database servers which normally replicate several databases between them. One server is MSSQL 2008, another is MSSQL 2005, and the last is MSSQL 2000.
This has recently gone wrong, and I'm trying kind of desperately to fix things.
We have one MSSQL server which, every morning, receives a copy of an Informix database from our Informix server and dumps all of the data into the CompanyInformix database on the MSSQL server. It does this, as far as I can tell, correctly, and without error.
An hour later, that SQL server Pushes a Replication Publication to our two other MSSQL Servers, and to itself, Pushing out several tables from CompanyInformix to CompanyInforbits.
On two servers this works fine. On the MSSQL 2000 server, however, when Publishing occurs, all of the columns of datatype "date" are changed to datatype "nvarchar(10)". This is a problem.
I assume the root of this problem is that MSSQL2000 doesn't appear to have a "date" datatype.
This was working last week, and my attempt to recreate the Replication that was going on last week has obviously gone wrong, somewhere.
Can anyone suggest what might be going wrong, here and what I can do to prevent Replication from changing these column datatypes?
Answer: Yes correct, the date data type is not supported in SQL Server 2000.
What you have here is a mixed Replication topology, so you are going to have to implement some of the Microsoft recommendations for working with such an environment.
Take a look at the following reference: Using Multiple Versions of SQL Server in a Replication Topology
If you modify the data type at the Publication to be datetime, you "should" be able to maintain this data type throughout the topology.
Comment: The top SQL Server Publication database (to which all others Subscribe directly, or indirectly) in the topology should use the datetime data type. Then all Subscriptions will use this data type also, ensuring consistent use throughout the whole topology.
Comment: Keep in mind that to get this to work you will need to re-create your Publications and Subscriptions.
Comment: When you say "modify the data type at the Publication" do you mean to change the datatype of the column in the CompanyInformix table, or is there some way to change the datatype of the column in the Publication itself?
Comment: Okay, thanks. I'll have to go and talk to the Informix guy, then, because he's the one exporting that data. Thanks very much.


NSAttributedString Strikethrough makes my attributed text disappear

Question: I am trying to make an attributed string with a strikethrough. I can set other attributes such as foreground color and font size but when I try to set a strikethrough through part of the text, that part of the text disappears. Any Idea what might be causing it?
Below is the code. Thanks for looking!
// ...
    //Price
    NSLog(@"RESULT NUMBER %d", cell.result.resultId);
    priceString = (priceString == nil) ? @"$150.00\n$100.00" : priceString;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:priceString];
    NSRange linebreak = [priceString rangeOfString:@"\n"];

    if (linebreak.location != NSNotFound) {
        [attributedString beginEditing];
        // RegPrice
        NSRange firstLine = NSMakeRange(0, linebreak.location);
//        [attributedString addAttribute:NSFontAttributeName
//                                 value:[UIFont boldSystemFontOfSize:11]
//                                 range:firstLine];
        [attributedString addAttribute:NSForegroundColorAttributeName
                                 value:[UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1]
                                 range:firstLine];
        @try {
            [attributedString addAttribute:NSStrikethroughStyleAttributeName
                                     value:@(NSUnderlineStyleSingle)
                                     range:firstLine];
        } @catch (NSException *e) {
            NSLog(@"ATTRIBUTE EXCEPTION: %@", e);
        }

        // Sale Price
        [attributedString addAttribute:NSFontAttributeName
                                 value:[UIFont boldSystemFontOfSize:14]
                                 range:NSMakeRange(linebreak.location + 1, priceString.length - (linebreak.location + 1))];
        [attributedString endEditing];
    }
    cell.lblPrice.attributedText = attributedString;

    return cell;
}

Answer: I had the same problem of string disappearing until I realised that the value for NSStrikethroughStyleAttributeName should be an NSNumber.
Therefore the code above should look like:
Objective-c
[attributedString addAttribute:NSStrikethroughStyleAttributeName
                         value: [NSNumber numberWithInt: NSUnderlineStyleSingle]
                         range:firstLine];

In Swift 4 attributes are passed using dictionary of type [NSAttributedStringKey: Any] and the strike trough style attribute would look like this:
[NSAttributedStringKey.strikethroughStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue)]

Comment: This is the only answer here that worked for me. It is clearly a bug / not what Apple intended...
Comment: Happy that helped. Not sure that is a bug, but is definitely not very "swifty"
Comment: Thank you so much!! This saved me!
Answer: For me boldSystemFontOfSize: returns a font object with the HelveticaNeueInterface-MediumP4 font. Are you sure this font has a strike-through? Not all fonts do. Maybe try using a different font, one that you know has a strike-through.
Comment: Thanks, that's a good thought. However, I tried switching it to arial and did not seem to work. Do you know any font that does support strikethrough?
Comment: I don't. I had this same problem and eventually got fed up and drew the stirke-through lines myself as suggested by this http://stackoverflow.com/a/2489560/2033515
Answer: I had the problem with the strikethrough text disappearing in a UILabel in iOS 7.0 only. It works fine in iOS 6.1 and 7.1.
There seems to be a bug in iOS 7.0 that strikethrough text disappears if the label is too high for the text by a certain amount. It works when I set the label's frame to a small enough height or call sizeToFit after setting the attributedText.


How to use check validity to validate a form with jquery

Question: I'm trying to debug a snippet, so I can understand how it works the native javascript validation checkValidity():
Here's the problem:
First I create an array of value and a form connected with a click event:
jQuery('input[name="submit-request-form"]').click(function() {
    var fields = [ 'FirstName','Lastname','Email','Telephone','CampusID','ProgramID'];
    var form = 'flow-request-form';
    disableSubmitButton( $(this) , fields , form );

});

The next step is to create a function in order to get all the elements in the form based on my array and if all of them are filled, change the value valid to false and submit the form.
function disableSubmitButton( Obj , fields , form ){

    var valid = true;
    for (var i = 0 ; i < fields.length ; i++) {
        var element = jQuery('form[name="'+form+'"] [name="'+fields[i]+'"]');
        console.log( element[0].checkValidity());
        if( element[0] && !element[0].checkValidity() ){
            valid = false;
            break;
        }
    }
    console.log(valid);
    if(valid){
        Obj.attr('disabled' , 'disabled');
    }
}

In case the value of my form will be not filled or invalid, the valid variable won't change to false and it will disable the button.
Something though got wrong and my value will always be true.
Do someone knows why?
The snippet is the following:
if( element[0] && !element[0].checkValidity() ){
    valid = false;
    break;
}

that's where my code fails
Comment: You should disable the button if the form is *not* valid.
Comment: I think this code snippet should give you a better idea of how the checkValidity() function works. https://www.w3schools.com/js/tryit.asp?filename=tryjs_validation_check
Comment: I must admit, I'm a little confused - this seems like a highly convoluted way of checking the validity of a form. (And extremely brittle, given that you're hard-coding the names of form inputs into your script.) Other than this though I can't yet see anything *wrong* as such - but I'm bound to ask, since you have that `console.log` in there, what gets output in the console?
Comment: it should be `if (!valid)`
Comment: it outputs the input 6 true
Comment: You are all right, I just try to debug that snippet. I would have done differently, but I kind of like the approach and the challenging. The only thing is that it's not quiet clear for me the checkvalidity() native function
Answer: You could use form.reportValidity() for that. It basically checks the form and validates it, and if it detects an invalid field, it will return a popup message.

trackedInput = $('#trackedInput');
confirmSubmit = $('#confirmSubmit');
yourForm = document.querySelector('#confirm');

confirmSubmit.click(function(e) {
  yourForm.reportValidity();
});

  <input id="trackedInput" type="text" form="confirm" required>

  //Some other stuffs here

  <input id="confirmSubmit" type="submit" form="confirm" required>

<form id="confirm"></form>
Comment: You'd be surprised how difficult it is to find jQuery validation's `.reportValidity()`.  You're a lifesaver: Thank you!


Reproducing deadlock while using Popen.wait()

Question: From the docs using Popen.wait() may:

deadlock when using stdout=PIPE and/or stderr=PIPE and the child
  process generates enough output to a pipe such that it blocks waiting
  for the OS pipe buffer to accept more data. Use communicate() to avoid
  that.

In communicate docs it's written that:

The data read is buffered in memory, so do not use this method if the
  data size is large or unlimited

How to reproduce such a problematic behavior and see that using Popen.communicate() fixes it?
Deadlock means some circular wait between processes holding resources happens and is stuck forever.
What is the circular dependency here? Python process which waits for the child process to terminate is one wait. What's the other? Who waits for what in the below scenario?

it blocks waiting for the OS pipe buffer to accept more data
Comment: If you reached the deadlock, communicate won't 'fix' it. You should use communicate in the first place, which avoids reaching the deadlock.
Comment: actually i had a situation when the code using wait was stuck each time it was run, until it was modified to use communicate and it wasn't stuck anymore. so i want to reproduce the case of deadlock and see that communicate solves it
Answer: It's easy.
Create a process which outputs a lot of text and don't read the output:
p = subprocess.Popen(["ls","-R"],stdout=subprocess.PIPE)
p.wait()

after a while the standard output pipe is full and process is blocked.
It's a deadlock situation because the subprocess cannot write anymore to the output until it's consumed (which is: never), and the python process waits for the subprocess to finish.
To avoid the deadlock, you could use a read line loop:
p = subprocess.Popen(["ls","-R"],stdout=subprocess.PIPE)
for line in p.stdout:
    # do something with the line
p.wait()

communicate also fixes that but also fixes the much trickier case where both output and error streams are redirected to separate streams (in that case, the naive loop above could still deadlock).
Let's suppose you have a compilation process
p = subprocess.Popen(["gcc","-c"]+mega_list_of_files,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

Now you want to get the output from this one, so you do:
output = p.stdout.read()

unfortunately, a lot of errors pop up instead, blocking the error stream while you're reading the output stream: deadlock again.
Try to read error stream instead, and the exact opposite could occur: lots of stdout output blocking your process.
communicate uses multithreading to be able to process output & error streams at the same time and keep them separated, without risk of blocking. Only caveat is that you cannot control the process output line by line / print program output in real time:
p = subprocess.Popen(["gcc","-c"]+mega_list_of_files,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output,error = p.communicate()
return_code = p.wait()

Comment: yes, your python process. Of course if the output is unlimited, communicate never ends & consumes all the memory. in that case you have to kill the process when encountering a given line for instance. You have to read it line by line in that case.
Comment: thanks. what entity should consume the output that's full? parent process? don't understand also how communicate fixes it. it's written in its docs that `do not use this method if the data size is large or unlimited`
Comment: _Great_ answer.  Seems like there's an idea that you must always use `communicate()` when using `PIPE`, which as you point out isn't the case.  The docs aren't actually wrong, in that the read line loop prevents _and the child process generates enough output to a pipe such that it blocks..._.
Comment: if you use `communicate()` there are things you cannot do, like reading line by line and performing actions in real-time when the process is outputting data. Simplest example: printing and logging to the console at the same time, and detecting a special line to terminate the process (specially if the process runs forever if not stopped, which forbids the use of communicate…). Also most of the time merging output & error streams are okay, and it avoids deadlocks (if output is consumed of course)


Packing IOS App with Large Amount of Data

Question: How can I have the customer of an IOS app select and change selection data for use with an app?
I have an app that is designed to operate away from wifi. As such, it needs to carry its data around with it. This makes the data requirements rather large.
A base package is 25MB of data.  However, it is likely people who use this app would want as much as 1GB of data.
Is it possible to do selective data downloads and updates from the app store?
How else could this be done
Answer:
How can I have the customer of an iOS app select and change selection of data for use with an app?

Hard to say. It's not clear what you're talking about. Downloading data through an app is a well researched topic. You shouldn't have any trouble finding examples for downloading data to an app, here or elsewhere.

Is it possible to do selective data downloads and updates from the app store? How else could this be done?

Again, its not 100% clear what you mean. I don't think you can use the app store to provide new data to users who downloaded your app, unless you're talking about a full app update that comes bundled with your new data set.
I worked on a project once that had to work offline, but also work with a very large data set as well as some mapping components. We required users to first download our app, then after authenticating, the app would automatically download a cache of data while connected to a WiFi hotspot. When the user was out of WiFi range the app would operate off the data set they downloaded and would operate normally. When they came back into range it would ping the server to find out if their data was stale. If it was stale it would download new data. The WiFi connection requirement ensured that they would have an optimal experience fetching the latest data.
Answer: My thought is to create a menu in your app that lets the user select which "packages" of data they want to save to their device and run those downloads in the background when the user has an internet connection.


Get data from textbox to pass to controller without refreshing page/submitting form in MVC

Question: Right now, on my page I have a button at the top of one of my views <button type="button" id="show">Find Project</button> that when pressed, renders a partial view (which is a table) at the bottom of the page. My layout is formatted as:

        @RenderBody()

The javascript that makes the table appear is:
$(document).ready(function() {
    $("#show").on("click", function() {
        $.ajax({
            url: '/Projects/SearchTable',
            type: "GET"
        }).done(function(partialViewResult) {
            $(".wrapper").html(partialViewResult);
            $(".wrapper").css('display', 'block');
        });
    });
});

/Projects/SearchTable is the controller action that renders the partial view:
[HttpGet]
public ActionResult SearchTable()
{
    var states = GetAllStates();
    var model = new ProjectClearanceApp.Models.ProjectViewModel();

    model.States = GetSelectListItems(states);
    model.Projects = from m in db.Projects select m;

    return PartialView("~/Views/Projects/_ClearedProjects.cshtml", model);
}

The text boxes are dispersed throughout my main view, and all appear in the same format:

    @Html.LabelFor(model => model.Project.FirstNamedInsured, htmlAttributes: new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Project.FirstNamedInsured, new { @class = "form-control text-box single-line", maxlength=150 })
    @Html.ValidationMessageFor(model => model.Project.FirstNamedInsured, "", new { @class = "text-danger" })

Except for two dropdowns that are formatted like so:

     @Html.LabelFor(m => m.Project.FirstNamedInsuredAddress.State, htmlAttributes: new { @class = "address-label" })
     @Html.DropDownListFor(m => m.Project.FirstNamedInsuredAddress.State,
                           Model.States,
                           "--",
                           new { @class = "form-control address-entry" })
    @Html.ValidationMessageFor(model => model.Project.FirstNamedInsuredAddress.State, "", new { @class = "text-danger" })

where Model.States is an enumerable to populate the drop down list with all of the states.
Is it possible to get the data from those textboxes and pass them as data/arguments to the controller for use in the partial view without submitting a form or refreshing the page?
Answer: Send the parameter like this:
        public ActionResult SearchTable(string firstNamedInsured)
        {
            //Use the parameter in the model or any where
            var states = GetAllStates();
            var model = new ProjectClearanceApp.Models.ProjectViewModel();

            model.States = GetSelectListItems(states);
            model.Projects = from m in db.Projects select m;

            return PartialView("~/Views/Projects/_ClearedProjects.cshtml", model);
        }

And javascript:
$(document).ready(function () {
        $("#show").on("click", function () {
            $.ajax({
                url: '/Projects/SearchTable?firstNamedInsured=' + $('#' + @Html.IdFor(m => m.Project.FirstNamedInsured)).val(),
                type: "GET"
            }).done(function (partialViewResult) {
                $(".wrapper").html(partialViewResult);
                $(".wrapper").css('display', 'block');
                });
        });
    });


regular expression: trying to include unlimited whitespaces for any words in ASP.NET C#

Question: <code>[RegularExpression(@"\S*[a-z\s]\S*\s*", ErrorMessage = "Please add
category name letters only")]
</code>
This works fine if I input some words something like this...test test. But if I try to do this... test test test, I will get the ErrorMessage that I implemented. The thing is that I don't know how many words are going to put in by the end user. Is there a way where unlimted whitespaces could put in place? Could some tell me how to do this? Thanks in advance. I am using VS2010
Comment: I don't understand. Do you think that you could restate the rule(s) for me?  What do you want to allow, and what to disallow?
Comment: What format do you want exactly? Only lower-case letters? Any starting or ending requirements? How many spaces between words? No idea what you need it for but IMHO a category name ending with space sounds strange. You should `exactly` state what is allowed and what is not.
Answer:
([a-zA-Z\s]{1,})

use regex from above to resolve your problem.
Baically a-zA-Z will match any word case insensitive, and \s will match any whitespace character and {1,} will tell that this combination needs to have one or any number of matches.
I hope this helps
Comment: Thanks, Senad Meskin exactly what I was looking. Most Appreicated.


H2OTypeError: Argument `x` should be a None | integer | string | ModelBase | list(string | integer) | set(integer | string), got H2OFrame

Question: I working with the Titanic dataset and made some basic preprocessing (such as normalization, ohe, etc.).
Then, I tried to use H2O algorithm and got following error:
from h2o.estimators.gbm import H2OGradientBoostingEstimator
classifier  =  H2OGradientBoostingEstimator(nfolds =    5,
                                            ntrees =   15,
                                            seed   =    42,
                                            max_depth = 4)

classifier.train(predictors, target, training_frame = train_data)

H2OTypeError: Argument x should be a None | integer | string |
ModelBase | list(string | integer) | set(integer | string), got
H2OFrame

My target is train_data["Survived"].asfactor()
I tried to read to dataframe from file, instead of coverting the preprocessed df into H2OFrame but to no vail.
Any ideas would be appreciated.
Answer: It seems to me that you are passing frame instead of list of column names.
Both x and y are supposed to be "pointers" to columns in the training_frame.
If you want to use all columns as predictors (all except the target), you can specify just the y parameter.
Something like the following should do the trick:
train_data["Survived"] = train_data["Survived"].asfactor()
classifier  =  H2OGradientBoostingEstimator(nfolds =    5,
                                            ntrees =   15,
                                            seed   =    42,
                                            max_depth = 4)

classifier.train(x=["pclass", "sex", "age",  ...], y="Survived", training_frame = train_data)


What is the benefit of tagged PDF in comparison with logical PDF in reflowing

Question: I'm making a PDF viewer and try to make reflowing.
I read the PDF Reference 1.7
http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/pdf_reference_1-7.pdf
When I read the section "Logical Structure" (10.6), I think it's sufficient to make reflowing PDF. Because I can extract each chapter, each heading, each paragraph with layout, I can put them in xml to present as web displaying with reflowing by javascript.
Then I read the section "Tagged PDF" (10.7), it says it support reflowing, I don't recognize the different benefit here in comparison with "Logical Structure". Can anyone explain me?
Many thanks for your time!
Answer: They are both related, the logical structure is a tree at document level where each node may (or may not) have a reference to a marked-content (tag) in a page. Marked-content or tags is what will really tell you wich part of a page is a paragraph, or a figure, or something else. The logical structure tree is just the structure of the document, but using that alone you will not be able to process the content of each page.
Comment: Many thanks! I have one more question: I read somewhere, they say about "auto-tagging", can you explain more?


How i can create the function for the countdown in React native?

Question: My skills in react native is basic, i want to create a basic countdown,  when i click play the countdown start, like this example:

My Code:
render() {
return (

<Grid>
<Row>

<Col style={styles.col_exercise}>
<Image source={require('../../assets/images/done.png')} resizeMode="contain" style={styles.icon_videoexercise} />
<Text style={styles.titlecol_exercise}>Done</Text>
</Col>

<Col style={styles.col_exercise}>
<View style={{borderWidth: 2, borderColor: '#f39c12', borderRadius: 50, height: 100, width: 100,alignItems: 'center',
justifyContent: 'center'}}>
<Text style={{fontSize: 18, color: '#000'}}>
00:30
</Text>
</View>
</Col>

<Col style={styles.col_exercise}>
<Image source={require('../../assets/images/play.png')} resizeMode="contain" style={styles.icon_videoexercise} />
<Text style={styles.titlecol_exercise}>Play</Text>
</Col>

</Row>

</Grid>
);
}

Comment: You haven't actually asked a question. What **specific** problem are you stuck with at the moment?
Comment: How i can create the function for the countdown..
Comment: Edit your question to say that, and then post the relevant code you've written for doing that thus far.
Answer: constructor(props) {
  super(props);
  this.state = { timer: 30 };
}

componentDidMount() {
 this.clockCall = setInterval(() => {
   this.decrementClock();
 }, 1000);
}

componentWillUnmount() {
 clearInterval(this.clockCall);
}

decrementClock = () => {
 this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};

You can create a countdown with setInterval. Every second this.decrementClock() will be called after the component mounts.
You will want to render this.state.timer in your render method.
constructor(props) {
  super(props);
  this.state = { timer: 30 };
}

startTimer = () => {
 this.clockCall = setInterval(() => {
  this.decrementClock();
 }, 1000);
}

decrementClock = () => {
 if(this.state.timer === 0) clearInterval(this.clockCall)
 this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};

componentWillUnmount() {
 clearInterval(this.clockCall);
}

In render add the button with Onpress event listener.
<button Onpress={this.startTimer}> Play </button>

<Text style={{fontSize: 18, color: '#000'}}>
 {this.state.timer === 0 ? 'Times Up!' : {this.state.timer} }
</Text>

Comment: How ia can integrate it with play button? with Onpress?
Comment: i test it but not working. i need to change this line right?  00:30
Comment: that should not be 00:30 , it needs to be `{this.state.timer}`
Comment: Is working when i replace the onClick with Onpress, but how i can stop the timer when is finish and prevent -1,-2-3...
Comment: ok thank you, how i can pause it ? because when i click one more makes the countdown very fast
Comment: i think have answered a lot of your questions, that being said If i solved your initial problem please accept the answer, if you are having trouble with this app consider opening up a new StackOverflow question.
Comment: ok thank you, just im waiting the final code to accept it , don't worry xD, i change this code: {this.state.timer === 0 ? 'Times Up!' : {this.state.timer} } but i get this error: this is . a reserved word.
Comment: { this.state.timer === 0 ? 'Times Up!' : (this.state.timer) }
Comment: how can I prevent negative numbers, because it does not stop at times up, it continues -1, -2, -3 ..etc
Comment: you can help to complete it please?
Answer: To prevent negative numbers try this:
decrementClock = () => {
  this.setState((prevstate) => ({
    timer: prevstate.timer-1
  }), () => {
    if(this.state.timer === 0) {
      clearInterval(this.clockCall)
    }
  })
}


Reduce file size of a video with ffmpeg

Question: So i'm tried to reduce video filesize by scale down video<code> -vf 640:-2</code>, but nothing changes. Scale down or up doesnt affect video filesize
I've read ffmpeg wiki about Scaling but it dont have any information about scale and filesize.
When i'm scale down images, filesize have big drop but for video, nothing changes
Comment: Your question doesn't contain enough information. You need to show all the information about your video both before and after your attempt to reduce its size. Try using `ffprobe` on both.
Comment: i found other answer on website, he's said that resolution and codec are two different things, to reduce file size you must use better codec, in this case i'm using libx265
Answer: You can use -crf option to reduce final video size.
The range of the CRF scale is 0–51, where 0 is lossless (for 8 bit only, for 10 bit use -qp 0), 23 is the default, and 51 is worst quality possible.
<code>-crf 23 (for default)
</code>
You have to use H.264 encoder. this will help almost all type of video. works batter in mp4 videos.
Comment: yes, -c:v libx265 -crf 25 -x265-params profile=main10 -preset fast -pix_fmt yuv420p10le
with this, quality is better and file size is lower but encode time is longer, -vf scale is just for visual, not for size/quality
Comment: You can use '-preset ultrafast' for decrease conversion time. use that before your add your output path.
Comment: ok thank you, i will try that, hope quality is same and encode time is reduce
Comment: look like ultrafast = higher size, not reduce size at all, should fast or slow
Comment: -crf use for reduce the size of video and -preset is use for decrease conversion time. I personally used that.
Comment: Can you do sound and video separately? Like I want perfect sound but the video can be trash. It's for creating subtitles. Then I can add the subtitles to the high-quality video afterwards.

Reduce file size of a video with ffmpeg