Google Search Bar?

Question: I wanted to test the waters and see how other fellow usability people felt about Google's search bar in all of their sub sites. For instance if you are on google search, on google drive, or in Gmail the search bars position stays consistent in all of these pages however I don't feel that it is clear what the search bar is doing(searching the web, your email, or the drive).
Do you think it is clear to the user that you are searching inside those parts of the websites vs doing a google search?
Comment: I think it's fairly clear, you've explicitly entered a specific context of the Google Services and so you know what you're dealing with.
Answer: I agree with Rudi Visser. However a simple solution would be to change the default text from "Google search bar" to something like "Search within site" makes it quite obvious where a user is searching.
Answer: One option that I happened to use, not specifically as a solution to this problem, is to the the critieria input's placeholder attribute to be something like "Search customers", "Search locations" etc. It doesn't add to the UI real estate but gives added context.
Comment: Does that mean that you had found that your users were having difficulty distinguishing between searches in different parts of your site?  Did the added word in the label have any impact that you measured?  Please provide some more context.
Comment: This is in an app that I haven't even deployed yet so I can't speak to whether it provided any value. I just offered as an alternate way to show context of what they are searching. And in fact, Google calendar does use this idea, though not within Google mail which is weird since multiple entity types (mail, contacts) can be searched within it (would think the context would be more useful there).

Google Search Bar?


Can you cut open a plastic junction box and just lay splices inside?

