Format current date and time in VBScript

Question: I was wondering if someone could help me.
I'm very new at ASP I want to format the current date and time as follows:
yyyy-mm-dd hh:mm:ss

But all i can do is the following
Response.Write Date

Can someone help me out please.
Answer: Date formatting options are limited in Classic ASP by default, there is a function FormatDateTime() which can format your date is various ways based on the servers regional settings.
For more control over date formatting though there are built in date time functions

Year(date) - Returns a whole number representing the year. Passing Date() will give back the current year.

Month(date) - Returns a whole number between 1 and 12, inclusive, representing the month of the year. Passing Date() will return the current month of the year.

MonthName(month[, abbv]) - Returns a string indicating the specified month. Passing in Month(Date()) as the month will give back the current Month string. As suggested by @Martha

Day(date) - Returns a whole number between 1 and 31, inclusive, representing the day of the month. Passing Date() will return the current day of the month.

Hour(time) - Returns a whole number between 0 and 23, inclusive, representing the hour of the day. Passing Time() will return the current hour.

Minute(time) - Returns a whole number between 0 and 59, inclusive, representing the minute of the hour. Passing Time() will return the current minute.

Second(time) - Returns a whole number between 0 and 59, inclusive, representing the second of the minute. Passing Time() will return the current second.

IMPORTANT:
When formatting date / time values, always store the date / time value first. Also, any needed calculations (DateAdd() etc.) should be applied before attempting to format or you will get unexpected results.

The functions Month(), Day(), Hour(), Minute() and Second() all return whole numbers. Luckily there is an easy workaround that lets you pad these values quickly Right("00" & value, 2) what it does is append 00 to the front of the value then from the right take the first two characters. This ensures that all single digit values return prefixed with a 0.
Dim dd, mm, yy, hh, nn, ss
Dim datevalue, timevalue, dtsnow, dtsvalue

'Store DateTimeStamp once.
dtsnow = Now()

'Individual date components
dd = Right("00" & Day(dtsnow), 2)
mm = Right("00" & Month(dtsnow), 2)
yy = Year(dtsnow)
hh = Right("00" & Hour(dtsnow), 2)
nn = Right("00" & Minute(dtsnow), 2)
ss = Right("00" & Second(dtsnow), 2)

'Build the date string in the format yyyy-mm-dd
datevalue = yy & "-" & mm & "-" & dd
'Build the time string in the format hh:mm:ss
timevalue = hh & ":" & nn & ":" & ss
'Concatenate both together to build the timestamp yyyy-mm-dd hh:mm:ss
dtsvalue = datevalue & " " & timevalue

Call Response.Write(dtsvalue)

Note: You can build the date string in one call but decided to break it down into the three variables to make it easier to read.

How Can I Format Date
Example of Parsing a Date String (Answers provide approaches to taking a date string format and parsing it to a valid Date variable).
Format the date of the previous day format yyyymmdd with VBScript  (Example of why storing date / time before performing formatting is important)
VBScript ISO8601 (Example of functions to construct an ISO 8601 compliant date string)
Comment: The OP doesn't appear to need it, but there's also the MonthName(mm,abbr) function - mm is the month number, and abbr is a boolean indicating whether to abbreviate the month name or not.
Comment: You can simplify more, instead format_zeros use this other format: right("00" & month(date()),2) same format for day and year
Comment: @ Lankymart you should use the shortcut you provided to me to revise your answer here like, tmp = Right("00" & Hour(Time()), 2).  Couldn't you dump the format_zeros() function then? I appreciate you letting some of us others answer questions when I'm sure you could easily.
Comment: @kneidels In that scenario `00` isn't required but if I was passing a variable in (not `Day(dtsnow)`) and it's value was null or empty I'd want it to default to `00`.
Comment: @Martha Yeah, didn't include it as it wasn't relevant to the date format the OP wanted to achieve.
Comment: @Mastercafe That is also true.
Comment: @Jake Yeah I need to go back and revise this answer.
Comment: It never ceases to amaze me how ridiculous complex and faffy VBScript can manage to make even the simplest of tasks that can be accomplished with half a line of code in any sane language…
Comment: @JanusBahsJacquet is a scripting language that is over 20 years old.
Comment: Why does the padding need **2** zero's (as in `Right("00" & Day(dtsnow), 2)` - surely **one** zero should be enough, seen as at minimum, the day,month,hour etc will have one digit: `Right("0" & Day(dtsnow), 2)` ?


Why Jest is not letting me use node testing environment even though they changed it themselves?

Question: I am trying to test a React component in Next.js with Jest.
Jest officially announced that they are changing the default test environment to Node:

For this reason, we are changing the default test environment from
"jsdom" to "node".

I need to use the Node environment and they are not letting me.
I am receiving the following error:
  ● basic test

    The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
    Consider using the "jsdom" test environment.

    ReferenceError: document is not defined

      40 | it("basic test", async () => {
      41 |   render(<Hellopage />);
    > 42 |   expect(true).toBe(true);
         |                 ^
      43 |   screen.debug();
      44 | });
      45 |

      at Object.render (node_modules/@testing-library/react/dist/pure.js:83:5)
      at Object.<anonymous> (components/__test__/hellopage.test.tsx:42:17)

The reason I need to use node is that Firebase Firestore is not working under JSDOM.
How can I fix this error?
Comment: It _is_ letting you use the Node environment. It's failing because that environment doesn't include definitions of things like `document`, which are part of the DOM API (and hence provided by JSDOM) and **not** in Node.
Comment: Because the default test environment is now Node, which is for... a Node environment. **Not** the DOM environment, which is where React (however simple a component) runs. Developers testing code for the DOM environment are supposed to use a testing environment that provides the DOM APIs, like JSDOM.
Comment: @jonrsharpe is there a way for me to get these definitions and still use node, as the firebase require it for testing?
Comment: You'd have to provide them into the global scope for the tests yourself. Basically you'd be rewriting some subset of what JSDOM provides. It's unclear what specific problem you had that pushed you in this direction to begin with; you might be better off asking with a [mre] of that, this could be an [XY problem](https://meta.stackexchange.com/q/66377/248731).
Comment: @jonrsharpe When I am using jsdom testing environment I get error : "FIRESTORE (9.1.3) INTERNAL ASSERTION FAILED: Unexpected state".
Sorry, but im very lost, how come the default testing environment that jest comes with can't render the simple react component, what else are developers supposed to test it?
Comment: Or more broadly: they changed the default because not everyone who wants to test JavaScript code is using React, or the DOM at all (from the doc you quoted and I linked: _"Running tests in a JSDOM environment incurs a significant performance overhead... users who are writing Node apps, for example, may not even know they are given an expensive DOM environment that they do not even need"_).
Answer: If you are unit testing a React component, you definitely need the jsdom testing environment. But what you're trying to achieve is to test the UI, not the database access. If you access external resources it's not unit testing anymore, it's integration testing.
What you want to do is to decouple the UI component from the database queries, so that your tests can provide fake data without hitting the database. Similarly if your component writes anything to the database, it could do it through a function that your tests are providing instead of the one you use in production.


Is there a connection between $a \nmid b$ and $ax + by = d$?

Question: I should point out that I am not very good at mathematics. For example if $3 \nmid n$ is it true that $3x + ny = 1$? If $a \nmid b$ then $a$ and $b$ have no common factors. However $14 \nmid 21$ but $\text{gcd}(14,21) =7$ so does that mean that $14x +  21y = 7$. The question: Is there a connection between $a \nmid b$ and $ax + by = d$ and how do you express $a \nmid b$ as $ax + by = d$ (that is if that is possible).
Comment: If $a,b$ have a common factor then the least positive integer expressible as $ax+by$ is their gcd.  The condition $a\nmid b$ is not sufficiently informative; it can be true with their gcd as 1  or gcd > 1.
Answer: The equation $aX+bY = d$ can be solved in integers if and only if $\gcd(a,b)\mid d$. A relevant keyword is Bézout identity.
The condition $a \nmid b$ does not guarantee this in general, yet if $a$ is a prime number  then $a \nmid b$ is equivalent to $\gcd(a,b)=1$.
On the question on how to express $a \nmid b$ via such an equation, one could say that the following are equivalent:

$a \nmid b$
there exists a $d$ that is not a multiple of $a$ such that $aX+bY = d$ has a solution.
there exists some $1 \le d \le |a|-1$ such that $aX+bY = d$ has a solution.


PVC electrical conduit connection to service panel

Question: I am installing an outdoor conduit that consists of four #8 AWG THHN wires inside gray 1" PVC. I need to hook it up to the main service panel and I am not sure what's the best way to do it.
I understand I can install an adapter that hooks the PVC pipe, or some other conduit, directly into a knockout in the panel. The problem is that the panel is not easily accessible without tearing down chunks of the wall on which it hangs (it's solid drywall behind the panel and stucco all around).
Or I could terminate the pipe at a conduit body near the panel, drill a 1" hole in the stucco, route the wires into the wall through the hole and somehow fish them out into the service panel through an available knockout. But then some section of the wire (maybe 6-12" long) would hang inside the wall without any conduit around it.
Is that acceptable by the code or do I need a continuous conduit all the way to the panel?
Answer: Short answer: no it is not acceptable it needs to be continuous.
The pertinent article of the National Electrical Code follows:

300.12 Mechanical Continuity — Raceways and Cables
  Metal or nonmetallic raceways, cable armors, and cable sheaths shall be continuous between cabinets, boxes, fit- tings, or other enclosures or outlets.

You could terminate the conduit into a junction box and then take a cable that is approved to be fished into walls (NM or MC) from there. Then make joints in the j-box. However, the j-box has to be accessible after it is installed.
Good luck with your project!
Comment: Is THHN not approved to be fished into walls? And if it's NM/MC, do I need any sort of seal/connector in place of the knockout where the cable goes into the panel?

