Msg 547, The INSERT statement conflicted with the FOREIGN KEY constraint

Question: In SQL Server 2012 Management studio, I tried many time to create some tables and insert into the tables some values, but the problem here is in relationship with tables :

The INSERT statement conflicted with the FOREIGN KEY constraint

The Errors :

Msg 8152, Level 16, State 14, Line 116 String or binary data would be
  truncated.
Msg 547, Level 16, State 0, Line 122 The INSERT statement conflicted
  with the FOREIGN KEY constraint "eworkerFK". The conflict occurred in
  database "7", table "dbo.member_clup", column 'manager_id'.
The statement has been terminated.
Msg 547, Level 16, State 0, Line 128
  The INSERT statement conflicted with the FOREIGN KEY constraint
  "SALEDFk". The conflict occurred in database "7", table "dbo.worker",
  column 'worker_number'.

Can anyone help me to insert values into the correct
 tables ?

CREATE TABLE address
(
code_place int,
PLACE_NAME VARCHAR (15),
OUT_israel varchar (15)
CONSTRAINT address1 PRIMARY KEY(code_place)

)

create table member_clup
(
manager_id int,
manager_name varchar(15),
manager_last varchar(12),
phone_num int,
type varchar(10),
CONSTRAINT manager1PK PRIMARY KEY(manager_id)
)

create table worker
(
worker_number int,
worker_name varchar(50),
worker_last varchar(49),
id varchar(9),
type varchar(50),
manager_id int
CONSTRAINT workerPK PRIMARY KEY(worker_number)
CONSTRAINT eworkerFK FOREIGN KEY(manager_id)
REFERENCES member_clup(manager_id)

)

  CREATE TABLE rooms(
     room_number int,
  floor int,
  room_type varchar(8)
  CONSTRAINT roomsKEY PRIMARY KEY(room_number)

  )

 CREATE TABLE cars
(
cars_number int,
car_type varchar(15),
car_model int,
CONSTRAINT carsPK PRIMARY KEY(cars_number)
)

CREATE TABLE tourest(
   Cust_number int ,
   Cust_name varchar(50),
   cust_lastname varchar(50),
   cust_phone varchar(10),
   code_place int,
   Room_id int,
   Saledby int
   CONSTRAINT tourest1 PRIMARY KEY(Cust_number)
   CONSTRAINT addressFK FOREIGN KEY(code_place)
   REFERENCES address(code_place),
    CONSTRAINT SALEDFk FOREIGN KEY(Saledby)
   REFERENCES worker(worker_number),
     CONSTRAINT roomsFK FOREIGN KEY(Room_id)
   REFERENCES rooms(room_number)
   )
   CREATE TABLE kesher
(
Cust_number int,
cars_number int,
CONSTRAINT custPK1 PRIMARY KEY(Cust_number,cars_number),
CONSTRAINT kesher1FK FOREIGN KEY(Cust_number)
   REFERENCES cars(cars_number),
     CONSTRAINT kesherFK FOREIGN KEY(Cust_number)
   REFERENCES tourest(Cust_number)
)

insert into cars VALUES
(100100,'mazda',2002),
(100205,'ford',2017),
(100206,'porch',1998),
(100207,'mazda',2017),
(100208,'opel',2002),
(100209,'mazda',2016),
(100210,'pijuot',2002),
(100211,'mazda',2015),
(100212,'mazda',2010),
(100213,'volvo',2002),
(100215,'ford',20012)

insert into rooms VALUES
(100,1,'single'),
(101,1,'double'),
(102,1,'single'),
(103,1,'double'),
(201,2,'signle'),
(202,2,'signle'),
(203,2,'signle'),
(204,2,'signle'),
(300,3,'double'),
(301,3,'double'),
(302,3,'double'),
(303,3,'double'),
(304,3,'signle')

insert into address VALUES
(500,'Akko','no'),
(501,'Haifa','no'),
(502,'Nahariya','no'),
(503,'Nataniya','no'),
(504,'carmieal','no'),
(505,'Nahef','no'),
(507,'Nitsrat','no'),
(510,'OUT','yes')

insert into member_clup VALUES
(5400,'shmolek','snaa','0525732572','General'),
(5696,'malloc','ali','0525552501','Rooms'),
(5991,'ramada','hassan','0532731212','Rooms & Tips'),
(5210,'meri','yako','0525022572','General Manager')

insert into worker
VALUES(1234,'halaa','khaled',1234567,'none',5696),
(2234,'fares','adoon',6542897,'none',5696),
(6670,'halaa','khaled',1001234,'none',5991),
(2554,'halaa','khaled',5658741,'none',5210),
(9987,'halaa','khaled',1123456,'none',5400)
insert into tourest VALUES
(1510,'moshe','yke','0525732579',500,101,2234),
(1520,'ninar','lait','052655541',500,102,6670),
(1521,'hasan','ahmad','0532578741',501,101,2234),
(1522,'ameer','karm','0545222741',500,104,6670),
(1523,'aliel','sraa','0525771572',504,100,2234),
(1524,'hasa','veto','0525122579',505,303,6670),
(1525,'saed','snaa','05255632579',505,303,2234),
(1526,'yakov','mero','0528132579',502,202,6670),
(1527,'mece','loka','0525962579',502,302,9987),
(1528,'ana','yokaf','0525791179',502,302,9987),
(1529,'lelya','mandlina','0527832579',505,203,9987),
(1530,'mnal','khokha','0525758579',507,204,5991),
(1531,'moka','panana','0525805579',507,200,2234)

insert into kesher VALUES

(1510,100100),
(1520,100209),
(1521,100100),
(1522,100209),
(1523,100206),
(1524,100206),
(1525,100213),
(1526,100206),
(1527,100213),
(1528,100213),
(1529,100209)
Comment: Does this answer your question? [The INSERT statement conflicted with the FOREIGN KEY constraint](https://stackoverflow.com/questions/1828376/the-insert-statement-conflicted-with-the-foreign-key-constraint)
Answer: This code is straightforward to debug, you surely can work it out. Run each statement on it's own and see its result. If it fails, split it into smaller statements and repeat. If you can't split it, it's already small enough to debug by eyesight, it won't take long to figure the issue.
Before debugging though, know this, restarting from scratch is sometimes helpful/necessary, so have restart script(s) ready. In this scenario only a bunch of DROP TABLEs are necessary, they'll remove the tables and their records.
Your CREATE TABLE statements are working fine, that's one thing passed. Even if you had problems with them though, run them one by one to debug, not all at once.
Your INSERTs are problematic, yeah. Run each INSERT block one by one, and for the block that fails, split it into individual INSERT statements, one per record, and now you'll be able to tell which row is the problem.
Even though you cite certain foreign key conflict issues, I'm getting a bunch of different foreign key issues. Double-check the code you provided. Also,
the order of what statement is ran first matters (can I furnish the third floor of my house while I don't even have third and second floors? Can you cancel a booking that you didn't book yet?)
Lastly, the data seem to have truncation issues, whether the table column should be bigger or the records' values are incorrect is something only you can tell.


Fast graphing library

Question: I've been using Incanter for my graphing needs, which was adequate but slow for my previous needs.
Now I need to embed a graph in a JPanel. Users will need to interact with the graph (e.g. clicking on certain points which the program would need to receive and deal with) by dragging and clicking. Zooming in a out is a must as well.
I've heard about JFreeChart on other SO discussions, but I see that Incanter uses that as it's graphing engine, and it seemed somewhat slow then. It it actually fast, but perhaps Incanter is doing things that slow it down?
I'm graphing up to 2 million points (simple xy-plots, really), though generally will be graphing less. Using Matlab, this is plotted in a few seconds, but Incanter can hang for minutes.
So is JFreeChart the way to go? Or something else, given my needs?
(Also, it needs to be free, as it is for research.)
Comment: Alternatives to JFreeChart: http://java-source.net/open-source/charting-and-reporting
Answer: Unfortunately, general purpose graphing solutions probably aren't going to scale well to 2 million points - that's big enough that you will need something specialized if you want interactive performance.
I can see a few sensible options:

Write your own custom "plotter" function that is optimized for drawing large numbers of points. You'd have to test it, but I think you might just about get the performance you want by writing the points directly to a BufferedImage using setRGB in a tight loop. If that still isn't fast enough, you can write the points directly into a byte array and construct a MemoryImageSource.
Exclude points so that you are only drawing e.g. 10,000 points maximum. This may be perfectly acceptable as long as you only really care about the overall shape of the scatter plot rather than individual points.
Pre-render all the points into e.g. a large BufferedImage then allow users to zoom in and out / interact with this static image. You might be able to "hack" JFreeChart to do this.
If OpenGL is an option (will require native code + getting up a steep learning curve!), then drop all the points in a big vertex array and get the graphics card to do it all for you. Will handle 2 million points in real-time without any difficulty.
Comment: Thank you for the advice: I might look into using OpenGL or only drawing as many points as are needed at a certain time. However, MatLab seems to handle around 1-2 million points quite nicely–and this is on an old, crappy Dell.
Comment: You can reduce the number of points arbitrarily while keeping the overall shape using the Douglas-Peucker algorithm: http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
Comment: @Isaac - I expect that MatLab internally uses something like one of the approaches I mentioned.
Comment: I'm going with (well, trying to…) rolling my own OpenGL alternative. Also, point 2 will be used with my overview graph! Cheers, and thanks.
Comment: @Isacc- no problem and good luck! If you haven't found them already its well worth looking at the NEHE Java ports for Java OpenGL examples .... http://pepijn.fab4.be/software/nehe-java-ports/
Answer: MathGL is fast and free (GPL) plotting library. But I never test its java interface (swig based) since I'm not familiar with java :( . So, if one can help with testing then I'll be thankful.

Fast graphing library


Is it possible to complete the Crimson Room?

Question: I decided to play the Crimson Room, but at one point you need to go to a url:
<code>http://takagism.fasco-cs.com/yellow_chamber.html
</code>
This page has gone away over the last 10 years, is it possible to progress without it?
Answer: One seems to be unable to complete it from the site you have linked, since it has the version with the random code. If you play it from this source, it seems to have the code being hardcoded to 1994. I played it 3x to the safe and it accepted the same code every time.


How to make armor stands follow you when in a specific vehicle in 1.17.1

Question: I have tried to make an artillery cannon data pack. I want it so that when sitting in a minecart with tag "gun" multiple armor stands with blocks on their heads make the cannon body move where the player does.
I tried to do this:
/execute as @e[type=minecraft:minecart, tag=gun] at @p[distance=..1] run tp @e[type=armor_stand, tag= gunmain, distance=..2] ^ ^ ^3 ~ ~

It does not seem to work reliably but when it does work the armor stand gets teleported only once. Does anyone have a solution for this?
Thanks in advance :)
Answer: By examining your command, it is clear that all armor stands are being teleported to the tiny space 3 blocks ahead of you, which I don't think is what you want to achieve.
I am afraid you have to deal with the cannon parts separately.
E.g. The cannon composes of a stone block and a glass block.
execute as @e[type=minecraft:minecart, tag=gun] at @p[distance=..1] run tp @e[type=armor_stand, tag= stone, distance=..2] ^ ^ ^1 ~ ~

