How to hint at how many characters are in an answer? _ _ _ (3)

Question: I'm trying to show how many letters are in a word.
I want to do that with underscore characters. BUT  there is no space demarcating the underscore in most fonts. E.g., how many characters is this?  ____
One solution is to use a common web font that does have space, although I'm open to other suggestions.  (I'd prefer not to have to put in dummy spaces).
Robo Slab happens to do this nicely, but Not sure how common it is.
But I'd also love to do this with standard fonts in our PC software as well.
Are there any special characters what are commonly available in Arial, etc.?
Comment: I wish I could help, but I don't understand the context of your problem. Is this for a game? Are you looking to program this? Do you need to code a function that takes this space into account? You can easily do this with jQuery...
Answer: Adding an extra space is the only fully portable answer, as even common fonts are only guaranteed on specific operating systems. Look-alike fonts are not guaranteed to look alike in minor details like underscore spacing. Not all clients support web fonts.
If you are OK with using images, you could use a small 'underscore' image with the desired spacing. If it's alt text was 'underscore' it would remain about as usable for blind users.
Answer: Why not instead of dummy spaces insert some straight slashes/vertical lines?
Something like this:
"_ | _ | _ | _ | _ | _"
It would make it look like a string of boxes, or like there are some walls between the letters, but for your purpose it's as clear as it can get.
If the vertical lines are too big, try using some commas:
_ , _ , _ , _ , _
Choose a font where commas are square-shaped, so that they would appear as smaller "walls" between the underscore characters.
Answer: System fonts providing that space you're looking for:
Geneva Regular, Sathu Regular, Myanmar Sangam MN Regular, Malayalam Sangam MN Regular, PT Mono Regular, Lao Sangam MN Regular, Khmer Sangam MN Regular, Kannada Sangam MN Regular, Oriya Sangam MN Regular, Gurmukhi Sangam MN Regular.
No system fonts providing that space you're looking for:
Nexa Light Regular, Museo Sans 100, Monaco Regular,
Bottom Line:

grand _ _ _ _ _ _ (using spaces between letters)

I agree with Myrddin Emrys using spaces between letters is perhaps your best option. It really doesn't seem that bad, the spaces are not so distant, and the message of what's happening is clear and understandable.


MySQL Workbench not working in Ubuntu 20.04

Question: When I upgraded the ubuntu 19.10 to 20.04,MySQL Workbench not show in the system.Then I installed the MySQL Workbench community & run it then.It gives a below error.How can I resolve it?
Answer: https://dev.mysql.com/downloads/workbench/
Visit this URL, choose the OS and there is a package for Ubuntu 20 ! it is running smoothly but i have a problem in creating the new user apart from root still have to figure it out, but it is okay for me now i can use the different schemas in the root.
Comment: The download link contains a deb package while the asker have installed a snap package. Debs don't have such limitations. If you install the deb package from this link, remember to remove the snap package.


XOR of three values

Question: What is the simplest way to do a three-way exclusive OR?
In other words, I have three values, and I want a statement that evaluates to true IFF only one of the three values is true.
So far, this is what I've come up with:
((a ^ b) && (a ^ c) && !(b && c)) || ((b ^ a) && (b ^ c) && !(a && c)) || ((c ^ a) && (c ^ b) && !(a && b))
Is there something simpler to do the same thing?

Here's the proof that the above accomplishes the task:
a = true; b = true; c = true
((a ^ b) && (a ^ c) && !(b && c)) || ((b ^ a) && (b ^ c) && !(a && c)) || ((c ^ a) && (c ^ b) && !(a && b))
=> false

a = true; b = true; c = false
((a ^ b) && (a ^ c) && !(b && c)) || ((b ^ a) && (b ^ c) && !(a && c)) || ((c ^ a) && (c ^ b) && !(a && b))
=> false

a = true; b = false; c = true
((a ^ b) && (a ^ c) && !(b && c)) || ((b ^ a) && (b ^ c) && !(a && c)) || ((c ^ a) && (c ^ b) && !(a && b))
=> false

a = true; b = false; c = false
((a ^ b) && (a ^ c) && !(b && c)) || ((b ^ a) && (b ^ c) && !(a && c)) || ((c ^ a) && (c ^ b) && !(a && b))
=> true

a = false; b = true; c = true
((a ^ b) && (a ^ c) && !(b && c)) || ((b ^ a) && (b ^ c) && !(a && c)) || ((c ^ a) && (c ^ b) && !(a && b))
=> false

a = false; b = true; c = false
((a ^ b) && (a ^ c) && !(b && c)) || ((b ^ a) && (b ^ c) && !(a && c)) || ((c ^ a) && (c ^ b) && !(a && b))
=> true

a = false; b = false; c = true
((a ^ b) && (a ^ c) && !(b && c)) || ((b ^ a) && (b ^ c) && !(a && c)) || ((c ^ a) && (c ^ b) && !(a && b))
=> true

a = false; b = false; c = false
((a ^ b) && (a ^ c) && !(b && c)) || ((b ^ a) && (b ^ c) && !(a && c)) || ((c ^ a) && (c ^ b) && !(a && b))
=> false

Answer: For exactly three terms, you can use this expression:
(a ^ b ^ c) && !(a && b && c)

The first part is true iff one or three of the terms are true. The second part of the expression ensures that not all three are true.
Note that the above expression does NOT generalize to more terms. A more general solution is to actually count how many terms are true, so something like this:
int trueCount =
   (a ? 1 : 0) +
   (b ? 1 : 0) +
   (c ? 1 : 0) +
   ... // more terms as necessary

return (trueCount == 1); // or some range check expression etc

Comment: @gg.kaspersky, only in JavaScript, C, and languages which have truthy/falsy tests via the `!` operator. For example, this wouldn't work in Java or C#.
Comment: `a ? 1 : 0` can be simplified to `!!a`
Comment: Great, but the general solution does not short-circuit.
Comment: @DrewNoakes, when I made the comment, I thought for some reason that the question was C specific. Indeed, certain syntax constructs are valid only in certain languages.
Answer: bool result = (a?1:0)+(b?1:0)+(c?1:0) == 1;

Comment: I love it.  Very simple and understandable.
Comment: The simplest and must understandable when reading the code (well, I'd add few spaces)
Comment: In Haskell: `list_xor xs = sum ( map (\x -> if x then 1 else 0) xs ) == 1`
Answer: a^b^c is only 1 if an uneven number of variables is 1 (two '1' would cancel each other out). So you just need to check for the case "all three are 1":
result = (a^b^c) && !(a&&b&&c)

Answer: Another possibility:
a ? !b && !c : b ^ c

which happens to be 9 characters shorter than the accepted answer :)
Comment: Kinda glad this is not the accepted answer for readability reasons, but still, I had to upvote as shortness still has some kinky appeal to me. On university in C class, we had a contest in writing the shortest source code that generates a song similar to Heidis Kuken, and I was in TOP 5 in a contest.
Comment: @Vlasec I assume you know about [code golf](https://codegolf.stackexchange.com/), but if you didn't here you go.
Answer: Better yet on Python:
result = (1 if a else 0)+(1 if b else 0)+(1 if c else 0) == 1

This can be used also on if statements!
It saved my day for CLI mutually exclusive arguments through Click (everyone hates click)
Comment: and if a, b and c are already booleans, you can simply say `result = a + b + c == 1`
Comment: python converts bool to int, so `result = bool(a) + bool(b) + bool(c) == 1`
Answer: You could also try (in C):
!!a + !!b + !!c == 1
Comment: @blgt, my mistake, I should specify that I meant to be an answer for C language.
Comment: Using `!!` to guarantee a C true is `1` is actually pretty neat. A bit paranoid in the context of a boolean logic question though. If the rest of your code is well-written `a+b+c==1` should still be sufficient
Comment: This is only valid in some languages [eg. javascript], and it's not a simplification. In a language which auto-converts boolean to number for `+`, if `a`, `b`, and `c` are already boolean, you also don't need the double negation `!!`: just `a+b+c===1` will be equivalent.
Answer: Here's a general implementation that fails quickly when more than one bool is found to be true.
Usage:
XOR(a, b, c);

Code:
public static bool XOR(params bool[] bools)
{
    return bools.Where(b => b).AssertCount(1);
}

public static bool AssertCount<T>(this IEnumerable<T> source, int countToAssert)
{
    int count = 0;
    foreach (var t in source)
    {
        if (++count > countToAssert) return false;
    }

    return count == countToAssert;
}

Answer: f= lambda{ |a| [false, false, true].permutation.to_a.uniq.include? a }
p f.call([false, true, false])
p f.call([false, true, true])

$ true
$ false

Because I can.
Answer: In C:
#include <stdbool.h>

bool array_xor(size_t array_size, bool[] array) {
    int count = 0;

    for (int i = 0; i < array_size && count < 2; i++) {
        if (array[i]) {
            count++;
        }
    }

    return count == 1;
}

Comment: I'm not sure this works, nor is it simple.
Comment: Define "simple". It definitely works, as what it's doing is checking that exactly one element of the array is `true`. It works for an arbitrarily large array of booleans, not just 3 elements, and short circuits as soon as it finds a second element that is `true` (hence `&& count < 2`).
Answer: result = (
BOOL_TO_INT( a)
+  BOOL_TO_INT ( b )
+  BOOL_TO_INT ( c )
) = 1
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

XOR of three values


How to control the painting of the player

Question: I am trying to draw something on a live video. The best way to do that in my opinion is to handle the WM_PIANT event.
My purpose is to make the player draw first and after that the application. That way I will be able to draw on the video.
It means that I want to be notified each time before we need to paint a new frame on the window and then handle the event.
I use DirectshowNet so I am programming in C# (I have all the interfaces the c++'s API
has). I understand that the graph manager forward certain window messages to the Video Renderer such as the WM_PAINT.
How can I cause the player to draw a frame before the application and not after?
Answer: WM_PAINT is not the best way, moreover it is the wrong way.
Check out DxText sample from DirectShow.NET library. Its description is:

A sample application showing how to superimpose text strings on a
  datastream.  The stream is read from an avi file.

This is so close to what you are trying to reach. An alternate approach is shown in another sample there, BitmapMixer:

BitmapMixer is an example of how to draw things over a video using
  VMR9.
This sample is mainly built around the IVMRMixerBitmap9 interface.
  This interface accept bitmaps as a GDI Device Context or as a Direct3D
  Surface. The main advantage  of the Direct3D Surface is that it
  enables the use of true alpha transparency. GDI DC  don't support
  alpha bitmap and transparency is accomplished by using color keying.
This sample dynamically generates bitmaps using GDI+.
Comment: I tried the BitmapMixer and it didn't work for me because I am using a Graphic object to draw on the player, I have a truly transparent panel over the window and I created graphics of that panel and then I used the hdc of the graphic object with the bitmapMixer thing and then I can't draw anymore on the graphics because the graphic object from now on is in use with someone else. Now I need to be able to draw something dynamically on the player, means that I will draw different thing on the player and they will stay there. Do you have any other idea? thanks for the help man.
Comment: DShow playback is never transparent. That is, you need to check out the samples on how to get frames out of there into `Graphic` objects and do not actually visualize the video. Instead you will use the individual frames and paint them the way you need outside of DShow.
Comment: No this isn't what i am trying to do, I am using a transparent **panel** it is a **contol** object that I made it transparent, I don't want the player to be transparent.