Question: This doesn't look like it should fly to me, but the "electrician" hired by the seller of this property is arguing that this is an acceptable way to put an open splice into an box. I know this shouldn't be allowed, but is there phrasing in the code to support this being unacceptable? Their contractor is saying it just needs to be in a box, and if he staples it down within 8" it is fine. He "repaired about 20 open splices this way. You can see how he just modified the boxes and placed the open splices into them as they were before and just left them all over the attic like this. What kind of tradesman takes this little pride in their work?
Comment: "Hello, electrician licensing board?  I have an allegedly licensed electrician who has committed at least forty dangerous violations in my house and claims it's okay because nobody is going to inspect it. Is that how it's supposed to work?"
Comment: My guess is that modification negates UL listing, which would therefore violate code. Waiting for one of our resident sparkies to come along....
Comment: ***110.12 Mechanical Execution of Work.** Electrical equipment shall be installed in a neat and workmanlike manner.*
Comment: I gather that the previous owner had made a lot of open splices and this guy then came along and "fixed" them by fitting boxes around them.  I doubt that this would pass inspection in most parts of the country (unless the inspector's palm was "lubricated"), but it's probably a hair better than before.  The real problem is that, if the previous owner created such blatant violations, what else did he do wrong, and how trustworthy are those splices?
Comment: (Do note that it would have been **a lot** of **tedious** work to fix things properly, which is why the sparky was reluctant to tackle the job "correctly".)
Comment: That's just hideous.  I'm not a master anything, but I guarantee my effort would have been a helluva lot better than that.  Someone should reconsider all of this guy's credentials.  Having seen this horrible example, I would be willing to bet that he routinely compromises quality across the board, no matter what discipline.
Comment: I'm more interested in the "should" than the "can". That fella wouldn't get any more work from me.
Comment: Whether the county requires inspections or not, I would insist on an inspection as a condition of the sale. Assuming you are not paying cash for the house, the bank has an interest in their collateral not burning to the ground.
Comment: How about 300.11 Securing and Supporting.
(A) Secured in Place. Raceways, cable assemblies,
boxes, cabinets, and fittings shall be securely fastened
in place.
Comment: @Agent_L OP mentioned in a comment that this is in SC, which [currently uses NEC 2014](http://www.nfpa.org/NEC/NEC-adoption-and-use/NEC-adoption-maps). There may be local addendums, but they are typically fairly minor and generally don't change the large-scale, "don't burn your house down" prohibitions.
Comment: I wouldn't hire this guy, but the buyer is taking care of this. I am a master plumber, and I know this isn't right, but I'm hoping to be able to cite the code and reference the phrasing on why this clearly isn't up to acceptable standards and needs to be fixed properly, no matter what her "electrician" is trying to say.
Comment: Jack Leg says if he just staples them down he is covered. This is in the county and the county doesn't actually inspect repair work down here in Spartanburg SC so guys like this aren't easy to hold accountable.
Comment: You ask about local code, yet you don't specify a locale...
Comment: Yes this work is clearly out of line. Hopefully you can get more than just older and wiser out of this situation. ITF, get references first and don't pay until the job meets your satisfaction.
Comment: @Snowman Yes, I inferred USA from using inches as measurement. However, a good question specifies this explicitly. Your second paragraph is out of place, as OP wrote: *already knows it violates common sense, the question is about **code specifically.***
Comment: I have four questions to answer the question with: (a) Would it be appropriate to contact the city inspectors directly, ask for an inspection, and use their report to pressure the worker (who said no one is going to inspect it anyway, but in this case an inspection is needed to protect the owner)? (b) Is this kind of shoddy work going to affect the owner's insurance protection (especially fire insurance)? (c) If the owner calls in the inspectors and they find violations, who will be punished? I would hope the worker, but knowing the way bureaucracy works, would they assess the fines on the own
Answer: Red tag party, anyone?
Hoo boy, that installer needs to get knocked back to school with a Codebook!  What's in the photos alone violates several sections of the NEC, starting with 314.17(A) on the excessive openings for conductors:

(A) Openings to Be Closed. Openings through which conductors enter shall be closed in an approved manner.

We then move on to 314.23, where the utter lack of box support strikes:

314.23 Supports. Enclosures within the scope of this article shall be supported in accordance with one or more of
  the provisions in 314.23(A) through (H).

Note that nowhere in the subsections does it allow for a box to flop loose on some insulation, supported only by cabling that is not strain-relieved to the box by an approved means (such as a cord grip).
Also note the bulging box lids, which are indicative of a violation of the general provisions of 314.16:

314.16 Number of Conductors in Outlet, Device, and
  Junction Boxes, and Conduit Bodies. Boxes and conduit
  bodies shall be of an approved size to provide free space
  for all enclosed conductors. In no case shall the volume of
  the box, as calculated in 314.16(A), be less than the fill
  calculation as calculated in 314.16(B). The minimum volume for conduit bodies shall be as calculated in 314.16(C).
The provisions of this section shall not apply to terminal housings supplied with motors or generators.
Informational Note: For volume requirements of motor or
  generator terminal housings, see 430.12.
Boxes and conduit bodies enclosing conductors 4 AWG
  or larger shall also comply with the provisions of 314.28.

From there, we continue the party at 300.11(A) on support:

300.11 Securing and Supporting.
(A) Secured in Place. Raceways, cable assemblies, boxes,
  cabinets, and fittings shall be securely fastened in place.
  Support wires that do not provide secure support shall not
  be permitted as the sole support. Support wires and associated fittings that provide secure support and that are installed in addition to the ceiling grid support wires shall be
  permitted as the sole support. Where independent support
  wires are used, they shall be secured at both ends. Cables
  and raceways shall not be supported by ceiling grids.

and move on to 300.3(A) and (B) for the single wires run loose in the attic:

300.3 Conductors.
(A) Single Conductors. Single conductors specified in
  Table 310.104(A) shall only be installed where part of a
  recognized wiring method of Chapter 3.
Exception: Individual conductors shall be permitted
  where installed as separate overhead conductors in accordance with 225.6.
(B) Conductors of the Same Circuit. All conductors of
  the same circuit and, where used, the grounded conductor
  and all equipment grounding conductors and bonding conductors shall be contained within the same raceway, auxiliary gutter, cable tray, cablebus assembly, trench, cable, or
  cord, unless otherwise permitted in accordance with
  300.3(B)(1) through (B)(4).

Finishing things off, we can write the installer up for violating 110.12, including 110.12(A) specifically:

110.12 Mechanical Execution of Work. Electrical equipment shall be installed in a neat and workmanlike manner.
Informational Note: Accepted industry practices are described in ANSI/NECA 1-2010, Standard Practice of Good
  Workmanship in Electrical Construction. and other ANSI-
  approved installation standards.
(A) Unused Openings. Unused openings, other than those
  intended for the operation of equipment, those intended for
  mounting purposes, or those permitted as part of the design
  for listed equipment, shall be closed to afford protection
  substantially equivalent to the wall of the equipment.
  Where metallic plugs or plates are used with nonmetallic
  enclosures, they shall be recessed at least 6 mm (1/4 in.)
  from the outer surface of the enclosure.
Comment: Thank you! Between these two answers I should have enough to shame this turkey into refunding this woman's money.
Comment: He has a residential builders license and carpenter certification that I could find. Dude shouldn't be doing electrical work if you ask me. We have almost no code enforcement where I live.
Comment: A "code violation" is not necessarily the same as an administrative, let alone criminal violation of licensing laws. In theory, even if "done to code", work without the required license may be illegal.  I have seen license boards pass the buck (to the District Attorney) when they have no jurisdiction over non-licensed workers.
Comment: ...also not counting what appears to be unsheathed lone conductors going into that first box.  That's definitely a violation - sheathing needs to go all the way into the box.
Comment: I agree the square cut out is not legal also you may have covered this in "a" . this guy has a license? Really, wow...+
Comment: Also, no mention of the splice made with just tape and outside of the box? That's the only red flag I'd need to say it's time for a second box and to sort all this crap out properly.
Answer: In my jurisdiction, the owner (and his contractor) is responsible for making sure there are no violations of fire code and building code, including electrical code, whether or not anyone inspects prior to a catastrophe.
NFPA 70 (2014):

110.3 (B) Installation and Use. Listed or labeled equipment shall be installed and used in accordance with any instructions included in the
  listing or labeling.
110.12 Mechanical Execution of Work. Electrical equipment shall be installed in a neat and workmanlike manner....
  (B) ...There shall be no damaged parts that may adversely affect
  safe operation or mechanical strength of the equipment
  such as parts that are broken; bent; cut; or deteriorated by
  corrosion, chemical action, or overheating.

314.17:

Conductors Entering Boxes, Conduit Bodies, or Fittings. Conductors
  entering boxes, conduit bodies, or fittings shall be protected from
  abrasion and shall comply with 314.17(A) through (D).
(A) Openings to Be Closed. Openings through which conductors enter
  shall be closed in an approved manner.
(C) Nonmetallic Boxes and Conduit Bodies....Where nonmetallic sheathed
  cable or multiconductor Type UF cable is used, the sheath shall extend
  not less than 6 mm (1⁄4 in.) inside the box and beyond any cable clamp. In all instances, all permitted wiring methods shall be secured to the boxes.

However,

Exception: Where nonmetallic-sheathed cable or multiconductor Type UF
  cable is used with single gang boxes not larger than a nominal size 57
  mm × 100 mm (21⁄4 in. × 4 in.) mounted in walls or ceilings, and where
  the cable is fastened within 200 mm (8 in.) of the box measured along
  the sheath and where the sheath extends through a cable knockout not
  less than 6 mm (1⁄4 in.), securing the cable to the box shall not be
  required. Multiple cable entries shall be permitted in a single cable
  knockout opening.

I doubt that cutting or drilling your own holes in a listed and labeled box (as shown in your situation) counts as "a cable knockout", thus the exception would not apply.  Also, some of the photos show boxes more than "single gang", nor are ANY of them "mounted in walls or ceilings", if they're shown in unfinished attic spaces.
Comment: You can punch holes in some listed boxes but clamps / bushings are required.
Comment: @upnorth go to an electrical supply house and browse the tools up front, they make several kinds of drills and punches *specifically for that purpose* for standard knockout sizes.  Fit a cable clamp and yer done. However you wouldn't do that on those cheap plastic boxes, by cheap I mean construction not price.  I have seen field applied knockouts overlap factory  knockouts, no big deal, the bolted cable clamp/nipple holds them together.
Comment: Thank you! This is the sort of detail I needed to fight for this to be properly corrected!
Comment: Yes, there are certainly "some listed boxes" that can be punched for your purpose, but the "exception" shown clearly says "cable knockout". Would you say a field-modified punch-out/cut-out would qualify as "permitted" here?
Comment: @Upnorth -- half the problem with the field cutouts the OP found is they don't strain-relieve the cable to the box.
Comment: @Harper  No argument here, which is why I modified my answer to include "as shown in your situation".  I have used or authorized others to use punches numerous times in the field, thankyouverymuch, but not in the side of a single-gang, non-metallic j-box.
Answer: Most likely these are taut splices, twisted/added onto cables by cutting themmid-run.  That means there is not the free wire length needed in the box.

300.14 Length of Free Conductors at Outlets, Junctions, and Switch Points. At least 150 mm (6 in.) of free conductor, measured from the point in the box where it emerges from its raceway or cable sheath, shall be left at each outlet, junction, and switch point for splices or the connection of luminaires or devices. Where the opening to an outlet, junction, or switch point is less than 200 mm (8 in.) in any dimension, each conductor shall be long enough to extend at least 75 mm (3 in.) outside the opening.

It would be some real work to fix it properly, but certainly less work than all that hacking up and stuffing.  This electrician just didn't have confidence or experience. I would have got some 4" or 4-11/16" square metal boxes (coz that's what I work in), place them smartly to try to include 2 of the 3 cables with available length,then run new Romex to replace the third.
Take that second pic, one of the three cables goes straight down, I'd disassemble it to preserve every inch of that cable, have that cable make a back entry into a 4" square shallow box, then probably have to sacrifice the other two.
Comment: There was actually plenty of slack to do them proper.


(23634) wsgi starting up on http://0.0.0.0:8080/

Question: I have followed tutorial to install OpenStack from here
http://ilearnstack.com/2013/04/26/setting-up-a-single-node-openstack-environment/ (http://ilearnstack.com/2013/04/26/set...)
and I tried to install Savanna
When I execute this command
savanna-venv/bin/python savanna-venv/bin/savanna-api --config-file savanna-venv/etc/savanna.conf

No progress shows and Terminal is stuck and keeps showing this for long time, and does nothing.
WARNING keystoneclient.middleware.auth_token [-] Configuring auth_uri to point to the public
identity endpoint is
required; clients may not be able to authenticate against an admin endpoint
(23634) wsgi starting up on http://0.0.0.0:8080/

Comment: What are you expecting? Have you tried accessing that computer on port 8080?
Comment: I think that's how its *supposed* to work.
Comment: @Oli it says    Authentication required
Comment: See from #6 here: http://docs.openstack.org/trunk/install-guide/install/apt/content/neutron-install.dedicated-network-node.html (you might need to do some more configuration)
Answer: I can't comment as I have too little karma, so I will ask in the answer.
Did you install Savanna UI with the following guide?
http://savanna.readthedocs.org/en/0.3/horizon/installation.guide.html
If yes, you should see a new Savanna tab to appear in your Horizon (OpenStack Dashboard).
Comment: I have not installed yet. I accessed the http://0.0.0.0:8080/ from browser but it said 'Authentication Error'
Comment: Did it showed to you too? Or I should just proceed to install Savavva UI?
Comment: You should proceed with installing Savanna UI. Savanna exposes REST API on port 8080, which you can not access with the browser.

When you install Savanna UI, it will use that port to work with Savanna service.
Comment: I did so... now this error
http://askubuntu.com/questions/442979/httpconnectionpoolhost-openstack-port-35357


initialize array size from another array value

Question: #include<iostream>
using namespace std;

const int vals[] = {0, 1, 2, 3, 4};

int newArray[ vals[2] ]; //"error: array bound is not an integer constant"

int main(){
    return vals[2];
}

//returns 2 if erroneous line is removed

Why doesn't this work?
Answer: Unfortunately you can't do that in standard C++ because vals[2] is not a constant expression! In the coming standard you would have constexpr(implemented in g++ 4.6) to request compile-time evaluation easily:
#include<iostream>
using namespace std;

constexpr int vals[] = {0, 1, 2, 3, 4};

int newArray[ vals[2] ]; // vals[2] is a constant expression now!

int main(){
    return vals[2];
}

Comment: The first sentence should now be "You *can* do that in standard C++ (ever since C++11); you only could not do it in C++03 or earlier" (or something like that), if I understand correctly.
Answer: It's possible that the value of a const expression is not even known at compile time. For example, you can initialize a constant with something returned from a function, like
const int size = rand(); // random size

So it is not that constant as you might think
Answer: The C++ compiler can only allocate an array with a size known at compile time.  If you want to allocated a variable size piece of memory, use the new operator.
Comment: or even better yet, `std::vector`.
Comment: Looks like an answer to some other question to me


Insight on difference between Euler characteristics of 2 manifolds: $\chi(U)-\chi(V)$?

Question: For the Euler characteristic,
we have the inclusion-exclusion principle:
$$\chi(U\cup V) = \chi(U)+\chi(V)-\chi(U \cap V),$$
and also the connected sum property:
$$
 \chi(U\#V) = \chi(U)+\chi(V)-\chi(S^n).
$$
However, is there any relation or topological/differential-geometric interpretation for the difference between two Euler characteristics
$$
\chi(U)-\chi(V)?
$$
This is studied in usual set theory, but I lack an intuitive understanding of what the above could mean. For instance, such an understanding could be gotten for the $+$ case by using the first equation above: $\chi(U)+\chi(V)=\chi(U\cup V) + \chi(U \cap V)$. I also haven't found too many resources on the matter. Any advice?
Answer: An obvious observation is that for two CW complexes $X,Y$, the number $\chi (X) - \chi(Y)$ is an obstruction to the two complexes being homotopy equivalent. A fruitful thing to do is to ask if this can be realized geometrically.
Recall the basic constructions of the mapping cone and mapping cylinder of $f: X \rightarrow Y$, Hatcher chapter 0 will do if you are unfamiliar. We can use the inclusion-exclusion formula to obtain the equality $\chi(\operatorname{cone}(f))=\chi(\operatorname{cylinder}(f))+\chi(\operatorname{cone}(X))-\chi(X)$.
We know $\operatorname{cylinder}(f)\simeq Y$ and $\operatorname{cone}(X) \simeq *$, so we deduce that $\chi (\operatorname{cone}(f))-1=\chi(Y)-\chi(X)$. Notably, we recover the necessary condition that homotopy equivalent spaces have the same Euler characteristic by realizing that the cone on a homotopy equivalence is contractible.
In fact, studying the algebraic properties of the chain complexes of a mapping cone is extremely fruitful. One can view this difference as a primary obstruction to a map being a "simple" homotopy equivalence (because of course it should be a homotopy equivalence), and this is detectable on homology. By studying homology of covers we may detect when it is an actual homotopy equivalence, and by studying the chain complex itself we may finally find the last obstruction to being a simple equivalence. The relevant things to look up in regards to this are "Whitehead torsion" and "simple homotopy equivalences".
The reason I bring this up is that you specifically mention manifolds, and it turns out that studying invariants like this is how you prove things like the s-cobordism theorem or much more scary things like the parametrized stable s-cobordism theorem. You just have to move to more manifold like decompositions of manifolds (i.e. handle decompositions).
Answer: I don't know exactly what niceness hypotheses are required for this, but if $Y$ is, say, a finite CW complex and $X$ is a CW subcomplex of $Y$ then we should have
$$\chi_c(Y) - \chi_c(X) = \chi_c(Y \setminus X)$$
where $\chi_c$ is the compactly supported Euler characteristic, defined using cohomology with compact support $H_c^{\bullet}$. $\chi_c$ is not a homotopy invariant but besides that it behaves nicer in some ways, such as this one. We can equivalently write the above rleation as
$$\chi_c(Y) = \chi_c(X) + \chi_c(Y \setminus X).$$
Note that this is manifestly not true for the ordinary Euler characteristic!
Some $\chi_c$ examples:

$\chi_c(X) = \chi(X)$ if $X$ is compact, since then compactly supported and ordinary cohomology coincide. Hence if $X$ and $Y$ are both compact above then we have $\chi(Y) - \chi(X) = \chi_c(Y \setminus X)$.
$\chi_c(\mathbb{R}^n) = (-1)^n$ (this is a counterexample to homotopy invariance). This is because $\mathbb{R}$ is $[0, 1]$ minus two points, so $\chi_c(\mathbb{R}) = \chi_c([0, 1]) - 2 = -1$. It's still true that $\chi_c(X \times Y) = \chi_c(X) \times \chi_c(Y)$ so this determines the answer for $\mathbb{R}^n$. This can be used to explain the Euler characteristic of the sphere: we have $\chi(S^n) = \chi(\text{pt}) + \chi_c(\mathbb{R}^n) = 1 + (-1)^n$.
The wedge of $2$ circles satisfies $\chi(S^1 \vee S^1) = \chi(\text{pt}) + \chi \left( (0, 1) \sqcup (0, 1) \right)$ (the result of deleting the wedge point) which gives $\chi(S^1 \vee S^1) = 1 - 2 = -1$ as expected.
The torus $T^2$ satisfies $\chi(T^2) = \chi(S^1 \vee S^1) + \chi_c( (0, 1)^2) ) = -1 + 1 = 0$ as expected.
The above argument generalizes to the following: if $X$ is a finite CW complex with $c_i$ different $i$-cells, then $\chi_c(X) = \sum (-1)^i c_i$ (with no compactness hypotheses).


how can i disable ssl verification while sending Http POST request?

Question: when i execute this code
   url = new URL(url);
   urlConnection = url.openConnection();
   urlConnection.connect();

i get this message:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present

How can i disable ssl ?
Comment: *If* the server supports (at least) this resource on both https and http, change the https: at the beginning of the URL to http:. Alternatively, if the *only* error is the cert not having a matching hostname but it is otherwise valid, you can write a (tiny) class that `implements javax.net.ssl.HostnameVerifier` to accept whatever certs/names you want and apply it to a given `HttpsURLConnection` or as the default for all. Note that if you accept any cert/name, an active attacker may be able to redirect your connections to a fake server and access or modify your data, as they also can for http.
Comment: You cannot just disable SSL.
Comment: PS: Http[s]URLConnection defaults to GET. You'll only get POST if you set it explicitly or use `.setDoOutput(true)` and provide a (request) body.
Answer: You cannot simply disable SSL from client side. SSL is there for security. If the client can just disable it, no purpose of having it in the first place.
However if you are writing the server side as well, you can disable it. It depends on your server/implementation.


Netsuite: How do you edit the email preferences page?

Question: I am using Site Builder, and there is currently a less than ideal looking email preferences page.
The url of the page is: https://forms.netsuite.com/app/crm/marketing/campaignlistener.nl?...
Is there a way to edit it somewhere?
Comment: Is it different than the standard email preference page of website ?  -Setup > Site Builder > Set Up Web Site  and then Email tab of the site] If yes, how do you navigate to there?
Answer: There is no way to edit this directly.
Your best option is to inspect the classes and markup used and inject css and scripts (via a tab level tag override) to fix the page.
The other option is to replace the page entirely with a page of your own creation. The problem with that is once you do that you should only allow soft-opt-out because while you can set a hard opt-out with a script you cannot change from a hard opt-out with script.
Comment: "not particularly ideal" - could be Netsuite's motto.
Comment: So, I'm not sure I follow how to do this. There are no custom css files added to the header of this page. So how do I inject a css file to be used on this page to be able to override the class styles?
Comment: in your site theme add a tag in the "Additions to Head" section. The definition of the tag can be blank.
Then in your "My Account" tab (lists - > Web Site -> Tabs) add a tag override that either lists the css in a style tag or imports it in a link tag.
Comment: Ok, so how would I know that the email preferences page is controlled by the My Account tab logic? That's the piece I was missing.
Comment: Doesn't work. The addition to head logic for the theme isn't written to the header on the email preferences page. It's only NS-specific stuff in the header.
Comment: Ugh!. That's how I normally decorate NS pages and thought I'd done this one. If you can you should de-certify this answer.
Comment: @bknights , there is any way that we can generate URL for Email Subscription Preferences Page ? Kindly reply me. I have an urgent issue.
Answer: This is a pain. I think what I may have done in the past was to insert some code on the My Account page that creates an iframe. Then you grab the Subscription Center link and replace it with a Suitelet URL that has the escaped Subscription Center url as a parameter and change its target to the iframe(same domain - forms.netsuite.com))
When the Suitelet opens it uses a postMessage to make the My Account let it take over and then creates another iFrame and makes the source of that iFrame the original Subscription Center iFrame. the Suitelet detects (on open) that the center is open an then because you are in the same domain you can inject CSS. When the subscription center goes away (a new onOpen function sourced from the Suitelet page) you can again use postMessage to "return" to my account.
I think this breaks in Safari but it's such a hack that I have steered away from this sort of thing and these days would tend to roll my own and manage hard opt-outs with the email from the Netsuite GUI.