Splicing with NM in a junction box is a way to do it but it would require amending the permit (and I don't see the point of having the splice).
Comment: THHN is not approved without a raceway. Yes, NM and MC both need a connector where they are connected to the panel. We use a short piece of tie wire or fish tape to attach the wires of the cable and pull them back into the panel then slide the locknut up the tie wire until you can secure the connector. Working in a panel is dangerous it should all be de-energized before you begin work.
Comment: Yup, that's how you do it. Terminate in any junction box (not a conduit body), and then change wiring type for the last section, making the splice inside the junction box.  They do make fittings to support NM cable entering a junction box, and you must use them.
Comment: I thought a conduit body is considered a type of junction box? I have another conduit (though this one is metal) terminating in a conduit body right next to the panel, installed by one of the previous owners.

Is there a maximum length of NM I am allowed to have between the junction box and the panel without having to staple it to a stud?
Comment: "Only those conduit bodies that are durably and legibly marked by the manufacturer with their volume shall be permitted to contain splices, taps, or devices." 314.16(C)(2) NM cable needs to be secured within 12 inches of a J-box or panel and every 4 ½ feet thereafter. That means even a short length should have at least one staple.


How many wires should be in a new thermostat cable?

Question: When roughing in thermostat wire, how many pair wire would you use to cover most   thermostats?
I'm asking because keep seeing questions about C wire and wifi.
Comment: What is normal,? No less than 5.
Comment: @manassehkatz Same number *plus one* typically, for C.
Comment: WiFi is actually quite the opposite - cuts down on the need for wires. But typical is a WiFi thermostat in the location of a regular thermostat - same number of wires as "normal". Also, unlike phone/ethernet/etc., thermostat wire is a bunch of separate wires, not actually pairs.
Answer: If you're building a new building and having new HVAC installed, I would simply put 1/2" conduit in the wall and be done. That way, you let the installer run the wire they need. I don't know that I would do this without at least consulting an HVAC installer to see where they would put the unit and the air return (typically the thermostat is as near the return as possible).
If you're going to just pre-run wire and dictate where the return will be and the HVAC unit will sit, I would run 18/5 wire if you know you will have a AC + gas heat, and 18/8 if you know you will have a heat pump (if you're in doubt, more will not hurt). Your most basic setup on most modern units needs 4 control wires plus the fifth blue "C" wire that provides power to the thermostat. It won't cover anything elaborate like a heat pump, but your greatest risk would be the installer uses your wire to pull the wire they actually need.
Comment: If running a cable instead of putting in conduit, I would err on the side of "extra". We're talking about literally just a few dollars for a typical run between 18/5 and 18/8. If the installer ends up needing more than a basic 5 wires, it will cost a **lot** more to fix it later.
Comment: @RobertMoody Not at all. Costs a bit more is all
Comment: Is extra bad? 5 seems to be ok  8 seems to cover the unknown.
Answer: For traditional Heat + Fan + AC systems, you need 4 for the system to work at all, and 5 if you want to support the C wire for smart 'stats.
However when you get into heat pump and multistage systems, just throw an 8 in there - it's readily available and not that much more expensive.  You're not going to get very many latté's with the cost savings from using 4-wire.
Comment: I personally would run an 18/10 or 18/12 depending what was available to me, if I didn't already have some ENT roaming around the job that is ;)
Answer: I'd use 20/8 which is pretty standard today.  That will cover anything up to a 2-stage heat pump system. I'm not sure how WiFi factors in here.  An smart/electronic thermostat like a Nest does support WiFi but not between the HVAC unit and the thermostat.
Comment: "FOR THE FUTURE", RUN CONDUIT NOW. Conduit is the **most future-proof technology there is** for wiring. Pull out the obsolete, pull in the up to date, done.
Comment: When using 20/8 does it leave extra wires in case one gets nicked?
Comment: It's not common to run extra wires in anticipation of damage. If you expect it, run conduit.
Comment: Not so much anticipation of damage.But for the future.


Appium on Windows for Android : Command failed: can't find 'C:\Program' to install

Question: Attempting to just start up Appium with an emulator using an example program.
Output:
debug: executing: "C:\Program Files (x86)\Android\android-studio\sdk\platform-tools\adb.exe" -s emulator-5554 install C:\Program Files\Appium\node_modules\appium\build\unlock_apk\unlock_apk-debug.apk
warn:  killed=false, code=1, signal=null
info: Stopping logcat capture
info: Sent shutdown command, waiting for UiAutomator to stop...
warn: UiAutomator did not shut down fast enough, calling it gone
info: Cleaning up android objects
info: Cleaning up appium session
error: Failed to start an Appium session, err was: Error: Command failed: can't find 'C:\Program' to install

info: Responding to client with error: {"status":33,"value":{"message":"A new session could not be created. (Original error: Command failed: can't find 'C:\\Program' to install\r\n)","killed":false,"code":1,"signal":null,"origValue":"Command failed: can't find 'C:\\Program' to install\r\n"},"sessionId":null}
POST /wd/hub/session 500 11733ms - 316b

Tried with an emulator with the apk already installed and a fresh emulator, get the same result.
code:
DesiredCapabilities caps = new DesiredCapabilities();
    caps.SetCapability("device", "Android");
    caps.SetCapability("browserName", "");
    caps.SetCapability("app-activity", "MainActivity");
    caps.SetCapability(CapabilityType.Version, "4.2");
    caps.SetCapability("app-package", "com.example.android.interactivechart");
    caps.SetCapability("app", @"C:\scm\InteractiveChart\out\production\InteractiveChart\InteractiveChart.apk");

RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4723/wd/hub"), caps, new TimeSpan(0,5,0)); //error here

Anyone know why it's doing this? I've had a look around and I can't find anything. It's probably something simple but the 'C:\Program' is throwing me since I don't pass in anything containing this.
Edit: added windows tag as the default install locations were the source of the issue
Answer: I don't know anything about Appium but it seems like it has a problem with the directory name,The  directory should not have a space while using some command line tools,move the Android sdk and Appium folders to a directory with no spaces (like to C:) and try the command with that directory.
Comment: I agree this is a possibility but since this is on windows I'll have to re-install the whole android studio to a custom location to test it, I'll be a while.
Comment: no need,just need to copy the sdk folder to any other location and run the command
Comment: All the devices are in the studio as well, the whole thing would need to be moved. Already tested with just copying the sdk(and changing the path variable) and appium directories out to C:
Comment: The devices(u mean AVDs?) are in %USERPROFILE%/.android folder there's  no problem in moving the sdk folder or the android studio folder itself to another folder since android studio does not have any registry entries( at least nothing that can be re-configured )
Comment: ahh no you were right I take it back, no idea why it failed the first time but its running now with appium and the sdk moved out. Irritating since they are in standard windows install folders.


Non-standard back button in Action Bar Android

Question: I've seen in several apps a non-standard back button (image #2) in the action bar,
Normally when I config a navigation drawer or the setDisplayHomeAsUpEnabled it just looks like image #1
How can i accomplish the non-standard style?
Comment: It looks like the standard home button to me.
Answer: That is not a back button. It is sometimes called a "hamburger icon", and it is specifically used for indicating the presence of DrawerLayout navigation. You can find more information in the Android documentation. You can see more about the icon's functionality here.
Comment: I'm not reffeering to the tree lines of the navigation drawer, I'm talking about the button contains text and is larger that the standar back button
Comment: [Other example](http://i.stack.imgur.com/581pV.jpg") of the non-standar back button
Comment: I'm sorry for the misunderstanding. I believe this is the standard behavior of the back button + Action Bar title on Android 4.2 and above. Try checking it out on a 4.2 device or emulator to see what I mean. Unfortunately, I don't know how to emulate that behavior in previous versions of Android.
Comment: My phone is running 4.1.2 and I'm getting apps like facebook messenger with the back button extended with the action bar title


Does Ubuntu support AMD Ryzen APUs with Vega 8 Graphics?

Question: I'm trying to install Ubuntu on my new laptop. It is a Lenovo Ideapad 330s-15ARR with a Ryzen 2500U APU with Vega 8 Graphics, 12GB of RAM, and a 128GB M.2 NVMe boot  SSD. I have downloaded the most recent ISO of Ubuntu and flashed it onto my usb drive. Tested it on my main computer, where it works perfectly and I can boot into Ubuntu. However, on my laptop, I get to the boot screen where I select whether to install, or test without installing. And I have tried both (and with their safe options) and I just get a black screen after. Nothing happens. My BIOS is up to date. All that I'm left to assume is that it has something to do with support for Vega 8 Graphics on APUs. I tried the most recent Ubuntu LTS (18.04.3) and the most recent new version of Ubuntu (19.10). They both have the same issue. I have gotten Manjaro (KDE Plasma 18.1.5, XFCE 18.1.5 had strange random artifacting issues) installed and working perfectly. However I would like to install Ubuntu and use it instead. Is there anything I can do? I've heard some people have gotten Ubuntu working on the same APU and haven't even had the issues I have so I'm not sure what's going on.
Comment: Check again for a BIOS update, and also check for any SSD firmware updates.  Any additional hardware, like Nvidia in the machine?  19.10 kernel should be good for your 2500U. A friend got a 2400U+Vega working with BIOS+5.0 kernel.
Comment: @ubfan1 Everything is as up to date as it can be. And there's no Nvidia hardware, it's using the Vega 8 integrated graphics on the 2500U. So I'm very unsure as to why it's happening.
Comment: See if acpi=0 on the grub linux boot line gets you running in a limited fashion (like with only 1 CPU).  If that works, try other acpi=xxx things which might not be as drastic.
Comment: I'm on mobile and on the way to an NYE party so I can't check right now but Google "2500U raven_dmcu.bin" see if you can get into recovery mode to delete this file in firmware folder
Comment: @Tek There is no recovery mode. The SSD in the system currently only has Manjaro installed. I have the Ubuntu ISO flashed onto a USB for install so there's no recovery mode for me to do anything like that. I saw similar things with the raven dmcu bin file before but I have a bigger issue it seems.
Answer: I found another question from October that had the same issue that I had, and found that the answer did fix my problem. Secure Boot needed to be disabled (which I already had done). And APIC support needed to be disabled at the boot. I followed the intructions in the following post for that and got Ubuntu installer from my flash drive to boot up and was able to install it to my NVMe SSD. The trackpad didn't work on the live Ubuntu build while installing, but after installing it and allowing the installer to download all necessary drivers Ubuntu boots up perfectly and my trackpad works perfectly.
See answer here:
Trying to install Ubuntu 18.04 on Lenovo 330s ryzen 5 2500u


Show only once a div per user

Question: I´m new in Javascript and i´m trying to do a animation a "terms and conditions" of the website, and it works!
Now I just trying to use cookies to show only once the "terms and conditions" until a new version of the "terms and conditions", but it not working!
This accept terms will be used in a wordpress site.
I don´t know what is wrong
Any tips, articles, anything else will be a great useful

document.cookie="username, expires= Sat, 31 Dec 2016 12:00:00 GMT";

$('txt .avia-button').click(function()){
    if ($.cookie('#txt .avia-button')) $('#txt').animate();
    else {
        $('#txt .avia-button').click(function(){
            $('#txt').animate({
         bottom: '-300px',
  height: 'toggle',
            });
        });
    }
});
Comment: `$.cookie('#txt .avia-button')` so do you store a cookie value for that?
Comment: Alternate to using a cookie, you can use HTML5 localStorage to store a boolean if they have already read the Terms. It is a lot easier for people to block cookies than it is to block localStorage.
Comment: `$('txt .avia-button').click(function()){` is missing a `#`
Comment: `document.cookie="username, expires= Sat, 31 Dec 2016 12:00:00 GMT";` should be inside an if statement somewhere where you show your terms and conditions
Comment: You've got a click event nested inside a click event (probably not what you want)
Comment: yes! @epascarello  '$.cookie('#txt .avia-button)' will make the "terms" dissapear
Comment: @SeuZeRicardo Where do you set it?
Comment: @epascarello in a custom.js
Comment: @Korgrue i see the localStorage but in Brazil, many users don´t have a browser updated, so i prefer using cookies ... Thanks!
Comment: @RobertMcKee This 'if' is to verify that the button has been clicked, at least that's what I wanted to do
Comment: @SeuZeRicardo You know your audience far better than I do, so if you know the majority of your potential users will be hitting your site with non HTML5 compatible browsers, then yes - definitely use cookies over localStorage.
Comment: @RobertMcKee The code will be like this ?
'$('#txt .avia-button').click(function()){
   if ($.cookie('#txt .avia-button')) $('#txt').animate();
   else {
    $('#txt .avia-button').click(function(){
     $('#txt').animate({
      bottom: '-300px';
      height: 'toggle';
      document.cookie="username, expires= Sat, 31 Dec 2016 12:00:00 GMT";
     });
    });
   }
  });'