Reading csv into array

Question: I know the topic has been discussed a lot but I still don't really get it. Admittedly I am pretty new to C++ coding, so please go easy on me :)
Anyhow: I have this examplatory csv file:
    ,313,315
91.5919,1.44421,1.74019
91.592,1.44254,1.73816
91.5921,1.43859,1.73336
91.5922,1.43449,1.73109

I need an array with unknown dimensions a priori, since the csv will expand unpredictably -> dynamic array in both x and y direction.
This is what I managed to do so far:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<vector<double> > values;
    vector<double> valueline;
    ifstream fin("in.csv");
    string item;
    for (string line; getline(fin, line); )
    {
        istringstream in(line);

        while (getline(in, item, ','))
        {
            valueline.push_back(atof(item.c_str()));
        }

        values.push_back(valueline);
        valueline.clear();
    }
}

It appears to be doing the job, but if I try to output the array or parts of it, I get strange results. For example     cout << values[0][3] << endl; yields 1.63042e-322. values[0][4] yields 91.5919. Also sizeof(values[0]) is 24.
Am I doing something I am not supposed to here?
Any help would be great! Thanks
Answer: Try using .at() operator to see whether you aren't reading beyond the end of the vector? values[0][3] is the fourth element of the first line, which doesn't exist in your input?
You probably want to do:
std::cout << values[3][0]; // Fourth line, first element;

or
std::cout << values.at(3).at(0); // Fourth line, first element;

Index operators on vectors do not do bounds checking. This is for performance reasons. You are reading out of bounds, and thus you get the strange numbers. at() throws a std::out_of_range exception.
Answer: Using sizeof on a vector is mostly useless -- it tells you the size of the top-level vector data structure (generally two size_ts and a pointer) in bytes, which is not terribly useful.  If you want the size of the vector, use the size method -- values[0].size() tells you how many values are on the first line.

Reading csv into array


How can I fix a clothes washer faucet that is leaking?

Question: I just moved the clothes washer out of the way but now I found the faucet that connects to the washer is leaking. I tried to replace the faucet but looks like it is soldered and I cannot find a way just to remove the stem.
Is there a way to fix it without calling the plumber?
Comment: From the deposits left by the leak, it may be that all you have to is tighten the bonnet nut.  Do this no more than a 8th of a turn at a time.
Answer: The stem should be able to be removed after unscrewing the part of the faucet as pointed to here:

Remove the red tap handle first. Then use a pair of wrenches, one on the indicated part and the other on the faucet body to loosen and remove the threaded part. The usage of two wrenches is very important because you do not want to stress the soldered pipe the goes off into the wall.
I have found the following type of groove lock pliers to be one of the most effective tools for this type of job. The fine range of adjustability and the jaw shape make the grip to the faucet parts easy. Do note that these tools can cause marks to appear on the faucet parts, especially of soft brass or bronze materials or if the threaded part is really tight.
Comment: Don't forget to shut off the water supply first! It is **very** unlikely that you will be able to replace just the stem. You could repair it though; repack with graphite packing material and install a new bib washer.
Comment: Thanks! I went ahead and replace the whole thing with ball valve so I don't need to worry about it wear out for long time
Answer: Rather than repair the valve, the other option is to replace it.

Shut the water off to this area.
Drain the water from the line.
Fill a small bucket with water, or use a small bucket to catch the water that drains out of the pipe.
Wear a good pair of leather gloves, and eye protection.
Open the valve all the way.
Use a torch to carefully heat the solder joint.
Using a pair of channel locks; or other pliers, continually check if the fitting is loose.
DO NOT touch the fitting, pipe, or anything else that might be hot, with your hand.
When the valve comes free, twist and pull it off. Then drop it in the bucket of water, to cool.
Wipe away as much of the excess solder with a damp rag, before it cools.

Now you can install a new valve. I recommend a 1/4 turn ball valve, as they tend to last a bit longer.
If there's a bit of solder left on the pipe, preventing the new fitting from going on. You can heat it back up, or use fine grit sandpaper to remove it.
Comment: Thanks all. I went ahead and bought the solder kit. Turned out its not too hard to sweat and solder. I replaced both valves with new ball valve andsoldered a screw adapter then screw the hose bibs so next next I can just screw it off when I need replacemeny


How to work out device type in titanium (iOS)

Question: I am trying to work out the device type in titanium for iOS i.e. if the user is using iphone 4, 5, 6, or 6 +
I have used:
Titanium.platform.model but it just returns simulator (I guess because I am running it in a simulator), what is the correct way to do this?
Answer: You cannot get the actual model, but you can derive it from other info:

iPhone 6+ would have @3x for Ti.Platform.displayCaps.logicalDensityFactor
iPhone 5/6 would have @2x and could be further split up via Ti.Platform.displayCaps.platformHeight
iPhone 4 and older would have @1x

In Alloy, you could create globals with this in alloy.js - e.g.:
Alloy.Globals.iPhone6P = Ti.Platform.displayCaps.logicalDensityFactor === '@3x';
...

Comment: Ti.Platform.displayCaps.platformHeight is "568" for iphone 6 plus and iphone 6 and when I do Ti.Platform.displayCaps.logicalDensityFactor it is "2" for iphone 6 and iphone 6+. How can I differentiate it?
Comment: Solved this, there is a bug with older titanium versions where the height is always 568 and the width is ALWAYS 320, essentially making it a fixed size. To resolve this, copy and paste all of your files into a new titanium mobile alloy project. Be warned all old styling will go out of position.
Comment: Just found a bug, when I build the app on my phone the width is 320
Comment: @bobo2000 if you don't include the launch images for iPhone 6 or 6+ then iOS will automatically start in compatibility mode (letterbox or upscaled) and report the dimensions of that mode. So please check if you have all the required assets.
Comment: Yep that was the issue. I have kept it in compatibility mode for the time being.


How to sort an XML file using .NET?

Question: So you have a third-party web service that likes to abuse XML and return things in an order that makes your programming a complete pain in the neck.  For example...
<file>
  <node1>Foo</node1>
  <price>4.99</price>
  <node2>
    <key>XX999</key>
  </node2>
</file>

There are about a thousand of these sorted in order by price.
How can you re-sort this XML document by the key value?
I need the result to be a sorted XML file.  Thanks!
EDIT:
.NET version 2.0 (no LINQ)
Comment: You should define what you mean by sorting. I see nothing wrong with the XML you posted.
Comment: Assume I have a thousand of those nodes in order by price.  I need them sorted in order by key.
Answer: Here's how to do it with XSLT:
assuming your data takes this form (file.xml):
<?xml version="1.0"?>
<listing>
<file>
  <node1>Foo</node1>
  <price>4.99</price>
  <node2>
    <key>XX999</key>
  </node2>
</file>
<file>
  <node1>Bar</node1>
  <price>5.67</price>
  <node2>
    <key>aa743</key>
  </node2>
</file>
<file>
  <node1>Was</node1>
  <price>5.67</price>
  <node2>
    <key>rr321</key>
  </node2>
</file>
</listing>

This transform (stylesheet.xsl):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:strip-space elements="*"/>
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="listing">
    <xsl:copy>
      <xsl:apply-templates select="file">
        <xsl:sort select="node2/key" data-type="text"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

When used with this .Net code (need to add a using System.Xml;):
XslCompiledTransform xslt= new XslCompiledTransform();
xslt.Load(@"c:\stylesheet.xsl");

xslt.Transform(@"C:\file.xml", @"c:\sorted.xml");

Results in this output in sorted.xml:
<?xml version="1.0" encoding="utf-8"?>
<listing>
  <file>
    <node1>Bar</node1>
    <price>5.67</price>
    <node2>
      <key>aa743</key>
    </node2>
  </file>
  <file>
    <node1>Was</node1>
    <price>5.67</price>
    <node2>
      <key>rr321</key>
    </node2>
  </file>
  <file>
    <node1>Foo</node1>
    <price>4.99</price>
    <node2>
      <key>XX999</key>
    </node2>
  </file>
</listing>