What is the control in the new Windows Store (Windows 8.1) for the top app bar?

Question:

I'd like to know if there is a control that can imitate the look and behavior of the AppBar that is in the current Windows Store for Windows 8.1.
Which control has such kind of paging? I am new to Windows 8 and 8.1 development. I have worked on Windows Phone 8.
Also, how to get that flyout menu that opens when there are subcategories in the menu item (third screenshot)? How do i get the small triangle?
Also, would this work on Windows 8.1 only or would it support windows 8 also??
Thank You for all help! :)
Answer: The creation of App Bars is a built in component of Microsofts Windows Store Apps.
Quick Start: adding app bars
The Flyout control was introduced with Windows 8.1.
Adding flyouts and menus


Value of algebraic functions at algebraic numbers

Question: I have read that the value of an algebraic function at an algebraic number (root of a polynomial with integer coefficients) is also an algebraic number, and that all polynomials are algebraic functions. However, if I take the polynomial e*x, its value at algebraic numbers is not another algebraic number.
Can anyone tell me what I'm missunderstanding?
Thank you.
Comment: @freakish And it is written there that "any polynomial function $y=p(x)$ is an algebraic function, since it is simply the solution $y$ to the equation $y-p(x)=0$".
Comment: @JoséCarlosSantos This is incorrect. The definition of an algebraic function requires polynomials to be of integer (or rational) coefficients: "where the coefficients $a_i(x)$ are polynomial functions of $x$, with integer coefficients.". The example is missing the assumption.
Comment: @freakish Really? Please tell me where can I find *that* definition of algebraic function.
Comment: $e$ as in Euler constant? $f(x)=ex$ is not an algebraic function. The statement "all polynomials are algebraic" is wrong. Polynomials with rational coefficients are algebraic.
Comment: @freakish Yes, it is. What do you think an algebraic function is?
Comment: @JoséCarlosSantos Algebraic functions as [defined here](https://en.wikipedia.org/wiki/Algebraic_function). How is $ex$ algebraic?
Comment: @JoséCarlosSantos Dude, I've just quoted wiki. How about you read the article, hmm? But I'm happy to hear your definition.
Comment: @freakish As I told you already, that article claims that **every** polynomial function in one variable is an algebraic function. Therefore, it cannot possible support your claim.
Comment: @JoséCarlosSantos And I'm telling you that claim is wrong. The definition is at the top of the article. It's not the first time for wiki to be wrong. But it's hard to be wrong in a definition. So unless you have another one we are done.
Comment: @freakish The first two sentences read "In mathematics, an **algebraic function** is a function that can be defined as the root of a polynomial equation. Quite often algebraic functions are algebraic expressions using a finite number of terms, involving only the algebraic operations addition, subtraction, multiplication, division, and raising to a fractional power." *Where* is the reference to integer or rational coefficients?
Comment: @JoséCarlosSantos Obviously you didn't read the article. "In more precise terms, an algebraic function of degree n in one variable x is a function (...) with integer coefficient". It's a third paragraph. For the last time: **read the article** or we have nothing to talk about. I'm done quoting the same thing over and over.
Comment: @freakish: wiki has unnecessarily restricted the definition to include integer coefficients. The analytical nature and behavior of algebraic functions (like their derivatives or techniques for integrating them) are not dependent on the nature of coefficients. It would be very strange to think of polynomials like $\pi x$ as transcendental functions.
Comment: @ParamanandSingh it wouldn't be strange at all. It's a perfect analogy to $\pi$ being a transcendental number. But if there is some other definition then please show me where it is. Also mapping algebraic numbers to algebraic numbers **clearly** depends on coefficients.
Comment: Let me extend on my comment: algebraic functions can be defined over any field extension $K\subseteq L$. And indeed all polynomials in $K[X]$ are algebraic. But not all polynomials in $L[X]$. So perhaps I incorrectly assumed that op is talking about $\mathbb{Q}\subseteq\mathbb{R}$. But still unless the extension is algebraic then not every polynomial is algebraic just like not every element is algebraic.
Comment: @freakish: the point of defining algebraic functions is not to guarantee that they map algebraic numbers to algebraic numbers, but rather to show that function values can be obtained from the argument using algebraic operations. I really don't understand why wiki people chose to have that guarantee.
Comment: @ParamanandSingh again: show me a book or article that doesn't use this definition. Otherwise further conversation is pointless.
Comment: @freakish: if one wants to argue via authority (insistence on source) then it is really pointless.
Comment: @ParamanandSingh oh, wow, your "this is not the correct definition even though noone uses different" surely is a better way to argue. Yes, this is pointless.
Answer: I'm going to assume that this is the definition of an algebraic function (following this wiki article):

Definition: A function $f(x)$ is algebraic if it is continuous in its domain and
  $$a_n(x)f(x)^n+\cdots +a_1(x)f(x)+a_0(x)=0$$
  where each $a_i(x)$ is a polynomial with integer coefficients.

(Although I don't think that the continuity assumption matters much). The "integer coefficients" assumption is  crutial. It is an analogy to the usual algebraic number definition. Now
the statement

If $f(x)$ is an algebraic function and $a$ an algebraic number then $f(a)$ is algebraic number as well.

is true in this setup. It is not true if we omit "integer coefficients" assumption. And the statement

All polynomials are algebraic

is false as your $f(x)=ex$ example shows. The statement should say

All rational polynomials are algebraic

This one is quite easy to prove. Also I think that

All polynomials with algebraic coefficients are algebraic

is true but I couldn't figure out the details. And in fact I think that for polynomials this is "if and only if" meaning if a polynomial is algebraic then its coefficients are algebraic.


Google Analytics Api Error

Question: I am trying to make a call to get data from Google Analytics.
<?php

require_once 'lib/apiClient.php';
require_once 'lib/contrib/apiAnalyticsService.php';
session_start();

$client = new apiClient();

$service = new apiAnalyticsService($client);

if (isset($_GET['logout'])) {
    unset($_SESSION['token']);
}

if (isset($_GET['code'])) {
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
    $accounts = $service->management_accounts->listManagementAccounts();
    print "
Accounts

" . print_r($accounts, true) . "
";

    try {
        $data = $service->data_ga->get('ga:29214712', '2012-01-01', '2012-01-15',
            'ga:visits', array('dimensions' => 'ga:source,ga:keyword', 'sort' =>
            '-ga:visits,ga:source', 'filters' => 'ga:medium==organic', 'max-results' => '25'));
    }
    catch (apiServiceException $e) {
        echo $e->getCode();
        print_r($data);
    }

    $_SESSION['token'] = $client->getAccessToken();
} else {
    $authUrl = $client->createAuthUrl();
    print "Connect Me!";
}

After Wrapping the code in the TRY Catch Block i am getting the following error

403
Error calling GET https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A29214712&start-date=2012-01-01&end-date=2012-01-15&metrics=ga%3Avisits: (403) Forbidden
( ! ) Notice: Undefined variable: data in
  C:\wamp\www\gitgrow\index.php on line 43

Note: I have granted the permission and have forced the Profile ID to test it.
Answer: The 403 error you're getting means the authorized user doesn't have access to the ga:29214712 reporting profile that is defined in your query.
Take a look at the HelloAnalyticsAPI.php sample in the examples/analytics/demo directory, and make sure you can connect to the API:
http://code.google.com/p/google-api-php-client/source/browse/#svn%2Ftrunk%2Fexamples%2Fanalytics%2Fdemo
Also, take a look at the Google Analytics developer guide. It will describe how you can obtain the correct profile IDs:
https://developers.google.com/analytics/devguides/reporting/core/v3/#user_reports
Comment: Thank you. i was forcing the Account ID instead of Profile ID

Google Analytics Api Error


Does cannibalism count as food?

Question: I'm going for the Desert Survivalist achievement, and throughout my Fallout experiences, I've never taken the Cannibalism perk. I'm thinking that, since I'm playing a very evil character this time, I might take Cannibalism at some point. If I do, does engaging in cannibalism count as food?
And what of the Ghastly Scavenger perk? Does feasting on ghouls and super mutants count as food?
(Wow, this sounds sick as I read it ... )
Answer: I'm not sure if consuming corpses directly counts. Even if it doesn't, once you've consumed 25, you'll gain the Dine and Dash challenge perk, which allows you to harvest Human Remains, which can be used from your inventory, and are most definitely food.
Ghastly Scavenger is unaffected by Dine and Dash, so if eating corpses directly doesn't count, then I suspect the same would apply for super mutants et al. The easiest way to test this by the way, is to take the perk, and check the challenge counter viewable on your Pip-Boy before eating a corpse.
Comment: Consuming corpses doesn't count; I've used the technique of checking the challenge counter on the PIP-Boy as you recommended.

Does cannibalism count as food?


identifying a decoded string and what method to use for decoding

Question: I have a string that looks like this. That I need to decode.
<code>DE9F6B7AB96AA0D5B01F8E51BE2B4D8951CC2C8A10E42F5EA1DB089D677BF15E
</code>
I am not sure what method is being used to encode this string so if someone could tell me what the method is and how to decode it?
Comment: That looks like a hash, but it could be anything. You're probably not going to be able to decode it.
Answer: From the length of the string (64 hex digits = 32 bytes = 32 x 8 = 256 bits), it appears to be SHA256 hash or one of these hashes: BLAKE/GOST/Snefru(256) (if they are still in use)
By theory a hash, if it is created using a cryptographic hash function, is supposed to be "infeasible to generate" back the original clear text. So, I doubt if you could decode this. Crackstation yielded the type as "unknown" and failed to get its cleartext.


Chaining async functions with pure React?

Question: I'd like to know if there is a way to chain async functions with React only. I know how to do it with Redux, but wondering if there's a method using only React.
Basically, I'd like to call the function computerMove(), but only after this.state.myMove is set to false. Something like this:
this.setState({ myTurn: false }).then(() => {
            this.computerMove();
          });

(Above code doesn't work, but that's what I'm trying to do).
Any suggestions?
Comment: Why not pass a callback to `setState`?
Answer: Have a look at: https://facebook.github.io/react/docs/react-component.html#componentdidupdate, which is what you want. It passes the props & state as they were before the last render. Check if the myTurn value has changed.
componentDidUpdate(prevProps, prevState) {
  if (!this.state.myTurn && this.state.myTurn != prevState.myTurn) {
    this.computerMove();
  }
}

Answer: setState is asynchronous and has the ability to fire off a callback:
this.setState({ myTurn: false }, this.computerMove);


MYSQL query very slow using PHP but fast in phpMyAdmin and Command Line

Question: I don't understand why MYSQL query takes more time in PHP script but takes less time in phpMyAdmin
Query :
<code>SELECT `id`, `title`, `slug`, `price`, `image`, `seller` FROM (`products`) WHERE `price` >= '0' AND `price` <= '2000' AND `cp_price` != '0' AND `category` LIKE '%,2,%' ORDER BY `id` DESC LIMIT 20, 20
</code>
phpMyAdmin time : 0.00 sec
php script time : around 8-12 sec
Comment: Paste some PHP code....
Answer: Make a page and connect the page to DB. On that page keep nothing but only your query and then run the page ad see. Your query will not take much time. The issue is somewhere else.
Comment: Lolz.. Great catch..
Answer: Please try using persistent connection to MySQL DB: http://www.php.net/manual/en/features.persistent-connections.php - they pay off because you do not have to setup a connection first.
You may also try using a profiler to find out where the bottleneck is. For instance: http://www.php-trivandrum.org/open-php-myprofiler/
Answer: Install this => PhP Debug Toolbar, setup database connection and then you will get the profiling details about timing in the database connection, maybe the time that the server took to serve the page its not mysql's fault


What does the Elder Sign do?

Question: I've purchased several Elder Signs from Acubens Town, and have used them at various locations around the map to no avail. The alt text shown when hovering over the item in-store and in the inventory is simply "???" and using is anywhere seems to result in the "Nothing happened" message. So where am I supposed to use it? What does it do?
Answer: The Elder Sign is used to defeat a boss late in the game.
Hint:

 Your quest involving the Elder Sign begins in the Surtr Mountains. Wander there until you find a new item.

Full Spoiler:

 While travelling through the Surtr Mountains, you have a chance to encounter an event that gives you a Mirror of Nitocris. The Mirror of Nitocris reveals Yuggoth Cave. Using the Elder Sign there gives a special message and reduces the boss's defense.

What does the Elder Sign do?


find a rectangle limited to 4 lines

Question: I want to find center of rectangle given w = width and h = height. The rectangle is limited to 4 lines:

as you see, all of lines cross trough (0, 0, 0). I know unit vector of each lines (a, b, c, and d). So each point on each line can be shown as:

where a(i), b(i), c(i), and d(i) are unit vectors of L1, L2, L3, and L4, respectively.
My questions are:
1- How can I calculate point C (center of rectangle)?
2- How can I calculate points P1, P2, P3, and P4?
3- Are the points (center and other) unique?
Any pseudo code or real code in Matlab, C++, C, or Python will be appreciated.
Answer: Since vectors $a,b,c,d$ are known, then to specify the rectangle you have four unknowns which are $t_1, t_2 , t_3, t_4 $.  We can assume that $t_1 = 1$ and this will generate all the rectangles parallel to it in space.  Now, $t_2, t_3, t_4$ need to satisfy the following orthogonality conditons:
$ P_1 P_2 \perp P_1 P_4 $
$ P_2 P_1 \perp P_2 P_3 $
$ P_3 P_2 \perp P_3 P_4 $
The above equations translate to
$ (\mathbf{b} t_2 - \mathbf{a} ) \cdot ( \mathbf{d} t_4 - \mathbf{a} ) = 0 $
$ (\mathbf{b} t_2 - \mathbf{a} ) \cdot ( \mathbf{c} t_3 - \mathbf{b} t_2 ) = 0 $
$ ( \mathbf{c} t_3 - \mathbf{b} t_2 ) \cdot ( \mathbf{d} t_4 - \mathbf{c} t_3 ) = 0 $
These nonlinear equations can be solved numerically.
Comment: I wrote a program in Matlab using `fmincon` with 4 params (t1, t2, ...). It works correctly. I remove `t1` and `set to 1` as you said but it does not answer correctly as I expect.
Comment: fmincon is used for minimization.  What are you minimizing ?

find a rectangle limited to 4 lines


Mistakes in $\lim_{a\to \infty}(a^2 - a) = - \frac{1}{6}$?

Question: One can say, using Ramanujan summation or the zeta function regularization, that the sum $\sum_{k=1}^{\infty} k=- \frac{1}{12}$. Using this result I've gotten a very confusing and counterintuitive result, which I suspect it's wrong, but I can't see any mistakes in the reasoning. Could you tell me if it's right or not and where is the mistake?
Consider a number $a \in N$, then it's square can be written as:
$$a^2 = (a-1)^2 + 2(a-1) + 1$$
$$a^2 = (a-2)^2 + 2(a-2) + 1 + 2(a-1) + 1 $$
$$a^2 = (a-3)^2 + 2(a-3) + 1 + 2(a-2) + 1 + 2(a-1) + 1$$
$$...$$
$$a^2 = (a-a)^2 + 2(1+2+3+...+(a-1)) + a$$
$$a^2 = a + 2\sum_{k=1}^{a-1} k$$
Then:
$$a^2 - a = 2\sum_{k=1}^{a-1} k$$
Taking limits on both sides:
$$\lim_{a\to \infty}(a^2 - a) = \lim_{a\to \infty}2\sum_{k=1}^{a-1} k$$
Using the result from above we get:
$$\lim_{a\to \infty}(a^2 - a) = 2(- \frac{1}{12}) = - \frac{1}{6}$$
Comment: Ramanujan summation is not the limit of the sum you have written, the limit of the sum you have written is obviously $\infty$, that is the origin of the "contradiction". A summation method, such as that of Ramanujan, or e.g. Pade or many others, is a way to assign a value to a divergent series, which is not the value one assigns to ordinary infinite sums (and such method recovers the correct result for convergent series)
Comment: Why do you accept that the sum of the positive integers is $-1/12$?
Comment: Ramanujan summation is a property of a sum
Answer: While your working is admirable, your final step of 'taking limits' is completely undefined, i.e., ask yourself, what are you really doing when you 'take limits' in this context? What definition or process are you referring to?
If you are using the usual, elementary calculus notion of 'limit', then you have a divergent limit 'equalling' a divergent limit - it doesn't make sense to 'take' such a limit.
If you want to use (in)famous 'identity' $1+2+3+\ldots=-1/12$, then you have even more problems to worry about: firstly, it's vague as to what the symbol $\lim$ now means in your argument; secondly, it's not clear that, under whatever definition of $\lim$ you fix upon, $\lim_{a\rightarrow\infty}2\sum_{k=1}^{a-1} k=2\lim_{a\rightarrow\infty}\sum_{k=1}^{a-1} k$, and so you cannot necessarily conclude that $\lim_{a\rightarrow\infty}2\sum_{k=1}^{a-1} k=-1/6$.
That being said, I rather enjoyed your round-about way of proving the well-known formula $\sum_{k=1}^{a} k = a(a+1)/2$. It's just the 'taking limits' part that makes no sense.
Comment: Thanks for the help! It looked very confuse to me, but now I can see my mistake.


LTSP on Ubuntu 17.04

Question: I am trying to install LTSP on Ubuntu 17.04
Have used ltsp-server and dnsmasq as dhcp proxy.
Sailed through installation.
Was able to create chroot i386.
However, when testing client i receive messages like
/dev/nbd0 is not present. dropping to shell
Nbdserver status has a message "unable to export....."

I need your help with this issue.
TIA
Answer: take a look on How to configure pxelinux.cfg/default properly in order to install Ubuntu from network?
After change "NBD boot"  for "NFS boot" in pxelinux.cfg/default/ltsp ,  it works for me.
1. Install nfs-kernel-server
 https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nfs-mount-on-ubuntu-16-04

2. Add follow line in /etc/exports:
 /opt/ltsp/i386/ 192.168.0.0/255.255.255.0(ro,no_root_squash)

Note: Change 192.168.0.0/255.255.255.0 by your Network addr
3. Change update-kernels.conf and run "sudo service ltsp-update-kernels" ( the pxe files are regenerated)
On the file /etc/ltsp/update-kernels.conf , change the line BOOT_METHODS for
BOOT_METHODS="NFS"

and the line TIMEOUT for
TIMEOUT=120

4. Configure pxe files
On the /var/liv/tftpboot/ltsp/i386/pxelinux.cfg/ltsp
a)change line "default ltsp-NBD"
default ltsp-NFS

b) on the section "label ltsp-NFS"
change string "boot=nbd" for
   boot=nfs
change the string "root=/dev/nbd0" for "root=/dev/nfs"
and add at the end of line :
nfsroot=192.168.0.1:/opt/ltsp/i386

(Note: change 192.168.0.1 by your server IP addr )
Ref How to configure pxelinux.cfg/default properly in order to install Ubuntu from network?
Comment: Welcome to Ask Ubuntu! Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to [edit] to include the essential parts of the answer here, and provide the link for reference as if digitalocean.com goes down step one is lost. Thank you!

LTSP on Ubuntu 17.04


How to get value from any HTML tag in php variable?

Question: what I am asking is
I have some value in

eg.
Hello

now I want to know  is there any way to get the value inside
 in a PHP variable  $getPara
(in session variable or normal variable or global variable)
so that when I write <?php echo $getPara; ?> then it will print Hello
Comment: funnily?? lol :=) is that a word?
Comment: please revise, this question is rather vague.
Comment: Funnily enough, in IE6, it will send the innerHTML of a button element when submitted.
Answer: No, you can't.
The browser will submit all form fields (input, select, and textarea) to the server, but it won't send any other data.
You need to use Javascript.
Comment: +1. The PHP script runs server-side and generates the HTML, Javascript runs client-side and reads/manipulates the PHP-generated HTML. It seems to me as if you want to do a Javascript trick in PHP.
Answer: You could look for any element having .includeMe as a class name, and create a  form element for it. The next time the form is sent, those items will be sent as values too:

Georgia

--
$(function(){
  // Everything with class 'includeMe'
  $(".includeMe").each(function(){
    var id   = $(this).attr("id"),
        text = $(this).text(),
        elem = $("<input type='hidden'/>").attr("id", id).val(text);
    // Add to form
    $("form").append(elem);
  });
});

Answer: if the problem is with input specifically, then you can use
<textarea name="some_name_to_use_in_php">hello</textarea>


MSTest: One thread at a time

Question: I have many 'TestClass' in my project. Each TestClass have many 'TestMethod' in them. These test methods are against exchange online. And exchange online allows only 3 runspaces to be created/active at a given point of time.
But MSTest creates multiple threads to execute each 'TestMethod' within a 'TestClass'. Because of this, I wont be able to re-use (reason is exchange online runspace gets broken frequently and if so, I need to create a new one) just 1 runspace and creating single runspace for each test method is not an option.
Is there anyway I can execute 1 test method at a time ? Is there any alternative. Please help. Thanks.
Comment: As far as I know, MSTest guarantess that every test is executed one at a time in a sequence (except in Load Test scenarii). What exactly is your problem?
Answer: To my knowledge, you can't force MSTest to run tests single threaded but there are ways to achieve what you want.
One possibility would be to create OrderedTest and add all your tests to it. Ordered test runs one test after another.
It could be a lot of work if you have really many tests, though.
For another possibility please check this post: MSTest executing all my tests simultaneously breaks tests - what to do