execute as @e[type=minecraft:minecart, tag=gun] at @p[distance=..1] run tp @e[type=armor_stand, tag= glass, distance=..2] ^ ^ ^2 ~ ~

You may also want to rotate the armor stand facing the same way as the player. I can provide you additional support shall the need arise.
Having that said, I concern that the method you employ may not be the most efficient and the most secure. First of all, teleporting is not exactly an efficient command. Secondly, what if the cannon parts are missing? What about the distance between the cannon parts? And would the structure of cannons be messed up if several cannons are placed rigidly?
Here is a method I have come up with.
Minecart + COAS Method
Brief overview
-Detect if player is on a minecart
-Give the player carrot_on_a_stick if so
-Execute at the players on the minecart and have right clicked
-Ka Boom
execute at @e[type=minecart] run execute if entity @e[type=player,distance=..0.5] run item replace entity @p weapon.mainhand with carrot_on_a_stick

(Make sure you have a scoreboard variable linked to used:minecraft.carrot_on_a_stick)
execute at @e[type=minecart] run execute as @p[scores={right_click=1}] run say ShootAmmo

Lastly, reset the scoreboard right click
scoreboard players reset @a right_click

Put all the above in a tick function and you should be able to get a fully functioning turret.
On the topic of the turret model, I strongly advise you to use an App called BlockBench, which helps to create models and textures for Minecraft. Simply set up a resource pack and make your life easier, it is not difficult at all, I promise.
Comment: thanks a lot. I cant believe that it was such a simple fix


Are @Scheduled Threads terminated?

Question: I am wondering what happens if I schedule a Bean method with @Scheduled at, lets say, every hour, but the method execuation takes more than one hour actually.
Will the execution be terminated?
Answer: No, there is no mechanism that will terminate your thread. If the thread runs for "too long", that is your problem :-).
Note: You can use the annotation @Scheduled(fixedDelay=xxx) to only start a new thread when the old thread has finished. That would avoid the problem of multiple threads running in parallel. However, a thread running for too long or even hanging) may of course still cause other problems.
If you are worried that a thread might take too long, you will have to address that in your code. There really is no other way - the framework/runtime has no way of knowing how long is "too long", and even if it had, it has no way of knowing how to properly terminate your thread. It could just kill it, of course, but that is unlikely to be a good solution (cf. the mess about Thread.stop()).

Are @Scheduled Threads terminated?


Django css isn't working

Question: I have added some bootsstrap to my django template and that works fine - but yet when I add my own css and it doesn't have an effect on the page; no errors are produced.
I have a personal web app with a dir static/personal/images/bg01.png
The image isn't loading and the ul isn't being put inline.
views.py:
def index(request):
    return render(request, 'personal/home.html')

HTML:
<!DOCTYPE html>

    <title>Deps</title>
    <meta charset="utf-8" />
    {% load staticfiles %}
    <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/>
    <meta name="viewport" content = "width=device-width, initial-scale=1.0">

Programming, Teaching, Entrepreneurship

Home

Blog

Contact

1

2

3

               {% block content %}
               {% endblock %}

Contact | LinkedIn | Twitter | Google+

Comment: Can you include your view function as well? do you define the STATIC_URL that you use in the style when rendering your view? (i.e. return render(home.html, context={"STATIC_URL": {static url})

That notation in django will tell the html to look for the variable STATIC_URL in the page context
Comment: Have you already reloaded your browser? Browsers will chache static files (css, javascript, html) You can force a hard reload with command + shift + r on mac, which will cause it to recache static files
Comment: @RichardStoeffel Yes. This has been an ongoing problem which I have tried to solve and since have restarted my computer many times
Comment: @RichardStoeffel that makes sense. ive updated it with my code from views.py - what is it exactly i need to add in
Comment: So you are using two different variables to refer to your static files right now,
{% static 'personal/images/bg01.jpg' %} is a syntax that automatically points to your static root (which you set in the settings already).

the {{ STATIC_URL }} syntax implies that in the render function, there is a context variable called STATIC_URL, which would look like this in your view:

return render(request, 'personal/home.html', context={'STATIC_URL':{your path here}). You can try setting that STATIC_URL variable to the path of your static directory
Comment: @RichardStoeffel if I was to do it the first way how would I do it. Because it's not displaying when I refer to it using {% 'personal/images/bg01.png' %}. I've checked the settings and it's referring to the static path so I'm unsure why the image won't load
Comment: if you use that syntax you need to include the static keyword, so it would be {% static 'personal/images/bg01.png' %}
Comment: @RichardStoeffel I've added that and its still not displaying. in the terminal its responding with: "GET /static/home/images/bg01.png HTTP/1.1" 404 1673, so I presume its found the image, but still the background isn't changing.
Comment: sorry meant /static/personal/images/bg01.png
Comment: If its getting a 404 that actually means it isn't finding the image, 404 is "Not Found", so if there are no typos in the directories and image name, the path django is trying to use is probably wrong. Check out this question https://stackoverflow.com/questions/20047364/how-to-give-the-background-image-path-in-css, which shows how to use relative paths to use the different directories in a project
Comment: @RichardStoeffel Thanks a lot. It turns out I just had to get rid of the .png
Answer: In your style block, the background-image property isn't nested within a selector. If you wanted that to also be applied to the html/body, just move it up into the curly braces (and add a semi-colon after the height property); otherwise, add an appropriate selector to apply the property to instead.
You may also need to remove the space after {{ STATIC_URL }} so you don't end up with a space in the image path.

Comment: It's now displaying inline but the image isn't displaying. Someone commented about linking the static file in views but I'm not too sure what is meant by that

Django css isn't working


On the Commutativity of Cycles in Permutation Groups

Question: Let $\sigma,\tau$ be two cycles in $S_n$ such that

$\sigma$ and $\tau$ have different length;
$\sigma$ and $\tau$ are not disjoint.

Then is it always true that $\sigma\circ \tau\neq \tau\circ\sigma$?
Comment: Note that if we drop one of the conditions, then we *can* have that $\sigma\circ \tau=\tau\circ\sigma$.
Answer: Yes, this is correct. Treating $\sigma$ and $\tau$ as permutations on a set, we can notice that the different lengths condition allows us to assume one of these permutations has a fixed point that the other does not. Assuming there exists some $s$ such that $\tau(s)=s$ but $\sigma(s)\neq s$ we can prove the following:

There exists an $s'$ such that $\tau(s')=s'$ but $\tau(\sigma(s'))\neq \sigma(s')$.

To prove this, we let $n$ be the least $n$ such that $\sigma^n(s)$ isn't a fixed point of $\tau$. Then, $s'=\sigma^{n-1}(s)$ satisfies the condition.
The rest is easy. We start with our second condition on $s'$:
$$\tau(\sigma(s'))\neq \sigma(s')$$
and then substitute $s'=\tau(s')$ to get:
$$\tau(\sigma(s'))\neq \sigma(\tau(s'))$$
meaning that $\tau\circ \sigma$ and $\sigma\circ \tau$ are different as they evaluate differently on $s'$.
Answer: Yes. Two cycles that generate the same cyclic subgroup must have the same length, so it follows from the following result:

Suppose $\sigma$ and $\tau$ are cycles in $S_n$. Then $\sigma$ and $\tau$ commute iff one of the following holds:

$\sigma$ and $\tau$ are disjoint, or
$\langle\sigma\rangle = \langle\tau\rangle$.

Proof Suppose $\sigma$ is a cycle in $S_n$, say $\sigma = (a_1,\ldots,a_m)$, and $\tau$ commutes with $\sigma$. Then $$\sigma = \tau\sigma\tau^{-1} = (\tau(a_1),\ldots,\tau(a_m)),$$ so there is an integer $k$ such that $\tau(a_i) = a_{i+k} = \sigma^k(a_i)$ for $i = 1,\ldots,m$ where the subscripts are taken mod $m$. It follows that $\tau = \sigma^k\rho$ where $\rho$ fixes $a_i$ for $i=1,\ldots,m$.
Now suppose $\tau$ is also a cycle. Then one of $\sigma^k$ and $\rho$ must be trivial. If $\sigma^k$ is trivial then $\tau$ and $\sigma$ are disjoint cycles. If $\rho$ is trivial then $\sigma^k$ is a cycle, so $\gcd(k,m) = 1$ and $\langle\sigma\rangle = \langle\sigma^k\rangle = \langle\tau\rangle$.


Extract Hex String from varbinary to File

Question: this is pretty much a noob question but i can't find a solution.
I'm using a SQL Server Database. In one table a column has the DataType varbinary(max). The values for this column are shown a hex values(When i'm using a select - query).  What is the best way to write the shown hex String completly into a text file?
Two Constraints:
* Copy&Paste is not an Option. The value i want to extract has a length of approx. 69000 Chars. The Windows Clipboard seems to store only around 43000 Chars.
* I've tried to save the query Result as a .csv File. But the maximum size for these files is around 65000 chars.
Comment: Why can't you query that column, store it in a StringBuffer and then write it to a File?
Comment: Would this answer help? http://stackoverflow.com/a/5172100/2061621
Comment: Using transact SQL? Or Java? I've been using a small Java Program to query the value. But i don't know which method to call to get the hex value and not the bytes.
Answer: From the command line:

<code>bcp "select * from [<yourtable>]" queryout C:\Temp\yourfile.dat -S yourserver -d yourDatabase -T -c
</code>

-T means a Trusted Connection; you can use -U and -P to supply a user name as password.
Comment: Whooohoooo!!! :-) Works! Thanks. I've tried bcp yesterday but did not give the Database as an extra Parameter. I've had it in my query.


Can I transfer Pokemon X/Y save files between cartridges/digital copies?

Question: Specifically, I want to know if the following situations are possible.
Can I have played pokemon X on a cartridge, make a save file and play the game to completion, then download a DIGITAL copy of the game and continue the previous game on the digital copy instead of the cartridge?
Or,
Can I have played pokemon X on a cartridge, make a save file and play the game to completion then buy ANOTHER cartridge of the same game and continue my previous game on the new cartridge?
Comment: This question is generally applicable to all 3DS games, not just Pokemon. It might make sense to edit the title to reflect that.
Answer: The first scenario (transferring a save game to a digital copy) should be possible. In the 3DS's E-Shop there is a free app called "Save Data Transfer Tool". To quote the store page:

The Save Data Transfer Tool allows Nintendo 3DS users to transfer save data from the packaged version of a game to the downloadable version. Players that originally purchased a physical version of a game will be able to pick up right where they left off with their save data if they decide to download the digital version of the same game. Save data that is transferred to a digital game cannot be moved back to the physical version.

This would seem to move the save from the cartridge to the digital version, not copy. Note that it would probably require an exact game match; as in transferring the save from the Pokemon X cartridge to the Pokemon X digital, not from X to Y. Also as the store description indicates, this is a one-way transfer only. from physical to digital, no going back.