Comment: No, I need to sort this prior to parsing the XML.  I'd prefer to have a way to sort it without casting it to an object.
Comment: "How are you consuming this data?"  It's nothing but a classic HTTP request, and I have a huge string to be parsed.
Comment: XSLT?  Please hook me up with an example or something - I am clueless!
Comment: OK I am reading W3 specs on XSLT, but what would the select string be?
Comment: Excellent answer! Reformatted your stylesheet to enhance readability.
Comment: I had to come back to this answer again today, and I just wanted to say THANK YOU very much!
Answer: Apply an Xml Style Sheet  to transform to source XML into an XML format suitable for your use. You can easily sort elements by values during the xsl transformation.
Answer: XSLT rules, of course, but I'd go with LINQ To XML (i.e., what's in the System.Xml.Linq namespace). Specifically, what you need to do is something like this:
newElement = new XElement(oldElement.Elements().OrderBy(x => x.Whatever);

Answer: Will Linq to XML handle this for you?

How to sort an XML file using .NET?


VB.NET Databinding from 2 Tables

Question: I have the following structure
|-Table 1
|--PK IDT1
|--Name field
|-Table 2
|--PK ID
|--FK IDT1
|--Name field

I want to bind Table 1 to combobox1 and Table 2 to combobox2 so as when someone selects a value in combobox1, combobox2 populates with only the rows with the FK IDT1 value from combobox1. Is this possible with databinding or do I have to code it?
Comment: Is this about WinForms, WPF or ASP.Net?
Answer: on the FORM_LOAD of your application just populate only ComboBox1. this psuedocode may help you:
ON FORM_LOAD of your Application:
      Bind ComboBox1
      SET DISPLAY MEMBER Property of BomboBox1 to field
      SET VALUE MEMBER Property of ComboBox1 to IDT1
      Clear ComboBox1 current Text

On the SelectionChangeCommitted of your ComboBox1
      Bind ComboBox2 using the following Query:
           SELECT ID, field FROM Table2 WHERE IDT1 = ComboBox1.SelectedValue.ToString
      SET DISPLAY MEMBER Property of ComboBox2 to field
      SET VALUE MEMBER Property of ComboBox2 to IDT

The SelectedIndexChanged event is raised every time the SelectedIndex property value changes. If your ComboBox is initially empty then its SelectedIndex is -1. When you bind data to it the first item is selected by default and the SelectedIndex changes to 0. You are then explicitly setting the SelectedIndex to -1 again.
If you're only interested in knowing when the user makes a selection then handle the SelectionChangeCommitted event instead.

VB.NET Databinding from 2 Tables


Ubuntu 13.10 Killed my Desktop computer!

Question: I need help. I have an HP Pavilion g7 and I was wondering how to fix it. What happened was it originally came with Windows 7, and I upgraded to 8, but today I decided to make the switch from windows to Ubuntu, so I partitioned my hard disk, and backed up everything to one partition, which I don't wanna delete because It contains my backups, and partitioned again. I also kept note, luckilly, of how much free space Windows 8 had. And when I booted to Ubuntu, I gave all of the free space to swap and I deleted the Windows partition (Note: I left the system partition there, that was there maybe after upgrade to 8.) Then, I installed Ubuntu where Windows was originally. It completed install, and I reboot it, then get a suspisious black screen, so I power off the PC, and power it back on, I then get a Light-Blue (Like the color of the sky) screen with white text, it says something like this:
Recovery
A required device cannot be accessed or is not plugged in.
Insert your installation media or contact your system administrator.
I try hitting enter, screen goes black for a split second and re-appears, the same thing happens when I press F8. Is there any way to fix this without completely formatting the hard disk?
(Note: I followed a video by AvoidErrors about dual-booting Windows 8 and Ubuntu 13.04, but instead deleted the Windows Partition (Atleast I thought it was due to the amount of space used, all the other partitions were full, except the Windows one, which was half-full.) It was also obvious AvoidErrors was using a Virtual Machine instead of actual hardware.
Comment: Can you boot a live cd?
Answer: "Is there any way to fix this without completely formatting the hard disk?"
I don't think so. But maybe you can try to boot a Live CD or Live USB with Ubuntu to see what really happened to the disk partitions.
Comment: I've also noticed after booting to the LiveCD, both the system partition I mentioned and Ubuntu have a folder named "boot" I don't know if I'm right but I'm inferring this happened:
Comment: The computer gets confused when it boots up, and doesn't know where to go, so it goes to system... If I delete that, will it go to Ubuntu?


How do I Unstick a Fixture Mounted to Bathroom Tile

Question: Let's say, hypothetically, that I bought one of those lighted, fogless mirrors like this which stick to the tile in your shower and chose a really bad location to mount it. How do I get it off? I thought it would pull off fairly easily, but it feels too stuck and I will just break it by pulling.
Also, if you all have any good recommendations for shower stall mirrors, I'd like to hear them, too.
Answer: Dental floss (bathroom handy) or fishing line. Wrap it around a couple of handles (toothbrushes also seem handy in a bathroom) and saw the thing free of the wall.
Comment: We could stay bathroom centric and use toothpaste, but you might get it off faster with shortening or vegetable oil from the kitchen. That's a guess, not a guarantee, but often works - depends on the adhesive residue. Shampoo or conditioner might also work? Or rubbing alcohol...
Comment: I had some Goof Off. Sprayed that on and was able to slowly peel it off using my fingernail (still the best cleaning tool ever created). All done.
Comment: I did that. It worked surprisingly easy. But now there's a lot of residue. How do I get that off?


Redux - Resolve a Promise after calling dispatch action in component

Question: I have an 'addToFolder' action which dispatches an action that is handled in my Redux reducer.
export function addToFolder(folderIds, contentId, contentType) {
  const item = {};
  item.folder_ids = folderIds;
  item.content_id = contentId;
  item.content_type = contentType;

  return function(dispatch) {
    return fetch(`${getAPIPath}api/addtofolder`, {
      method: 'PUT',
      body: JSON.stringify(item),
      credentials: 'include',
      headers: {
        Accept: 'application/json',
      },
    })
    .then((response) => {
      response.json().then((res) => {
        dispatch(addToFolderSuccess(res.data));
      });
    }).catch((error) => {
      throw (error);
    });
  };
}

In my component after clicking on my 'Add to Folders' button I dispatch the action. I would like to use .then to fire a snack/notification action, but use the response from my API call in order to fill in the id and message text displayed by the notification. Currently response is undefined.
addToFolder = () => {
    this.props.actions.addToFolder(this.state.activeItems, this.props.contentId, this.props.contentType)
      .then((response) => {
        this.setState({ addBtnLoading: false });
        this.props.actions.dispatch(showSnack(response.id, {
          label: response.message,
          timeout: 4000,
        }));
      });
  };

Answer: You forgot to return
.then((response) => {
      // nested promise
      return response.json().then((res) => {
        dispatch(addToFolderSuccess(res.data));

        // the result
        return res;
      });


Hide text of Android spinner

Question: I have a spinner with a background image. But when I add array adapter to the spinner, the text is shown on the background image. I want to hide this text. There is also a TextView. My requirement is, when I click the image, the spinner should pop up and when I selects an item, the TextView gets updated with the selected item.
Comment: duplicate question but with no answer: http://stackoverflow.com/questions/4342273/how-do-i-hide-the-text-on-a-spinner
Comment: I got across the same problem but i found my 9 patch png invalid and hence,fixing 9 patch and cleaning-building project worked for me. Can you please post your code so that it is easy for us to suggest you something.
Comment: http://stackoverflow.com/questions/15479579/remove-text-from-spinner - your solution
Answer: Spinner spin = (Spinner) d.findViewById(R.id.searchCriteria);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
  public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// hide selection text
((TextView)view).setText(null);
// if you want you can change background here
}
  public void onNothingSelected(AdapterView<?> arg0) {}
 });

Answer: Create ghost_text.xml in your layouts folder with this text:
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/transparent" />

Then use that file in your adapter like this:
    ArrayAdapter<String> your_adapter = new ArrayAdapter<String>(this,
        R.layout.ghost_text, your_list);
    your_spinner.setAdapter(your_adapter);

You should also be able to use this technique with other resource-based adapters.
Answer: Probably you can define a xml-layout file, without any textview in it, and supply it to the adapter for the spinner.
e.g. empty_spinner_item.xml
<ImageView xmlns:android="http..."
    android:layout_width=".."
/>

and then use any adapter:
spinner.setAdapter(new SimpleAdapter(this, data, R.layout.empty_spinner_item, ... ));

Comment: I can't hide the text of spinner. So I replace the spinner with a button. When button clicks, the spinner pop ups (spinner.performClick). I also wrote a OnItemSelectedListener to update the TextView with the selected item. But OnItemSelectedListener is not working :(. Any help please..
Comment: It works. StorageSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            public void onItemSelected(AdapterView arg0,
            View arg1, int arg2, long arg3)
            {

             tv.setText(StorageSpinner.getSelectedItem()+"");
            }

            public void onNothingSelected(AdapterView arg0) {}
        });
Comment: I have a spinner with a background image. But when I add array adapter to the spinner, the text is shown on the background image. I want to hide this text. There is also a TextView. My requirement is, when I click the image, the spinner should pop up and when I selects an item, the TextView gets updated with the selected item.
Comment: When I tried this, my app crashed with the error "ArrayAdapter requires the resource ID to be a TextView."

Hide text of Android spinner


questions about scraping a review website

Question: I am currently crawling a review site with beautiful soup.
the review page contains reviews from different students,
and each student would evaluate the school on several aspects.
therefore, the structure of the page generally looks like:

student A - title A:

aspect 1
comment toward aspect 1
aspect2
commet on aspect 2
aspect3
commet on aspect 3

student B - title B:

aspect 1
comment toward aspect 1
aspect2
commet on aspect 2
aspect4
commet on aspect 4

some students only made comments on particular aspects. the aspects they dont comment on will not be shown on the website.

each review in code

            title 1 : It was ok.

           Total Evaluation

           We can freely choose the course we want, and thus a lot of different knowledge can be learned.

           Course

           the courses are good.

           Lab

           we don't join lab in the first 2 year.

you can see that even though the title of aspects are different, they all start with 'div class="mod-reviewTitle3" ' , and the comments all start with 'div class="mod-reviewList-txt"'.
my question is that how do i write good code to store these information into a data set:
| title | aspect1 comment | aspect2 comment
     A       good               very nice
i have tried the code below, but aspect comment in each block doesnt work well
datatest = soup.find_all("div", {"class":"mod-reviewTop"})
datatest1 = soup.find_all("div", {"class":"mod-reviewBottom"})

for item in datatest:
    a = item.select('.mod-reviewTitle')
    c = item.select('.mod-reviewTitle3')
    d = item.select('.mod-reviewList-txt')
    g = item.select('.js-mod-reviewList-list')
    f= item.select('.mod-reviewItem')

for i in range(len(a)):
    f1= f[i].text[7]
    f2= f[i].text[17]
    f3= f[i].text[26]
    f4= f[i].text[37]
    f5= f[i].text[46]
    f6= f[i].text[55]
    f7= f[i].text[63]

    print a[i].text
    print f1, f2, f3, f4, f5, f6, f7
    for item in datatest1:
        for k in range(len(g)):
            print g[k].text
            print e[k].text
            print k

i regard this as a programming problem..
i have try loops but didnt work well
if you can kindly give me some reference or how the structure shall work logically, pls kindly leave me a comment.. thanks
Comment: You should only talk about the problem you have not write the whole story here. what is your question? how to write good code to store information in a dataset? what's good code? anyways you can store data in datasets using pandas, you can use xlwt to write in an excel file, or you can write in a text file with your own separators.
Answer: Tips:

You should attach aspects and comments to corresponding titles, which means you store them together by using a proper data structure. like this(Just one possible way)
[
    (title1,[
                (aspect1, comment1),
                (aspect2, comment2),
                ...
            ]),
    (title2,[
                (aspect1, comment1),
                (aspect2, comment2),
                ...
            ]),
    ...
]
So when retrieving data you want, organize operations with nested for loops. i.e. Once you find an aspect, for example, try to get the  corresponding comment and store them together. Escape finding all aspects, then all comments.

Code
Here is a demo.
blocks = soup.find_all("div", {"class":"mod-reviewTop"})
contents = soup.find_all("div", {"class":"mod-reviewBottom"})
data = []

for i,block in enumerate(blocks):
    aspects = []
    title = str(block.find('div',{'class':'mod-reviewTitle'}).text).strip()
    for aspect_block in contents[i].find_all('li'):
        aspect = str(aspect_block.find('div',{'class':'mod-reviewTitle3'}).text).strip()
        comment = str(aspect_block.find('div',{'class':'mod-reviewList-txt'}).text).strip()
        aspects.append((aspect,comment))
    data.append((title,aspects))

print data

with open("output.txt","w") as file:
    for title, aspects in data:
        file.write(title)
        for aspect in aspects:
            file.write('|'+aspect[0]+'\t'+aspect[1])
        file.write('\n')


How to retrieve response from server using angularjs?

Question: I am sending filename to server and trying to get some sort of response to make sure api calls are working but its always returing 404 even though path is correct, I am not sure where i am making mistake , Any idea ?
angularjsFactory.js
getFile:function(file_name){
            return $http.get("/file?file_name="+file_name);
        }

server.js
var express = require('express');
var app = express();
var fs = require('fs');
app.use(express.static(__dirname + "/public"));
var readDirectory = require('./readDirectory');

app.get('/file', function(req, res) {
    var path = './ditLogs';
    var fileParam = req.query.file_name;
    console.log(fileParam);
    fs.readdir(path, function(err, items) {
        items.forEach(function(items) {
            if (fileParam === items) {
                res.sendFile(items);
                console.log(items);
            }
        });
    });
});
app.listen(3000, function() {
    console.log('Example app listening on port 3000!');
    //console.log('app is printing data',obj);
    //ditProducer.startProducer();
    setTimeout(function() {
        ditconsumer.start();
    }, 2000);

});