Comment: How about using AJAX to query the database or whatever storage you are using to find out whether a new terms and conditions has been released. Other wise can you not use session storage to see if your terms and conditions has been shown once or more.
Answer: Something like this:
if ($.cookie('seenTOS')!='1'))
{
  $('#txt').hide();
}
$('#txt .avia-button').click(function() {
    $.cookie('seenTOS','1', { expires: 7, path: '/' });
    // Show #txt
    $('#txt').animate({
        bottom: '-300px';
        height: 'toggle';
    });
});

Show only once a div per user


How can the shortcut doors be used effectively?

Question: Throughout the game you come across "shortcut" doors marked with intersecting squares.  Is there any way to predict where these doors will take you without just going through?  It seems they are intended as a shortcut, yet they don't seem to show a preview of the destination like normal doors, and the connections don't seem to appear on the main map.  This makes them hard to use as a shortcut unless you have a photographic memory of their locations.  Am I missing something?  Do they serve some other non-obvious use?
Comment: I finished the game without ever using those effectively, and I wondered this too
Answer: They're mostly useless. They usually lead to the nearest warp area or a room near it. They don't have any other use. It is almost always easier to seek out a known route instead of guessing where these doors might lead.


Find all classes availible at runtime java

Question: I am attempting to find the names of all classes available at runtime in Java and have had some success using reflection in Guava with code such as:
ClassPath classPath = ClassPath.from(ClassLoader.getSystemClassLoader());
contextClasses = classPath.getAllClasses();

This appears to work to some extent getting me about 2500 class names, however it does not find all of them, in particular the java.lang, java.util, etc. classes which i really do need to know about.
Is there a different class loader I should be using for this?  I have also tried
Thread.currentThread().getContextClassLoader()

Any pointers would be much appreciated.  Thanks
Ewen
Further detail about solution.
I used further information from this post: How can I list all classes loaded in a specific class loader to actually implement the solution suggested in the answer.  This seams to get all of the standard java libraries (some 500 ish) but not the ones I go in my method previously.  I could combine with the previous to get everything I need.
Thanks to everyone for their help.
Comment: system classes are loaded by bootstrap class loader, it is null e.g. java.lang.String.class.getClassLoader()
Comment: try using java instrumentation framework, it won't disappoint you.
Answer: For a post 1.5 JVM, you can use http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html#getAllLoadedClasses().


How can I isolate an indoor water pipe to prevent freezing?

Question: In my basement I have a 1/2" copper water pipe that goes to an outdoor faucet for a garden hose/sprinkler. This line has its own shutoff, so during the winter it is turned off and emptied.
The problem is that about 15 feet from the exterior wall the pipe reaches a critical junction in the water lines. If it gets really cold outside, below 10F, the pipe will transmit the cold all the way to this junction and freeze it and then the water supply to the whole house is cut off. I have used heat tapes, propane torches etc to solve the problem when it crops up, which is once every 5 years or so.
However, what I would really like to do is install a passive (non-energy-using) solution to get rid of the problem permanently.
What I envision doing is installing some kind of thermal isolator in the line to the faucet. So, for example, if I replaced say a 12" length of the pipe with a PVC pipe it would probably solve the problem because the PVC will not conduct the cold nearly so well as the copper, so basically the PVC should "thermally isolate" the faucet. That's my theory at least. Another option would be to create a removable link or section in the pipe. The section would be removed/disconnected in the winter, then connected back up again in the spring.
Is there a way to do either of these things?
Comment: I think you need to look for some other culprit here.  I'd be really very surprised if the empty copper pipe is conducting enough heat to freeze pipes 15 feet inside of the basement.  We get much colder here (-15F) and I have a typical sillcock, with a shutoff at the junction that doesn't freeze upstream connections only 2-3 feet away in my crawlspace, even when I'm using the wood burner extensively (so the furnace in the crawlspace isn't running).
Comment: I'd agree with CoAtroGeek.  It's currently 2 degrees where I live, and I have a metal spigot outside.  It gets colder than 55F in my basement.  Crazy cold here is -25F, and it certainly got that cold last winter for several hours.  We have days where it never gets above zero the whole day.  I've never had problems with a spigot leaking enough heat to freeze a junction, and there's no heat tape or insulation around the pipes.  The junction is perhaps 10 feet away.  So I'd say your problem is the air getting cold, not the copper leaking heat outside.
Comment: @CoAstroGeek That is, indeed, what is happening. The basement is pretty cool (about 55 F typically) to begin with, since it is unheated. I can actually measure the temperature along the copper line using the bulb of a thermometer so I know that is what is happening. The cold is actually creeping down the pipe until it reaches the junction.
Comment: I'm sure my crawlspace is no warmer.  15' is a long way in a 55 degree space - I've never seen empty pipes conduct enough heat to freeze stuff even a few feet in.  If that were the case, all the plumbing underlying my kitchen & bath should freeze solid.  Are you sure it's freezing there and not someplace else upstream?
Comment: @CoAstroGeek Look, I know what's happening. There is a big metal spigot on the outside of the house that is acting like a cold sink. The pipe connected to that faucet is then transmitting the cold to the junction. If I heat up the junction with a propane torch water starts flowing again, its that simple. This only happen happens if it gets crazy cold outside, like below 10F for 24 hours or more.
Comment: Ok, just trying to save you the trouble of working on something that I don't think will fix your problem. If copper pipes could conduct enough heat to freeze pipes 15 feet away in a 55F basement at only 10F outside temp, then this would happen all the time.  I've never seen it happen. It's always much closer to a wall, in a draft or in an unconditioned/uninsulated space where the pipes don't belong to begin with. Most sillcocks don't even have a shutoff upstream, water 15 inches away doesn't freeze. But putting a piece of PEX in as Steven suggests won't hurt anything, so go for it.
Comment: What may be happening when you put the torch to it, heat tape, etc. , especially if the pipe is sloped, is that you're setting up a convection current that's carrying the heat to where it's really frozen.  Anyway, I'm done, good luck.
Comment: [spigot cover](https://www.google.com/search?q=spigot+cover&source=lnms&tbm=isch&sa=X&ei=cXmwVN36I4ezyQSQvIKQDg&ved=0CAkQ_AUoAg&biw=1280&bih=890)
Answer: I agree with the comment in that its surprising the copper pipe would conduct enough heat to freeze the downstream pipe, are you sure there's not a draft or something like that?
Your idea to isolate the pipe seems relatively sound though.  You would likely want to use PEX instead of PVC. PEX normally requires a special tool to crimp the connectors, so I would recommend using a SharkBite push-in coupling fitting to connect the PEX to the copper and vise versa as these don't require any special tools to install.

From http://www.sharkbite.com/product/couplings/

SharkBite is the Push-Fit connection system that is really taking hold. It's the easiest way to join copper, CPVC or PEX pipe in any combination with no soldering, clamps, unions or glue. Just insert the pipe and the stainless steel teeth bite down and grip tight, while a specially formulated O-ring compresses to create a perfect seal.

I don't have any affiliation with SharkBite, they are just a well known brand of push-in fittings.  Your local store might have other brands too
Answer: Get yourself one of these faucet insulation covers.

The stretchy cord on the inside has a loop or hook that grasps the faucet handle. You then press the foam insulator cup over the faucet with the foam seal against the house wall. The foam is thick enough that it is able to conform over an irregular wall surface such as a lap type siding. Then the squeeze clamp is moved down the cord which is slightly stretched. The clamp goes against the outside apex of the faucet cover. The stretch of the cord holds the cover securely against the house wall.
Here is a picture of a typical installed cover.

This will surely solve your problem in the easiest way. The cover keeps outside cold air from causing the faucet to be the extreme cold sink. As a matter of fact the piping may well conduct heat from inside the dwelling to the faucet helping to warm the inside of the foam cover.
Best thing of all is that these covers are inexpensive.
Word of advice
Steer away from faucet covers that use a hard plastic hook with a plastic wing nut. These are a pain to use because of several factors. 1) The hook is often short and hard to get hooked onto the faucet and hard to unhook in the spring. 2) The plastic threaded hook bolt takes forever to thread the wing nut down two to three inches of the bolt while you try to hold the cover in place and keep the hook to stay hooked. 3) The plastic threads are really cheap and (especially ones with a plastic wing nut) can easily cross thread or become stripped out.


nim game by python?

Question: The rule of the game is that you've been given 3 piles of sticks. First pile has 3, second has 5 and last one has 7 sticks. Two players take turn to remove the sticks on each pile but the pick has to more than one and less than the amount of sticks on that pile.  who picks the last sticks will win the game.
Question: the first time pick is fine, the sticks are cut off as the way it supposed to be, but on second time, it goes back to initial status.
def bill_board():
    player=1
    pile_1='*'*3
    pile_2='*'*5
    pile_3='*'*7
    player=1
    print('Player ',player,"'s Turn",sep='')
    print('1: ',pile_1)
    print('2: ',pile_2)
    print('3: ',pile_3)

def pile_input():
    while True:
        while True:
            pile=int(input('pile? '))
             if pile in range(1,4):
                break
            print('illegal choose: only 1-3')

        if pile==1:
            while True:
                stick=int(input('Sticks? '))
                pile_1='*'*3
                pile_2='*'*5
                pile_3='*'*7
                length_1=len(pile_1)
                if stick>0 and stick<=length_1:
                    break
                    print('bad choose')
            length_1=len(pile_1)
            pile_1=length_1-stick
            pile_1='*'*pile_1
            print('1: ',pile_1)`enter code here`
            print('2: ',pile_2)
            print('3: ',pile_3)

        elif pile==2:
            while True:
                stick=int(input('Sticks? '))
                pile_1='*'*3
                pile_2='*'*5
                pile_3='*'*7
                length_2=len(pile_2)
                if stick>0 and stick<=length_2:
                    break
                    print('bad choose')
            length_2=len(pile_2)
            pile_2=length_2-stick
            pile_2='*'*pile_2
            print('1: ',pile_1)
            print('2: ',pile_2)
            print('3: ',pile_3)

        else:
            while True:
                stick=int(input('Sticks? '))
                pile_1='*'*3
                pile_2='*'*5
                pile_3='*'*7
                length_3=len(pile_3)
                if stick>0 and stick<=length_3:
                    break
                    print('bad choose')
            length_3=len(pile_3)
            pile_3=length_3-stick
            pile_3='*'*pile_3
            print('1: ',pile_1)
            print('2: ',pile_2)
            print('3: ',pile_3)