The second scenario (transferring from one cartridge to another) is not, to my knowledge, possible. However, with the Pokemon bank, it might be possible to withdraw stored pokemon on different cartriges, so long as it is your Nintendo Network ID. As the bank will not store items, this is only usefull for transferring pokemon. Your progress throughout the story, and items in your backpack will remain with the save file on the cartridge.
Answer: As far as I know you cannot play any save file on anything other than the original game you bought/downloaded. You would have to start a brand new file, though you could find a way to trade all your Pokemon over if you had another 3DS handy.
Answer: I can only tell you my experience with one game.  The only game I have two copies of is Bravely Default.  I tried to duplicate my savegame onto a second cartridge.  The second cartridge (on first start up since restoring) went straight to a message like "creating new save file".  I could properly restore the second game's save back onto itself but it would not take my first one's savegame.
Answer: buy powersaves for 3ds. back up your save. simple as that. thats how there are people selling pokemon x on ebay with over 600 shiny pokemon. backing up the save from 1, then restoring it to multiple cartridges.


How to pull keys and values in jq csv when you don't know the key name

Question: I have a semi working jq filter that pulls out .key, .value.sitename and shows it in a one line csv format. I'd like to add any tag_* keys and values (if found) at the end of the csv line.
[.key , .value.hostname, .value.attributes.sitename  ] | @csv

I need help with the .value.attributes.tag* keys since they might be completely missing or different tag_ names. They all start with tag_ but could be anything. I'd like to pair the found tag name and value together if possible and append it on the csv line with the host.
{
  "key": "computer1.domain.com",
  "value": {
    "attributes": {
      "TESTID": "23423423",
      "sitename": "siteidname",
      "tag_robo_equip": "boopbeep",
      "tag_modern": "cybertruck"
    },
    "hostname": "computer1.domain.com",
  }
}

Comment: Would you mind including the expected output for that sample in your question?
Answer: At the end of the line "hostname": "computer1.domain.com", the comma is an error.
If you correct this, the solution could be:
Proposal
At the you have 2 additional columns one with the keys an other with the values in your csv file.


Defense against Artillery Spam?

Question: Situation:

It's been a few months since I've last played so I'm a bit rusty
I remember my favorite strategy was a resource boom (made easy by Portugal's free Covered Wagons increasing Settler output).
I put some minor thought into my prior strategies and I feel the best strategy would be for me to add a bit of improved turtle tactics to my boom strategy since my largest problem was getting attacked before having troops.

I understand the nature of a boom-strategy therefore I'm not here asking how to prevent getting rushed, I know some tactics on that but inevitably the only acceptable way is spam walls or build troops.
I specifically play Portuguese but I'm open to any tips.
Question:
How do you defend/turtle against a well-done enemy artillery spam?
Attempted Strategies:

I've tried lining the inside of my walls with my own artillery. This either ends in my artillery getting shot instead of the walls or the enemy shooting walls at max range and then going for my artillery.
Lining my walls with a mix of troops which unsurprisingly yields similar results.
Sent troops out and attacked. This seems to work about 50% of the time, the bad 50% ends with another anti-(insert my troop-type here) force picking them off as I attack.

Obviously a decent portion of this is failure to micromanage but ignoring that portion are there any decent strategies that would help me promote my Boom/Turtle strategy? (Allow me to defend my base with the combination of Walls, Outposts, and a small troop force? I do my best to keep my build HP upgrades coming while keeping my troops strong too, but obviously until late-game (where I destroy everything) I am primarily focused on economy boosting.
Answer: Turtle strategies just do not work in Age of Empires 3. The problem with walls and other defensive structures such as outposts is that they only give you control over a small area of the map.
If you "turtle" and build outposts near your town center, you will be completely safe from rushes and such for the first few minutes. The problem is that a competent opponent will not run around your towers and let his units die to them.
He will wait just outside of your base. When the food and gold in your base run out, you will want to move to herds and mines outside of your base, but you will not be able to because you invested your resources into stationary towers and walls, while your opponent invested his into a mobile army.
You will be forced to build mills and plantations. While you are spending 400w and 800w for every mill and plantation respectively, your opponent is happily gathering natural resources which are not only free but gather significantly faster. Even if you have more villagers than him, he will have a much much stronger economy, and inevitably win.
With that said, if you really do want to go for a turtle, the only way to deal with cannons (unless he is not protecting them appropriately) is to use culverins.

Defense against Artillery Spam?


hostapd gives error nl80211: Register Action command failed: ret=-19

Question: I'm trying to get hostapd working on a RT3290 (pci-based) network adapter, and a Ubuntu 12.04.3 LTS release. I use the approach taken in How to setup an Access Point mode Wi-Fi Hotspot?
I verified with the "iw list" command that it has AP mode for acting as a access point.
When starting the hostapd daemon, I get the following error:
<code># sudo hostapd -d /etc/hostapd/hostapd.conf
Configuration file: /etc/hostapd/hostapd.conf
nl80211: Register Action command failed: ret=-19 (No such device)
nl80211: Register Action match - hexdump(len=1): 06
nl80211: Failed to register Action frame processing - ignore for now
nl80211: Add own interface ifindex 0
Could not read interface wlan0  flags: No such device
nl80211 driver initialization failed.
ELOOP: remaining socket: sock=4 eloop_data=0x8a5b900 user_data=0x8a5bea0 handler=0x807c5e0
ELOOP: remaining socket: sock=6 eloop_data=0x8a5dd30 user_data=(nil) handler=0x8086770
</code>
What can be wrong with this set-up?
Answer: Removing a space character after the "interface=wlan0 " line solved the issue.
I had copied the hostapd.conf from a website: hostapd is due to a bad implementation very sensitive to whitespaces.
Comment: This freaking nuance kept me awake all night. Thanks for the tip.
Answer: The answer is here only
<code>  Could not read interface wlan0  flags: No such device
  nl80211 driver initialization failed.
</code>

you may have disabled your wlan0 , so please enable it , if it is so.
The device drivers are not installed properly , reinstall the drivers.
If your wireless device has connected with some other name like wlan1 or wlan2 , please edit that file and replace it with the corresponding device name.
Comment: Thanks for your suggestion. The device drivers work and the device is enabled, because I can connect with it to an other access point. I also disabled the networkmanager to see if that was in conflict with hostapd, but that did not work. The device is made available as wlan0 as shown by 'iw list' or ifconfig.
Comment: I was indeed related to the device not being recognized, see my accepted answer below. But in other cases your line of trouble shooting may help as well.
Comment: @Roalt glad that you have accepted your issue.


How to make server ip property driven in karaf

Question: I am deploying a jar in karaf .
My jar consists of a camel route
Copyin only the route part :
<code>                from("file:/app/billing/billingip/HOBSRating/data/mediation/voice/input?include=USAGE_VOICE.*.txt")
                .doTry()
              .log("#########The Camel Header before loading into kafka topic ######## :${headers}")
              .log("#########The Camel Body  before loading into kafka topic  ######## :${body}")
              .to("kafka:172.20.211.201:9092?topic=VoiceStream&zookeeperHost=172.20.211.201&zookeeperPort=9092&serializerClass=kafka.serializer.StringEncoder")
             /* .to("kafka:${kafkaserver}?topic=DataStream&zookeeperHost=${zookeeperHost}&zookeeperPort=${zookeeperport}&serializerClass=kafka.serializer.StringEncoder")*/
              .to("file:/app/billing/billingip/HOBSRating/data/mediation/voice/success")
              .doCatch(Exception.class)
              .log("########The exception message is             ####### :${exception.message}")
              .log("########The stack trace of the exception is  ####### :${exception.stacktrace}")
              .to("file:/app/billing/billingip/HOBSRating/data/mediation/voice/error")
              .log("###############    End of Voice Cdr to Kafka Topic Route      ################")
</code>
Currently ,I am hard coding the kafka server credentials but i want to make this property file driven.
Answer: Read about Camel's property placeholder where you can externalize configuration and refer to them from your Camel routes: http://camel.apache.org/using-propertyplaceholder.html
Comment: Ahh for *** sake please spend more time learning how to ask a question on stackoverflow where your question is readable and understandable. Dont just copy a bunch of code/stacktaces to a comment section that is unreadable,


Convert object into specific format with recursive function

Question: original object : [
    {
        Name: 'ZoneName',
        Value: 'Box A',
    }
    ,
    {
        Name: 'AirSide',
        Value: {
            JZCleanTipFlowResults: {
                LeakageAirFlowRate: 2.0519336991674058,
                LeakageAirFlowRate_Uncertainty: 0.05755421849942835,
                LeakageAirFlowRate_lbmhr: 16285.188088630204,
                LeakageAirFlowRate_lbmhr_Uncertainty: 456.779511900225,
            },
            UsedAmbientTemperatureForCombustion: true,
            SubStoichWarning: false,
        },
    }
    ,
    {
        Name: 'FuelSide',
        Value: {
            Fuels: {
                'Header 0': {
                    CleanTipResults: {
                        HR: 10776333.422366736,
                        HR_Uncertainty: 14383.420657232984,
                        HR_MMBTUhr: 36.77037592294784,
                    },
                },
            },
            CleanTipResults: {
                HR: 10776333.422366736,
                HR_Uncertainty: 14383.420657232984,
            },
        },
    },
];
Want object like :
denested shape  :[
    {
        Name: 'ZoneName',
        Value: 'Box A',
    }
    ,
    {
        Name: 'AirSide|JZCleanTipFlowResults|LeakageAirFlowRate',
        Value: 2.0519336991674058,
    }
    ,
    {
        Name: 'AirSide|JZCleanTipFlowResults|LeakageAirFlowRate_Uncertainty',
        Value: 0.05755421849942835,
    }
    ,
    {
        Name: 'AirSide|JZCleanTipFlowResults|LeakageAirFlowRate_lbmhr',
        Value: 16285.188088630204,
    }
    ,
    {
        Name: 'AirSide|JZCleanTipFlowResults|LeakageAirFlowRate_lbmhr_Uncertainty',
        Value: 456.779511900225,
    }
    ,
    {
        Name: 'AirSide|UsedAmbientTemperatureForCombustion',
        Value: true,
    }
    ,
    {
        Name: 'AirSide|JZCleanTipFlowResults|SubStoichWarning',
        Value: false,
    }
    ,
    {
        Name: 'FuelSide|Fuels|Header 0|CleanTipResults|HR',
        Value: 10776333.422366736,
    }
    ,
    {
        Name: 'FuelSide|Fuels|Header 0|CleanTipResults|HR_Uncertainty',
        Value: 14383.420657232984,
    }
    ,
    {
        Name: 'FuelSide|Fuels|Header 0|CleanTipResults|HR_MMBTUhr',
        Value: 36.77037592294784,
    }
    ,
    {
        Name: 'FuelSide|CleanTipResults|HR',
        Value: 10776333.422366736,
    }
    ,
    {
        Name: 'FuelSide|CleanTipResults|HR_Uncertainty',
        Value: 14383.420657232984,
    }
]
Comment: Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help.
Comment: When you were asking your question, there was a big orange **How to Format** box to the right of the text area with useful info in it. There was also a toolbar full of formatting aids. And a **[?]** button giving formatting help. *And* a preview area showing what your post would look like when posted, between the text area and the Post Your Question button (so that you'd have to scroll past it to find the button, so you'd look at it). Making your post clear, and showing that you took the time to do so, improves your chances of getting good answers.
Comment: People really are willing to help; T.J Crowder was telling it truly.  But you need to do your part first.  What have you tried?  Where are you stuck?
Answer: I will supply my thoughts since there is already a high-quality answer here.  But please, in the future, StackOverflow is meant to help you when you get stuck, not to write your code for you.  Please demonstrate your own effort and explain where you got stuck.
I stole helper functions from previous answers of mine.  path takes an array of node names and an object and returns the value at that path in the object, or undefined if any node doesn't exist.  For instance, path  (['foo', 'bar', 'baz']) applied to {foo: {bar: {baz: 42}, qux: 99}, corge: -1} yields 42.
getPaths is a generator function giving you the paths to the leaf nodes of an object.  So getPaths ({foo: {bar: {baz: 42}, qux: 99}, corge: -1}) yields ["foo", "bar", "baz"], then ["foo", "qux"], and ["corge"].
A custom transform function iterates over your array of Name/Value pairs, just returning them if Value is a string and otherwise using getPaths to turn the value into an array of Condensed|Path|Names / Value pairs.  These are joined into a single list with flatMap.

const path = (ps = [], obj = {}) =>
  ps .reduce ((o, p) => (o || {}) [p], obj)

function * getPaths(o, p = []) {
  if (Object(o) !== o || Object .keys (o) .length == 0) yield p
  if (Object(o) === o)
    for (let k of Object .keys (o))
      yield * getPaths (o[k], [...p, Number.isInteger (Number (k)) ? Number (k) : k])
}

const transform = (orig) =>
  orig .flatMap (({Name, Value}) =>
    typeof Value == 'string'
      ? {Name, Value}
      : [... getPaths (Value)] .map (
          route => ({Name: Name + '|' + route .join ('|'), Value: path (route, Value)})
        )
  )

const orig = [{Name: "ZoneName", Value: "Box A"}, {Name: "AirSide", Value: {JZCleanTipFlowResults: {LeakageAirFlowRate: 2.0519336991674058, LeakageAirFlowRate_Uncertainty: .05755421849942835, LeakageAirFlowRate_lbmhr: 16285.188088630204, LeakageAirFlowRate_lbmhr_Uncertainty: 456.779511900225}, UsedAmbientTemperatureForCombustion: true, SubStoichWarning: false}}, {Name: "FuelSide", Value: {Fuels: {"Header 0": {CleanTipResults: {HR: 10776333.422366736, HR_Uncertainty: 14383.420657232984, HR_MMBTUhr: 36.77037592294784}}}, CleanTipResults: {HR: 10776333.422366736, HR_Uncertainty: 14383.420657232984}}}];

console .log (transform (orig))
.as-console-wrapper {min-height: 100% !important; top: 0}
Comment: Nope, I don't particularly like typescript and use it only when absolutely forced to do so. Even the request demonstrates that you still don't understand what StackOverflow is about, though.  Please read the links in the first comment to your question.  This is not a code-writing service.  It's a Q & A site for programming topics.  People do want to help, but only if you're willing to put in the requisite work.
Answer: If you're just looking for a copy/paste answer, I won't bother supplying much of an explanation. But I don't mind completing the puzzle and sharing my work -

If the input is an object,
"Flatten" it.
Otherwise, the input is not an object. Return the "flat" result.

const transform = (o = {}, path = []) =>
  Object(o) === o   // 1
    ? Object        // 2
        .entries(o)
        .flatMap(([ k, v ]) => transform(v, [...path, k]))
    : [ { path: path.join("|"), value: o } ] // 3

const data =
  [{Name:'ZoneName',Value:'Box A'},{Name:'AirSide',Value:{JZCleanTipFlowResults:{LeakageAirFlowRate:2.0519336991674058,LeakageAirFlowRate_Uncertainty:0.05755421849942835,LeakageAirFlowRate_lbmhr:16285.188088630204,LeakageAirFlowRate_lbmhr_Uncertainty:456.779511900225},UsedAmbientTemperatureForCombustion:true,SubStoichWarning:false}},{Name:'FuelSide',Value:{Fuels:{'Header 0':{CleanTipResults:{HR:10776333.422366736,HR_Uncertainty:14383.420657232984,HR_MMBTUhr:36.77037592294784}}},CleanTipResults:{HR:10776333.422366736,HR_Uncertainty:14383.420657232984}}}]

const result =
  transform(data)

console.log(JSON.stringify(result, null, 2))

Output -
[
  {
    "path": "0|Name",
    "value": "ZoneName"
  },
  {
    "path": "0|Value",
    "value": "Box A"
  },
  {
    "path": "1|Name",
    "value": "AirSide"
  },
  {
    "path": "1|Value|JZCleanTipFlowResults|LeakageAirFlowRate",
    "value": 2.0519336991674058
  },
  {
    "path": "1|Value|JZCleanTipFlowResults|LeakageAirFlowRate_Uncertainty",
    "value": 0.05755421849942835
  },
  {
    "path": "1|Value|JZCleanTipFlowResults|LeakageAirFlowRate_lbmhr",
    "value": 16285.188088630204
  },
  {
    "path": "1|Value|JZCleanTipFlowResults|LeakageAirFlowRate_lbmhr_Uncertainty",
    "value": 456.779511900225
  },
  {
    "path": "1|Value|UsedAmbientTemperatureForCombustion",
    "value": true
  },
  {
    "path": "1|Value|SubStoichWarning",
    "value": false
  },
  {
    "path": "2|Name",
    "value": "FuelSide"
  },
  {
    "path": "2|Value|Fuels|Header 0|CleanTipResults|HR",
    "value": 10776333.422366736
  },
  {
    "path": "2|Value|Fuels|Header 0|CleanTipResults|HR_Uncertainty",
    "value": 14383.420657232984
  },
  {
    "path": "2|Value|Fuels|Header 0|CleanTipResults|HR_MMBTUhr",
    "value": 36.77037592294784
  },
  {
    "path": "2|Value|CleanTipResults|HR",
    "value": 10776333.422366736
  },
  {
    "path": "2|Value|CleanTipResults|HR_Uncertainty",
    "value": 14383.420657232984
  }
]

Comment: No, because your data is not well-typed. Even if I gave you the valid TS for this program, it would still be bad. Adding TS to this would be like saying "I have bad data, but I want to use TS to be 100% sure it's bad."
Comment: You didn't put up an attempt of your own, so it's hard to measure how much you've invested in solving the problem on your own. To that end, the only other advice I have for you is _not_ to convert it to TS. If you want type safety in JS, I would be looking at the more future-proof tools like ReasonML.


getActionBar() return null and requestFeature() appear in ActionBarActivity class

Question: I got some problem when I want to add an application icon at my action bar.
So I have ActionBarActivity class which have these following code in onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.activity_check_stock);

    if(this.getActionBar() != null){
        Log.d("ACTIONBAR_NOT_NULL", "ActionBar Not NULL");
        //getActionBar().setHomeButtonEnabled(true);
        //getActionBar().setDisplayHomeAsUpEnabled(true);
        //getActionBar().setDisplayUseLogoEnabled(true);
        //getActionBar().setDisplayOptions(getActionBar().DISPLAY_SHOW_HOME | getActionBar().DISPLAY_SHOW_TITLE);
        //getActionBar().setIcon(R.drawable.vanwellis_logo);
    }
    else{
        Log.d("ACTIONBAR_NULL","ActionBar NULL");
    }

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

}