Comment: Did you try adding a forward slash '/' to the end of the url
Answer: Your route on server is not correct comparing to the call from angular's side. You are not using route parameters, but query string.
Try this:
app.get('/file', function (req, res) {
    // get filename using: req.query.file_name
    res.send('FIle data');
 });

Or you can try this on angular and keep the server code:
 $http.get("/file/"+ encodeURI(file_name));

Comment: is there way to pass parameter as i am passing in question ?
Comment: i dont know filename is passing as /test.txt , i dont know why
Comment: @hussain: coz correct syntax will be: $http.get("/file?file_name="+file_name); if you change node js code to app.get('/file', function (req, res) {
    // get filename using: req.query.file_name
    res.send('FIle data');
 });
Answer: Server side code looks incorrect.
app.get('/file', function (req, res) {
    console.log(req.query.file_name);//This will give you filename passed as url param
    res.send('FIle data');
 });

Comment: i updated my server code to give you better understanding what i am trying to do
Comment: Can you confirm that you are not adding this middle-ware app.get('/file', function (req, res) {
    // get filename using: req.query.file_name
    res.send('FIle data');
 });  at the last in app.js
Comment: Its should be above: ` // catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
}); ` need to check your app.js
Comment: @hussain: all looks well to me dude..  Did you restart the node js server after making the changes? :D Sometime i missed out in early days.. Also just curious to know, what happens if you try hitting by browser?
Comment: problem is my if statement is not satisfying because fileParam value is /test.text that is not matching when if(fileParam === file) because file value is without forward / test.txt
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/116136/discussion-between-hussain-and-ritesh-nitw).


How would I replace a jQuery ajax error handler

Question: I have a global jQuery ajaxSend function. It is getting called anytime jQuery performs an ajax request. I am trying (unsuccessfully) to replace the error handler from that function. Here's an example.
$(document).ajaxSend( function (event, xhr, obj) {
    xhr.fail = xhr.error = obj.fail = obj.error = function () {
        alert("hook called");
    };
    xhr.abort();
});

$.ajax({ url: window.location.href, error: function () { alert("main called"); }});

Here's a fiddle to see what I mean: https://jsfiddle.net/a1zh6qtp/
How would I replace the original error handler?
Comment: Probably not, but did you want: [ajaxError](https://api.jquery.com/ajaxError/)
Comment: thanks for response - the ultimate goal is to remove logic that is set to run in the current error handler, rather than update a lot of client code, I was hoping I could remove or replace it globally
Comment: Possibly related: https://stackoverflow.com/a/29449922/2181514
Comment: Looks like the global error handler runs last: https://jsfiddle.net/fa2hp374/
Comment: thanks @freedomn-m - if you can figure out how to prevent that main error handler from being called that's what I'm after :)
Answer: It looks like jQuery has another global function called $.ajaxPrefilter() I am able to replace the original error handler from there.
Here's the updated code:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  options.fail = originalOptions.fail = jqXHR.fail =
    options.error = originalOptions.error = jqXHR.error = function () {
      alert("you've been replaced");
    }
});

$(document).ajaxSend( function (event, xhr, obj) {
  xhr.abort();
});

$.ajax({ url: window.location.href, error: function () { alert("replace me"); }});

Here's a fiddle to see it: https://jsfiddle.net/kbnwrj3v/


Show that, given $f:M→N$, if M is an artinian module so is N

Question: What it says on the tin. Note that $f:M→N$ is a surjective $R-module$ homomorphism.
This is what I have: Let ${I_n}$ denote a chain of submodules in $M$ such that ${I_0 \supseteq I_1 \supseteq ...}$. There is $k$ in $ \mathbb N$ such that $I_k = I_{k+1}...$.
Take $f(I_n)$. By definition, the inclusions are preserved and so is the submodule structure.
Now, I think that I have to check the descending chain condition for the $f(I_n)$s, is that correct? How would I go about doing that? Also, I  know that the surjectivity plays a part somewhere. Is it just the fact that $f$ maps every element of $N$ to a $f(I_n)$ thus guaranteeing that all of $N$ is artinian?
Answer: To show that $N$ is artinian, you are supposed to consider descending chains of $R$-submodules of $N$ rather than descending chain of $R$-submodules of $M$.
Let such chain be $N_1\supseteq N_2\supseteq\cdots$. Then we can obtain a chain $f^{-1}(N_1)\supseteq f^{-1}(N_2)\supseteq\cdots$ of $R$-submodules of $M$. Since $M$ is artinian, the second chain collapses.
That is, there exists $K\in\mathbb{N}$ such that $f^{-1}(N_k)=f^{-1}(N_K)$ for all $k\geq K$.
Since $f$ is surjective (this is essential), it follows that $N_k=N_K$ for all $k\geq K$. That is, the original chain collapses as well.
Hence $N$ is artinian.
Comment: Hey, just checking, is the inclusion preserved since f is homomorphism or does that not hold? Would I have to check it and also check if the second chain is a submodule?
Comment: You are encouraged to check both of them if you feel unsure. I) Given a function $f:X\to Y$ with $A\subseteq B\subseteq Y$, show that $f^{-1}(A)\subseteq f^{-1}(B)$. II) Given an $R$-module homomorphism $\phi:M\to N$ and a submodule $N'$ of $N$, show that $\phi^{-1}(N')$ is a submodule of $M$.
Answer: Here is a quick proof. While you have the correct idea, you need to start with a descending chain of submodules of $N$.
Let $\mathfrak{a}_0 \supseteq \mathfrak{a}_1 \supseteq \cdots$ be a descending chain of submodules of $N$ and let $M$ be an Artinian module with $f:M \to N$ an epimorphism of $R$-modules. For each $n \in \mathbb{N}$, define the submodule $\mathfrak{b}_n$ of $M$ by
$$
\mathfrak{b}_n = \lbrace m \in M \; | \; f(m) \in \mathfrak{a}_n \rbrace.
$$
That this is an Abelian group is a straightforward check, so let us just verify that it is a submodule of $M$. Pick an $m \in \mathfrak{b}_n$ and let $r \in R$ be arbitrary. Then $f(rm) = rf(m)$ because $f$ is $R$-linear and since $\mathfrak{a}_n$ is an $R$-module, $rf(m) \in \mathfrak{a}_n$ as well. Thus $f(rm) \in \mathfrak{a}_n$ so $rm \in \mathfrak{b}_n$ and hence $\mathfrak{b}_n$ is a submodule of $M$.
We now show that the $\mathfrak{b}_n$ form a descending chain. For this it suffices to show that for any $n \in \mathbb{N}$, $\mathfrak{b}_n \supseteq \mathfrak{b}_{n+1}$. To this end pick an arbitrary $m \in \mathfrak{b}_{n+1}$. Then $f(m) \in \mathfrak{a}_{n+1}$ and since $\mathfrak{a}_{n+1} \subseteq \mathfrak{a}_n$, we also have that $f(m) \in \mathfrak{a}_n$. Thus $m \in \mathfrak{b}_n$ so indeed we have $\mathfrak{b}_{n} \supseteq \mathfrak{b}_{n+1}$.
We now invoke that $N$ is Artinian to note that the descending chain
$$
\mathfrak{b}_0 \supseteq \mathfrak{b}_1 \supseteq \cdots
$$
stabilizes at some $k \in \mathbb{N}$. Now applying $f$ to the chain and noting as you did that this preserves the descent with $f(\mathfrak{b}_n) = \mathfrak{a}_n,$ we have that the chain
$$
\mathfrak{a}_0 \supseteq \mathfrak{a}_1 \supseteq \cdots
$$
stabilizes at $k \in \mathbb{N}$ as well. This gives that $N$ is Artinian.
Comment: Hey, is the inclusion preserved since f is homomorphism or does that not hold? Would I have to check it and also check if the second chain is a submodule like you did?


Do Cysts have any unique abilities?

Question: In the original Killing Floor, every enemy had a unique ability; Clots could grab and immobilize you, Gorefasts had a sword arm and could sprint, Scrakes had chainsaws, Fleshpounds ruined your life, etc.
In Killing Floor 2, now, there are a couple new types of enemies, one of them being the Cyst.
However, I can't seem to find any outstanding ability that they have, neither in-game nor documented. On top of that, they don't seem functionally different at all from the updated Clot specimen. Am I overlooking something or do Cysts really do nothing special at all?
Answer: They do, in fact, have a special ability explained in the link you provided :

Cysts move slowly when docile, and sprint when enraged.
On higher difficulties, Cysts have a chance to enrage upon sighting a Player, and have a chance to enrage when shot.
Once enraged, Cysts will never stop sprinting until they are killed.

They have a speedboost like the Gorefast had in KF. It's not that much of an ability, but after all, they're only cannon fodder.

The Cyst is a common specimen in Killing Floor 2. It is classified as a lesser enemy, and therefore, cannon fodder. Cysts are generally considered to be the weakest specimens in the game, whose only purpose is to populate the level.
Comment: Look at the KF2 Clot's wikia. It says the *exact* same thing about the speed boost.
Comment: Well, your question is  "Am I overlooking something or do Cysts really do nothing special at all?" They do run and grab like the Clot. You need to specify if you want a point by point comparison with the Clot.
Comment: I believe the question itself was pretty clear, though the title may not have been, so I updated it.
Comment: I would suggest to clarify the question. "do Cysts really do nothing special at all" is too broad. Enraging and grabbing is a special ability. Nothing different from the Clot I concede, but still special.
Answer: After doing some more research, it appears that the reason Cysts have the same abilities that were once unique to Clots is that they are Clots, to some extent. More accurately, they are somewhat deformed or failed versions of Clots.
From the Specimens wikia page, you can see that Cysts and Clots (as well as Slashers) have the exact same stats as each other, as well as money and experience rewards for killing them.
This led me to go to the Slasher wikia page, where I found the following line:

However, Slashers are more agile, aggressive and unpredictable than the other Clot variants.

From there, I found various references to the fact that Cysts and Slashers are variants of the Clot Specimens, such as here:

The Cysts are new, weaker Clot variants—the underdeveloped killer babies of the genetic freak family.

Thus, Cysts do not have any unique abilities, as they share the ability to grab and immobilize the player with the other Clot variants. Cysts are, however, unique in the ability to stumble repeatedly while attempting to grab the player, as they are the most unstable variant of the Clots.

Do Cysts have any unique abilities?


Parsing & Checking Condition Expression in Javascript

Question: I have string that have variable conditions in it, like this:

(@IS_VERIFIED = 'True' OR @CONFIRMATION_NEEDED  != 'True') AND @REQUEST_LIMIT != '0'

This is just an example and there are unknown number of variables & cases.

Every variable starts with @
There are ORs and ANDs with sometimes parenthesis
Values are always in quotation marks like 'xyz', so all can be considered strings.
Conditions are always checked with either = or !=

I also have a javascript map which holds all the variables like:
const vars = {
 IS_VERIFIED: 'True',
 CONFIRMATION_NEEDED: 'True',
 REQUEST_LIMIT: '2'
}