def game():
    print('Welcome to NIM!!!')
    print()
    bill_board()
    pile_input()
game()`enter code here`

Answer: There are a whole bunch of places in your code where you're reinitializing the variables you're storing the sticks in:
            pile_1='*'*3
            pile_2='*'*5
            pile_3='*'*7

Each time you run those lines, the piles will be reset to their initial state. If you want the effects of the changes you make to persist, you need to only change the values once and then keep using the modified values as you go through the rest of the code.
(Note that it would also probably be much easier to keep track of the lengths of the three stacks with a list of integers, rather than with numbered variables. You can loop over the list to produce the strings of * characters as needed when you're going to output them.)

nim game by python?


The intersection of the facets on the polyhedron

Question: Given a point set $E=\{\alpha_j\}_{j=1}^m\subset \mathbb{N}^{n}$ ($1\leq m< \infty$).
Define the polyhedron $\mathcal{N}(E)$ to be the convex hull of the set
\begin{equation*}
    \bigcup_{j=1}^m \left(\alpha_j + \mathbb{R}^n_{+}\right),
\end{equation*}
where $\mathbb{R}^n_+=\{x\in \mathbb{R}^n:x_j\geq 0, \, 1 \leq j\leq n\}$. If there are $n$ facet (the face has dimension $n-1$)
$
F_1,\,F_2,\,\cdots,\,F_n
$
on $\mathcal{N}(E)$ satisfying
$$
\bigcap_{j=1}^n F_j\neq \emptyset.
$$
How to prove that for $n\geq 3$, if the intersection of $n$ facets is nonempty, then it must be a single point?
For a general convex polytopes, this claim is not feasible. For a 4-dimensional example, see Show that each edge of the cyclic polytope $C_4(6)$ is contained in either three or four facets, and either three or four 2-faces.
I think the concepts of redundant face maybe helpful. And I can only prove the case $n=3$, in the following answer (I post it to avoid a length question) I show if three facets intersect, then they must coincide with a single point.
Comment: Is it true that $\mathcal{N}(E) = \mathbb{R}^n_{+} + \Gamma(E)$ where $\Gamma(E)$ is convex hull of $E?$
Comment: yeah and we can assume that $E$ is finite.
Comment: Then, I guess, you can find all facets of $\mathcal{N}(E)$ from facets of  $\Gamma(E)$ and $\mathbb{R}^n_{+} $ and maybe apply counterexample you provided.
Comment: It is different.  That counterexample is a bounded closed polytope.
Comment: Thanks, I thought facets $\mathcal{N}(E)$ is union of some subset of facets of $\Gamma(E)$ (which is also bounded polytope) and of some subset of facets of $\mathbb{R}^n_{+}.$
Comment: The union of facets on $\mathcal{N}(E)$ is not a convex polyhedra.
Comment: Sorry for confusion, I meant that each facet of $\mathcal{N}(E)$ is either facet of $\Gamma(E)$ or facet of $\mathbb{R}^n_{+}.$
Comment: what do you mean by "each $\mathcal{N}(E)$"?
Comment: "Each facet of $\mathcal{N}(E)$"
Answer: This answer is only for the case $n=3$.
Since the affine hull of a facet is a 2-dimensional plane, there exist $w_j\in \mathbb{R}^n$ ($n=3$) such that the equation of these (support) plane is $w_{j}\cdot x=1$, $j=1,2,3$, with $$\mathcal{N}(E)\subset\bigcap_{j=1}^3\{x:w_j\cdot x\geq 1\}.$$ In our framework, one can easily show that $w_j\in \mathbb{R}^{n}_+$ (in higher dimension this fact is also true). Then our claim is equivalent to the linear independence of $\{w_1,w_2,w_3\}$. If they are not linear independent, we show there is a contradiction. Firstly, we can assume that there exist $\lambda_j$, $j=1,2$ such that
$$
w_3=\lambda_1 w_1+\lambda_2 w_2.
$$
Let $\beta\in \cap_{j=1}^3 F_j$ is a point on $\mathcal{N}(E)$. Then $\beta\cdot w_j=1$. Thus $\lambda_1+\lambda_2=1$. Without loss of generality, we can always assume that $\lambda_1,\lambda_2$ are non-negative. (Indeed, if there is a negative, say $\lambda_1$, then  we rewrite the relation of $w_j$ as
$$
w_2=\frac{1}{\lambda_2}(w_3-\lambda_1 w_1)=:\mu_1 w_3+\mu_2 w_1
$$
with $\mu_j$ non-negative.)
Now we assume $\lambda_j$ are non-negative, however, since $w_3$ is the normal vector of the (proper) facet $F_3$, we can choose $\alpha\in F_3$ and $\alpha$ not belong to $F_1,F_2$, then $w_j\cdot\alpha>1$ for $j=1,2$. And
$$
1=w_3\cdot\alpha=\lambda_1 w_1\cdot \alpha+\lambda_2 w_2\cdot \alpha>\lambda_1+\lambda_2=1.
$$
A contradiction.
In higher dimensions, I can also use a similar arguments but I stuck.


Modify custom entry in Info.plist

Question: I have a custom key in Info.plist that I would like to modify during resigning. Is this possible?
I have tried unzipping the ipa and setting the value for my custom key using terminal but when I tried to side load it through iTunes, it did not install.
Answer: Got it. Modifying Info.plist invalidates the signature on the ipa. I just had to resign after modifying the file and it works now.

Modify custom entry in Info.plist


Can a failed expansion tank cause water heater to stop heating water

Question: Yesterday we saw that the expansion tank on our < 8yr old water heater looked like this:

Hot water is no longer available. If it's possible for the tank spill to cause the heater to stop heating then I'll try to replace the tank. Otherwise, it's wait a week for a plumber to take a look. It's a very busy time for that profession.
Comment: Is the pilot light still lit? You may have to relight it. Have you checked to see if the burner ignites? Review the basics first.
Comment: Gas or electric heater?  Is the heater not heating the water or no water coming out?
Comment: It's a gas heater. Heater not heating; water flows.
Comment: Did the leak from the tank go over/onto the heater or just on the floor?  If onto the heater it might have damaged some electrical/control circuit.
Comment: I would drain the expansion tank first and inspect the pilot fire.
Answer: After replacing the tank (easy job after watching a video) I was able to reignite the pilot and the heater is now doing it thermo-increasing job.


multithread segment fault destructors

Question: i have a segment fault when it calls the function unit_thread_data,Actually it is caused by ~Data(). thread1 is all right, but thread2 cause the segment fault, the whole code is as fallows:(forgive the poor code style), error info is double free or corruption. Other info: gcc5.4.0, centos7. any help? thank you very much!
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
class Data
{
public:
    int* A_;
    Data()
    {
        cout<<"111\n";
        A_=NULL;
    }
    ~Data()
    {
        cout<<"222\n";
        if(A_) {
            delete A_;
        }
    }
};

struct thread_data_t
{
    Data* d;
};

void* _add(void* _pthread_data)
{
    thread_data_t* pthread_data = (thread_data_t*) _pthread_data;
    pthread_data->d->A_ = new int[2];
    pthread_data->d->A_[0] = 1;
    pthread_data->d->A_[1] = 2;
    std::cout<<pthread_data->d->A_[0]+pthread_data->d->A_[1]<<endl;
    return (void*)0;
}

void unit_thread_data(thread_data_t* pthread_data)
{
    for(int i=0;i<2;i++)
    {
        delete[] pthread_data[i].d->A_;
        delete pthread_data[i].d;
    }
    delete[] pthread_data;
}
int main()
{
    int num_threads = 2;
    pthread_t threads[num_threads];
    thread_data_t* pthread_data = new thread_data_t[num_threads];
    for(int i=0;i<num_threads; i++)
    {
        pthread_data[i].d = new Data();
    }
    for (int i=0; i<num_threads; i++) {
        pthread_create(&threads[i], NULL, _add, (void*)(pthread_data+i));
    }
    for (int i=0; i<num_threads; i++) {
        pthread_join(threads[i], NULL);
    }
    sleep(1);
    unit_thread_data(pthread_data);
    return 0;
}

Comment: Remove `delete[] pthread_data[i].d->A_;`, `A_` is deleted by destructor of `Data`.
Comment: Recommendation: If you are using C++11 or newer, use the standard [`std::thread`](https://en.cppreference.com/w/cpp/thread/thread) class instead of the platform specific C API `pthread`.
Comment: This doesn't address the question, but you don't need to test whether `A_` is null in the destructor. `delete A_;` can handle a null pointer.
Comment: @Pete Becker: thank you Pete, i have learnt it
Answer: delete[] pthread_data[i].d->A_;

This deletes the A_ member of your Data class, an int *.
Immediately afterwards, this happens:
delete pthread_data[i].d;

And this deletes the Data itself. Data's destructor then does the following:
    if(A_) {
        delete A_;
    }

This then proceeds to attempt delete the same pointer. This should be delete[]d instead of deleted in the first place, but this is moot because this pointer is already deleted, and this tries to delete it a 2nd time.
This results in undefined behavior.
Comment: yes! I got it, thank you Sam :)
Answer: It is because you first delete member A_ here:
delete[] pthread_data[i].d->A_;

without assigning nullptr to A_ afterwards, and then you call delete A_; in the destructor.
Apart from that, in your code it is not clear who should be the owner of the memory allocated under A_ (functions _add and unit_thread_data, or a class itself), hence it is easy to do this kind of mistakes.
Quick fix (not recommended): just remove your destructor's body, and let your external functions _add and unit_thread_data manage the memory.
Better fix (recommended): think about who should be the owner of the allocated data (I would say class Data) and use std::unique_ptr if you can.
Answer: You need to assign NULL after deleting A_.

multithread segment fault destructors


Cannot create connection from JS Plumb Endpoint which is in use by another connection

Question: I have set set of DIVs which should be connectable using jsPlumb (v2.0.7).
Each of the div elements has an Anchor and Endpoint on all of its four sides. I'm able to create connections from these endpoints by drag and drop.

The Problem: As soon a connection between two endpoints is established, it cannot act as a source Endpoint for a new "create connection" drag operation anymore. Using such used endpoint as the target of a connection, works fine though.
The configuration looks like this:
jsPlumbConfig = {
      PaintStyle: {
        lineWidth: 1
        outlineWidth: 5
        strokeStyle: "#FFF"
        outlineColor: "transparent"
      }
      Connector: [ "Bezier", { curviness: 69 } ]
      ConnectionsDetachable: false
      DeleteEndpointsOnDetach: false
      ReattachConnections : false
      Anchors: [ "Top", "Right", "Bottom", "Left" ]
      MaxConnections: 50
      Endpoint: [ "Rectangle" ]
      EndpointStyle : {
        paintStyle: { fillStyle:'#FFF' }
      }
}

The Endpoint options are like that:
endpointOptions = {
      endpoint: "Rectangle"
      maxConnections: 50
      connectionsDetachable: false
      deleteEndpointsOnDetach: false
      paintStyle: { fillStyle: "#EEE", outlineColor: "rgba(0, 0, 0, -0.8)" }
      endpointHoverStyle: { fillStyle: "rgba(255, 255, 255, 0.8)" }
      isSource: true
      isTarget: true
}

JSFiddle: https://jsfiddle.net/v0aw81v3/
Answer: I found the solution by setting
ConnectionsDetachable: true

Strangely this doesn't remove existing connections from one Endpoint, but allows adding additional ones.


How to remove recommended and suggested dependencies of uninstalled packages?

Question: I know of How to remove an uninstalled package's dependencies? and I tried
apt-get autoremove

but that does not remove dependencies that are recommended/suggested by other packages.
That is, if I install a package X that recommends Y, but I do not install Y, and then I install package Z that depends on Y. and later I do
apt-get remove --auto-remove Z

then Y is not automatically removed even though nothing depends on it.
(X "picked up" Y, even though it does not depend on it).
Comment: Could you instead say what is the package that do this?
Comment: There are many examples, so I tried to extract the essence of the problem in the above description. You are right that I should have also included a concrete example: Consider installation of texlive-full. It installs a lot of font packages, which are suggested (but not required) by many pre-existsing packages (I cannot remember precisely which, but I think pre-existing libreoffice or matplotlib or octave suggested these). So the problem is that "apt-get install texlive-full" followed by "apt-get remove --purge --auto-remove texlive-full" does not leave the system in the same original state.
Answer: If you want to remove recommended packages from your system, even if there are still some installed packages recommending (or suggesting) them, put the following in the file /etc/apt/apt.conf.d/99_norecommends (create it):
APT::Install-Recommends "false";
APT::AutoRemove::RecommendsImportant "false";
APT::AutoRemove::SuggestsImportant "false";

The documentation for these options is here.
Then, the next apt run (try apt-get autoremove) should remove them all. If it doesn't, launch aptitude, and type g and g again.
This configuration also disables the automatic installation of recommended packages when using apt-get. For aptitude it can be done from the console GUI, menu Options > Preferences > "Install recommended packages automatically" (uncheck it).
Comment: InstallRecommends: Because why install 5MB of stuff you want, when you could also install 1GB of stuff you don't want?
Comment: @Braiam This is not what the OP asked though. Your comment is for him, not for me.
Comment: @Braiam That's your POV. I live pretty well with `InstallRecommends` disabled. For the record, it was disabled by default until Debian Squeeze released, that is since February 2011 (don't know about Ubuntu). Furthermore, you may not need the same configuration on a server or a desktop setup.
Comment: I wouldn't recommend not installing recommendations as they most of the time are *useful*.
Comment: I'm just saying that that's maybe overkill.
Answer: Overriding APT options
Unlike dependencies, automatically installed "recommended" or "suggested" packages may be ignored by apt-get autoremove.
As described elsewhere, this behavior of APT can be changed in the configuration.
Likewise, the configuration of the apt-get command can be temporarily changed through the -o command line option.
This is, how you would force autoremove to remove left-over "recommended" and "suggested" packages, in addition to unused dependencies.
sudo apt-get autoremove -o APT::Autoremove::RecommendsImportant=0 -o APT::Autoremove::SuggestsImportant=0