Since my getActionBar() return null, so I add getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
But this approach still return an error, but with this new error :

android.util.AndroidRuntimeException: requestFeature() must be called
  before adding content

So I try to put requestFeature() right before super.onCreate(savedInstanceState);
and the result is...the getActionBar() return null again, but without any errors occurred.
and this is my style.xml
I don't know is this applied to all my activities or not, but here you go...
<resources>

[UPDATE]
So this is my whole Activity class
package com.vanwellis.vinnomobile;

import java.util.Locale;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.vanwellis.vinnomobile.fragment.CheckStockFragment;

public class CheckStockActivity extends ActionBarActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_check_stock);

        if(this.getActionBar() != null){
            Log.d("ACTIONBAR_NOT_NULL", "ActionBar Not NULL");
            //getActionBar().setHomeButtonEnabled(true);
            //getActionBar().setDisplayHomeAsUpEnabled(true);
            //getActionBar().setDisplayUseLogoEnabled(true);
            //getActionBar().setDisplayOptions(getActionBar().DISPLAY_SHOW_HOME | getActionBar().DISPLAY_SHOW_TITLE);
            //getActionBar().setIcon(R.drawable.vanwellis_logo);
        }
        else{
            Log.d("ACTIONBAR_NULL","ActionBar NULL");
        }

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_check_stock, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a CheckStockFragment (defined as a static inner class below).
            return CheckStockFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

}