What I need to do is parse the condition string and check the values using the map above to reach a final result, true or false. I came up with few ideas but they were all too complicated. Is there any known, easy method for this or do I have to create something from scratch?
Any help is appreciated, thanks.
Edit: After achieving this, next goal for me will be showing which variables break the condition, somehow.
Comment: Regular Expressions might come in handy here. Did you try using that?
Comment: @AnindyaDey yeah, I thought about it but couldn't figure out how to apply it to cases where there might be multiple paranthesis inside each other and all. I think I have to create a recursive logic but not sure how.
Comment: I can think of a solution using `eval`, but are you willing to use `eval`?
Answer: Caution: eval solution ahead, be very careful while using this!
Simply modify the string to be a valid JS expression and then use eval.

const vars = {
  IS_VERIFIED: "True",
  CONFIRMATION_NEEDED: "True",
  REQUEST_LIMIT: "2",
};

const str = `(@IS_VERIFIED = 'True' OR @CONFIRMATION_NEEDED != 'True') AND @REQUEST_LIMIT != '0'`;

const evalStr = str
  .replaceAll("@", "vars.")
  .replaceAll("OR", "||")
  .replaceAll("AND", "&&")
  .replaceAll("!=", "!")
  .replaceAll("=", "===")
  .replaceAll("!", "!==");

const res = eval(evalStr);
console.log(res);
Comment: I know `eval` is not going to be liked much here, but I loved this. Very clever.
Comment: I thought about using eval but the condition string will be a user input, it is not an option for me due to security risks and I am not allowed to use it. Also even if I could eliminate the security risks somehow, than it would be impossible to do the next step(check the edit). So I guess I have to parse the string somehow.
Comment: @Nanoturka That's unfortunate! Some fancy string parsing with regex might be able to help.
Answer: Here is a snippet using RegExp:
let test = "@XYZ='True' AND @ABC='False'";

const regexp = /(@\w+)|(\'\w+\')/g;

const regexpResult = [...test.match(regexp)]
// Returns something like this:
// ["@XYZ", "'True'", "@ABC", "'False'"]

const vars = {};

for (let i = 0; i < regexpResult.length; i += 2) // We will be using two consecutive values at a time
{
  let keyName = regexpResult[i].replace("@", "");
  let keyValue = regexpResult[i+1].replaceAll("'", "");

  vars[keyName] = keyValue;
}

// OUTPUT of "vars":
// {
//   XYZ: "True",
//   ABC: "False"
// }

I hope this gives you an idea about how to solve your problem.


"image" is not accessed - Pylance

Question: Pyance is showing false warnings in certain functions.

Even the variable is used it still shows as it. For example in the above picture

The varible image from line 1984 is accessed in line number 1986.
The varible image_obj from line 1985 is accessed in line number 1991 and 1992.
And similar cases on other lines too.

Can anyone help me figure why this is happening?
Answer: This problem cannot be reproduced with simple code. I think we can refer to this case on Github for a solution.
Perhaps Pylance analysis code exceeded the limit and some of the code was omitted.
In this case, patch t.maxCodeComplexity= in .vscode/extensions/ms-python.vscode-pylance-%version%/dist/pyright.bundle.js and increase the limit back to 1024 can solve it.

"image" is not accessed - Pylance


How do I solve this valueerror while installing pyautogui?

Question: Please note that this query is not the same as:
How to install PyAutoGUI
or
how to solve ValueError in Python
I am working on an Ubuntu machine. I used the command pip install pyautogui. Everything goes well until I get this on the terminal:
File "/tmp/pip-build-gXkSEJ/Pillow/setup.py", line 516, in build_extensions

(f, f))

ValueError: jpeg is required unless explicitly disabled using --disable-jpeg, aborting

----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-gXkSEJ/Pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-d_80Eq-record/install-record.txt --single-version-externally-managed --compile --user failed with error code 1 in /tmp/pip-build-gXkSEJ/Pillow
Storing debug log for failure in /tmp/tmpHnGt1t

Comment: `sudo apt-get install libjpeg-dev`
Comment: what about with `easy_install pyautogui`?
Comment: Message shows that problem is with `Pillow` and `JPEG`. Maybe find answer for this problem. Probably you have to use `apt-get` to install some jpeg library (C/C++)
Answer: You must first run pip install pillow. However, as of 0.9.34 of PyAutoGUI, you do not need to do this anymore and can just try running pip install pyautogui


async nodejs execution order

Question: When does processItem start executing. Does it start as soon as some items are pushed onto the queue? Or must the for loop finish before the first item on the queue starts executing?
var processItem = function (item, callback) {
    console.log(item)
    callback();
}

var myQueue = async.queue(processItem, 2)

for (index = 0; index < 1000; ++index) {
    myQueue.push(index)
}

Answer: The simple answer is that all of your tasks will be added to the queue, and then executed in a random (undefined) order.

background information, via https://github.com/caolan/async#queueworker-concurrency
queue(worker, concurrency)
Creates a queue object with the specified concurrency. Tasks added to the queue are processed in parallel (up to the concurrency limit). If all workers are in progress, the task is queued until one becomes available. Once a worker completes a task, that task's callback is called.

In other words, the order is undefined. If you require the tasks to be executed in a particular order, you should be using a different asynchronous primitive, such as series(tasks, [callback])
https://github.com/caolan/async#seriestasks-callback
Comment: Clarified to relate to actual question
Answer: The current call stack must resolve before any asynchronous tasks will run. This means that the current function must run to completion (plus any functions that called that function, etc.) before any asynchronous operations will run. To answer your question directly: all items will be fully queued before the first one runs.
It might be helpful for you to read more about the JavaScript event loop: asynchronous jobs sit in the event queue, where they are handled one by one. Each job in the event queue causes the creation of the call stack (where each item in the stack is function call -- the first function is on the bottom, a function called within that first function is next-to-bottom, etc.). When the stack is fully cleared, the event loop processes the next event.

async nodejs execution order


htaccess redirect when entering path in address bar

Question: I want to move some files to another directory on my web server, but these files are images,
that my clients link to. I have not got the time to go and change over 100 image urls, so is there a way i can get .htaccess file to do a mod_rewrite to point then image url to where it should be?
Thanks
Fero
Answer: You can limit this on the server side.
One way it to check the referer header if it matches with your site.
The other is to use a special loading mechanism between the server and flash that passes some sort of token or HTTP authentication, and maybe protect the token/auth with SSL.
Whatever you choose it will not be 100% bullet proof and IMO is not worth the hustle.
Comment: Note that the referer header is optional and some personal security software modifies it. You can't depend on it.
Answer: Yes, that's rather the point of mod_rewrite.
If you are just moving a directory wholesale, then a simple redirect will be easier though.
<code>Redirect 301 /old/images/ http://example.com/new/images/
</code>
Comment: David.. I am not moving the directory wholesale. I need just if any one type the path in the address bar then "FORBIDDEN" page should be redirected. Awaiting for the answer. thanks in advance
Comment: That doesn't appear to have anything to do with the question you asked.
Comment: Hang on. When you say "FORBIDDEN" do you mean "NOT FOUND"? I don't think you can trap that in mod_rewrite. You could set up a mod_perl handler, PHP script or similar as your ErrorHandler document though.
Comment: http://www.splocs.com/images/ Please use the above URL. This is exactly what i need...
Comment: You want to disable the directory index? That's one of the settings of the Options property in the Apache configuration.
Comment: But i did using .htaccess. But in the mean time if i enter the name of the image following by the path the image is displaying. This should not happen. Any better way to do.
Comment: In simple images in my project should be protected.
Comment: Might as well just delete them from the server then. You can't let people use images in a webpage but not let them view the images outside the page.


What do the stats in Jet Set Radio Future do?

Question: I've recently had the opportunity to play Jet Set Radio Future again, but I don't remember what any of these stats do.
What do the stats in Jet Set Radio Future do?
Answer: Stamina is health.
G-stamina is how much graffiti the character can take in Tagger's Tag mode.
Spray is how many spray cans they can carry.
Graffiti is how fast the character can spray each graffiti point on a medium, large, or extra large tag.
Acceleration is how fast they get to top speed while on the ground.
Cornering is just how they handle turns.
Grind is how easily they latch on to grindable surfaces.


PySpark: How to drop non-numeric columnsfr a DataFrame?

Question: I want to drop all columns from a DataFrame which are non-numeric. I am attempting to replicate some Pandas code that does this like so:
df = df[df.select_dtypes(exclude=['object']).columns]

How would I do this for a PySpark DataFrame?
Answer: First of all, please find here a reference on different PySpark types.
The code below removes the String cols:
df = spark.createDataFrame([
    (1, "a", "xxx", None, "abc", "xyz","fgh"),
    (2, "b", None, 3, "abc", "xyz","fgh"),
    (3, "c", "a23", None, None, "xyz","fgh")
], ("ID","flag", "col1", "col2", "col3", "col4", "col5"))

from pyspark.sql.types import *
num_cols = [f.name for f in df.schema.fields if not isinstance(f.dataType, StringType)]

df2 = df.select([c for c in num_cols])
df2.show()

+---+----+
| ID|col2|
+---+----+
|  1|null|
|  2|   3|
|  3|null|
+---+----+

Alternatively (to be precise) you can replace not isinstance with isinstance and include the types from the link above you are interested in.
Hope this helps.


Fetching Json from URL - null object reference

Question: I am trying to fetch an array from the data.police.uk website.
Unfortunately, when running the code an error comes up: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
Here's the code, no idea, what I am doing wrong:
 package com.example.cosmin.crimerate.Latest_crimes;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.cosmin.crimerate.R;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class JsonCrimesActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json_crimes);

        final ListView listView = findViewById(R.id.crimesList);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = retrofit.create(Api.class);

        Call<List<Crime>> call = api.getCrimes();

        call.enqueue(new Callback<List<Crime>>() {
            @Override
            public void onResponse(Call<List<Crime>> call, Response<List<Crime>> response) {
                List<Crime> Crimes = response.body();

                String[] crimeCategories = new String[Crimes.size()];

                    for (int i=0; i < Crimes.size();i++){
                        crimeCategories[i]= Crimes.get(i).getCategory();
                    }

                    listView.setAdapter(
                            new ArrayAdapter<String>(
                                    getApplicationContext(),
                                    android.R.layout.simple_list_item_1,
                                    crimeCategories

                            )
                    );

                }

            @Override
            public void onFailure(Call<List<Crime>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });

    }
}

That's the Api class:
public interface Api{

    String BASE_URL = "https://data.police.uk/api/";

    @GET("/crimes-no-location?category=all-crime&force=leicestershire&date=2017-02")
    Call<List<Crime>> getCrimes();

Do you think it can be because of the array?
If you can please me give me a hint or anything what's happening.
Thank you for your help!
LE: CRIME MODEL:
public class Crime {

    private String category;
    private String persistent_id;
    private String location_subtype;
    private String id;
    private String location;
    private String context;
    private String month;
    private String location_type;
    private String outcome_status;

    public Crime(String category, String persistent_id, String location_subtype, String id, String location, String context, String month, String location_type, String outcome_status) {
        this.category = category;
        this.persistent_id = persistent_id;
        this.location_subtype = location_subtype;
        this.id = id;
        this.location = location;
        this.context = context;
        this.month = month;
        this.location_type = location_type;
        this.outcome_status = outcome_status;

    }

    public String getCategory() {
        return category;
    }