Caution!
Some functionality may be lost. Be prepared to investigate and reinstall things. It may be easier to leave these packages alone.
Other options
To uninstall the 'recommended' and 'suggested' packages solely for a particular package, have a look at the apt history log.
Comment: to simply **analyze** such packages, perform a **dry run** with `apt-get`'s `-s` option and pipe to `grep ^Remv` — so that's the command: `apt-get autoremove -s -o APT::Autoremove::RecommendsImportant=0 -o APT::Autoremove::SuggestsImportant=0 | grep ^Remv`
Answer: Actually the command is:
sudo apt-get autoremove <Z>

But this has a trick! If any of the dependencies has some other previously installed packages that recommend/suggest them then apt would not remove them.
You didn't specified what package was but for example, if I were to install the IcedTea plugin, it would install Java/OpenJRE by dependencies. If I uninstall them using sudo apt-get autoremove icedtea-7-plugin you would notice that it won't remove Java/OpenJRE, since LibreOffice also suggests the packages.
So, to remove them you has to be overly specific about the package you wants to uninstall that normal autoremove won't:
sudo apt-get autoremove <Z> <dependency of Z>

This way you could be sure your package get removed.
You can also use deborphan to remove some dependencies.
Comment: Yes, you described my problem perfectly. Thank you. But, unfortunately, you have not solved it, because I do not want to go to /var/log/apt/history.log and look for all the packages Y that where installed a couple of months ago with Z (in your example, Y=java/jre, Z=icedtea plugin) and then manually add all of them to the apt command line. I want to only specify Z, and the rest of the dependencies to be picked up automatically, *even if they are suggested* by another existing package X (X=libreoffice in your example).
Comment: By the way, my understanding from the apt manpage is that autoremove does not expect a package name, and will simply clean all un-needed package dependencies in the system. So you would have to do 2 steps: "apt-get remove Z" followed by "apt-get autoremove". These 2 steps can be done at once with "apt-get remove --auto-remove Z", as mentioned in my original question. But like I said, the problem is that there are some leftover packages which are not removed if they were suggested by something else.
Comment: Unfortunately,this is the way the apt system works, it prefers to keep packages installed rather than remove them, even if they are not needed anymore. The only way to remove them is manually or with `deborphan` but deborphan may miss some packages still. You can use the `Debug::` options and also check my [other answer about this](http://askubuntu.com/q/138484/169736). You can also use the `--no-install-recommends`, but apt-get don't install suggested packages by default.
Comment: You're stating the obvious: if you uninstall them by hand one by one, then yes, you will get rid of them; but the OP is complaining because: "Y is not **automatically** removed". See [my answer](http://askubuntu.com/a/399078).
Comment: @Braiam I tried that and was surprised to get no output whatsoever. `apt-config dump | grep -i APT::Install-Recommends` shows Install-Recommends is enabled (1) and `APT::Install-Suggests` is disabled (0).
Comment: @user2809402 you should also check http://askubuntu.com/q/244470/169736
Comment: Braiam- Thanks for the deborphan pointer. I will check it out.
Comment: @Totor as it's said in my upvoted comment: *it prefers to keep packages installed rather than remove them*. I'm stating the reasons why it works that way. I'm dead sure that if a package has no more dependencies when you run `apt-get autoremove Z` the dependencies of Z will get uninstalled by default. Your answer is just overriding the behavior (I'm not saying that it's wrong, just that it doesn't explain the behind curtains of the current behavior).
Comment: @Totor is said in my answer too "If any of the dependencies has some other previously installed packages that recommend/suggest them then apt would not remove them."
Comment: @Braiam `apt-get don't install suggested packages by default.` I can't find documentation stating what the default is, but on Ubuntu server 16.04 it is definitely installing recommended packages. I believe suggested packages by default are not installed, but recommended packages are.
Comment: @Nateowami ? I don't get why are you saying this? Just run `grep APT::Install-Recommends /etc/apt/apt.conf.d/*` and `grep APT::Install-Suggests /etc/apt/apt.conf.d/*` and you will find out which are the defaults.
Comment: @Rolf autoremove does takes package names. I recommend you to try it.
Comment: @Braiam I took your suggestion and here is what I found out: it does however it will proceed to remove any package given but then proceed to autoremove all orphaned packages on the system, so basically `apt-get autoremove x` would be equivalent to `apt-get remove x`  followed by `apt-get autoremove`. So you cannot specify which packages you want to "autoremove"
Answer: Right, if you want to remove package <Z> with dependances just type:
sudo apt-get autoremove --purge <Z>

Comment: Thanks, but unfortunately, adding "--purge" simply removes the configurations of packages that are removed with "autoremove". But as far as I can see, it does not change the decision about *which* packages to remove. That is, dependencies of Z which are suggested by some pre-existing package X, are still not removed, whether or not I specify "--purge".
Comment: Also, `autoremove` works system-wide. So anytime you call `autoremove`, it will remove all unused packages on your system. Installing a package, then `autoremoving` will usually not return the system to the same state, and will instead leave a bunch of "leftover" packages.


initialize() before actionPerformed()

Question: I have a class which implements ActionListener.  My actionPerformed() method runs fine.  However, there are some things I want to do once before my program starts to run actionPerformed().  I could put a boolean in actionPerformed() and just run it once that way, but I was looking for something cleaner.  I cannot just use my constructor, because I need a fully constructed object for what I am trying to do.  Is there a way to add a method such as initialize() or start() which will run before actionPerformed() starts?
Some sample code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Game implements ActionListener {

    public Game() {
        // Constructor
    }

    public void initialize() {
        // I want a method of some sort here which is run before the main game
        // loop so I can set it up
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // main game runs
    }

}

Comment: `I need a fully constructed object` - then add the code at the end of the constructor. The actionPerformed() method has nothing to do with constructing an object. You need to first create the object before you can invoke its actionPerformed() method.
Comment: do you want initialize() to execute every time you create an object ?
Comment: @camickr I cannot unfortunately.  Because I need the instance of the Object itself to set up some stuff.  Quite the noodle scratcher, eh?
Comment: @karibasappa G C yes.  i will (probably) only be creating the object one time tho, if it is relevant
Comment: ok then see my answer below
Comment: @mKorbel downvote because i didnt include the Swing tag?  or perhaps u can shed some light on why you find this a poor question, please.  An answer would also be appreciated
Comment: @Evorlor by default I'm always notify about reason(s), this is important for OP, true is that I'm suprised that this empty question isn't closed as of topics, e.i., look into my profile for more info about my voting score
Comment: @mKorbel hmm...if this is off topic and only relevant to OP, i suppose i need to reread the definition of a good question.
Answer: you can use Instance initialization block(IIB) if you want initialize to happen every time we create object.
and Static Initialization block(SIB)if you want initialize to happen only once.
so in your case yo want on object creation but before building an object.
so go for IIB block like below
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Game implements ActionListener {

    public Game() {
        // Constructor
    }

    {
        // I want a method of some sort here which is run before the main game
        // loop so I can set it up
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // main game runs
    }

}