MSTest: One thread at a time


JAXRS client - Deserialization Issue with Pojo

Question: Helo Everyone. I am new to jersey and Jackson and finding it really difficult to deserialize a JSOn response from my REST service on client side. I am pretty sure that I am still not grasping the Object mapper and JSON provider APIs that well. Any help or guidance is appreciated in advance. Here is my source code.
Source Code
POJO Class
    @XmlRootElement(name = "user")
    public class User  implements Serializable{

        private String firstName;
        private String lastName;
        private String email;
        private String userID;

        public User() {

        }

        public User(String firstName, String lastName, String email, String userID) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.email = email;
            this.userID = userID;
        }

        public String getFirstName() {
            return firstName;
        }
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
        public String getLastName() {
            return lastName;
        }
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public String getUserID() {
            return userID;
        }
        public void setUserID(String userID) {
            this.userID = userID;
        }

    }

Client Code
package com.example.service.client;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.jackson.JacksonFeature;

import com.example.service.bean.User;
import com.example.service.client.mapper.MyMessageBodyReader;
import com.example.service.client.mapper.MyObjectMapperProvider;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;

public class GetJSONResponse {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JacksonJaxbJsonProvider provider1 = new JacksonJaxbJsonProvider();
        Client c = ClientBuilder.newClient()register(provider1);//.register(mapper);
        WebTarget target = c.target("http://localhost:8080/RestfulWebserviceExample").path("/jaxrs/user/Nishit");

        Response resp = target.request(MediaType.APPLICATION_JSON).get();
        System.out.println(resp.getStatus());
        String user1  = resp.readEntity(String.class);
        System.out.println(user1);

        User user  = target.request(MediaType.APPLICATION_JSON).get(User.class);
        System.out.println("User : " + user.getUserID());

    }

}