    public String getPersistent_id() {
        return persistent_id;
    }

    public String getLocation_subtype() {
        return location_subtype;
    }

    public String getId() {
        return id;
    }

    public String getLocation() {
        return location;
    }

    public String getContext() {
        return context;
    }

    public String getMonth() {
        return month;
    }

    public String getLocation_type() {
        return location_type;
    }

    public String getOutcome_status() {
        return outcome_status;
    }
}

Comment: what does `response.body()` return?
Comment: First, I noticed you have an extra `/` in your URL, remove that and test again, if the issue is still there, can you please share your Crime Model Class?
Comment: Thanks for your replies.
Removed the /, unfortunately a new error comes up: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 93 path $[0].outcome_status.
Answer: Make sure this piece of code if working fine.
List<Crime> Crimes = response.body();

Your Crimes List is probably empty or null.
Answer: Your response.body() is returning null. I'm pretty sure it's because you misconfigured your Api. As is, you're making an http call to the following uri (notice the double //):
https://data.police.uk/api//crimes-no-location?category=all-crime&force=leicestershire&date=2017-02

Remove the leading slash in your @GET
Comment: Thanks for your replies.
Removed the /, unfortunately a new error comes up: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 93 path $[0].outcome_status.
Comment: So you had more than one problem. That means there was likely a problem parsing your model. `outcome_status` is expecting a string but it returns a json object instead. You need to update your model to consider that. Look closely at the returned json from your endpoint (I formatted it for you nicely here: https://pastebin.com/tWV7rhvS)


Independence of Vertex Degrees in Erdős-Rényi Random Graph $G(n,p)$

Question: I am self-studying Chapter 8 (Random Graphs) of the book Foundations of Data Science. The example on page 250 tries to bound the probability of the existence of a vertex in $G(n,1/n)$ with degree $\Omega(\log n/\log\log n)$. I am having trouble with the last few lines:

But the degrees are not quite independent since when an edge is added to the graph it affects the degree of two vertices. This is a minor technical point, which one can get around.

How do I get around this technical point?
I also saw something similar in Exercise 2.4.4 of Vershynin's High-Dimensional Probability (which I am unable to solve):

Exercise 2.4.4 (Sparse graphs are not almost regular). Consider a random graph $G\sim G(n,p)$ with expected degrees $d=o(\log n)$. Show that with high probability, (say, $0.9$), $G$ has a vertex with degree $10d$.

Hint: The principal difficulty is that the degrees $d_i$ are not independent. To fix this, try to replace $d_i$ by some $d_i'$ that are independent. (Try to include not all vertices in the counting.) Then use Poisson approximation (2.9).

I found an answer in this post but I have some doubts about it:

The answer says that with high probability, the degrees of the vertices in $V'$ are independent. Does it mean something like $\mathbb{P}(\mathbb{P}(AB)=\mathbb{P}(A)\mathbb{P}(B))\ge 1-\epsilon$? Why does it make sense?
The answer seems to use approximation to Poisson$(d)$. But isn't $d$ changing with $n$? The Poisson Limit Theorem does not seem to apply.
How does one get rid of the $o(1)$ term in Poisson approximation?

Update: Sameer Kailasa has provided a very nice solution to Exercise 2.4.4 using conditional probability (conditioned on a subset of vertices being an independent set). I wonder if there is an alternative solution that follows the hint of the book by defining some independent $d_i'$?
Answer: We consider the situation of the Exercise 2.4.4 from Vershynin. Take a small $\epsilon > 0$; since $d = o(\log(n))$, we have that $p < \epsilon \log(n)/n$ for all sufficiently large $n$.
For a fixed subset of $k$ vertices, the probability that there is no edge joining any two of them is $$(1 - p)^{\binom{k}{2}} > \left(1 - \frac{\epsilon \log(n)}{n} \right)^{k^2} \ge 1 - \frac{\epsilon \log(n) k^2}{n}$$ where we applied the Bernoulli inequality. Hence, for any $\delta > 0$, if we set $k = n^{1/2 - \delta}$, then as $n \to \infty$ the probability that any particular set of $k$ vertices is independent approaches $1$.
Thus, we can proceed as follows. Choose a particular set of $k$ vertices, and consider the event $E$ that none of them has degree equal to $10d$. We have
$$\mathbb{P}(E) \le \mathbb{P}(E \, | \, S \text{ is independent}) + \mathbb{P}(S \text{ is not independent})$$
By the argument above, the latter probability can be made arbitrarily small as $n \to \infty$. Thus, we must bound the former probability, which is computable due to the conditional independence; it is exactly $$\left(1 - \binom{n-k}{10d} p^{10d} (1-p)^{n-k-10d} \right)^{k}$$
Using the binomial coefficient lower bound $\binom{n}{k} \ge (n/k)^k$, we have now that $$\binom{n-k}{10d} p^{10d} (1-p)^{n-k-10d} \ge \left(\frac{(n-k)p}{10d} \right)^{10d} (1-p)^{n}  $$ $$\ge \left( \frac{1}{20} \right)^{10\epsilon \log(n)} \left( 1 - \frac{\epsilon \log(n)}{n}\right)^n$$ since $n -k > (n-1)/2$ for large enough $n$. Crunching further with the numerical inequality $1 - x > e^{-2x}$ for $0 < x < 1/2$, we have for sufficiently large $n$ that $$\left( \frac{1}{20} \right)^{10\epsilon \log(n)} \left( 1 - \frac{\epsilon \log(n)}{n}\right)^n > e^{-10 \epsilon \log(20) \log(n)} e^{-2 \epsilon \log(n)} = n^{-C\epsilon}$$ for absolute constant $C$. Finally, we conclude that $$\mathbb{P}(E \, | \, S \text{ is independent}) \le \left(1 - \frac{1}{n^{C\epsilon}} \right)^{n^{1/2 - \delta}} < e^{-n^{1/2 - \delta - C\epsilon}}$$
Assuming $\delta$ and $\epsilon$ are chosen sufficiently small to ensure $1/2 - \delta - C \epsilon > 0$, the last inequality implies that the conditional probability vanishes as $n \to \infty$. We conclude that $\mathbb{P}(E) \to 0$ as $n \to \infty$, i.e. with high probability, there is a vertex of degree exactly $10d$ among our arbitrarily chosen set of $k$ vertices.
To sum up, the technical point mentioned in your question is that although vertices are not independent, with high probability a sufficiently small set of vertices (in this case $k = n^{1/2 - \delta}$) is independent. Then, conditioning on the very likely event enables us to finish the calculation.
Comment: Thank you so much for your detailed answer! If my understanding is correct, then "$S$ is independent" means that no two vertices in $S$ are adjacent? Alternatively, if I approach this problem by following the hint from the book, how should I define $d_i'$ so that they are independent (in the sense of probability)?
Comment: Yes! In graph theory an "independent set" is a set of vertices, no two of which are joined by an edge.


Unity working with Async and Await in Firebase

Question: I'm implementing a little game with Unity which use firebase services. I had a little problem with Firebase RealtimeDataBase.
I have a method "UpdateScoreAsync", this method publish the new player's record on database. Now I call this method with a code like this:
await UpdateScoreAsync();
LoadScene("ReloadActualScene"); // It starts the game again.

It works well, but like you could see in code, the new scene is loaded when the score is totally updated. My goal is load the new scene while the score is updating but if I just remove the "await" the game break when the scene is reloaded. I see my device's log (Android) and I think the problem is this:

Native thread exiting without having called DetachCurrentThread (maybe it's going to use a pthread_key_create destructor?) (etc)

The object of UpdateScoreAsync method is a singleton and it doesn't destroy when the scene is reload. Althoug the game cracks, the score is updated on database!
My current method "UpdateScoreAsync" is like this:
public async Task UpdateScoreAsync(string userId, int newScore)
{
    Debug.Log("Actualizando puntuación en la base de datos...");
    await FirebaseDatabase.DefaultInstance.GetReference("string").Child("string").Child("Score").SetValueAsync(newScore).ContinueWith(task => {
        if (task.IsFaulted) {
            ...
        } else if (task.IsCanceled) {
            ...
        } else if (task.IsCompleted) {
            Debug.Log("Score updated");
            ...
        }
    });
}

I try to change this method like this one:
public void UpdateScoreAsync(string userId, int newScore)
{
    Debug.Log("Actualizando puntuación en la base de datos...");
    FirebaseDatabase.DefaultInstance.GetReference("string").Child("string").Child("Score").SetValueAsync(newScore).ContinueWith(task => {
        if (task.IsFaulted) {
           ...
        } else if (task.IsCanceled) {
           ...
        } else if (task.IsCompleted) {
           Debug.Log("Score updated");
           ...
        }
    });
}

And the call to this method:
UpdateScoreAsync();
LoadScene("ReloadActualScene");

With this new code I obtain the error I explained before. Could anyone help me?? I don't know where is the error.
Thanks in advance!
Answer: Per the Unity documentation for LoadScene():
Note: Since loading is set to complete in the next rendered frame, calling SceneManager.LoadScene forces all previous AsynOperations to complete, even if AsyncOperation.allowSceneActivation is set to false. This can be avoided by using LoadSceneAsync instead.
Try using LoadSceneAsync instead.
Comment: But if I don't understand bad, with this what I do is that the scene doesn't load until the other async operations are finished. But I want load new scene while the other operations are executing in background, event I should be able to play in the new scene while async operations (throws in the previous scene) are still executing.
Comment: Did you try this way out?  Did it work?  If not, what happened?
Comment: I will try next week! Just now my computer is broken. I will post again when I test it! Thanks in advance!
Comment: I'm afraid that the mistake continues... :( The error is: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast. Any idea what the problem is??
Comment: That looks like a different error message then you were receiving before, correct?


Finding growth bounds on Fibonacci Sequence

Question: I've been working on this following problem:

Find a constant $c< 1$ such that $F_n \leq 2^{cn}$ for all $n \geq 0$.

I honestly have no idea where to begin on this. I've done plenty of proofs the one function is Big-O another, but I'm not sure where to start looking for c in this case. Guidance appreciated. Thanks!
Comment: Do you know Binet's formula?
Answer: Binet's formula seems like overkill, given the (relatively weak) desired conclusion.
A more naive strategy is to pretend that $F_{n} = 2^{cn}$ and see what the recursion relation $F_{n+2} = F_{n} + F_{n+1}$ suggests. Here,
$$
2^{c(n+2)} = 2^{cn} + 2^{c(n+1)}, \quad\text{or}\quad
2^{2c} = 1 + 2^{c}.
$$
The latter is a quadratic in $2^{c}$, and by the quadratic formula has roots
$$
2^{c} = \frac{1 \pm \sqrt{5}}{2}.
$$
It's therefore natural to attempt to show $F_{n} \leq \bigl[(1 + \sqrt{5})/2\bigr]^{n}$ for $n \geq 0$; this is a straightforward induction.
Answer: Let $0\lt x=2^c\le 2$.
If $F_{n-2}\le x^{n-2}$ and $F_{n-1}\le x^{n-1}$ you have $F_n=F_{n-1}+F_{n-2}\le x^{n-1}+x^{n-2}$
So you will definitely succeed if you get the initial conditions (first values) to work and if  $x^{n-1}+x^{n-2}\le x^n$ which gives you $x^2-x-1\ge 0$ (dividing through by $x^{n-2}\gt 0$). For example, $x=\frac 53$ works for the inequality.
There has been some debate elsewhere about the initial values of $F_n$ - whether $F_0=0$ or $F_0=1$ - $F_0=0$ is the best choice, because then $F_n\mid F_{kn}$ for all positive integers $n$ and $k$. Then $x=\frac 53$ works for the initial values too.
Then you need to take logs to get the appropriate value of $c$. Note that $\varphi = \frac {1+\sqrt 5}2$ is the least value of $x$ which would satisfy the inequality.
Comment: (+1) I was typing up essentially the same strategy, but posted anyway since the details seemed sufficiently distinct from yours.... :)
Comment: @user86418 Indeed. I wanted to show that the question as posed didn't require Binet's formula or a precise calculation of $\varphi$.
Answer: By Binet's formula you may prove that:
$$0<F_n =\frac{1}{\sqrt{5}} \left(\frac{1+\sqrt{5}}2\right)^n-\frac{1}{\sqrt{5}} \left(\frac{1-\sqrt{5}}2\right)^n<\left(\frac{1+\sqrt{5}}2\right)^n$$ then choose $c$ such that
$$
2^c=\frac{1+\sqrt{5}}2,
$$ giving
$$
c=\frac{\ln \left(\frac{1+\sqrt{5}}2\right)}{\ln 2}=0.6942...<1.
$$
Answer: Hint:
$$\text{If }\phi = \frac{1 + \sqrt5}{2}, \ F(n) = \frac{\phi^n - (1-\phi)^n}{\sqrt 5}\text{ where } F(n)\text{ is the nth Fibonacci number}$$


NSString value not retained

Question: I'm trying to assign data from a string to another string within a different viewcontroller however it seems that the data is not retained - i get a null response in NSLog. I would like to know why, thanks ..
Comment: Maybe beacause viewDidLoad is fired before 'schoolController.courseDetails = @"passing new content"' line
Answer: Try changing the order a bit, as below, and use retain instead of copy:
SchoolDetailViewController *schoolController = [[SchoolDetailViewController alloc]initWithNibName:nil bundle:nil];
schoolController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
schoolController.courseDetails = @"passing new content";
[self presentModalViewController:schoolController animated:YES];
NSLog(@" %@",schoolController.courseDetails); // 'passing new content' is shown

.h
    NSString *courseDetails;
@property (nonatomic, retain) NSString *courseDetails;

.m
@synthesize courseDetails;

- (void)viewDidLoad {

    NSLog(@" text : %@",courseDetails); // returns null ... why?

    [super viewDidLoad];
}

This should work.
Answer: Well that is because the viewDidLoad method is called when you present the view controller with or without animation.
So just flip these 2 statements
[self presentModalViewController:schoolController animated:YES];
schoolController.courseDetails = @"passing new content";

like this
schoolController.courseDetails = @"passing new content";
[self presentModalViewController:schoolController animated:YES];

And then check the results once again...

NSString value not retained


What is the difference between a Sampler and an Image variables in GLSL?

Question: Reading through some code about voxelization I found the following line in the fragment shader
layout (binding = 0, r32f ) coherent uniform writeonly image3D volumeTexture;
I have only used samplers in the past and have never seen image3D before.
I have read the entries about Sampler Varibles and Image Variables but I really don't grasp the differences, advantages/disadvantages between Sampler and Image.
Can someone help me pointing out what are the difference between these two types of variables and when should I used one over the other?
Comment: The title refers to `Image2D` and the code and body refer to `image3D`. Does one of these need to be edited? Which one are you asking about?
Answer:
Images creation is the same as texture, but it must be binded as
image to image units. These are equivalent of "texture units".
With them you can arbitrarily perform read/write/modify operations
using imageStore/imageLoad or atomic operations at some coordinates. Unlike samplers these
coordinates are in unsigned integer range.
They do not need to be part of framebuffer color attachments to write
into them. This is useful and simplify some techniques like injecting
data into volume textures and is used in compute shaders. No need to use draw calls with buffer data upload.
There is no mipmapping or texture filtering available when doing
operation on texture binded as image.
Comment: Is there a typo in the third bullet point? I'm guessing it should say "they do _not_ need to be part of framebuffer color attachments to write into them"?
Comment: Yes you are right. Hmm strange, I meant the opposite - edited.
Answer: Image and Samplers differ in many ways. Unlike Samplers, images can only be addressed with an integer coordinate that ranges from  (0,0) to (x,y), where x and y are the width and height of the image. They support random access reads like texelFetch, and support no filtering as you're accessing raw texels. The most interesting thing with images is that they support read and write access, in Open GLES there are limitations, wherein an image may only be specified as readonly or writeonly, not both, in desktop GL though you may specify an image as read/write so that you can both read and write to that image in a single pass.
Using a sampler, if you wanted to write a color into it you'd have to use an FBO, then a second pass to consume that. With images, you can do this all in one pass by writing to the image and reading from it, you'd have to handle the synchronisation yourself of course.
Images are very useful for image processing etc.
Answer: Unlike samplers imageLoad (Load in HLSL) requires a texel coordinate (integer). This will load the value at that location only. The range of the coordinate can be (0,0) to (image width, image height). Because only an integer can be supplied no sampling is applied to blend between multiple texels (e.g. bilinear in 2D). I'd therefore assume it is a cheaper operation.
Image processing algorithms such as blurs often use image load so that discrete texel values can be processed.


Direct Proof involving Rational Numbers

Question: I have been trying to figure out the following proof: "If a is rational and b is rational, then a + b is rational."
I am new to proofs, and still trying to familiarize myself with the process. I know that definitions of things are very important to proofs, and I know that a rational number is any 2 integers that can be written as a fraction. But I am not sure how to express this idea in the proof.
Comment: Nothing more than $$\frac{a}{b}+ \frac{c}{d} = \frac{ad+bc}{bd}$$ one line proof.
Answer: $a\in\mathbb{Q}\iff \exists p,q\in\mathbb{Z}:a=\frac{p}{q},\quad q\neq 0$
Then $a,b\in\mathbb{Q}\implies$ we can write $a=\frac{p}{q}$ and $b=\frac{m}{n}$ with the above properties for $p,q$ and $m,n$ respectively.
Then $a+b =\frac{p}{q}+\frac{m}{n} = \frac{pn+mq}{qn}$
Now since $p,q,m,n\in\mathbb{Z}$, we also have that $pn+mq\in\mathbb{Z}$ and $qn\in\mathbb{Z}$. Therefore $a+b\in\mathbb{Q}$ as required.
Comment: @MiloBrandt Upon re-reading I agree. I have edited it out.
Comment: Thank you very much for this simple example, I proofed the log2 with this :)
Answer: "I know that definitions of things are very important to proofs, and I know that a rational number is any 2 integers that can be written as a fraction. But I am not sure how to express this idea in the proof."
Then that means you have to prove that if $\frac ab$ is a rational number and $\frac cd$ is a rational number then $\frac ab + \frac cd = \frac ef$ for some rational number that is $\frac ef$ for some two integers $e,f$.
So
$\frac ab + \frac cd = \frac {ad}{bd} + \frac {cb}{bd} = \frac {ad+cb}{bd}$.
$ad+cb= e$ is an integer.  $f= bd$ is an integer.  So $\frac ef = \frac {ad+cb}{bd} = \frac ab + \frac cd$ is a rational number.  That's it.
"I know that a rational number is any 2 integers that can be written as a fraction"
Well... nitpick.  The rational is the fraction; not the two integers.  But I know what you meant.
Comment: Thank you for the help. I knew that that was the solution I wanted to arrive at, I even had it partially written out, but I just am trying to learn how proofs work, and what is and isn't acceptable as a mathematical explanation. I appreciate your help

Direct Proof involving Rational Numbers


Took over iPhone development on an app from another developer and getting code signing error

Question: I am able to get the software to build and run in the simulator and when I set it to device I get a code signing error as it has the previous developers code signature.  How do I get it to use my provisioning profile.
Answer: Project > Edit Project Settings > Code Signing Identity


Show/hide input text after click with multiple selectbox

Question: I have selectbox like this
rows 1
<form action="" method="POST">
  <select id="showhide">
      <option value="0">-SELECT-</option>
      <option value="1">Show</option>
      <option value="2">Hide</option>
  </select>
  <input id="txtname" type="text" name="txtname" style="display:none;">
</form>

rows 2
<form action="" method="POST">
  <select id="showhide">
      <option value="0">-SELECT-</option>
      <option value="1">Show</option>
      <option value="2">Hide</option>
  </select>
  <input id="txtname" type="text" name="txtname" style="display:none;">
</form>

and javascript
$(document).ready(function(){
    $("#showhide").change(function(){
        var valx = $('#showhide').val();
        if(valx == '1'){
            $("#txtname").show();
        }else if(valx == '2'){
            $("#txtname").hide();
        }
    });
});

when i use selectbox in rows 1 show/hide the inputbox in rows 1 working, but when i use selectbox in rows 2 the show/hide not working like rows 1.
how to solved this.
thankyou
Comment: @Ramanlfc. after i change to class with the same class name, this not work to. i can't use uniqname because this rows is dynamic.
Answer: Replace id attribute with name in select, and remove id attribute from input, because id attribute must be unique over all document.
<form action="" method="POST">
  <select name="showhide">
      <option value="0">-SELECT-</option>
      <option value="1">Show</option>
      <option value="2">Hide</option>
  </select>
  <input type="text" name="txtname" style="display:none;">
</form>
<form action="" method="POST">
  <select name="showhide">
      <option value="0">-SELECT-</option>
      <option value="1">Show</option>
      <option value="2">Hide</option>
  </select>
  <input type="text" name="txtname" style="display:none;">
</form>

JS:
$(document).ready(function(){
    $("select[name='showhide']").change(function(){
        $(this).siblings('input[name="txtname"]').toggle(this.value == 1);
    });
});

Example: https://jsbin.com/pavijufige/edit?html,js,output
Answer: Do this changes.
In the current scenario,use $(this) to get current context selection
$(document).ready(function() {
        $("select.showhide").change(function() {

        var valx = $(this).val();
        if (valx == '1') {
            $(this).next().show();
        } else if (valx == '2') {
            $(this).next().hide();
        }
    });
});

Add class class="showhide" to your select drop-down.
Id Should be unique.So, you can not use same id twice.
HTML :
<form action="" method="POST">
        <select class="showhide">
            <option value="0">-SELECT-</option>
            <option value="1">Show</option>
            <option value="2">Hide</option>
        </select>
        <input id="txtname" type="text" name="txtname" style="display:none;">
    </form>
    <form action="" method="POST">
        <select class="showhide">
            <option value="0">-SELECT-</option>
            <option value="1">Show</option>
            <option value="2">Hide</option>
        </select>
        <input id="txtname" type="text" name="txtname" style="display:none;">
    </form>

Comment: not work, when i change  selectbox in rows 1 and 2 the inputbox in rows 1 working and show and hide but not to input box in rows 2


find primitive elements in $\mathbb Z_2[x]/\langle x^5+x^2+1\rangle$

Question: Somebody can help me with this exercise?

How many primitive elements are there in $\frac{\mathbb{Z}_2[x]}{\langle x^5+x^2+1 \rangle}$?

Thank you.
Comment: Z2[x]/
Answer: The primitive elements are exactly the generators of the multiplicative group, which is always cyclic for a finite field.
So it is enough to find how many elements the field has.


open covering and open intervals covering

Question: A compact set is a set that its each open covering has finite sub-cover.
Since non-empty open set is disjoint union of countable open intervals.

Is there some connections between open cover and open interval cover?
Comment: has a finite SUB-cover. An open set is not necessarily a disjoint union of countable open intervals, take for example, $\mathbb{R}$
Comment: @qbert $\mathbb{R}=\cup_{n=1}^\infty(-n,n)$
Answer: An open interval cover is just a special case of an open cover where the open sets are intervals.
There is no direct connection between this theorem and the definition of a compact set.
Answer: If compact set $\displaystyle K=\bigcup_{i\in \Lambda}\mathcal{O}_i$, since $\displaystyle \mathcal{O}_i=\bigsqcup_{k=1}^{n_i}I_{ik}$, so $\displaystyle K=\bigcup_{i\in \hat\Lambda}\mathcal{O}_i$, where $\hat\Lambda$ includes all index of $i,k$. Thus, we have a finite sub-covering denoting $\displaystyle \bigcup_{j=1}^mI_j$. So they are equivalent.


Adding event listener to button without using class or id property?

Question: <!doctype html>

<meta charset="utf-8">
<title>css demo</title>