Note: i removed method signature of initialize and made it IIB. which will fulfill your requirement.
when you do Game g = new Game();
before your constructor Game() executes IIB block executes and you will have all set to call actionPerformed() method.
Comment: So if i wanted to do something like a Start Menu here, I would just make a new thread with an ActionListener of its own?  And then actionPerformed would not be called until this thread died?
Comment: oh so it sets the field before my object is contstructed?  i need the object to be instantiated before i can mess with those fields tho
Comment: I just read up on this, and I don't think this is what I am looking for.  Thanks though.  Learned something new (that I will use in other areas :)  )
Comment: oh then you cant use SIB or IIB as stated above..you need to call initialize() method at the end of the constrctor
Comment: correct.  thanks though.  I will give you an upvote after I find the answer to my question :) want to wait tho so others dont think i have it yet
Comment: ok thats not a problem..other option is call initialize at the start of actionPerformed() method...or if you know AOP in spring that will also work very nicely.

initialize() before actionPerformed()


How to update the files locally after a rollback on Heroku?

Question: I have, let's say 10 deployments on Heroku of a web application;
I would like to rollback to the 6th release
The first step is to rollback on Heroku, then I have to git clone the web application through this command
heroku git:clone -a myapp

My question is, how to update the developpment files, locally, do I have to delete manually all the folders and the files of the app, and replaced them by the folders and files downloaded from git clone ? does the Git will remain the same ?
Many thanks
Answer: "Running on a rolled-back release is meant as a temporary fix to a bad deployment."
In order to rollback your code you have a few different options. Just note that the --hard flag will destroy any local modifications.
Comment: thank you, just an important question for me, if I execute "git reset --hard xxxx", will the local files be updated automatically (with the previous Git) ? many thanks
Comment: Yes. So just be careful to not overwrite any new code.


Can google chromecast receiver app work without sender app... fed from web server

Question: I am currently exploring the possibility of using Chromecast + a custom receiver app instead of a raspberry pi custom code application, or something similar. My goal is to be able to have a Chromecast receiver app pull down various streams/images/text and display them on the TV in some custom layout. If I understand the SDK, the custom receiver html/css/js files would be hosted on my public server, and the chromecast device would pull those down to the device (possibly stored on it?). What I am not quite clear on is if that app can then pull down media files, images, etc and display them, or if the only thing that can be displayed is from a sender app? My concern is we'd like to potentially have 100's of Chromecast devices set up, and using a single server (or possibly a couple) feed the video/image/etc to them individually. In some cases some of the TVs would be used to display the same video/images/text. In other cases they'd be completely separate feeds.
Is it possible to do this, or is this too open ended for what the Chromecast SDK allows for? I am trying to decide if I should look at either custom code on Raspberry Pi with custom code, or if perhaps even something more powerful like the new intel MinnowMax, which I realize is $100, but I need to make sure I can display overlapping graphics, video, text as I want and that I can do so from dozens (or more) devices feeding from a server of mine. One more time, to be clear, I want to store various videos, images, etc on my server, and have them pulled down (and cached) to the local device at a TV to display... so if for example the internet is severed, the device can still display the videos/images/text.
Thanks.
Answer:
First, in order to start an application on your chromecast, you would need to have a sender device on the local wifi network to start the app; after it starts, what shows up there on the screen can be anything that your receiver's logic decides; for example your html5 receiver may have instructions to go to Url A and grab Video A and then go to a different Url to get a different image, etc. The main point is that there needs to be a sender to load your application and cannot be done automagically.
The content of the page is the usual stuff that you support in html5 but that little dongle is not very strong on CPU and memory, hence you won't be able to do things that you would normally do on a desktop browser, or if you try to do, it would not be as slick. Also, you cannot have two concurrently active video elements on the same page.
In terms of caching, it doesn't cache things for long time and in a addition, its disk space is limited. As a result, you would need to have and maintain a network connection.
Comment: Ok, it's as I suspected.. oh well I'll use the one I bought to test out for other purposes then I guess ;). Thanks for the reply.


How to I fasten this toilet flange down?

Question: I'm redoing my bathroom and had to replace a toilet flange. The old one was rusted cast iron whose flanges had all but disintegrated, and I ground down what was left of it with an angle grinder. It was fastened directly to the pipe, not the subfloor--which is concrete (house is on a slab). Here's what the result looks like:

Then I bought a new flange that fits inside the existing pipe. Unfortunately I haven't found a good way to secure it to the subfloor, which is old (very hard) concrete. I tried Tapcons with little success. The problem is the angle of the concrete I need to drill into:

The walls of the existing concrete are so steep that it's almost impossible to drill pilot holes.
So what should I do? I've contemplated pouring some new concrete to fill the void and embed threaded rods in it to which I can fasten nuts though the flange, but I worry that it won't adhere well to the old concrete and tightening the nuts will just pull it loose.
What do you guys think?
Comment: In the days when we used cast pipe we would fill the void with lead and use brass wood screws for a case like this. Filling with concrete may work but that's not much material it may break up. I would consider epoxy.
Comment: The go-to solution for drilling a cone like that would be to drill through a block of wood laid across the top. I'm partial to the epoxy idea.
Comment: No room for wood, I'm afraid. Also there's nothing to anchor the wood to without drilling into concrete, which is the original problem.
Comment: I would also vote for the epoxy idea. Clean out the area in the gap as really well as you can. Include getting all the scale and corrosion off the outside of the pipe as well. If you do this cleverly you should be able to mount bolt studs from the new flange that extend down into the epoxy. It may be necessary to chisel out some of the existing concrete where the embedded studs will hang into the epoxy. Make sure to use studs that are not likely to rust any time soon. One choice would be to select a top grade stainless steel product.
Comment: You misunderstand. I mean you put a 2x4 on the floor, put a knee on it, then drill straight down with the hole in the wood keeping the bit straight. Cheapo portable drill-press. (Alternately you drill the wood first, then put it down so you can see where the bit is.) Also, since you have an angle grinder a masonry cutoff wheel might be preferable to a chisel if you can fit it. Less chance of shattering the floor you want to keep.
Comment: Ah, interesting plan! Maybe make that into an answer?
Answer: I would drill out and break out more concrete to develop a hole that would hold a new concrete plug/doughnut around the pipe, rather than the difficult pointy cone you have now.
So, drill from the flat surface you have, lots of holes, and chisel carefully between holes.
My personal experience with Tapcons and "hard concrete" is abysmal. In green (new, fresh) concrete they seem to work OK most of the time.
Comment: That worked perfectly! I embedded nuts deep in the new concrete and fastened the flange down with machine bolts.


Formula that would check a column of cells and say if he found an exact word

Question: Alright, so I want a formula that would search in a column of words a specific word, I was helped at  making one but it only logs the first one and stops there (even though it's not the one I want it to find)
<code>=ARRAYFORMULA(IFERROR(VLOOKUP(A1:A50, IMPORTRANGE("(sheetid)", "Project Automation Checker!B1:D50"), {2,3}, 0))).
</code>
I want it to find the word "CT" in column D of the Project Automation Checker.
https://docs.google.com/spreadsheets/d/1n8DF771658l-7lIMu2Jx7YF9ZoHGb3H8UA0eOVd8iaE/edit?usp=sharing
Answer: to check for an exact match you can use regex like:
<code>=ARRAYFORMULA(IF(REGEXMATCH(D2:D9, "^CT$"), "CT found", "CT NOT found"))
</code>


water pressure drops when irrigation system is turned on

Question: I am using well water. The static pressure measured with the outside faucet is 60 psi. When irrigation system is turned on, the water coming out of all sprinkler heads in any zone is weak. I guess the pressure at sprinkler heads is low. When irrigation system is on, water pressure inside the house is very low too and the PSI I read at outside faucet drops to 20 PSI. What could be the problem? Can low water in the well cause the problem?
Thank you!
Comment: The problem is that the well is not producing enough water for the sprinklers.  the cause of that cannot be determined from the information given
Comment: Hello, and welcome to Home Improvement. When the irrigation system turns on, does the interior water pressure drop immediately, or over time? And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know you'll know the details of contributing here.
Comment: Simplest effective solution might well be to convert the sprinkler system so it runs individual zones one at a time, not all at once. If already doing that, smaller zones.
Comment: Pressure and flow rate are not the same.  You have plenty of pressure from the pump, but low flow rate.  This could be a factor of your well, the pipe sizing, the distance/depth.
Answer: It sounds like your well is not able to provide the flow rate needed to supply your sprinkler system.
Let's say that your well/pump/plumbing are able to provide 5 gal./minute.  If you exceed that rate then the pressure will drop.  It's unlikely that low water level in the well is the source of your problem as in that case the pump would start sucking air and you would notice the air in the system as it "burps" out.
I'd start by checking your plumbing for suitable sizes of pipes and fittings and see if there are any obvious problems such as way too small pipes.  If that fails to reveal any issues you likely need to engage a well service professional who can evaluate your well and pump and make any recommendations that might correct your problem.
Keep in mind, especially if your well and pump are old, that fixing this may involve replacing the pump, drilling a new well, running a new pipe from the well to the home, etc.  In other words, it may be expensive.
Answer: There could be several causes.  Is this a new problem? Have you made any changes to the irrigation system? The most likely cause is you are simply using too much water than the pump can provide so the pressure drops until the delivery rate matches the consumption rate.  Reducing the number of heads on a zone would address that issue. You may have to increase the number of zones to cover the same area.  I assume you are only running one zone at a time, right?
It could also mean your well isn't producing enough water anymore, but the production rate of wells is usually pretty consistent.   Still, the water level in your well might be dropping, making the pump work harder.  And the pump could be wearing out.  They don't last forever and maybe slowly failing.
Answer: One thing that has not been mentioned is what happened to me. I suppose through the minor vibrations caused by the pump turning on and off, over time, my main shutoff valve rotated itself into the off position. At first, pressure was dropping when more then one thing was using water in the house, eventually, no water at all.
When I went to turn the shutoff off, I noticed it was already off. So that is an easy thing to check before looking at other things. If it's a gate valve, also make sure it is fully open (and then back off half a turn to help prevent it seizing).
Answer: Your question is a bit misleading, you state: The static pressure measured with the outside faucet is 60 psi. When irrigation system is turned on, the water coming out of all sprinkler heads in any zone is weak." I am assuming the so PSIG drops with the sprinklers, if that assumption is wrong you have a restriction or partly closed valve in the sprinkler feed.
I have city water and the sprinklers did the same thing, I added a length of 1/2" copper tubing in the feed and it now works great and the inside pressure is good.
I am assuming the pump does not shut off, this is the way I would expect it to operate. The pump can pump so much water at a given pressure. Use more water the pressure will drop, use less and the pressure will go up.
Many sprinklers will allow you to adjust the flow. If you have that type of sprinkler head lower the flow and let them run longer. The end result the area gets the same amount of water in the end. That would be by far the most cost effective. As mentioned earlier you can add more zones.


Whose .equals() method is called to resolve hash collision in HashMaps?

Question: On every single article about HashMaps hash collision one thing is in common and my question revolves around that.
Let me explain what i understand about hashmaps internal working.
Saving two entries(e1,e2) with same hashcode using map.put(k,v)
1) when the map.put(k,v) is called, hashmap finds the hashCode() of the key 'k'.
2) then it uses this hashcode it found as a seed for its internal static hashing method & gets another hash value.
3) then this new found hash value is mapped to the internal index of bucket.
4) then a Entry is added to the bucket.
In case of a hash collision.
1) same as normal, when the map.put(k,v) is called, hashmap finds the hashCode() of the key 'k'.
2) again same as usual, then it uses this hashcode it found as a seed for its internal static hashing method & gets another hash value.
3) the new found hash value is mapped to the internal index of the bucket, now there is a problem as it already has a entry at this bucket position.
Resolution : since the Entry is actually a simple linked list, the new item with the collided hash is stored at the next of the previous Entry.
Fetching the entry e2 with map.get(k)
1) hash generated from key & again static hash method called using the hash obtain from the key as seed.
2) finding the mapped bucket using the hash value obtained by the static hash method, now if there are more than one entries here equals() method comes to the rescue.
that is the linked list would traverse & keep on calling the "equals()" method until it finds the match.
Now my question is where is this so called equals() method defined ?
I opened the official documentation of HashMap & it doesn't override the .equals() method, so where is it overriden? Or is it the default .equals() from the Object class ?
Comment: Wait what? `HashMap` doesn't call it's own equals-method, this would make no sense, it calls the objects equals method which you're trying to insert.
Comment: @tkausl can you explain it in further detail ? Do you mean to say the default "==" in the Object class's equal() is used to find the key?
Answer: Both hashCode() and equals() methods belong to the class of the key object, not to the hash map.
The methods are defined in the Object class, but it is expected that the objects used as keys in a hash map provide their own implementation for both these methods. Therefore, it's not the default .equals() from Object class, it is the specific .equals() from the actual key class that gets called for collision resolution.
For example, if you use String objects as keys, the overrides of hashCode() and equals() provided by String would be used.
Comment: @SujalMandal The default `equals()` inherited from object will return true only when comparing two of the same instances, regardless of values.  `String`, however does implement `equals()` so your two string keys would be considered to be equal and therefore the same key.  It is typically recommended that all objects overwrite `equals()` and `hashcode()` especially if you are going to be using them as keys in a map.
Comment: so by default if i do not specify equals() in the key , the references of Key class will be used?