`
The first 2 sysout generates an output as

200
{"user":{"firstName":"Nishit","lastName":"Ladha","email":"email@example.com","userID":"nishiz"}}

But when i tries to directly get the User object from response, I get an error as
Exception in thread "main" javax.ws.rs.client.ResponseProcessingException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "user" (class com.example.service.bean.User), not marked as ignorable (4 known properties: "lastName", "firstName", "email", "userID"])
 at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@10163d6; line: 1, column: 10] (through reference chain: com.example.service.bean.User["user"])
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:806)
    at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:696)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
    at com.example.service.client.GetJSONResponse.main(GetJSONResponse.java:40)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "user" (class com.example.service.bean.User), not marked as ignorable (4 known properties: "lastName", "firstName", "email", "userID"])

It will be really kind if anyone of you can guide me how to resolve this.
I am not using Maven as I first wanted to try without Maven
I am not sure why my rest service is wrapping the response. Here is the code :
Service Method
@GET
@Path("/{username}")
@Produces(MediaType.APPLICATION_JSON)
public User helloWorld(@PathParam("username") String name){
    User user = new User();
    user.setFirstName("Nishit");
    user.setLastName("Ladha");
    user.setUserID("nishiz");
    user.setEmail("firstname.lastname@example.com");
    return user;
}

Web.xml##
<servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>
        com.example.service,
        com.fasterxml.jackson.jaxrs.json
    </param-value>
</init-param>
<init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>

Answer: Man, look, you are trying to bind unexistent field User.
If you want to properly parse this json
{"user":{"firstName":"Nishit","lastName":"Ladha","email":"email@example.com","userID":"nishiz"}}

You need to have similar to this class
public class UserWrapper implements Serializable{

    private User user;
    // Constructors
    // Getters, and setters
    // HashCode and equals
}

Then this client code will work:
public class GetJSONResponse {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JacksonJaxbJsonProvider provider1 = new JacksonJaxbJsonProvider();
        Client c = ClientBuilder.newClient()register(provider1);//.register(mapper);
        WebTarget target = c.target("http://localhost:8080/RestfulWebserviceExample").path("/jaxrs/user/Nishit");

        Response resp = target.request(MediaType.APPLICATION_JSON).get();
        System.out.println(resp.getStatus());
        String user1  = resp.readEntity(String.class);
        System.out.println(user1);

        UserWrapper userWrapper  = target.request(MediaType.APPLICATION_JSON).get(UserWrapper.class);

    }

}

If you have any questions - just ask.Hope your code will work.
Comment: Thanks Ivan. I need some help with my service now as I do not want to use wrapper classe.


No app in ubuntu dock

Question: Ubuntu 20.04, latest update.
I tried Gnome Extensions Dash to Dock, but it was not working well with the Ubuntu Dock (the ubuntu dock was spawning behind the dock) So I disabled it from the website. When I go to the Gnome extensions utility there's no more Dash to Dock extension, but if I go to the built-in > Ubuntu Dock > Website it open dash to dock github... So I think there's is something corrupted here...
Why do I explain all that ? Since then, I have to enable and disable the dock to see running app in the dock, if not there's only the app launcher icon.
Anybody ever experienced that ? Or anybody have a solution or a hint to fix that ? It's really annoying !
Update:

I tried to remove dash-to-dock has stated here:
Annoying dock in Ubuntu 17.10
I rebooted the machine and now... No more dock! The Settings still
have the option but no way to make it appear... So I re-installed
dash-to-dock, still no option in settings, but I can configure it
through dash-to-dock.
It could have fixed the first problem that the original dock was
spawning behind, but now there's no more default dock ! Oopsie!

Thank you!
Answer: My process was to install Dash to Dock (DTD) via FF, refresh FF, click on the tools icon and configure as desired.  To effectively disable Ubuntu Dock and have DTD work properly, I had to reboot, but then all was well and DTD appeared in the Extensions app.  I disabled Ubuntu Dock, but it doesn't seem to make a difference while DTD is enabled.

No app in ubuntu dock


No progress installing ruby via macports. How long should this action take?

Question: I'm in the process of installing ruby using macports. I typed the following command into terminal:
sudo port install ruby

Terminal responded by returning some lines that indicated the action was working, then it just stopped returning any new lines. I typed:
which ruby

and didnt get a response, so I closed the terminal window and consequently ended the processes.
I opened a new terminal window and re-typed the original install command and now I get the following message:
Waiting for lock on /opt/local/var/macports/registry/.registry.lock

How should I proceed from here? Should I just wait? If so, how long? Will terminal try to complete this action twice? How can I know if it's working?
Comment: Thank you @ctcherry, @TinMan, and @charlie. I took your advice and installed Ruby using RVM. I'll say it was a fairly painless process. SUCESS! As an ironic aside, macports won't even let me uninstall it (more locks), so I'm just going to leave it. I hope there's no harm in that.
Answer: A more appropriate thing to check, when you've seen no progress, is your system's activity.
On Mac OS, you could either open "Activity Monitor" and sort by CPU, or open a terminal and type top -o cpu. Watch for some app showing consistent activity, especially something with "port" in the name.
To deal with the lock... odds are REALLY good it's stale since you cut it off at the knees by closing the terminal, so use sudo rm /opt/local/var/macports/registry/.registry.lock to remove it and retry if you want.
I will recommend RVM for installing new versions of Ruby. It's really convenient. Before you jump into RVM read the "Installation" and "Rubygems" pages entirely, and after installing RVM type rvm notes and follow the directions it spits out.
Finally, do not, under any circumstance, no matter how good an idea it seems to be, try to replace or upgrade the system version of Ruby installed by Apple. Apple installed it for their own use, and messing with it invites bad juju.
Comment: Thanks. I am decided to give macports one more try. I followed your instructions to stop the lock (twice or so) until getting a message the file no longer existed, which was the objective. I typed the original install command again and now am running into this error:    --->  Computing dependencies for ruby
--->  Dependencies to be installed: libiconv ncurses ncursesw openssl zlib readline
Waiting for lock on /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_textproc_libiconv/work/.macports.libiconv.state
Comment: should I re-apply your rm command to this file as well? Thanks for being patient with me, by the way.
Comment: I think it's safe to delete the second lock file. It's like the old saying "In for a penny, in for a pound". You'd already started the process by killing the terminal, then deleting the first lock file. Sometimes installs don't happen easily.
Answer: "Waiting for lock on /opt/local/var/macports/registry/.registry.lock" means MacPorts is already running and doing things. You could check for any running "port" processes in Activity Monitor. Wait until these tasks are finished (or terminate them if you don't care that they don't finish) before trying to do other things with MacPorts.
ps -A | grep tclsh if you can't find the running process so you can kill it.
Answer: A more recent way to install Ruby is via RVM. Not a direct answer to you question, but I would highly recommend it.
Answer: Here is another vote for rvm. If you are like me, and you program on a mac, but you deploy to some other *nix, then you can make sure you have the same version of Ruby (and Rails, and gems) on each, using rvm's gemsets.
Also, you can switch among gemsets easily, so that if you find a gem that you can't get working right with Ruby 1.9.2, then you can switch to 1.8.7 or some such whilst you try to figure it out. Stuff like that.
As far as I'm concerned, you can jump right in on your mac (as yourself, not using sudo) with rvm install 1.8.7 or rvm install 1.9.2. Then make sure you switch to use the correct rvm, and make the one you want your default, and you're golden. If it doesn't work, delete it - all the gemsets will be installed below your home directory in .rvm/*
The pain you are going through now will resurface when you try to keep your system version of Mac's ruby working with all the stuff you write -- RVM is definitely easier than using Mac's Ruby.
Answer: In addition to what the Tin Man mentioned, if other "lock" errors start coming up, I found disabling the internet connection for a moment was helpful to stop all port processes that were occurring.


How to develop sortable column by click on header ( ngx-datatable)?

Question: How to develop sortable column by click on the header?
I am trying to do like in the documentation, but it does not work.
 <ngx-datatable
    #table
    ...
    [rows]='vendors'>

    <ngx-datatable-column name="VENDOR" [flexGrow]="1">
      <ng-template let-column="column" let-sort="sortFn" let-sortDir="sortDir">
        {{column.name}}
      </ng-template>
      <ng-template let-row="row" let-value="value" ngx-datatable-cell-template>

{{row.vendorName}}

      </ng-template>
    </ngx-datatable-column>

Comment: try
Comment: it works, but not by clicking on header
Comment: it works, but not by clicking on header
Answer: Sorting does not work if you use ng-template for defining your column header. Default sorting only works if you created a basic column with only the ngx-datatable-cell-template attribute.
This works:
  <ngx-datatable-column name="Navn" prop="name" [flexGrow]="3">
    <ng-template let-value="value" ngx-datatable-cell-template>
      {{ value }}
    </ng-template>
  </ngx-datatable-column>

this doesn't:

  <ngx-datatable-column name="Navn" prop="name" [flexGrow]="3">
    <ng-template let-column="column" ngx-datatable-header-template>
      {{ column.name }}
    </ng-template>

    <ng-template let-value="value" ngx-datatable-cell-template>
      {{ value }}
    </ng-template>
  </ngx-datatable-column>

Answer: First of all, ngx-datatable by default supports Sorting. Dont pass any parameter to sort function. It is not required. Do this:
<ngx-datatable-column name="VENDOR" [flexGrow]="1" [sortable]="true">

Comment: it adds "sort" arrow, but not sorting by clicking on the header.
Comment: Are you trying to achieve server side sorting. Have you set [externalSorting]="true". If not please show a demo in stackblitz of the problem.


If I install a snap package, will the config files be carried over and the already installed deb package be removed automatically?

Question: I'm running Ubuntu 22.04, Thunderbird is installed as deb package (version 91). I'd like to use the new Thunderbird version 102, which is only available as a snap package.
What will happen if I say sudo snap install thunderbird?
Will my TB config and mail folders be carried over? Will the deb package be removed?
Answer: Both installations of the app would work independently one from the other. The deb package won't be uninstalled. The snap one won't take the deb config.
You can also have a flatpak alternative, which much more people seem to prefer. Same with a lot of other apps like Firefox or Brave.
Related: How to completely remove snap and replace with flatpak?
Comment: [Yes](https://news.itsfoss.com/ubuntu-firefox-snap-default/), is a controversial decision, already done with Chromium.
Comment: @foobar in that case, [there's a placeholder apt package](https://packages.ubuntu.com/jammy/firefox) which causes the installation of the snap package. In a sense, you still have both apt and snap packages installed when upgrading.
Comment: But when upgrading to Ubuntu 22.04, the Firefox deb package was migrated to the snap version without losing any data. Was this a special-made upgrade script from the Ubuntu team?


Webservice does not work after being packaged into a Docker image

Question: I write a simple webservice in ruby with sinatra. If I run ruby app.rb it runs on localhost:4567. I write a Dockerfile to make an image and expose port 4567.
However, when I run the docker image the webservice runs but if I try to connect (with curl and browser) to port 4567, it says Connection reset by peer.
Anyone has any suggestion? Because I do not know what to check in this case. I have tried some vague things but still..
The webservice runs normally outside docker.
EDIT 1:
I have pushed the image to eivor/ruby. If you run it and go to browser to check it would say connection reset. Yes I tried docker run -p 4567:4567 eivor/ruby as said before posting the question.
EDIT 2: Here is the app.rb
require 'sinatra'
require 'referal' # this is the gem that calculate reward points to users
require 'json'
require 'byebug'

get '/' do
  'hello, world!'
end

# inside docker image, even get / returns connection reset by peer
# not to mention post data to it

post '/' do
  data = JSON.parse(request.body.read)
  input = []
  data.each do | key, value |
    input << value
  end
  invs, users = input.reduce([[],[]]) do | results, instruction |
    results = classify(instruction, results[0], results[1])
    results
  end
  res = export(users)
  # byebug
  puts res
end

post '/text' do
  @data = request.body.readlines
  #byebug
  @processed = @data.map{ |s| process(s) }
  @invs, @users = @processed.reduce([[],[]]) do | results, instruction |
    results = classify(instruction, results[0], results[1])
    results
  end
  @jsn = export(@users)
  puts @jsn
end

Here is the Dockerfile, i build a lightweight ruby from alpine
FROM alpine:3.5
ENV BUILD_PACKAGES bash curl-dev ruby-dev build-base git libstdc++ tzdata ca-certificates
ENV RUBY_PACKAGES ruby>2.3 ruby-irb ruby-rake ruby-io-console ruby-bigdecimal ruby-json

RUN apk update && apk upgrade
RUN apk add $BUILD_PACKAGES && apk add $RUBY_PACKAGES
RUN apk add ruby-bundler>1.17

RUN echo 'gem: --no-document' > /etc/gemrc && rm -rf /var/cach/apk/*

RUN gem install bundler

RUN mkdir /usr/app
WORKDIR /usr/app
RUN git init

COPY . /usr/app

RUN bundle install

RUN bundle exec rake install

EXPOSE 4567

CMD ["ruby", "./app.rb"]

If I run outside docker with command ruby app.rb or bundle exec rerun app.rb it works normally. But using docker image, it does not. I run the command:
docker run -p 4567:4567 eivor/ruby

The server runs,
[2019-03-14 16:59:59] INFO  WEBrick 1.3.1
[2019-03-14 16:59:59] INFO  ruby 2.3.8 (2018-10-18) [x86_64-linux-musl]
== Sinatra (v2.0.5) has taken the stage on 4567 for development with backup from WEBrick
[2019-03-14 16:59:59] INFO  WEBrick::HTTPServer#start: pid=1 port=4567

but when I try to access with browser or curl, it says connection reset by peer. If I try to post with curl, the data is actually sent but it does not respond, it hangs up on me instead.
curl -v localhost:4567 --data-binary @test/input

* Rebuilt URL to: localhost:4567/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 4567 (#0)
> POST / HTTP/1.1
> Host: localhost:4567
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Length: 369
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 369 out of 369 bytes
* Recv failure: Connection reset by peer
* stopped the pause stream!
* Closing connection 0
curl: (56) Recv failure: Connection reset by peer

Comment: Please review how to provide an [MVCE](https://stackoverflow.com/help/mcve). In this case, a copy of the ```Dockerfile``` and the command line arguments you used to start the container would be helpful.
Comment: Sorry, I have pushed the docker image and gave my command line.
Comment: Please post your ```Dockerfile``` and ```app.rb``` here so that we may better assist you.
Comment: Hello, I put ```app.rb```, `Dockerfile`, server log and curl log. When I post data with curl, the data is actually sent but the server hangs up on me.
Answer: This issue is happening because Sinatra by default (development environment) listen on 127.0.0.1 which not works in case of external connection to container

:bind - server hostname or IP address
String specifying the hostname or IP address of the interface to listen on when the :run setting is enabled. The default value in the development environment is 'localhost' which means the server is only available from the local machine. In other environments the default is '0.0.0.0', which causes the server to listen on all available interfaces.

So if you will continue on running in development mode, you need to change it to 0.0.0.0, for example:
docker run -p 4567:4567 --name stack eivor/ruby bash -c 'ruby ./app.rb -o 0.0.0.0'

Which can be used in Dockerfile as:
CMD ["ruby", "./app.rb", "-o", "0.0.0.0"]

Or you can use the following within your script:
set :bind, '0.0.0.0'

Then from outside the container you can get the result:
curl -v localhost:4567
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 4567 (#0)
> GET / HTTP/1.1
> Host: localhost:4567
> User-Agent: curl/7.64.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/html;charset=utf-8
< Content-Length: 13
< X-Xss-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< Server: WEBrick/1.3.1 (Ruby/2.3.8/2018-10-18)
< Date: Thu, 14 Mar 2019 17:17:20 GMT
< Connection: Keep-Alive
<
* Connection #0 to host localhost left intact
hello, world!

For more configuration check the following: CONFIGURING SETTINGS
Comment: Yes you can depend on puma, unicorn, passenger whatever works for you and also you may use `nginx` in front of your application. For the`POST` method i couldn't try it but it will be an issue related to the code not the communication between your host and docker
Comment: okay, this works for the get / method. I still got trouble with posting data to it though. would have to inspect further. but this answers the question. in production, do you use Puma?
Answer: From the documentation:

Flag value    Description
-p 8080:80    Map TCP port 80 in the container to port 8080 on the Docker host.

You need to map the TCP port 4567 in the container to a port on the Docker host. For example, to map it to port 8080:
$ docker run -it -p 8080:4567 image-goes-here

Comment: Thanks but I did try this. After trying this, do you know what other cue can I check?
Answer: Have a look at this article: https://docs.docker.com/config/containers/container-networking/
In few words - try to publish your exposed ports via -p argument.
For example:
$ docker run -it -p 4567 my-local-image

Comment: Yes I did try. If you have more suggestion after this step, I would like to hear.
Comment: Try to see is a service has been started or listen to your connections via:
- `docker ps -a`
- `docker logs {my-container-id}`


How to get autocompletion with ">|"?

Question: When trying to empty a text file with >| filename why doesn't bash's autocomplete work for the file name? Is there anyway to allow autocompletion like any other terminal command?
Comment: Works in `zsh` --- maybe bash autocompletion is expecting a command after "|"? (wild guess)
Comment: I rarely use this form, I don't run with `noclobber`, but I see this also. This might be a bug in the `bash-completion` package.
Answer: When Tab doesn't work, you can always try Alt+/, or whatever else bound to complete-filename.

How to get autocompletion with ">|"?


How to access 'this' in a java method?

Question: I have the following javascript method:
myFunc = function(callback) { callback.call(this, "hello", "world"); }

and I´m passing a java object that implements the 'call' method. In the java call method I get the two parameters "hello" and "world", but not 'this' (of course).  Is there a way to access 'this' from java?
I´m interfacing java with d3.js and d3 has lots of callbacks in this way and 'this' is where d3 stores a selection.
Thanks
Comment: Could you please provide code example of the Java class with the callback() method.
Comment: I´ve not managed to add code example in this comment, so I´ll add as an answer to the question bellow...
Answer: Please make sure that you follow the instruction at https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013062-calling-java-from-javascript and inject your Java object with the call() method correctly:
Java code:
browser.addScriptContextListener(new ScriptContextAdapter() {
    @Override
    public void onScriptContextCreated(ScriptContextEvent event) {
        Browser browser = event.getBrowser();
        JSValue window = browser.executeJavaScriptAndReturnValue("window");
        window.asObject().setProperty("java", new JavaObject());
    }
});
...
public static class JavaObject {
    public void call(JSValue window, String message) {
        System.out.println(message);
    }
}

JavaScript code:
window.java.call(window, 'Hello Java!');

Answer: I´m not actually coding in Java but JRuby.  In order to make a Java example
I´ll have to simplify my code bellow.  Maybe this can help some.  If not,
I´ll try to do a Java example.
# Function f1 will call the callback methods cb1 and cb2 with 'this' variable
# This is just a notation for creating javascript function.  It calls
# @browser.executeJavaScriptAndReturnValue(scrpt), whith the function
# body (everything between EOT) modified to make a valid javascript script.
# f1 is a function with 2 arguments cb1, and cb2 which should be the
# callback functions
f1 = B.function(<<-EOT)
  (cb1, cb2) {
      cb1.call(this, "banana", "milk");
      cb2.call(this, "arroz", "feijao");
  }
EOT

# Proc is a closure.  It receives two arguments |food1, food2|. This will
# become a java object per JRuby´s magic
proc = Proc.new { |food1, food2| puts "I hate #{food1} and #{food2}" }

# now call method f1 passing proc as the first argument and the block as
# the second argument. So cb1 = proc and cb2 = <the block bellow>. Method
# 'send' grabs the given arguments, converts them to java objects and then
# calls jxBrowser 'invoke' method with the given arguments.
f1.send(proc) { |food1, food2| puts "eu gosto de #{food1} e #{food2}" }

The result of executing this code is:
I hate banana and milk
eu gosto de arroz e feijao

As can be seen, the 'this' variable is just gone... I would like to be able to
capture the 'this' variable somehow in order to be able to use the context in the blocks. I´ve managed to make a workaround that allows capturing the 'this' variable, but it requires wrapping the block in another javascript function.
The whole idea of this code is to allow a JRuby developer to write Ruby code and get this code executed in jxBrowser without needing to use any javascript.  Examples of this can already be seen by downloading mdarray-sol GEM, or going to https://github.com/rbotafogo/mdarray-sol.  There you can see multiple examples of using d3.js with JRuby.
Comment: In your code example I don't see where you register Java object with the call() method using JxBrowser JavaScript Java Bridge API: https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013062-calling-java-from-javascript
Comment: I guess you didn´t understand my problem.  I did register everything fine, and the code is working. However, if I have a javascript function such as: myFunc = function(callback) { callback.call(this, 'Hello Java"); } and I do as you suggest in javascript: myFunc(window.java), then in JavaObject 'call' method I cannot read the 'this' variable.
Comment: The "this" will be converted to JSValue, so your call() java method should looks like call(JSValue theThis, String message).

How to access 'this' in a java method?


How do I detect if the mouse pointer is within the bounds of an object?

Question: I am trying to make my own components such as buttons and other things for my program and I cannot seem to get the MouseEvent to work properly. I want to be able to detect if a mouse pointer is within the bounds of a component and my methods always returns false for some reason.
Here is an example of what I tried:
public void mousePressed(MouseEvent e) {

    for (MyComponent component : components) {

        // getBounds() returns a Rectangle.
        if (component.getBounds().contains(e.getX(), e.getY())) {
            System.out.println("PRESSED");
        }

    }

}

Another example:
public void mouseEntered(MouseEvent e) {

    for (MyComponent component : components) {

        boolean isWithinBounds = isWithinBounds(e.getX(), e.getY(), component);

        if (isWithinBounds) {

            component.mouseEntered(e);

        }

    }

}

private boolean isWithinBounds(int x, int y, MyComponent component) {

    // getBounds() returns a Rectangle.
    if (x >= component.getBounds().x
            && x <= component.getBounds().x + component.getBounds().width
            && y >= component.getBounds().y
            && y <= component.getBounds().y + component.getBounds().height) {

        return true;

    } else {

        return false;

    }

}

Does anyone know why this does not work and how I should do it instead?
Thanks in advance!
Comment: You mean, if the mouse is just hovering over a certain component? or if the mouse clicks inside the specified area?
Comment: Yeah, exactly. Any MouseEvent really.
Answer: You should add a mouse listener and react to the mouseEntered-Event:

JFrame.addMouseListener( new MouseAdapter() {

     public void mouseEntered( MouseEvent e ) {
        // your code here
     }
} );

Maybe helpful:
Finding if my mouse is inside a rectangle in Java


Unique Hardware ID on VB.NET

Question: I have an application I want to protect by requiring my users to register.
I also want to ensure that they can't install on more than two machines.
To do this I need to know where to find a unique hardware ID number, and utilize that in the registration code.
All I need to know is how to get that number using code.
Comment: You may want to look at this  [SO Question](http://stackoverflow.com/q/9039212/479512) it is in C# but should give you and idea.
Comment: possible duplicate of [VB.net Unique Hardware ID ideas](http://stackoverflow.com/questions/2994549/vb-net-unique-hardware-id-ideas)
Answer: As others have pointed out, there is really no such thing as a unique hardware ID. Others who have come before you have tried to use various things (e.g. motherboard serial number, CPU serial number, HDD serial number, MAC address) or combinations of those things, but they are all problematic in their own way. Serial numbers are not always returned by all drivers and even if they do, they can easily change if the hardware is upgraded or replaced. Also, the serial numbers can technically be repeated by different vendors and especially on virtual machines. MAC addresses are problematic because there are often multiple and they change often, especially with VPN's. Also, MAC addresses are often duplicated by multiple machines using the same VPN software. You could use the Windows Installation serial number, but this can also be duplicated and changes with OS upgrades. The simple answer is, when possible, don't. If you must do something like this, it would be better to have a way to programmatically mark each computer that your software is installed on by writing an encrypted GUID to someplace on the harddrive and provide an easy mechanism for your support staff to retag any computer at will.

Unique Hardware ID on VB.NET


AWS Cognito credentialsProvider.login always shows NIL (SWIFT)

Question: I'm trying to implement Facebook Login with AWS Cognito.
After receiving the access token from Facebook, I'm not able to update the credentials provider.
let token = FBSDKAccessToken.currentAccessToken().tokenString
credentialsProvider.logins = [AWSCognitoLoginProviderKey.Facebook.rawValue: token]

After this, if I print [AWSCognitoLoginProviderKey.Facebook.rawValue: token] I get the long string but if I print credentialsProvider.logins I get NIL.
As a result, my identity pool always shows the user as unauthenticated even after logging in with Facebook.
Any help would be appreciated.
Thanks!!
Answer: Are you using the latest AWS iOS SDK? If yes, then credentialProvider.logins will always be NIL and will cause your app to create unauthenticated identities.
We are in process of updating our documentation for this but essentially this is what you need to do.
Use this constructor to create the credentials provider. The identityProviderManager here should be an implementation of AWSIdentityProviderManager Protocol and the logins method should return the dictionary mapping for your provider name to the token. The credentials provider will call this method every time it needs the identity provider token.
Comment: Is there any documentation on how to create the AWSIdentityProviderManager and how to add the dictionary mapping to the logins for Swift?
Comment: Hi sorry I've tried the construct as you said .. still not able to change unauthenticated user to authenticated   `code  let ip = AWSIdentityProviderManager?.init() ;
            ip?.logins().setValue(token, forKey: "graph.facebook.com") `
Comment: The logins are not supposed to be set in the managers. The logins method should return a valid dictionary of provered name as key and token as value. Check [this answer](http://stackoverflow.com/a/37146730/3204480) for more details.


Running programs are not displayed in the panel

Question: My wifes computer is running ubuntu 10.04. Since several days the running programs are not displayed on the panel. With alt tab you can still switch between open programs. Any idea what happened?
Comment: In my case, all I did is "Right" click on panel, and choose Troubleshoot and then select "Restore all settings to default"
Answer: Maybe the taskbar (Windows List) has been removed?
Right click on bottom panel, that click Add to panel, select Windows List and confirm.
Comment: I had to use **Alt** right click (Ubuntu 16.04 and gnome-flashback-metacity) to be able to open the context-menu
Comment: on Lubuntu 18.04 (its right click on taskbar -> manage widgets -> select add (+) -> Task Manager (Switch Between running application)
Answer: Probably you have removed the Window List on the panel.
Right-click on the bottom panel and choose "Add To Panel" - select the "Window List" applet
Comment: In Xface edition this is called "Windows Button", if anybody is looking for that.
Answer: More than likely the window switcher got removed from the panel. Simply right click on it, and click add to panel. Then drag and drop the applet on to the panel, and it should be back to normal.
Answer: Adding more tips : Once you add the 'Windows List' into the task bar and only single folder appears on the bar, right click and remove that folder, soon you remove this new folder from the task bar all the open windows will get appeared on the task bar


How to filter columns in Tk treeview based on column value?

Question: just started learning python/tkinter and already ran into a problem. I'm trying to open excel file in treeview which works perfect, now I found another script online which applies a drop menu to filter based on column values. But I'm failing to incorporate into mine, can anyone help please?
Current Code:
from tkinter import *
from tkinter import ttk, filedialog
import pandas as pd
win = Tk()
win.geometry("700x350")
style = ttk.Style()
style.theme_use('clam')

frame = Frame(win)
frame.pack(pady=20)

def open_file():
    global df
    filename = filedialog.askopenfilename(title="Open a File")

if filename:
    try:
        filename = r"{}".format(filename)
        df = pd.read_excel(filename)
    except ValueError:
        label.config(text="File could not be opened")
    except FileNotFoundError:
        label.config(text="File Not Found")

clear_treeview()

tree["column"] = list(df.columns)
tree["show"] = "headings"

for col in tree["column"]:
    tree.heading(col, text=col)
    tree.column("#1", anchor="center", width=200)
    tree.column("#2", anchor="center", width=150)
    tree.column("#3", anchor="center", width=150)
    tree.column("#4", anchor="center", width=150)

df_rows = df.to_numpy().tolist()
for row in df_rows:
    tree.insert("", "end", values=row)

tree.pack()

def clear_treeview():
    tree.delete(*tree.get_children())

tree = ttk.Treeview(frame)

m = Menu(win)
win.config(menu=m)

file_menu = Menu(m, tearoff=False)
m.add_cascade(label="Menu", menu=file_menu)
file_menu.add_command(label="Open Spreadsheet", command=open_file)

label = Label(win, text='')
label.pack(pady=20)

win.mainloop()

And code found online for filter:
from tkinter import *
import pandas as pd
from tkinter import ttk

df = pd.DataFrame({"currency":["EUR","XCD","ARS","CAD"],
               "volume":[400,500,600,700]})

class app(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title("Python Guides")

        self.tree = ttk.Treeview(self)
        columns = list(df.columns)
        self.Combo = ttk.Combobox(self, values=list(df["currency"].unique()),state="readonly")
        self.Combo.pack()
        self.Combo.bind("<<ComboboxSelected>>", self.select_currency)
        self.tree["columns"] = columns
        self.tree.pack(expand=TRUE, fill=BOTH)

        for i in columns:
            self.tree.column(i, anchor="w")
            self.tree.heading(i, text=i, anchor="w")

        for index, row in df.iterrows():
            self.tree.insert("", "end", text=index, values=list(row))

    def select_currency(self,event=None):
        self.tree.delete(*self.tree.get_children())
        for index, row in df.loc[df["currency"].eq(self.Combo.get())].iterrows():
            self.tree.insert("", "end", text=index, values=list(row))

ws = app()
ws.mainloop()

Example of table to be imported, How it's imported in treeview,
Example of drop menu filter with values from Column "currency"
Comment: While posting the code, stackoverflow was asking me to indent x4 messed up somewhere, apologies.
Comment: Other than the indentation issue, your code does not have any *dropdown* widget and *filtering* code.
Answer: I didn't know which column you want to populate with values so I left it as a Combobox selector, Selecting field will populate the values Combobox.
from tkinter import *
from tkinter import ttk, filedialog
import pandas as pd

win = Tk()
win.geometry("700x350")
style = ttk.Style()
style.theme_use('clam')

frame = Frame(win)
frame.pack(pady=20)
filename = None

def open_file():
    global df
    global filename
    filename = filedialog.askopenfilename(title="Open a File")

    if filename:
        try:
            filename = r"{}".format(filename)
            df = pd.read_excel(filename)
        except ValueError:
            label.config(text="File could not be opened")
        except FileNotFoundError:
            label.config(text="File Not Found")

    def create_column_combox():  # Creating the select field and value Combobox
        def populate_values_combo(e=None):  # populate values combobox with unique column values
            state = 'normal'
            combo_values = []
            if col_combo.get() == 'All':  # if option All selected
                state = 'disabled'  # disabling the option to select values
                select_value()
            else:
                combo_values = ['All'] + df[col_combo.get()].unique().tolist()  # adding option All to values

            col_values_combo.config(values=combo_values, state=state)

        def select_value(e=None):  # cleaning tree and populating with df values
            tree.delete(*tree.get_children())
            if col_combo.get() == 'All' or col_values_combo.get() == 'All':  # if All selected as column or value
                col_values_combo.current(0)  # setting values to All
                [tree.insert("", "end", text=str(index), values=list(row)) for index, row in df.iterrows()]
            else:
                for index, row in df.loc[df[col_combo.get()].eq(col_values_combo.get())].iterrows():
                    tree.insert("", "end", text=index, values=list(row))

        columns = ['All'] + list(df.columns)  # Adding option All to list of columns
        column_combo_label = Label(frame, text='Select field')
        column_combo_label.pack()
        col_combo = ttk.Combobox(frame, values=columns, state='readonly')
        col_combo.pack()
        col_combo.bind("<<ComboboxSelected>>", populate_values_combo)
        volume_combo_label = Label(frame, text='Select value')
        volume_combo_label.pack()
        col_values_combo = ttk.Combobox(frame, state='disabled')
        col_values_combo.pack()
        col_values_combo.bind("<<ComboboxSelected>>", select_value)

    create_column_combox()
    clear_treeview()

    tree["column"] = list(df.columns)
    tree["show"] = "headings"

    for col in tree["column"]:
        tree.heading(col, text=col)
        tree.column("#1", anchor="center", width=200)
        tree.column("#2", anchor="center", width=150)
        tree.column("#3", anchor="center", width=150)
        tree.column("#4", anchor="center", width=150)

    df_rows = df.to_numpy().tolist()
    for row in df_rows:
        tree.insert("", "end", values=row)

    tree.pack()

def clear_treeview():
    tree.delete(*tree.get_children())

tree = ttk.Treeview(frame)

m = Menu(win)
win.config(menu=m)

file_menu = Menu(m, tearoff=False)
m.add_cascade(label="Menu", menu=file_menu)
file_menu.add_command(label="Open Spreadsheet", command=open_file)

label = Label(win, text='')
label.pack(pady=20)

win.mainloop()

Comment: You sir are a magician! Thank you so much for this
Comment: One quick question, is it possible when filterling by Login to have the option Select All to switch back to entire tree view?
Comment: It possible but will require some modifications, like adding first option as 'All' and quering about the selection and modify the function with if to select different output.I'm currently not in front of my computer so I won't be able to show how.
Comment: I'm more than happy to wait until you can :) You already helped me with more than I asked. The Select All, and if Select Field could have just "Ownership" & "Login" as options, I will be forever in your depth
Comment: Updated, added a selection option 'All'
Comment: I've just happen to read all of your comment, you just have to replace: columns = ['All'] + list(df.columns) with: columns = ['All', "Ownership", "Login"] will do. It is no different if you choose All to any of the fields, it will display all anyway.
Comment: Works perfectly! Don't know how to thank you enough. I will break down piece by piece to understand the logic to learn my self!
Comment: Is there a way to open an excel automatically instead of using open file dialog?
Comment: replace the 'filedialog.askopenfilename' method with the file full path string


Is it acceptable to have users wait for their submission to be visible publicly?

Question: If a user creates a new ad or updates an existing ad, it may take up to X minutes before the changes are publicly visible on the website (the user will be informed of this). For what values of X is this acceptable to users? 10 minutes? 60? 0?
The primary pros for this:

Gives staff a window of time to potentially block malicious posts
Prevents cache-invalidation every time something changes, which improves responsiveness for users browsing ads
Comment: The best user experience will be 0. If not possible, notify users how long it will take (and why).
Answer: A non-blocking delay is acceptable.
While instant processing might be ideal, delayed processing is normal in many situations. When we apply for a credit card, apply to rent an apartment, apply to college, or apply for a job we understand that we will need to wait for our application to be reviewed and processed before we receive a decision. That said, it would be unacceptable for your software to appear frozen or to keep a person stuck looking at a progress bar for 10 minutes.
Consider providing instant feedback the post has been submitted followed by a delayed notification when the review process is complete. For example:

User submits a new post
User sees "Your Post has been Submitted" message
Review the post in the background
User receives a "Your Post has been Approved/Denied" notification when the review is complete
User clicks a link in the notification to view the approved post

This way your software never appears broken, frozen, or sluggish and the people using it understand their request is being processed in the background.


Unable to update a particular column on SQLite

Question: I've been trying to update on of my column in my database named COLUMN_NAME_PERIOD_END but it doesn't seem to be able to.
String[] endDate = new String[1];
endDate[0] = paraPeriodDetailsPojoObj.getPeriodEndDate();

Log.d("PeriodEnd.onClick()", "Date: " + endDate[0]);

/*UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
*/

sqliteDatabase.update(DBStorage.TABLE_NAME_PERIODSTART, contentValues, DBStorage.COLUMN_NAME_PERIOD_END+"=?", endDate);

No error messages were displayed so I suppose it is my update statement that is having errors. :(
Comment: How about some error checking?
Comment: may be query doesnt meet the WHERE condition? (no record contains `endDate[0]`)
Comment: how about trying `cursor` for `update`?
Comment: so my query above basically means that i am trying to "UPDATE period_startdate SET period_end_column= content values where period_end_column = endDate" ? I am rather confused :\
Answer: From the docs:
update(String table, ContentValues values, String whereClause, String[] whereArgs)

So, you are putting the array of contentValues (which you don't show, so the problem could be there) into the table defined by TABLE_NAME_PERIODSTART, and selecting which record to update by searching the column defined by COLUMN_NAME_PERIOD_END which must equal endDate.
The way I read your question title I'm under the impression you actually want to update the COLUMN_NAME_PERIOD_END column with the endDate...  if that's the case your SQL is incorrect.
Otherwise, some possibilities that leap to mind to look for are:
1) Constraints... do you have a not null field defined and you are trying to update with a null?
2) Your date format from the program is differing from the one in the database
3) There is no matching record for the endDate you are searching for in the DB
Comment: Yes, I want to update my column_name_period_end with the endDate. The query that I want to use is basically just "UPDATE period_startdate SET period_end_column='29-06-2012';" But I do not know understand how do i implement it into sqlitedatabase.update.
Comment: where the '29-06-2012' is basically retrieved from endDate[0]
Comment: HI EVERYBODY! I have solved my own question. thank you all for the big big help :)