I'm affraid the Widget.AppCompat.Light.ActionBar.Solid.Inverse will generate no-actionbar.
I'm using android studio with these configuration in my gradle app properties :
android {
        compileSdkVersion 21
        buildToolsVersion "21.1.2"

        defaultConfig {
            applicationId "com.vanwellis.vinnomobile"
            minSdkVersion 15
            targetSdkVersion 21
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

So what is really happened in here?
Comment: Use getSupportActionBar()
Comment: Can your please tell me witch class your activity extends
Comment: `.requestFeature(Window.FEATURE_ACTION_BAR);` Why are you using this? Just extend `AppCompatActivity`.
Comment: My sdk target is 21 and the min sdk target is 15. Is AppCompatActivity compatible with my sdk target settings?
Answer: Because your ActionBarActivity is imported from the support library...
import android.support.v7.app.ActionBarActivity;

...you need to use getSupportActionBar() instead of getActionBar().
Answer: if you using Theme.AppCompat Theme then you must extends your activity with ActionBarActivity other vise you will get null actionbar
Exp :
public class MyActivity extends ActionBarActivity {

}

Thanks
Comment: Use `AppCompatActivity`. `ActionBarActivity` is deprecated.
Comment: sorry forgot to include my whole class. So my class already extends ActionBarActivity
Comment: how I can use AppCompatActivity? I try to change ActionBarActivity directly with AppCompatActivity, and in my android studio shows me an error.


Bootstrap and IE9/8 - making me crazy

Question: What is the problem with Bootstrap in IE8/9?
http://www.stockholmcharterguide.com/
I've scanned the web and found some trix but - still the same grey overlay.
Is there a difference if you use the html5shiv.min.js local or remote?
Answer: I'm not sure what your question is, but from checking the link I see a tag written like so in the top menu:

The result being nothing renders in between your top menu and footer, resulting in the empty gray box--it's not an overlay, it's the page background.
HTH,
-Ted

Bootstrap and IE9/8 - making me crazy


Can't update variable in a do while loop

Question: Console.WriteLine("Would you like to go first or second?");
string firstSecond = Console.ReadLine().ToUpper();
if (firstSecond == "FIRST")
{
    Console.WriteLine("1");
}
else if (firstSecond == "SECOND")
{
    Console.WriteLine("2");
}
else
{
    string input = "x";
    bool first = input == "FIRST";
    bool second = input == "SECOND";
    do
    {
        Console.WriteLine("Please say first or second:");
        input = Console.ReadLine().ToUpper();
    }
    while (!(first | second));
}

The do while loop keeps on going even if I type first or second, I tried changing how I state the boolean but nothing seems to work. I am new so I am might some silly mistakes. How do I fix this?
Answer: You must put first and second condition into do while loop.
string input;
bool first;
bool second;
do {
  Console.WriteLine("Please say first or second:");
  input = Console.ReadLine().ToUpper();

  first = input == "FIRST";
  second = input == "SECOND";
}
while (!(first || second));

Comment: The difference between `first | second` and `first || second` when both `first` and `second` are boolean is that both operands are evaluated in the `|` case, but in the second (`||`) case, you get short-circuiting behavior (if `first` is true, `second` is not evaluated). The code-gen is simpler in the `|` case and the execution speed is likely (infinitesimally) better (without the short-circuiting branch). Idiomatically, most C# programmers will feel more comfortable with the short-circuiting form (BTW, in VB, `|` is the familiar `Or`, while `||` is the more unusual `Or Else`)


Android - numeric keyboard with decimal separator

Question: I have an edittext which is created programmatically (so not in xml) and I want to launch a numeric keyboard when user presses it. The problem is that I want this keyboard also to contain the decimal separator (.).
I tried many things but nothing seems to work
final EditText input = new EditText(this);
input.setKeyListener(new DigitsKeyListener()); // this gives numeric without decimal separator
input.setInputType(InputType.TYPE_CLASS_NUMBER); // this gives numeric without decimal separator
input.setInputType(InputType.TYPE_CLASS_PHONE);//this gives phone keyboard with all the digits and decimal separator in the second page. It is not exactly what I want
I know that there is a way to implement custom keyboard:
http://android-developers.blogspot.com/2009/04/creating-input-method.html
http://developer.android.com/resources/samples/SoftKeyboard/index.html
but it seems quite a pain and I am first looking for a quicker alternative.
All I want is one of the following:
1. Launch numeric keyboard that contains decimal separator
2. Launch standard keyboard, but set in the numeric "page"
Is something of the above possible? Thank you in advance!
Comment: Are you interested to perform regular expression over the editText value ?
Comment: hmm.. I do not understand, how will this change the keyboard that the user sees? Or help him insert decimal values?
Comment: [ok here is the link let the user input anything but during validation if it fails to input decimal number you can show error in Alert Box][1]

  [1]: http://stackoverflow.com/questions/308122/simple-regular-expression-for-a-decimal-with-a-precision-of-2
Answer: I have showed the keyboard using this code:
        // Set an EditText view to get user input
    final EditText input = new EditText(this);
    alert.setView(input);
    input.setInputType((InputType.TYPE_CLASS_NUMBER + InputType.TYPE_NUMBER_FLAG_DECIMAL));

Comment: The problem with this solution  is that user can write only  decimal number such as 6.3052 but he cannot use the dot more than once. we need a soft keyboard with numbers and dot that can be used for IP for example.
Answer: There is no keyboard for what you are describing, at least not one that you can get as a normal input type. Even if you made a custom keyboard, that wouldn't be a good way of handling this because the user would have to switch keyboards every time they wanted to use your app.
Also, you can't explicitly open the text keyboard "on the number page" because not all Android keyboards even have a separate number page. This is highly customized on each device.
My first suggestion would be to use the normal text keyboard, and let the user decide which keyboard suits the best.
My second suggestion would be to build a number pad on the screen using buttons/views for the specific keys you need.
Comment: that looks thorough thank you. I will research the options a bit and let you know
Comment: from all that I can find it looks that you are very right. So answer accepted and thank you very much!
Answer: Here it goes.
if (editText.getText().matches("^[0-9]+(\.[0-9]{1,2})?$")) {
            System.out.println("It is decimal number");
        }

Comment: you do not understand, the question is not how to assure that the input is decimal number, I want to launch a soft keyboard so that the user will have the ten digits and the decimal separator (mostly like the InputType.TYPE_CLASS_NUMBER does, but add the ".")
Answer: new DigitsKeyListener(false, true)

will give a decimal input keyboard


How to format output date php

Question: I have a small piece of my script when a user logs in that shows their membership expiration date, however it displays the output as yyyy-mm-dd. I am assuming this is because of how it is displayed in the sql table.
<? echo "Welcome, {$_SESSION['username']}"; ?>

<?php

// Make a MySQL Connection
mysql_connect("server", "db", "db") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());

$query =  "SELECT `Date` FROM `USERS` WHERE `username` = '" . $_SESSION['username'] . "'";
// Retrieve all the data from the "example" table
$result = mysql_query($query) or die(mysql_error())
or die(mysql_error());

// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );

echo "Membership Expiration Date: ".$row['Date'];
?>

I have tried putting format commands in
".$row['Date'];

such as
".$row['Date , M d, Y'];
".$row['Date , M-d-Y'];

However I am sure that is wrong. I'm reading date formats and conversions however if I need to convert it, I am not sure where to input it. If it needs to be defined before the echo, or if I'm missing something in the
".$row['Date'];

Still trying, however any help would be appreciated, thank you.
Answer: Use strtotime along with date:
echo "Membership Expiration Date: ". date("Y-m-d", strtotime($row['Date']));

If $row['Date'] is already a timestamp, then skip strtotime:
echo "Membership Expiration Date: ". date("Y-m-d", $row['Date']);

For more help, check all the similar questions asked on the column to your right --------------------------->>
Comment: This was it! I was looking into the strtotime function I just didn't know how to write it in the correct syntax. Thank you Aziz. Will accept the correct answer when I can in 10 minutes.
Answer: What you will want to do is use the date functions. Here is how you will manipulate your date:
echo date('Y-m-d', strtotime($row['Date']));

This will display a date to the M-d-Y format. If you want more details you can read the official PHP date documentation.
Answer: You could change the SQL string using the date_format() MySQL function. It should something like this:
SELECT DATE_FORMAT(`Date`, ''%m/%d/%y'') AS Date FROM `USERS` WHERE `username` = '

That should bring you the date as a formatted string.

How to format output date php


MSI Silent Installation not Working

Question: I am trying to install an MSI via PowerShell using the following code:
msiexec /a [MSI File] /qn

According to the Event Log, the software was installed successfully, but does not appear in either Add/Remove Programs nor inside the registry key. I am on a laptop that does not have Admin control, which is why I'm using /a instead of /i. I have also tried the following code to same results as before:
msiexec /a [MSI File] ALLUSER=2 ARPSYSTEMCOMPONENT=0 /qn

Any clue as to why this is happening, and how I can fix this so the software can be properly installed?
Comment: How is this related to PowerShell? The MSI failure is not related to PowerShell.
Comment: Have the installer [log what it's doing](http://stackoverflow.com/a/7130758/1630171) to actually see if anything goes wrong: `/l*v "install.log"`
Answer: The steps you are taking are not supposed to have the outcome you expect. As you briefly allude to, /a performs what is called an administrative install. This is not an installation of the software, but instead the creation of an uncompressed installation source. This is typically intended for a company to use in order to avoid having to physically share the installation disc (back when there were installation discs).
Your second command line has several errors:

/a still does not "install" the software
ALLUSER=2 is meaningless as the property ALLUSER is not defined. The correct property name would be ALLUSERS. You are probably looking for ALLUSERS=2 MSIINSTALLPERUSER=1 to invoke the Windows Installer 5 / Windows 7 or later per-user redirection. Note that MSIINSTALLPERUSER may not work correctly unless the package was authored with this so-called dual purpose in mind.
ARPSYSTEMCOMPONENT=0 might do the opposite of what you likely expect. Windows Installer works primarily on a defined/undefined (that is non-empty string vs. empty string) definition for truth rather than a 1/0 definition. While the documentation does say that setting it to 1 will prevent the application from being listed in ARP, the implementation likely checks for any non-empty string value. (Of course, per the first bullet it doesn't matter yet as you're not performing a normal installation.)

Your best bet is to acquire administrative privileges, in which case a simple msiexec /i package.msi will do the job. If you cannot acquire administrative privileges, and the package is authored appropriately, you may be able to install it with msiexec /i package.msi ALLUSERS=2 MSIINSTALLPERUSER=1. In either case you can also pass /qn or similar to suppress the UI, but I would suggest avoiding that until you have things working. As mentioned in a comment, adding /l*v verbose.log can help diagnose what's happening no matter the level of UI.
Comment: The 2nd command worked to get me around putting in Admin credentials, but I was prompted with the following error:

Error writing to file:
C:\Windows\system32\Drivers\fortiapd.sys. Verify that you have access to that directory.

Is there any way to get around this?
Comment: Unlikely. That appears to be (the first step of) installing a driver, which unequivocally requires administrative privileges. So this package is _not_ dual purpose. If the driver is not necessary, perhaps it can be removed with a transform, but only the vendor is likely to know the ramifications of such a change.
Comment: So it looks like I need to get the Admin credentials. If I were to get the credentials, would I be able to plug them into my installation command?

MSI Silent Installation not Working


Responsive media are not showing expected result

Question: I am working on a responsive screen. Result is not showing at certain point. Following example will help understand the mechanisam of my app. Kindly advice what exact media queries shall i apply to get all device result.
my code is
html, body{margin:0; padding:0; height:100%;}

.container{height:100%; width:64em; margin:0 auto}
.container header{height:12%; background:#D9DCA2; display: block; width:100%}
.container .wrapper{background:#EFF9B7; width:100%; height:88%;}
.container .wrapper nav{height:100%; background:#a1DFB9; position:relative; float:left; width:8%}
.container .wrapper article{height:100%; background:#FBF6CA; position:relative; float:left; width:92%}

@media only screen and (min-device-width : 1201px) {
    body{background:yellow}
    .container{width:100%; height:100%;}
    .container header{height:12%; background:#D9DCA2; display: block; width:100%}
    .container .wrapper{background:#EFF9B7; width:100%; height:88%;}
    .container .wrapper nav{height:100%; background:#a1DFB9; position: relative; float: left; width:8%}
    .container .wrapper article{height:100%; background:#FBF6CA; position: relative; float:left; width:92%}
}

@media only screen and (max-device-width : 1200px) {
    body{background:purple}
    .container{width:100%; height:100%;}
    .container header{height:8%; background:#D9DCA2; display: block; width:100%}
    .container .wrapper{background:#EFF9B7; width:100%; height:92%;}
    .container .wrapper nav{height:100%; background:#a1DFB9; position: relative; float: left; width:8%}
    .container .wrapper article{height:100%; background:#FBF6CA; position: relative; float:left; width:92%}
}

@media only screen and (max-device-width : 800px) {
    body{background:orange}
    .container{width:100%; height:100%;}
    .container header{height:10%; background:#D9DCA2; display: block; width:100%}
    .container .wrapper{background:#EFF9B7; width:100%; height:90%;}
    .container .wrapper nav{height:100%; background:#a1DFB9; position:relative; float: left; width:8%}
    .container .wrapper article{height:100%; background:#FBF6CA; position: relative; float:left; width:92%}
}

@media only screen and (max-device-width : 640px) {
    body{background:pink}
    .container{width:100%; height:100%;}
    .container header{height:14%; background:#D9DCA2; display: block; width:100%}
    .container .wrapper{background:#EFF9B7; width:100%; height:86%;}
    .container .wrapper nav{height:100%; background:#a1DFB9; position:relative; float: left; width:8%}
    .container .wrapper article{height:100%; background:#FBF6CA; position: relative; float:left; width:92%}
}

@media only screen and (max-device-width : 480px) {
    body{background:green}
    .container{ width:100%; height:100%}
    .container header{height:14%; background:#D9DCA2; display: block; width:100%}
    .container .wrapper{background:#EFF9B7; width:100%; height:86%;}
    .container .wrapper nav{height:100%; background:#a1DFB9; position: relative; float: left; width:8%}
    .container .wrapper article{height:100%; background:#FBF6CA; position:relative; float:left; width:92%}
}

@media only screen and (max-device-width : 320px) {
    body{background:blue}
    .container{ width:100%; height:100%}
    .container header{height:14%; background:#D9DCA2; display: block; width:100%}
    .container .wrapper{background:#EFF9B7; width:100%; height:86%;}
    .container .wrapper nav{height:12%; background:#a1DFB9; position: relative; float: none; width:100%}
    .container .wrapper article{height:88%; background:#FBF6CA; position:relative; float:none; width:100%}
}

</style>

    header

        navigation

article

Please advice. Thanks in advance. Keeping in mind that its for ie, firefox, chrome and safari.
Comment: Have you tried min-width and max-width instead of min-device-width and max-device-width? Just an idea.
Comment: Well how many jumps from screen to screen do i've to use.
Comment: If you do not know why certain things have certain results, simplify the problem. Instead of testing with fifty rules and seven iterations, simply use a single rule to change the background color of the page at a certain condition. Then listen to @Blackham and test using `min` and `max-width`s. You will learn a lot more.
Comment: that is what i am asking... 320min - 480max, 481min - ? and so on? didnt mean to throw anything on some 1.
Answer: Try this i hope it will be helpfull for you.

        Header

            Navigation

Article

        Footer


linear combination of certain complex numbers leads to ortogonality

Question: Please help me, sorry if it is dumb or too easy, but I'm really stuck.
I need to prove that: Let $X$ be an inner product space and $x,y\in X$.
If $\|x+\alpha y\|=\|x-\alpha y\|\:\forall \alpha\in \mathbb{C}$, then $\langle x,y\rangle=0$.
Expanding $\|x+\alpha y\|=\|x-\alpha y\|$, I got $\overline{\alpha}\langle x,y\rangle+\alpha\langle y,x\rangle=0$
The hint says I should take $\alpha=1,i$, so:
For $\alpha=1$,
\begin{equation}\label{e1}
\langle x,y\rangle +\langle y,x\rangle =0\quad (1)
\end{equation}
For $\alpha=i$,
\begin{equation}\label{e2}
-i\langle x,y\rangle +i\langle y,x\rangle =0 \quad (2)
\end{equation}
Subtracting (1) from (2) I got
\begin{align*}
(1+i)(-\langle x,y\rangle+\langle y,x\rangle)&=0\\
\langle x,y\rangle=\overline{\langle x,y\rangle}
\end{align*}
So $\langle x,y\rangle\in \mathbb{R}$, but I don't know how to get that $\langle x,y\rangle=0$.
I'm stuck there.\
I tried to add (1) and (2), getting
\begin{align*}
(1-i)\langle x,y\rangle+\overline{(1-i)\langle x,y\rangle}=0\\
\Rightarrow Re((1-i)\langle x,y\rangle)=0
\end{align*}
but also I don't know what to do next.
Comment: Divide (2) by $i$ before you subtract. Or add.
Comment: Thank you!! I got it
Answer: I'd recommend squaring both sides of the equation, and then using that for any vector $z$, $$||z||^2 = z^T \bar{z}.$$ Feel free to ask if you need additional hints!
Comment: Thanks :D and sorry, I forgot to mention that $x,y\in X$ where $X$ is an inner product space. So I think $\|z\|=z^{T}\overline{z}$ couldn't be helpful? I'm confused
Answer: Using conjugate symmetry property of inner product, we can slightly expand from what you have obtained:
$$
\begin{aligned}
0 &=
\overline{\alpha}\langle x,y\rangle+\alpha \langle y,x\rangle \\
&=
\overline{\alpha}\langle x,y\rangle+\alpha \overline{\langle x,y\rangle} \\
\end{aligned}
$$
Since the expression holds for all $\alpha\in\mathbb{C}$ and $\langle x,y\rangle\in\mathbb{C}$, we can choose $\alpha = \langle x,y\rangle$:
$$
\begin{aligned}
0 &=
\overline{\langle x,y\rangle}\langle x,y\rangle +
\langle x,y\rangle\overline{\langle x,y\rangle} \\
&=
2\left|\langle x,y\rangle\right|^{2}
\end{aligned}
$$
Comment: Thank you!! it would never have occurred that idea to me and it's really smooth :D
It it a better way of doing it instead of the hint given in my book :D
Thank you a lot
Comment: @AHexe no problem! If you find it helpful hope you don't mind to upvote it :)


how to make different sum over the same line in Spark

Question: I have a spark dataframe with, some numeric columns.
I would like to make several aggregationg operations on these columns creating a new column for each function, some of which may also be user defined.
The easy solution would be using dataframe and withColumn. For istance, if I wanted to calculate the mean (by hand) and the function my_function on fields field_1 and field_2 I would do:
df=df.withColumn("mean",(df["field_1"]+df["field_2])/2)
df=df.withColumn("foo", my_function(df["field_1"],df["field_2]))

My doubt is about efficiency. Each of the 2 above functions scans the whole database while a smarter approach would calculate both results using one single scan.
Any hint on how to do that?
Thanks
Mauro
Comment: if you want to do both computations in one setting, you can use `df.select("*", ((df["field_1"]+df["field_2])/2).alias("mean"), my_function(df["field_1"],df["field_2]).alias("foo"))` but it won't be more efficient. All the compuations will be done when you do an operation on the df (show, collect, write...) so it doesn't matter if you implement them sequentially or in one setting
Answer: TL;DR You're trying to solve problem which doesn't exist
SQL transformations are lazy and declarative. Series of operations is converted into logical execution plan, and then into physical execution plan. At the first stage Spark optimizer has freedom to reorder, combine or even remove any part of the plan. You have to however, distinguish between two cases:

Python udf.
SQL expression.

The first requires separate conversion to Python RDD. It cannot be combined with native processing. The second one is processed natively using generated code.
Once you request the results physical plan is converted into stages and executed.


Does drafting affect things other than speed?

Question: In Forza 5, you can draft opponents to relieve some drag and gain some more speed. Does this have any other affects on your car?
Answer: Yes, drafting has many other affects on your car. for example:

the lowered amount of drag means you have less downforce. Your braking and grip take a pretty noticeable hit when you draft into tight corners at high speeds
when you leave the draftstream your car may lurch because of the sudden change in drag (only noticiable on the really high powered cars, and with certain assists turned off [namely steering assist])
your fuel efficiency is improved as your car doesn't have as much air friction. (really only noticeable in endurance races)

On long straights you should definitely draft, but as you come up to corners leave the draftstream so you have your downforce and grip which is essential for proper cornering. when, where, and how to leave the stream is entirely situational to the track/corner/conditions/opponent position, though.


Prove that if $a^n\mid b^n$ then $a\mid b$

Question:
Prove that if $ a^n \mid b^n $ then $a\mid b$ (without use of GCD and factorization theorem).
Comment: Welcome. I don't know how you talk at home or with your friends, but here we enjoy a friendlier tone. In particular, some of us don't like being ordered to prove something, when being asked for help. Please phrase your question(s) a bit more politely. Thank you.
Comment: @AlexB. I'm so sorry about this subject for all visitors. I don't know about relationship in writing in in this site. before this comment, I think the question must be declared without exta subject as frank subject, I will do this in next topic and answer and respect to reader more and more.tnx
Answer: Suppose that $x=\frac pq$ where $p$ and $q$ are relatively prime; that is, there are $a$ and $b$ so that
$$
ap+bq=1\tag{1}
$$
Suppose that there are integers $c_k$ so that
$$
x^n+\sum_{k=0}^{n-1}c_kx^k=0\tag{2}
$$
Equation $(1)$ says $x=\frac{1-bq}{aq}$, and substituting into $(2)$ yields
$$
\begin{align}
0
&=\left(\frac{1-bq}{aq}\right)^n+\sum_{k=0}^{n-1}c_k\left(\frac{1-bq}{aq}\right)^k\\
&=\frac1{(aq)^n}
+\sum_{k=0}^{n-1}\binom{n}{k}\frac1{(aq)^k}\left(-\frac ba\right)^{n-k}
+\sum_{k=0}^{n-1}c_k\left(\frac{1-bq}{aq}\right)^k\tag{3}
\end{align}
$$
Multiply $(3)$ by $a^nq^{n-1}$ and move $\frac1q$ to the left side
$$
\frac1q
=b\sum_{k=0}^{n-1}\binom{n}{k}(-bq)^{n-k-1}
-a\sum_{k=0}^{n-1}c_k(1-bq)^k(aq)^{n-k-1}\tag{4}
$$
Everything on the right side of $(4)$ is an integer, so $\frac1q$ must also be an integer. Thus, $x=\frac pq$ is also an integer.
Therefore, any rational number $x$ which satisfies $(2)$ with integer $c_k$ must be an integer.

Finish off as awllower does. Let $x=\frac ba$. We are given that $x^n-k=0$ for some integer $k$. The argument above says that $x=\frac ba$ is an integer.
Comment: Intricate discussion of rational numbers. +1 Well done.
Comment: why we have for $({\frac{a}{b}})^n: x^n+\sum_{k=0}^{n-1}c_kx^k=0$?
Comment: @agustin: We are given that $a^n\mid b^n$ which means that $\left(\frac ba\right)^n\in\mathbb{Z}$, or equivalently, there is a $k\in\mathbb{Z}$ so that
$$
\left(\frac ba\right)^n-k=0\tag{$\ast$}
$$
Letting $x=\frac ba$, we see that $(\ast)$ is in the form of $(2)$, where $x$ is rational. The result above then says that $x=\frac ba$ is an integer. Thus, $a\mid b$.
Comment: **Simpler**: Bezout $\rm\color{#c00}{lead}$ term only. Let $\ x=\frac{p}q,\,\ ap\!+\!qb=1,\,$ and $\,\ 0\,=\,x^{n+1}+c_n x^n+\,\cdots\qquad$
$\tag*{}$
Note $\,(aq)^n \color{#c00}{x^{n+1}}\!=x(aqx)^n=x(ap)^n = x(1\!-\!qb)^n=x(1\!-\!qk)=\color{#c00}{x\!-\!pk},\,$ for some $\,k\in\Bbb Z\qquad$
$\tag*{}$
Also $\ (aq)^n (\color{#0a0}{c_n x^n + c_{n-1}x^{n-1}+\cdots)\, =\, m}\in\Bbb Z\ \ $ by $\ \ q^i x^i=(qx)^i=p^i\in\Bbb Z$
$\tag*{}$
$\,0=\,(aq)^n(\color{#c00}{x^{n+1}}+\color{#0a0}{c_n x^n+\cdots})\,=\,\color{#c00}{x-pk}\color{#0a0}{+m}\,\Rightarrow\, x = pk-m\in \Bbb Z\ \ \ {\bf QED}$ $\tag*{}$
Comment: The Rational Root Test can be proved without Bezout, e.g. [see here](http://math.stackexchange.com/a/658058/242) for a 2-line proof using [Euclid's Lemma.](http://math.stackexchange.com/a/847650/242)
Comment: Would the downvoter care to comment?
Comment: @BillDubuque: of course I was trying to be helpful. I did not want the author of the question to think there was something wrong with their answer, when there was not. I simply would not have left the comment since there was an answer showing an alternate approach. However, if necessary, I would have simply said, "your answer is fine, but I prefer to avoid the use of Bezout because..." You don't need to edit your comment to this answer since I know how you feel about Bezout. :-)
Comment: @robjohn Thanks for your insights. It did not occur to me that the author might interpret the comment as meaning something was wrong with the answer. Actually, thanks partly to your efforts, Bezout gets more respect from me these days. But those memories may fade if your Bezouka becomes a museum piece!
Answer: If $a^n|b^n$, then $b^n/a^n=(\frac{b}{a})^n$ is an integer. Since $\frac{b}{a}$ is rational, this implies that $\frac{b}{a}$ is an ordinary integer, by this theorem.
Q.E.D.
notice that the use of the theorem is suggested by @CalvinLin .
Comment: OK, provided OP is familiar with algebraic integers (and providing you can develop their theory without GCD and factorization).
Comment: You can just use the rational (integer) root theorem for the second line.
Comment: @CalvinLin This use of the Rational Root Test can be viewed more generally as the fact the GCD domains are integrally closed.  More generally these and related proofs (e.g. irrationality of radicals) can be done very elegantly by employing Dedekind's notion of conductor ideals (discussed in some of my prior posts).
Comment: Without any use of GCD nor factorisation theorems.
Comment: @CalvinLin Thanks for pointing out this! ^^
Comment: @awllower It's one of my favorite [uses](http://blog.brilliant.org/2013/01/02/theorems-on-rationals/) of the integer root theorem, as it demonstrates something more than "finding a root of a polynomial" to high school students.
Comment: @CalvinLin But it appears to use the concept of GCD implicitly; even the conclusion stems from the notion of GCD:How can you define the notion of division? By the GCD being equal to one of them? In any case, this looks better now. Thanks again!
Comment: @awllower I'm not sure the extent of what "without use of GCD} means (or what factorization theorem is). But the proof of integer root theorem just uses Euclid's Lemma (which arguable uses GCD?), and doesn't require to state that $\gcd(b,a)=1$.
Comment: It depends upon the explanations of OP.


Displaying additional information about elements in dropdown

Question: I need to let users pick 1 or up to many identifiers for an authentication process in a config setup. Each has a name (cant be changed, picked from a dropdown for now as seen below) and a label that can be edited by the user. There are 13 available identifiers to choose from, and each could need a little explanation.
With the current design I would need to use a tooltip or something similar to display information about each element in the dropdown list (or show it once an item is selected, but that is obviously cumbersome for the user). Any ideas of how I could design this in a better way, and let the user easily read information about each option?
Comment: How long are the explanations?
Answer: Google Analytics does this. You'll see this interaction in the Active Users Report when you try to build a condition. There are a large amount of specific dimensions to choose from, so these tips help quite a bit.

Here it is in action:
Comment: Thanks for your input. It doesnt suggest an alternative way of solving my problem, but its helpful to see that tooltips can be used this way. I might have to have longer descriptions in the tooltips however, and not sure how that would affect usability.


How to get object array from session stored with json.stringify?

Question: I have a class:
export class CartItem {
  productname!: string;
  quantity!: number;
}

I store an array of this in session as:
cartItems: Array<CartItem> = [];
...
...
sessionStorage.setItem("CurrentCart", JSON.stringify(this.cartItems));

When retrieving this, I tried:
this.cartItems = JSON.parse(sessionStorage.getItem("CurrentCart") || '') as Array<CartItem>;

But this returns:
Cart Items [object Object],[object Object],[object Object],[object Object]

and not the array with values.
From what I see in some examples Angular convert json to array of object, seems I need to map the array back or write a custom transformer https://medium.com/typescript-center/casting-json-objects-to-typescript-classes-a-deep-dive-835b8f8988bf
Is that the only way? Seems inefficient and cumbersome for bigger classes.
Comment: That should not happen and I sincerely doubt it actually happens. However, without a fully working example, it is hard to tell what and where things are going wrong. Please provide a working example demonstrating the problem.
Comment: The round trip to JSON just gives you vanilla objects, you can't serialise classes to JSON. So yes if you want to rehydrate class instances you have to have code to do that.
Comment: Is there a more efficient way to store and retrieve data in a session without having to parse every single time? We allow users to navigate all over the app and have cart visible
Answer: JSON.parse will not convert some arbitrary json to the CartItem class. It will simply convert a json string to json primitives (string, boolean, null, array, object).
You would need to implement some custom encoding/decoding. Example:
class CartItem {
  constructor(public productName: string, public quantity: number){}
  toJson(): any {
    return {productName: this.productName, quantity: this.quantity}
  }
  toString(): string{
    return `CartItem{${this.productName}:${this.quantity}}`
  }
  static fromJson(obj: any): CartItem {
    return new CartItem(obj.productName, obj.quantity)
  }
  static fromJsonList(obj: any): CartItem[] {
    return obj.map(item => CartItem.fromJson(item))
  }
}

class Cart {
  private cartItems: CartItem[] = []
  private static readonly STORE_KEY = "CurrentCart"
  function save(){
    const storedJson = JSON.stringify(this.cartItems.map(item => item.toJson()))
    sessionStorage.setItem(Cart.STORE_KEY, storedJson);
  }
  function load(){
    const storedJson = sessionStorage.getItem(Cart.STORE_KEY) || '[]'
    this.cartItems = CartItem.fromJsonList(JSON.parse(storedJson));
  }
}

Comment: Is there a more efficient way to store and retrieve data in a session without having to parse every single time? We allow users to navigate all over the app and have cart visible.
Comment: @BlahFoo I wouldn't worry about that. The performance hit should be negligible, unless you're doing it hundreds of times a second.


Would refilling an AC with refrigerant improve its performance after 8 years?

Question: I just got a little AC (8000 BTU). It works Ok, I guess its a bit small for the room (20m2) but even just bringing the temp down from 30C to 25C is enough of a difference to stop me from sweating.
I bought it second hand but it looks almost brand new, the previous owner used it for a few months and then had it in storage for 8 years. Question is though, how likely is it that some of the refrigerant has leaked over all those years? Would bringing it in for a refill likely make a difference?
I miss the winter and keep fantasizing of 16C.
Comment: Clean the filter,  evap and condensate coils....
Comment: What do you mean by AC?  Do you mean "window unit" or "portable" ?
Comment: Its one of those little ones where you stick the hose with hot air out of the window (or into a ventilation hole in the wall that goes outside in my case) @Harper
Answer:
how likely is it that some of the refrigerant has leaked over all
  those years?

Not very likely.
It's a pressurized system, so if you had a leak I would expect an 8 year period to be more than long enough for ALL the refrigerant to have escaped. There is a slight possibility of a seal partially failing and only letting refrigerant out when the unit is operating (pressure is greatly increased), but you would know pretty quickly - the cooling capacity would continue to decline as you use it, until it has little to no effect on the ambient air.

Would bringing it in for a refill likely make a difference?

That depends on the current charge level. An under/over charged unit will not perform to the manufacturer's specifications. Not having any leaks doesn't necessarily mean the system has the correct charge in it. But it sounds like you're talking about a portable unit that has probably never had any maintenance performed on it (so it should still have the factory charge, which should be correct).
Comment: To supplement this answer--assuming the unit has a satisfactory charge--you can try removing and cleaning its air filter, and you can also try to clean its coils, which will require removing the covering. If there is a slow-enough leak, and if it takes R134a (don't guess about this, there should be some sticker or otherwise near any serviceable parts) you might benefit from topping it off once or twice a season. There are [several YouTube vids demonstrating how to do this](https://www.youtube.com/results?search_query=refill+refrigerator+window+unit).
Comment: Note that a unit like this can be over filled ("over-charged"). If it is over-charged it will cool worse than if it has the correct charge.
Comment: Both overcharge and undercharge can cause the system to freeze and not cool efficently.
Answer: Give it a good cleaning to start with. Check to see that the fan is working as expected and the airflow is good. If that doesn't work scrap it and buy a new one. They're not made to be recharged.
Comment: A good spray with a garden hose and clipping the gfci off the end of the cord has 'fixed' 90% of every discarded window unit I've found in my alley. If it powers up and doesn't cool AT ALL, *then* it's actually garbage.
Answer: Small air conditioners are generally never meant to be recharged. They generally do not have access ports. They usually cost more to service than to get a new one. That being said the only reason to do anything with the refrigerant is if it is under charged. Just guessing and adding more will make it perform worse if it actually had the proper charge in the first place. At least in theory they should never require recharging. If it does you have a leak that needs to be fixed first.


A space homeomorphic to the connected sum $\mathbb{RP}^3$ # $\mathbb{RP}^3$

Question:
Problem    (1)  Consider the space $Y$ obtained from $S^2 \times [0,1]$ by identifying $(x,0)$ with $(-x,0)$ and also identifying
  $(x,1)$ with $(-x,1)$, for all $x\in S^2$.Show that $Y$ is
  homeomorphic to the connected sum $ \mathbb{RP}^3 $#$ \mathbb{RP}^3$.
(2)  Show that $S^2 \times S^1$ is a double cover of the connected sum
  $\mathbb{RP}^3$ # $ \mathbb{RP}^3$.

My main difficulty is that I cannot explain my proof and write down a rigor proof.
As for (1), if we decrease one dimension i.e.$ \mathbb{RP}^3 $ replaced by  $ \mathbb{RP}^2 $, I can explain it with some pictures.
However, in the case of (1), I cannot use any intuition to organize my proof. I also have same problem in (2). In fact, this is a qualifying exam problem and I hope I can write down a good answer for a test purpose.
Thank you!
Answer: $\newcommand{\Reals}{\mathbf{R}}\newcommand{\Proj}{\mathbf{P}}$Sketch: The space obtained from $S^{2} \times [0, 1]$ by identifying $(x, 1) \sim (-x, 1)$ and identifying $S^{2} \times \{0\}$ to a point is (pretty clearly) $\Reals\Proj^{3}$, viewed as a $3$-ball with antipodal identification on the boundary. Consequently, the space obtained from $S^{2} \times [0, 1]$ by identifying $(-x, 1) \sim (x, 1)$ is $\Reals\Proj^{3}$ with an open ball removed.
To express $S^{2} \times S^{1}$ as a double cover of $\Reals\Proj^{3} \mathop{\#} \Reals\Proj^{3}$, let $x$ denote a unit vector in $\Reals^{3}$, so $x \mapsto -x$ is the antipodal map of $S^{2}$; and let $\theta$ denote a real number in $[-\pi, \pi]$ viewed as an angular coordinate on $S^{1}$, so $\theta \mapsto -\theta$ is "reflection" of the circle.
The map $f:S^{2} \times S^{1} \to S^{2} \times S^{1}$ defined by $f(x, \theta) = (-x, -\theta)$ is a fixed-point free involutory homeomorphism. Projection on the second factor induces a map $p:(S^{2} \times S^{1})/f \to [-1, 1]$; the preimage of each endpoint is $\Reals\Proj^{2}$, and the preimage of each interior point is $S^{2}$. From this and the answer to Question 1, it's easy to see $(S^{2} \times S^{1})/f$ is homeomorphic to $\Reals\Proj^{3} \mathop{\#} \Reals\Proj^{3}$.
Comment: Sorry, I am a little confused with your exact meaning of the notation $S^2 \times S^1  /f$ and the followed argument.  Anyway, your sketch of (1) is really clear. Thank you
Comment: The map $f$ is a homeomorphism of $X := S^{2} \times S^{1}$ without fixed points, and is its own inverse; the quotient $M = X/f$ refers to the quotient space with $(x, \cos\theta, \sin\theta) \sim (-x, \cos\theta, -\sin\theta)$ [sic]. The map $$(x, \cos\theta, \sin\theta) \in X \mapsto \cos\theta \in [-1, 1]$$factors through $M$, defining $p:M \to [-1, 1]$. If $-1 < t < 1$, then $p^{-1}(\{t\}) \subset M$ is an $S^{2}$; if $t = \pm1$, then $p^{-1}(\{t\})$ is a projective plane, because the corresponding sphere in $X$ has been quotiented by the antipodal map. :)
Answer: Think of $S^2$ as the unit sphere in $\mathbb{R}^3$. Then define an embedding$$\varphi:S^2\times\left[0,\frac{1}{2}\right]\hookrightarrow\mathbb{R}^4,\quad((x,y,z),t)\mapsto(x,y,z,t).$$Let $\pi:\mathbb{R}^4\to\mathbb{R}\mathbb{P}^3$ be the quotient. Then $\pi\circ\varphi$ is a quotient map from $S^2\times[0,1/2]$ to $\mathbb{R}\mathbb{P}^3$ with an open ball removed. This should give you (1).


Error installing gtop on Ubuntu 22

Question: I just installed ubuntu on my work machine and trying to get gtop working on it. It's saying I'm missing the node:process package, but I'm not able to find any solutions. I figured that the easy install of npm and nodejs wouldn't have had any issues, but would greatly appreciate any guidance. Here's the steps I used to install gtop and the resulting error:

install npm and nodejs

sudo apt install npm nodejs

install gtop

sudo npm install gtop -g
And this is the error when I try to run gtop from the command line.
(base) octosaurus:~$ gtop
internal/modules/cjs/loader.js:818
  throw err;
  ^

Error: Cannot find module 'node:process'
Require stack:
- /usr/local/lib/node_modules/gtop/node_modules/marked-terminal/index.cjs
- /usr/local/lib/node_modules/gtop/node_modules/blessed-contrib/lib/widget/markdown.js
- /usr/local/lib/node_modules/gtop/node_modules/blessed-contrib/index.js
- /usr/local/lib/node_modules/gtop/lib/gtop.js
- /usr/local/lib/node_modules/gtop/bin/gtop
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
    at Function.Module._load (internal/modules/cjs/loader.js:667:27)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/gtop/node_modules/marked-terminal/index.cjs:3:17)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/usr/local/lib/node_modules/gtop/node_modules/marked-terminal/index.cjs',
    '/usr/local/lib/node_modules/gtop/node_modules/blessed-contrib/lib/widget/markdown.js',
    '/usr/local/lib/node_modules/gtop/node_modules/blessed-contrib/index.js',
    '/usr/local/lib/node_modules/gtop/lib/gtop.js',
    '/usr/local/lib/node_modules/gtop/bin/gtop'
  ]
}

Comment: You mention Ubuntu 22 in the title; but Ubuntu Core 22 cannot use `apt` or *deb* packages (is in final *beta* currently & due for release very soon). Are you sure you're using a 22 release, and not 22.04 ?  The *year.month* format products are different to the *year* or *snap* only products of Ubuntu.
Answer: It seems that my npm and nodejs were out of date. I upgraded npm by:
sudo npm install -g npm
I upgraded nodejs using the instructions by dylandhall here:
for anyone else with the same issue: delete the new package source:
cd /etc/apt/sources.list.d
sudo rm nodesource.list

update apt, fix the install, remove nodejs and the nodejs-doc packages
sudo apt --fix-broken install
sudo apt update
sudo apt remove nodejs
sudo apt remove nodejs-doc

then use the instructions to install the latest node
in my case:
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs

Error installing gtop on Ubuntu 22


Some excellent items may be permanently destroyed unless I act. What should I do?

Question: In Dungeon Crawl Stone Soup, I'm on a level with a vault. The vault contains stone-walled rooms that I still haven't found a way to enter. I've cleared the rest of the level though.
I heard one single solitary slurping sound. Then I walked around and searched for maybe 50 or 100 more turns. I haven't heard any more slurping sounds.
I fear that the vault contains really good generated items. Acquirement-class items. Plus, Crawl doesn't allow save scumming. So if the jelly eats the items, they'll be deleted from my savefile too. I'll never be able to get those items.
What should I do?
(Note: My character isn't a follower of Jiyva.)
Comment: On second thought, I plan to keep playing even without an answer. I realize that I'm playing Crawl to have fun, not to deal optimally with every single rare situation that comes up. If the items get destroyed because I didn't wait for an answer, then so be it. I'll still have fun.
Comment: That's the correct attitude.
Comment: [This wiki article talks about common vaults.](http://crawl.chaosforge.org/Example_Vaults)
Answer: Personally, I would not worry about it.  By the time you find a way in, the Jelly will be done clearing the vault.  However, Jellies don't eat artifacts, so I would find a way in at some point, just to check for those.
Non-artifact items are common enough throughout the game that it is not likely that you will miss whatever is in the vault.


Bootstrap 3 without Glyphicons replaced with Font Awesome

Question: I want to remove Bootstrap 3 Glyphicons in favor of Font Awesome. Since Font Awesome already includes most of the Glyphicons y don't want to include them and avoid duplicates and compatibility problems.
when I make a customized bootstrap download and I uncheck the glyphicon component, I still see some glyphicon references on the css file. http://getbootstrap.com/customize/
How can I disable those icons entirely ?
thanks
Answer: Those 6 remaining Glyphicons references in the compiled CSS are regarding the optional use of Glyphicons for the next+prev buttons in the Carousel component. Since the declarations in question are also used for the non-Glyphicon next+prev buttons and represent an absolutely trivial amount of the total file size, I suggest simply ignoring them. For all practical purposes, you've already eliminated Glyphicons from your build.
If you absolutely must annihilate said references, then compile Bootstrap manually, beforehand removing the offending lines from bootstrap/less/carousel.less and removing the @import "glyphicons.less"; line from bootstrap/less/bootstrap.less.
Or you can just manually edit the CSS that the Bootstrap Customizer already generated for you, since the relevant deletions are trivial.
Answer: As i use bootstrap with Font Awesome, i go to customize page and I unchecked the glyphicon component as you did, but for some time i also add this lines of code at my ( override file ):
[class^="icon-"],
[class*="icon-"] {
  background: none;
}

also you can open the main bootstrap file that you downloaded ( customized one ) and search for font-family: 'Glyphicons Halflings'; , then comment all the @font-face.
Hope this will help you
Answer: Solution for less (tested for bootstrap 3.3.5):
First, override icons for carousel:
// Overloading "glyphicon" class with "fa".
.glyphicon
{

    &:extend(.fa);

    // Overloading "glyphicon-chevron-left" with "fa-arrow-left".
    &.glyphicon-chevron-left
    {
        &:extend(.fa-chevron-left);
    }

    // Overloading "glyphicon-chevron-right" with "fa-arrow-right".
    &.glyphicon-chevron-right
    {
        &:extend(.fa-chevron-right);
    }
}

This part is taken from Slava Fomin answer, based on Steven Clontz's  base code.
Next step: disable glyphicons loading:
//** Load fonts from this directory.
@icon-font-path:          "../fonts/";
//** File name for all font files.
@icon-font-name:          "fontawesome-webfont";
//** Element ID within SVG icon file.
@icon-font-svg-id:        "fontawesomeregular";

Do not forget about lessc lazy loading: @icon-font-svg-id and other vars will have the latest value you have set.
Comment: Over here you can find a SCSS variant: http://stackoverflow.com/questions/26638215/how-to-replace-glyphicons-with-fontawesome-in-bootstrap-3-without-changing-html


How do I create a Terraria server on my Android phone?

Question: Me and my friend are wanting to play Terraria mobile version 1.3 and we both don't know how to create a server. Can someone help? We are not using the same wifi and want to play online multiplayer.
Answer: I have never created a mobile server, but you can try this:
Hosting via mobile device:
What you need:

You need to be on Wifi
Need a new and good device to host the server

What you have to do

Tap on multiplayer menu and choose the host option --> now you are hosting a multiplayer session
To play online you need to forward the port 7777. There are tons of guides in the internet how to forward ports
You MUST use the internal IP adress tied to your devicein the port forwarding process. You find the the internal IP here:
ANDROID:
Go to "Settings" and tap on "Wi-Fi" settings".
Here tap and hold on your connected network and then select "Manage network settings".
Now check the checkbox next to "Show advanced options" and select "Static" under "IP settings"
You'll find the device internal IP address under the "Gateway" section.
iOS:
Go to "Settings"
Tap on Wifi
Tap the little i button with a circle around it located next to the wifi network to which you are connected.
You'll find the device internal IP address next to the second entry labeled "IP Address"
Find out your external IP. Can be found here https://www.whatsmyip.org/
Now everybody can enter your server with the external IP and the port 7777
Comment: sadly i dont have a pc, but thanks anyways
Comment: I found a solution that does not require a pc


Sending response to the formpanel in gwt from servlet

Question: I am calling servlet from the gwt client program and setting
final FormPanel form = new FormPanel();
form.setMethod(FormPanel.METHOD_POST);
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setAction(GWT.getModuleBaseURL()+"/uploadservlet2");

Now on submit complete I want to retrieve a parameter from the servlet in this event,
 form.addFormHandler(new FormHandler() {
      public void onSubmit(FormSubmitEvent event) {
        // This event is fired just before the form is submitted. We can take
        // this opportunity to perform validation.
                RootPanel.get().add(new Label("On submit"));
      }

      public void onSubmitComplete(FormSubmitCompleteEvent event) {
**///I want parameter here**
                RootPanel.get().add(new Label("On submiting complete"));
      }
    });

Please tell me how I can do it.
Answer: in your onSubmitComplete:
public void onSubmitComplete(FormSubmitCompleteEvent event) {
String serverResponse = event.getResults();

}

you can let the server return HTML and put this in an HTML widget, or let the server return som JSON and parse this in GWT.