This brings me to another question what if i add two key objects with same value but different references?

EX -

String key1="game of thrones";
String key2=new String("game of thrones");

How will it affect the lookup ?
Comment: @SujalMandal The situation that you describe demonstrates precisely the reason why `equals` is used in place of `==`. You have two different object references that have values equal to each other, so `==` returns `false` but `key1.equals(key2)` returns `true`.
Comment: @puhlen i typically ignored this thing till now but now i promise i will override equals() & hashCode() in the key class till the rest of my life :3


HTML/Javascript popup box with table

Question: In my application I have a button, when the user clicks on the button I want a popup box (not window) to appear with a table populated with information I pass in to it.
I have been looking online and cant seem to find how to do this, or even where to start (use all HTML, use all Javascript, use both HTML and Javascript). Has anyone done something similar to this or know a good starting point for this (e.g. what components to use)?
Comment: Just create the html elements dinamically with javascript, pass the information using functions and make sure the new elements have a higher z-index in css.
Comment: you can use jquery dialog
Comment: where is your table. Please post once
Comment: Have a look over here http://jqueryui.com/dialog/ you can create table inside that `dialog div`
Comment: See this http://jqueryui.com/dialog/
Comment: see my answer with demo on jsfiddle :)
Comment: see updated [jsfiddle](http://jsfiddle.net/KnrEF/1/) link :)
Answer: There's a range of frameworks that'll do the trick for you.
An easy and common one is jQuery Dialog (http://jqueryui.com/dialog/)
A small example, given the html:

Adding the modal overlay screen makes the dialog look more prominent because it dims out the page content.

Click me

Assuming you've included jQuery and jQuery dialog on top, add the following javascript:

Comment: thanks for this, was able to use the jquery-ui to create the modal dialog then I created a table in this using HTML and passed my records then into the table :)
Answer: simply use JQuery
See Demo Here
HTML :
<!DOCTYPE html>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

table populated with information

<input id="help_button" type="button" value="Show Popup"/>

CSS :
#help{
    display:none;
}

Comment: this works but it pushes everything on my page down rather then actually giving me a pop up box with the information
Comment: it's not a popup
Answer: you can create a pop up like this .. plunker link
and pass the table values inside it.
.
Answer: Another way is to use Bootstrap 3 with this plugin (plugin-examples) (there you can find a bunch of similar plugin, take a look and choose one )
It is good way to build Your website based on some framework (bootstrap) :)

HTML/Javascript popup box with table


Django DetailView is not working with additional parameter

Question: Hi I am new to Django programming
please find my program which is not working.I am not getting any error though.
 urlpatterns = [
    url(r'departmentlist/',views.DepartmentList.as_view(),name='departmentlist'),
    url(r'^departmentlist/(?P<pk>\d+)$',views.DepartmentDetail.as_view(),name='departmentdetail'),
 ]

But when I am passing the '(?P<pk>\d+)$' alone it is working...Can any one help me.
Comment: actual urls,py is the following.                            url(r'departmentlist/',views.DepartmentList.as_view(),name='departmentlist'),
  url(r'^departmentlist/(?P\d+)$',views.DepartmentDetail.as_view(),name='departmentdetail'),          after saving the question the  was getting vanished
Answer: You didn't terminate the pattern for the list view.
url(r'^departmentlist/$',views.DepartmentList.as_view(),name='departmentlist'),

Answer: You can edit the URL to:
url(r'^departmentlist/(?P<pk>[\d+])$',views.DepartmentDetail.as_view(),name='departmentdetail'),
]

Comment: Thank you for your suggestion.I could figure out the issue.I have written the rgx for departmentlist first so , it was comparing that first and got a match and stopped.so it did not go to the next comparison(departmentlist/).


Closed form for a series of combinations

Question: Let $M$, $N$, and $n$ be three integer numbers such that $n$ is smaller than both $M$ and $N$ ($n < M$ and $n < N$). I would like to know if $\sum_{i = 0}^{n - 1}{N-1 \choose i} {M \choose n - 1 - i}$ has a closed-form solution.
Here is why I am interested in this sum: Assume we have $M$ white and $N$ black balls in an urn. If only one of the black balls has a dot on it and we randomly select $n$ balls from the urn, I need to calculate the probability that the dotted black ball is among the selected ones.
$\Pr(\text{dotted black ball is selected}) = \frac{\sum_{i = 0}^{n - 1} \text{(dotted selected)} \times \text{($i$ of the non-dotted blacks selected)} \times \text{($n-1-i$ of the white selected)}}{{\text{selecting $n$ out of $M+N$}}} =\frac{\sum_{i = 0}^{n - 1} 1 \times {N-1 \choose i} \times {M \choose n - 1 - i}}{{M + N\choose n}}$
Actually, I need to study the sensitivity of this probability to $M$ when both $M$ and $N$ are large. For example, when $N = 100,000$, I want to know how the probability changes by $M$ if it varies between $20,000$ and $50,000$, given $n = 10,000$. That is why I need to be able to have a closed-form for the numerator to be able to calculate the numerical value of the probability.
Answer: This is just a special case of Vandermonde's identity:
$$\sum_{i = 0}^{n - 1}{N-1 \choose i} {M \choose n - 1 - i} = {M+N-1 \choose n-1}$$
and the result follows immediately if you think that once chosen the spotted black ball you remain with ${M+N-1 \choose n-1}$ choices for the other balls.
And note that the probability is equal to:
$$\frac{n}{M+N}$$
because drawing one ball at a time, the probability of finding the spotted black one within attempt $k$ is:
$$P_k=P_{k-1}+(1-P_{k-1})\frac{1}{M+N-k+1}=\frac{k}{M+N}$$
and:
$$P_1=\frac{1}{M+N}$$.
Answer: Your formula is more complicated than it needs to be.  If you have $\ B\ $ balls of which exactly one is marked with a dot, and you choose $\ n\ $ of them at random, then the probability that the dotted ball will be among the $\ n\ $ chosen is $\ \displaystyle\frac{n}{B}\ $. In your case $\ B=M+N\ $, so the probability that the dotted black ball is chosen is $\ \displaystyle\frac{n}{M+N}\ $ for any $\ n=1,2,\dots,\ $$M+N\ $.
This tells you that you must have
\begin{align}
\sum_{i=0}^{n}{N-1\choose i}{M\choose n-i}&=
\frac{n+1}{N+M}{N+M\choose n+1}\\
&={M+N-1\choose n}\ ,
\end{align}
for $\ n=0,1,\dots,\min(M-1,N-1)\ $, and, indeed, this identity is not difficult to prove using generating  functions.


JSON Errors in Custom Signs

Question: I need help with a command that I am trying to make in a game inside of minecraft. It is a custom generated sign (using a sign generator) that allows players to upgrade their weapons (and armor).
The command is the following:
<code>/give @p sign 1 0 {BlockEntityTag:{Text1:"{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins=24] ~ ~ ~ /tellraw @p [\\"\\",{\\"text\\":\\"[MF2] \\",\\"color\\":\\"gold\\"},{\\"text\\":\\"[SHOP] \\",\\"color\\":\\"yellow\\"},{\\"text\\":\\"You do not have enough wins to upgrade your sword.\\",\\"color\\":\\"none\\"}]\"}}",Text2:"{\"text\":\"Upgrade Sword\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins_min=25] ~ ~ ~ /tellraw @p [\\"\\",{\\"text\\":\\"[MF2] \\",\\"color\\":\\"gold\\"},{\\"text\\":\\"[SHOP] \\",\\"color\\":\\"yellow\\"},{\\"text\\":\\"Sword upgraded!\\",\\"color\\":\\"none\\"}]\"}}",Text3:"{\"text\":\"$25\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins_min=25] ~ ~ ~ /scoreboard players add @p sword 1\"}}",Text4:"{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins_min=25] ~ ~ ~ /scoreboard players remove @p wins 25\"}}"},display:{Name:"Custom Sign"}}
</code>
The first line of the sign is empty, and the click-event runs an execute command that tells the player that they do not have enough wins to upgrade using a tellraw statement.
The second line of the sign says "Upgrade Sword", and the click-event runs an execute command that tells the player that they have enough wins and their sword has been upgraded using a tellraw statement.
The third line of the sign says "$25" (which is the amount of wins to upgrade), and the click-event runs an execute command that increments the "sword" scoreboard for the player by 1.
The fourth line of the sign is empty, and the click-event runs an execute command that subtracts 25 wins from the player using the "wins" scoreboard.