 My WebSite

        <button data-file="day">Day</button>
        <button data-file2="night">Night</button>

I just started learning jQuery, so forgive me my questions are vague or not of enough class. Is there anyway i can achieve separate clicks for Day and Night button without using ID or Class property.
I want to know if we can achieve the clicks collecting the data-file attribute [using either attr or data property].
Comment: `$('button[data-file="day"]')` will work.
Comment: The point here being: You can use **any** selector that will match, including an attribute selector.
Answer: Target the two different data attributes :
$(document).ready(function(){
    $('button[data-file]').on('click', function(){ // or [data-file="day"] to be
        console.log("Day button clicked");         // even more specific
    });

    $('button[data-file2]').on('click', function(){
        console.log("Night button clicked");
    })
});


Visibility in PHP? context of `$this` when inherited?

Question: I am new to php and I was going through the documentation for the visibility. I am little confused with this example in the documentation.
when the call to $myFoo->test() is made, shouldn't it make a call to Foos $this->testPrivate(); . I mean shouldn't $this be Foos Object rather than Bar object? . As per my knowledge(I might be wrong here) Foo will have kind of its own test() method which is inherited from Bar and calling $myFoo->test() will make a call to '$this->testPrivate' where the $this should be Foos object myFoo. so How is it calling Bar's testPrivate method?
class Bar
{
public function test() {
    $this->testPrivate();
    $this->testPublic();
}

public function testPublic() {
    echo "Bar::testPublic\n";
}

private function testPrivate() {
    echo "Bar::testPrivate\n";
}
}

class Foo extends Bar
{
public function testPublic() {
    echo "Foo::testPublic\n";
}

private function testPrivate() {
    echo "Foo::testPrivate\n";
}
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
            // Foo::testPublic
?>

Comment: The ambiguity of this constructed code should be taken as a warning sign. Avoid doing it in production code: Simply don't name two private methods the same when inheriting. If you assign the same name, the methods probably do the same, so you have code duplication. Or they look like they do the same, but don't - then they should have different names.
Answer: test() is in Bar, and will call the highest-level methods that Bar has access to. It has access to Foo's testPublic (because it is public) so it can call that, but it doesn't have access to Foo's testPrivate() (because it's private to Foo) so it calls it's own testPrivate() instead
Comment: ...but even with `class Foo [...] public function testPrivate()` Bar::testPrivate() is invoked ;-)
Comment: yes , but how is `$this` changing its context. I am still confused ,shouldn't it be opposite ,in the sense Foo has access to **test()** because its public in **class Bar**. so Foo has its own test method inherited from Bar?
Comment: Even though php starts its lookup for the method on the instance/scope, the _context_ in this case is still `Bar`, not `Foo`. You can test that by removing Bar::testPrivate. The error message will be `Call to private method Foo::testPrivate() from context 'Bar'`. Why `Bar::testPrivate` is called even with public `Foo::testPrivate` I can only explain (right now; I'm currently an endangered species with this internet addiction thingy....) by linking to the handler code: https://github.com/php/php-src/blob/PHP-5.6.16/Zend/zend_object_handlers.c#L1071


Cannot run angular-google-maps within ionic cordova build to android

Question: I have an ionic project where one of its pages uses the angular google maps directive.  On a browser everything works as it should, however when I emulate the project in android I get the following error on ADB catalog:

Error: [$injector:nomod] Module 'google-maps' is not availabl
  e! You either misspelled the module name or forgot to load it. If registering a
  module ensure that you specify the dependencies as the second argument.
  I/chromium( 1678): http://errors.angularjs.org/1.2.17/$injector/nomod?p0=google-
  maps

How can I correct this?
Answer: Did you try to look at the link given in your error, I guess it leads you to a very well explained documentation: https://docs.angularjs.org/error/$injector/nomod?p0=google-%20maps
Hope that helps.
Comment: hi thanks for helping , i saw that link but i know its not badly configured or badly spelled because i am able to run the application in my browser. this only happen when running in simulated android/ios


Python evdev [Error 16] Device or resource busy

Question: I connected 2D barcode scanner with Raspberry Pi 4 Model B and tried to scan few codes. on using evdev library I got the output successfully. But the issue is after 3 continues scans it's throwing me an exception saying "[Error 16] Device or resource busy". I can't able to find the root cause of this issue and tried many troubleshooting methods but nothing seems to work. Can anyone please help me. Here is the code I used.
from evdev import InputDevice, categorize, ecodes
from datetime import datetime
import calendar

scancodes = {
    # Scancode: ASCIICode
    0: None, 1: u'ESC', 2: u'1', 3: u'2', 4: u'3', 5: u'4', 6: u'5', 7: u'6', 8: u'7', 9: u'8',
    10: u'9', 11: u'0', 12: u'-', 13: u'=', 14: u'BKSP', 15: u'TAB', 16: u'q', 17: u'w', 18: u'e', 19: u'r',
    20: u't', 21: u'y', 22: u'u', 23: u'i', 24: u'o', 25: u'p', 26: u'[', 27: u']', 28: u'CRLF', 29: u'LCTRL',
    30: u'a', 31: u's', 32: u'd', 33: u'f', 34: u'g', 35: u'h', 36: u'j', 37: u'k', 38: u'l', 39: u';',
    40: u'"', 41: u'`', 42: u'LSHFT', 43: u'\\', 44: u'z', 45: u'x', 46: u'c', 47: u'v', 48: u'b', 49: u'n',
    50: u'm', 51: u',', 52: u'.', 53: u'/', 54: u'RSHFT', 56: u'LALT', 57: u' ', 100: u'RALT'
}

capscodes = {
    0: None, 1: u'ESC', 2: u'!', 3: u'@', 4: u'#', 5: u'$', 6: u'%', 7: u'^', 8: u'&', 9: u'*',
    10: u'(', 11: u')', 12: u'_', 13: u'+', 14: u'BKSP', 15: u'TAB', 16: u'Q', 17: u'W', 18: u'E', 19: u'R',
    20: u'T', 21: u'Y', 22: u'U', 23: u'I', 24: u'O', 25: u'P', 26: u'{', 27: u'}', 28: u'CRLF', 29: u'LCTRL',
    30: u'A', 31: u'S', 32: u'D', 33: u'F', 34: u'G', 35: u'H', 36: u'J', 37: u'K', 38: u'L', 39: u':',
    40: u'\'', 41: u'~', 42: u'LSHFT', 43: u'|', 44: u'Z', 45: u'X', 46: u'C', 47: u'V', 48: u'B', 49: u'N',
    50: u'M', 51: u'<', 52: u'>', 53: u'?', 54: u'RSHFT', 56: u'LALT',  57: u' ', 100: u'RALT'
}

class scan_barcode:

    def __init__(self,devicePath):
        self.devicePath = devicePath

    def readBarcode(self):

        dev = InputDevice(self.devicePath)
        dev.grab() # grab provides exclusive access to the device

        x = ''
        caps = False

        for event in dev.read_loop():
            if event.type == ecodes.EV_KEY:
                data = categorize(event)  # Save the event temporarily to introspect it
                if data.scancode == 42:
                    if data.keystate == 1:
                        caps = True
                    if data.keystate == 0:
                        caps = False

                if data.keystate == 1:  # Down events only
                    if caps:
                        key_lookup = u'{}'.format(capscodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(data.scancode)  # Lookup or return UNKNOWN:XX
                    else:
                        key_lookup = u'{}'.format(scancodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(data.scancode)  # Lookup or return UNKNOWN:XX

                    if (data.scancode != 42) and (data.scancode != 28):
                        x += key_lookup

                    if(data.scancode == 28):
                        return(x)

scanned_data = scan_barcode('/dev/input/event0')
def scanner_function():
  try:
    value = scanned_data.readBarcode()
    print(f"Scanned value:{str(value)}")
  except Exception as e:
    print(e)
    pass
while True:
  scanner_function()

Even though when I pass the exception It's not letting me to move to other tasks. The entire process stops here.
This is the output:
Scanned value: 4568hidhXGu
Scanned value: 1238fujXjje75
Scanned value: 789665
[Error 16] Device or resource busy
[Error 16] Device or resource busy
[Error 16] Device or resource busy
[Error 16] Device or resource busy
[Error 16] Device or resource busy

Comment: Could this be because you're continuously running `scanner_function()`, which initializes an `InputDevice` and does `dev.grab()` every time? The issue may be fixed if that will only happen once at the beginning of the program.
Comment: @ItaiSteinherz Hi thanks for the reply. Previously I tried initializing this `dev.grab( )` after importing header files and called the `scanner_function()` at last without `while True`. But I  got the same error again. This is the one I tried.

``` ```
Answer: I am not sure if the problem is related to your code. I think it is more related to your scanner. I have tested your script with the R32 QR Code reader (https://www.sycreader.com/en/3650/) and this is working perfect.
What scanner type are you using?
Result:
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:11.035355
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:11.675270
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:14.563287
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:15.007284
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:15.799299
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:20.959301
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:21.591286
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:24.515289
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:26.331292
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:31.323339
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:32.747289
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:34.495291
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:36.367294
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:37.903286
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:39.507295
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:41.099288
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:42.575295
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:44.123283
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:45.579286
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:47.055336
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:48.671301
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:49.983288
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:52.779284
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:54.755299
Scanned value:Toiletbezoek DateTime:2022-12-03 09:49:56.159286

Comment: Hi mario. I am using ZEBRA DS2208 barcode scanner. https://www.amazon.in/Zebra-DS2208-SR-Handheld-Omnidirectional-DS2208-SR7U2100AZW/dp/B06WGW816Y