My error is displayed as shown:
<code>Data tag parsing failed: Unexpected token '\' at: \\",{\\"text\\":\\"[MF2] \\",\\"color\\":\\"gold\\"},{\\"text\\":\\"[SHOP] \\",\\"color\\":\\"yellow\\"},{\\"text\\":\\"You do not have enough wins to upgrade your sword.\\",\\"color\\":\\"none\\"}]\"}}",Text2:"{\"text\":\"Upgrade Sword\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins_min=25] ~ ~ ~ /tellraw @p [\\"\\",{\\"text\\":\\"[MF2] \\",\\"color\\":\\"gold\\"},{\\"text\\":\\"[SHOP] \\",\\"color\\":\\"yellow\\"},{\\"text\\":\\"Sword upgraded!\\",\\"color\\":\\"none\\"}]\"}}",Text3:"{\"text\":\"$25\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins_min=25] ~ ~ ~ /scoreboard players add @p sword 1\"}}",Text4:"{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins_min=25] ~ ~ ~ /scoreboard players remove @p wins 25\"}}"
</code>
I have a similar command creating a custom sign again and the problem seems to be the tellraw commands. You can find my other question here.
I have tried using the answer from my other question to fix this command but I have just gotten completely lost. If anyone could help or explain to me how to use this properly (because I will also need to do this for other items), that would be fantastic.
Comment: If you were using a 1.9 generator with Minecraft 1.8 that could have been your problem.  1.8 can work with 1.9, but 1.9 can't work with 1.8.
Comment: @Jason_ That is incorrect. In 1.9, JSON must be strict. In 1.8, JSON *can* be strict. If you have lenient JSON from 1.8, it won't work in 1.9 because in 1.9 it must be strict. But 1.9 JSON will work perfectly in 1.8.
Comment: @Skylinerw, woops, sorry guess I didn't do my homework properly. Thanks for the clarification.
Answer: I was smart before writing this huh... I only used one generator to try and make the command. As soon as I posted this I was like "hey lets try another one" and it worked. This is the working command:

/blockdata ~ ~1 ~ {Text1:"[{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins=24] ~ ~ ~ /tellraw @p [\\"\\",{\\"text\\":\\"[MF2] \\",\\"color\\":\\"gold\\"},{\\"text\\":\\"[SHOP] \\",\\"color\\":\\"yellow\\"},{\\"text\\":\\"You do not have enough wins to upgrade your sword.\\",\\"color\\":\\"none\\"}]\"},\"text\":\"\"}]",Text2:"[{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins_min=25] ~ ~ ~ /tellraw @p [\\"\\",{\\"text\\":\\"[MF2] \\",\\"color\\":\\"gold\\"},{\\"text\\":\\"[SHOP] \\",\\"color\\":\\"yellow\\"},{\\"text\\":\\"Sword upgraded!\\",\\"color\\":\\"none\\"}]\"},\"text\":\"Upgrade Sword\"}]",Text3:"[{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins_min=25] ~ ~ ~ /scoreboard players add @p sword 1\"},\"text\":\"25 Wins\",\"color\":\"green\"}]",Text4:"[{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/execute @p[score_wins_min=25] ~ ~ ~ /scoreboard players remove @p wins 25\"},\"text\":\"\"}]"}

Well, I guess that solves that.
//Edit: The link to the generator I used is by MCtoolBox, and you can go straight to the sign generator by clicking here.

JSON Errors in Custom Signs


wpf binding user control loaded event no executed

Question: I have a usercontrol with a loaded event, when I included this in XAML in my content control it executed the loaded event perfectly.
However, I have changed this to dynamic binding on a content control and now the loaded event is not executed.
The header of my usercontrol:
<UserControl x:Class="DesignSuite.CanvasTools.DrawCanvas"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         xmlns:my="clr-namespace:DesignSuite.CanvasTools" Loaded="UserControl_Loaded">

I am binding the contentcontrol on the following way using a template:
<DataTemplate x:Key="FiniteStateMachineCanvasContentTemplate">
        <ContentControl Content="{Binding FiniteStateMachineCanvas}"/>
    </DataTemplate>

The Canvas which inherits content control shows up fine, only the loaded event is not executed.
The code for the binding is:
public DrawCanvas FiniteStateMachineCanvas { get; set; }

    public FiniteStateMachineCanvasTab (
        string NewName,
        ref Toolstate toolstatemanager,
        ref FiniteStateMachineDescriptor finiteStateMachineDescriptor)
    {
        HeaderText = NewName;
        FiniteStateMachineCanvas = new DrawCanvas(ref toolstatemanager, canvastype_e.CANVAS_FINITESTATE, ref finiteStateMachineDescriptor);
    }

Does anyone have a pointer in the good direction?
Answer: solved
Forgot to execute InitalizeComponent in the new constructor I created, this was the cause of the problems.


How to access/split items in a column that contains a list

Question: Let's say I received a dataset with a structure similar to this (I understand that this structure is not typical.)
The following code is just to generate an example of a dataframe that looks like my data.
tmp = pd.DataFrame(
    [
        {'foo': 123, 'bar': [1, 2]},
        {'foo': 456, 'bar': [1, 2]}
    ]
)

   foo    item
0  123  [1, 2]
1  456  [1, 2]

Is there an easy way to:

access items in bar.. like df.bar[1], resulting in 2 ?
(this clearly does not work)
or split the bar column into something like bar.0, bar.1, etc..

Ideally, I would like to plot all items in bar[0] vs bar[1]
Note the list in bar is not limited to 2 items and the number can vary a bit.
Comment: Thanks! Two great answers!
Answer: Yes, there is. Use str.get
tmp.bar.str.get(0)

0    1
1    1
Name: bar, dtype: int64

tmp.bar.str.get(1)

0    2
1    2
Name: bar, dtype: int64

To split, use pandas DataFrame constructor
col_names = ['bar.0', 'bar.1'] # Notice you can dinamically create this if needed
pd.DataFrame(tmp.bar.values.tolist(), columns=col_names)

    bar.0   bar.1
0   1       2
1   1       2

Answer: For your second request, you could apply pd.Series, and concatenate with your original dataframe:
>>> pd.concat((tmp,tmp.bar.apply(pd.Series).add_prefix('bar_')), axis=1)
      bar  foo  bar_0  bar_1
0  [1, 2]  123      1      2
1  [1, 2]  456      1      2

This works even if there are a variable number of elements in bar:
>>> tmp
         bar  foo
0  [1, 2, 3]  123
1     [1, 2]  456

>>> pd.concat((tmp,tmp.bar.apply(pd.Series).add_prefix('bar_')), axis=1)
         bar  foo  bar_0  bar_1  bar_2
0  [1, 2, 3]  123    1.0    2.0    3.0
1     [1, 2]  456    1.0    2.0    NaN


StateList for Compound ListView Row

Question: When I click a row in my ListView the row is using the statelist but the individual elements are not.

Setting duplicateParentState(true) on the image, text and image does nothing.
Setting the individual items to clickable(true) applies the statelist changes to each item, but does not change the parent even if addChildStates() (approximation of methodname) is set.

So, I want to click a row in the ListView and have the states of the individual items updated.  Obviously missing something.
I have the following row in a ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_row"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/statelist_row" >

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.1" >

        <ImageView
            android:id="@+id/product_image"
            style="@style/list_image"
            android:contentDescription="@string/product_image" />

        <ProgressBar
            android:id="@+id/product_image_progress"
            style="@style/list_image"
            android:visibility="gone" />
    </FrameLayout>

    <TextView
        android:id="@+id/product_name"
        style="@style/list_text"
        android:layout_weight="0.9"
        android:gravity="center_vertical" />

    <ImageView
        style="@style/list_caret"
        android:layout_weight="0.1"
        android:contentDescription="@string/caret" />

</LinearLayout>

In the adapter I make the row clickable:
    holder.productListRow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(context, "CLICKED: '" + holder.productName.getText().toString() + "'", Toast.LENGTH_LONG).show();
        }
    });

I have a statelist that is applied in the styles:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/selected_item" android:state_pressed="true" android:textColor="@color/white" android:color="@color/white"/>
    <item android:drawable="@color/std_background" android:color="@color/black"/>

</selector>

From colors:
<color name="list_text_color">@drawable/statelist_produce_row</color>

Finally, from styles:

Answer: Shouldn't you make the listview items clickable by setting an onItemClickListener for the listview instead of making each row clickable?
Try this
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ...
}
});

or if you're extending the ListActivity, you can directly implement onListItemClick():
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    ...
}

StateList for Compound ListView Row


disk will not mount

Question: I get the folowing error when I try to mount a drive:
Error mounting /dev/sda1 at /media/ubuntu/f2bebb2d-d57d-4c75-b719-cda5a73d8531: Command-line `mount -t "ext4" -o "uhelper=udisks2,nodev,nosuid" "/dev/sda1" "/media/ubuntu/f2bebb2d-d57d-4c75-b719-cda5a73d8531"' exited with non-zero exit status 32: mount: wrong fs type, bad option, bad superblock on /dev/sda1,
      missing codepage or helper program, or other error
      In some cases useful info is found in syslog - try
      dmesg | tail  or so

There are two partition on my hard disk. I have tried starting up with the install disk to see if there are any disk repair apps but it seem that there are not.
Comment: Please edit your question and tell us how you try to mount.
Comment: The drive is the main system boot hd. I downloaded the install image and burned it to a dvd and booted of it. In the side bar the drive is listed and I double clicked on it. A few seconds later the error message pops up.
Comment: I have pulled the drive out an put it into an external case and see if I could mount it on my Mac. In the Disk utilities on the Mac it sees the drive but it will not mount the two partitions.
Answer: wrong fs type, bad option, bad superblock on /dev/sda1
Either you have used the wrong partition or the filesystem is seriously scrambled.
First double check that your intent is really to mount /dev/sda1.
Look at the output of:
parted /dev/sda print

If you're sure that it is the right partition, try to do a file system check:
e2fsck /dev/sda1

If you need further assistance add the output to your question.
Comment: I was able to find the disk app and it shows the two partitions a 1.1 gigs. It is a 320gb drive and it looks like it is not seeing the third filesystem drive.
Comment: how do I do it as a super user form the try now disc. I get a command not found with e2fsck
Comment: The server has been running with no problem. The two partitions are the file system and swap disk. I and see the partitions when I use the disk app on the instal disk running test/try now instead of install. I did come across this page http://superuser.com/questions/278864/cant-mount-hard-drive-ubuntu and it seems like the problem I am having. The only thing get privilege problems when I run off the disc (sudo). How can I do the test as a super user running of the disc.

disk will not mount