D3 Zoom's translateExtent not working as expected

Question: I am trying to create a tile map with d3 tile and d3 zoom. I have set both the zoom.extent and zoom.translateExtent to [[0,0], [width,height]]. but when I zoom, the map jumps to the left top corner.
Here is the sample code
const tile = d3.tile()
    .extent([[0, 0], [width, height]])
    .tileSize(512);

const zoom = d3.zoom()
    .translateExtent([[0, 0], [width, height]]) //  issue in this line
    .extent([[0, 0], [width, height]])
    .scaleExtent([1 << 10, 1 << 15])
    .on("zoom", () => zoomed(d3.event.transform));

// applied zoom like this
svg
    .call(zoom)
    .call(zoom.transform, d3.zoomIdentity
    .translate(width / 2, height / 2)
    .scale(-initialScale)
    .translate(...projection(initialCenter))
    .scale(-1));

function zoomed(transform) {
    projection
        .scale(transform.k / (2 * Math.PI))
        .translate([transform.x, transform.y]);
}

Here is the complete demo in Observable
Comment: Trying to unify zoom, projection, geographic, screen, and tile coordinates is enough to drive someone crazy. I'll take a look in a few days - on the road right now, home late next week, but the problem of clarity in units drove me to create an [alternative](https://bl.ocks.org/andrew-reid/3b1fb5ce8957dab2e3f5042931dddf6c) (which is certainly not finished, more of a demonstration of what could be possible - d3.tile is better now (early versions were a bit more cumbersome), but the units still leave a bit to be desired in terms of clarity)
Comment: Thanks @AndrewReid for your comment. In your d3-slippy you have a method `zoomTranslateConstrain` which i have passed to the d3 zoom. Will doing the same work in my case?
Answer: The key challenge here is understanding what you are constraining. The original scale of the projection is 1/(2π): world is projected to a space one pixel by one pixel (2π per pixel or 360 degrees per pixel). This allows for easier integration with d3-zoom, but is certainly not intuitive.
D3 zoom is used to modify the projection and has a scale value of along the lines of 1<<n. This represents the width of the world after the zoom is applied. If the base projection uses a width of 1 pixel for the world, the zoom stretches it across 1<<n pixels. 1<<10 being 1024 for example.
Now, the tricky part is that the zoom translate extent is applied at a zoom scale of 1. So, we need to apply the translate extent to the world as if it was shown within a 1x1 pixel box, even though, given a lower scale extent value of 1024 (1<<10), we never actually show the world as occupying one pixel.
So, our translate extent should be within a box bounded by the two corners: [-1,-1] and [1,1]. This helps explain the comment by Cornel. But can we do this programmatically? Yes.
This is what drove me bonkers about this library: the zoom extent is not registered in something straightforward such as geographic coordinates, or screen coordinates, but zoom units relative to a 1x1 pixel world, introducing a new coordinate system to keep track of which could instead be tracked behind the scenes. This is certainly not intuitive and partially drove me to leave this module behind (explaining the link in my comment, d3-slippy is still pretty experimental, but should show what could be done - btw, the constrain method in the link would only work if you convert everything over to it).
So, let's programmatically get the zoom translate extent of the screen as shown.
First, after we call the zoom and and apply the initial transform, the projection is updated to reflect the new zoom level and translate, so we can use projection.invert() to get the geographic coordinates of the top left and bottom right of the screen.
Second, we can (re)create a projection for our one pixel world and push the geographic coordinates of the top left and bottom right through it to get their projected coordinates within a one pixel world.
Third, we take the top left and bottom right projected coordinates within a 1 pixel world and we pass them to zoom.translateExtent:
   // Call zoom, same as before:
   svg
      .call(zoom)
      .call(zoom.transform, d3.zoomIdentity
          .translate(width / 2, height / 2)
          .scale(-initialScale)
          .translate(...projection(initialCenter))
          .scale(-1));

  // Now we can work on setting the zoom translate extent:
  // Zooomed projected limits of screen in lat long:
  var top = projection.invert([0,0])[1];
  var left = projection.invert([0,0])[0];
  var bottom = projection.invert([width,height])[1];
  var right = projection.invert([width,height])[0];

  // original projection:
  var baseProjection = d3.geoMercator()
    .translate([0,0])
    .scale(1/Math.PI/2);

  // Projected limits of screen in projected unzoomed coordinates:
  var topLeft = baseProjection([left,top])
  var bottomRight = baseProjection([right,bottom])

  // Set the zoom translate extent:
  zoom.translateExtent([topLeft,bottomRight])

Comment: Thanks @Andrew Reid for your detailed answer. However it is still jumps to the bottom corner now. Can you apply the answer in my demo please?
Comment: I didnt see that, will look again, but won't be able until Thursday - I have 24 hours of driving over the next two dys... I had copied the code straight from the modified  obseevable, but will check it again.
Comment: @AbdulAlim, Able to look more now, however, I'm not seeing any issue: https://observablehq.com/d/a028605a652a6274
Comment: Thanks @Andrew Reid for your answer. Did you publish the observable example? I am unable to open it.
Comment: My bad: https://observablehq.com/@andrew-reid/zoomable-raster-vector-with-translate-limit (hadn't ever published anything on observable before)


Bitshift operator on unsigned short in NodeJS

Question: I am trying to perform a Bitwise NOT on an unsigned int in nodeJS/JavaScript. In my understanding every bitwise operator is done on a signed 32bit integer which makes it confusing for me when I want to do it on an unsigned 16bit integer (short). This is what I want to do:
c#
ushort value = 41003;
value = (ushort)~value;
//Value is now 24532 which is correct

nodeJS
var value = 41003;
value = ~value;
//value is now -41004 which is NOT correct

How do I convert the last value to an unsigned 16bit int in nodeJS/JavaScript?
Comment: Well, node doesn't know you want the value to be an `unsigned short`.
Answer: You could just do a bitwise AND to get the same result:
value = ~value & 0xFFFF;

Comment: This seems to be the result I am looking for. Thanks
Answer: You could use a the maximum value of a 16 bit number and perform a bitwise XOR ^.

function not16Bit(v) {
    return ((1 << 16) - 1) ^  v;
}

console.log(not16Bit(41003)); // 24532
console.log(not16Bit(24532)); // 41003
Answer: Or you could simply use the Uint16Array
(new Uint16Array([~41003]))[0] //24532


passing data to javascript in webview before android level 17 (4.2.2)

Question: I am working on some charting library in javascript that call from android.
Understand that JavascriptInterface only available after Android API Level 17 (4.2.2)
http://developer.android.com/reference/android/webkit/JavascriptInterface.html
I want to support android device before 4.2.2
is there anyway to pass a json to javascript?
Answer:
Understand that JavascriptInterface only available after Android API Level 17 (4.2.2)

addJavascriptInterface() has been around since API Level 1. What you are linking to is the @JavascriptInterface annotation, which has only been around since API Level 17. Neither of these things have anything to do with your problem.

is there anyway to pass a json to javascript?

On API Level 19+, use evaluateJavascript(). On API Level 18 and below, use loadUrl("javascript:"), using the same basic syntax used for bookmarklets on desktop browsers.


Arangodb - @include configuration file

Question: In configuration file I can put
<code>@include some_other_file
</code>
The "issue" is that this "some_other_file.conf" has to be under:
<code>/etc/arangodb3/some_other_file.conf
</code>
I tried absolute path, but it seams I can include other files only if they are in /etc/arangodb3/.
/etc/arangodb3/ corresponds to @SYSCONFDIR@ variable I can use in configuration file.
Is there any way to include configuration file from any location ?
Or maybe some way to set @SYSCONFDIR@ to point to directory I want ?
Comment: can you retry with current arangodb 3.1.RC2 whether this is still a problem for you?
Answer: This issue has been meanwhile resolved in ArangoDB 3.1.

Arangodb - @include configuration file


Interlock and backfeed setup with NEMA L6-20

Question: Am starting to put a generator setup together.  I'm planning on setting up an interlock and backfeed breaker into my panel with an outdoor receptacle for the gen to plug into.  The issue is this.  My generator is older(its an old garden way with a cast kohler engine, 5500 and runs like a top), and is setup with a NEMA L6-20 for the 220 which I'm planning on using--it also has two standard nema 5 outlets.  This means it is straight 220...so, can I just wire the whole thing 3 wire, no problem?  meaning in the panel, the 2 hots to the backfeed breaker and the grd to the grd bus bar?  Am I missing something, or do I need the neutral?
Thanks in advance for any input!
Comment: Well, with a NEMA 6 connection, your two hots will be 240V across, but with no neutral to stabilize them, your two 120V legs won't necessarily be 120V.  They might be 130V and 110V... They might be  200V and 40V... Might be 230V and 10V.  That could change minute by minute.    Is that something you can live with?
Comment: Does your generator not have a NEMA 14 (four prong) receptacle whatsoever?
Comment: @Harper    Thanks, interesting-sounds like that could be a problem and fry things plugged into the 110 outlets....  That appears to be how the main power seems to be coming into the house as well, a 3 wire setup, with a braided copper ground going from the ground bus bar to a well feed pipe.   The house was built in 1960.  Its an old Square d QO series panel with the main setup as a 2 pole 100 am breaker on the left leg, lowest spot.
Comment: @ThreePhaseEel nope, just theL6-20 and the nema 5's :./
Comment: On your service entrance, that third bare wire is actually the neutral. Power companies don't supply ground as a rule.
Comment: @Harper  appreciate the responses. ...Sounds like I'm screwed unless I can rewire the gen plug to an L14-20....or I'm running two extension cords to through wall recepticles and setting up seperate "generator" outlets for the well pump/furnace, etc.  Guess I could cut those wires I need and install correct male/female plugs where convenient so I could just unplug form service power, and plug into the gen power outlet..  A little more work running wire and such, but might be a good solution for now.  Thoughts?
Comment: @Harper the braided bare copper is the neutral? I thought it was the ground and the third leg from the power company was the neutral?  I have 3 coated wires coming in from the pole.
Comment: @woodsVT sorry, I misunderstood. You are right.  I was thinking it's common for the power company to bring neutral across the poletop as a bare wire, heck it's often the steel messenger!  But on the service entrance it will be insulated.
Comment: I would say if the generator's design has the NEMA 6 hots bused with the 120V receptacles' hots, then I wouldn't see a big problem with tapping neutrals in the same way and bringing that to a NEMA 14.  Be careful with neutral-ground bonding, that should be present in mobile generator use and absent in home power use.  If you can't get rid of it, you need a 3-pole transfer switch, backfed breakers won't do.
Comment: @Harper, thanks!  I"m going ot pull the gen model numbers when I get home tonight and see if I can find a wiring diagram and specs...It's old...but in awesome shape.  Ugh, really hoping not to have to go to a 3-pole transfer swtich, at that point I might just wire an old fuse box I have as a 120 to some outlets for things and run the nema l6 from the gen with an extension cord and add a nema l6 plug into the well powere just before the pressure switch.  Nothings ever easy is it unless you have unlimited funds, ha!
Comment: @woodsVT -- yes, the generator's wiring diagram would be quite helpful :) if you find it, posting it here would help us figure out if the retrofit option's feasible
Comment: @ThreePhaseEel diagram is above. the generator is a northstar 5500bdg 120/240.  The wiring diagram is above.  I found the manual as ell which states it requires a copper grounding rod, which leads me to believe it is not bonded at the gen.  Its a 4 wire stator from the lol of it and the wire harness.  What do you think? Can I convert to l14-20?  Thanks for the help!!!
Comment: Do you still want/need the NEMA 6-20 receptacle for other purposes? Do you still want to be able to use this generator for portable power, for that matter, or do you plan to dedicate it as a standby power source?
Comment: This will pretty much be for just backup power,but I dont want to ellliminate the 120 outlets so I can still used them if needed.  I was honestly surprised when I read in the manual a grounding bar was needed when running the generator hooked up to the house, or as a portable generator.  Both are specified uses in the manual found here: https://www.northerntool.com/images/downloads/manuals/165913.pdf
Comment: so there are 4 wire coming from the stator/harness, 2 black 2 white that plug into a plastic harness.  the 2 white are bonded and attached to the 120 outlet.  green grd s are attached to screw at center of generator frame internal.  are the two wites just neutral? can I just jump from that contact point to the neutral plug on a newe l14?  new diagram above.  THanks.
Comment: Can you tell me how the wires are attached to the existing receptacles?
Answer: Running the house off the L6-20 receptacle (without the neutral) would be almost sure to start wrecking things on your 120V circuits in short order, blowing light bulbs, refrigerator, etc.  And at the worst possible time, during some emergency.
Since there are 120V receps you know there's a 120V tap in there that can be used to supply line-to-neutral loads.  However there's a chance it is too small to carry the full neutral load for this application.  I am not sure, but from that wiring diagram but it looks like the neutral tab on the 120V receptacle is the neutral-ground bond.
I think it would be possible to modify the wiring and install a L14-30R receptacle, but it wouldn't be a modification I'd be comfortable making.  The alternative would be to use a transformer between the generator and the backfed breaker, but at that point maybe you just buy a different generator better suited for the application .
Answer: One could put a 14-20R on this instead of the 6-20R, yes
About the only feasible way to use this particular generator to power a house would be to replace the existing 6-20R with a NEMA 14-20R (a P&S 3820 appears suitable, but fitment may require modifications to the receptacle yoke ears and/or generator housing).  You'll also need a piece of 12AWG white wire of the appropriate type for use here (a flexing service MTW is what the factory used), a piece of heat shrink tubing, and a suitable splice connector (a 12-10AWG crimp butt splice will do), as well as a suitable crimp tool (preferably of the ratcheting variety).
The wiring changes are as follows:

The brass and black screws on the new receptacle are wired to the existing B50/B52 and B51/B53 ring terminals
The green screw on the new receptacle goes to the G50/G51 ring terminal to ground it
The W51 wire (this is the generator's N/G bond) is cut and the end connected to the ground screw on the receptacle is insulated with shrink tubing, and a 12-10AWG crimp butt splice is used to connect the neutral-screw end to a piece of 12AWG white wire going to the neutral screw on the 14-20R, yielding a floating neutral generator suited for powering a house through a transfer interlock.

With all that done, you can button the generator back up, label it as a floating neutral generator (important!), and use it to power your house up.  (If you need bonded neutral functionality, I'd simply make a 14-20P up with a jumper from N to G to replace the existing bond.)


How to read formatted cell value data using excel vba?

Question: What I'm trying to is read formatted cell value in excel 2007 using VBA.
For example I have a cell with value "01/01/2015" and when formatted it looks like Jan/2015.
Is there a way to read that formatted value Jan/2015 into a variable instead of "01/01/2015"?
Thank you
Answer: try to use
someVariable = Range("A1").Text

instead
someVariable = Range("A1").Value

you can read more here


prevent event from spawning another thread

Question: I bit ago I was reading about delegates and events (for a completely different reason) from this [website][1] In there I got the impression that if your event takes long enough a seperate thread is generated. Well that got me thinking about a bug that I can't seem to fix. So I am making a keyboard wedge program for my MSR device that communicates via the RS232 port. I made this class to handle the input.
    public ComPortInput(SerialPort sp, int delay)
        : this(delay)
    {
        if (sp == null)
            throw new System.ArgumentNullException("Serial port can not be null");

        serialPort = sp;
    }

I subscribe to the DataReceived event when I open this ComPortInput class. If I am guessing correctly then if i set my delay high enough then my dataevent would create a new thread. I think the problem is best described with looking at my code.
Program.cs
    [STAThread]
    static void Main()
    {
        singleton = new System.Threading.Mutex(true, "Keymon");
        if (!singleton.WaitOne(System.TimeSpan.Zero, true))
        { return; }

        InstantiateProgram();
        System.Windows.Forms.Application.Run(main);
    }
    private static void InstantiateProgram()
    {
        System.Windows.Forms.Application.EnableVisualStyles();
        System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
        main = new frmMain();
    }

ComPortInput.cs. Just the datareceived event
    void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        if (Delay > 0)
            System.Threading.Thread.Sleep(Delay); //waits for all the data to be sent to the card.

        int bytesRead = serialPort.BytesToRead;
        if (bytesRead > 0)
        {
            byte[] buffer = new byte[bytesRead];
            serialPort.Read(buffer, 0, bytesRead);

            OnDataAvailable(buffer);
        }
    }

SerialPortWedge.cs
    void Input_DataAvailable(byte[] data)
    {
        Sound.Play();
        Output.SendData(data);
    }

FormattedHexStringOutput
    public override void SendData(byte[] buffer)
    {
        string str = "";
        for(int i=0; i<buffer.Length; i++)
        {
            if ((i+16)%16==0)
            {
                str += string.Format("{1}{0}: ", i.ToString("X3"), System.Environment.NewLine);
            }
            str += string.Format("{0}:", buffer[i].ToString("X2"));
        }
        Clipboard.Clear();
        Clipboard.SetText(str);
        SendKeys.SendWait("^v");
        SendKeys.SendWait("{ENTER}");
    }

On Clipboard.Clear() the program crashes with this error
Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.
at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
at System.Windows.Forms.Clipboard.Clear()
at SerialPortDataSender.FormattedHexStringOutput.SendData(Byte[] buffer) in c:\SerialPortDataSender\Output\FormattedHexStringOutput.cs:line 28
at SerialPortDataSender.SerialPortWedge.Input_DataAvailable(Byte[] data) in c:\SerialPortDataSender\SerialPortWedge.cs:line 34
at SerialPortDataSender.IInput.OnDataAvailable(Byte[] data) in c:\SerialPortDataSender\Input\IInput.cs:line 41
at SerialPortDataSender.ComPortInput.sp_DataReceived(Object sender, SerialDataReceivedEventArgs e) in c:\SerialPortDataSender\Input\ComPortInput.cs:line 135
at System.IO.Ports.SerialPort.CatchReceivedEvents(Object src, SerialDataReceivedEventArgs e)
at System.IO.Ports.SerialStream.EventLoopRunner.CallReceiveEvents(Object state)
at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)

I am at a loss as to why it is doing this. If i add a watch to the current thread appartment state sure enough it is MTA. Yet if i Put a break in the start of the program it says it is STA. So why did it switch? What even stumps me more is that if I use a different Output class it doesn't throw that error
SendRawClipboardOutput.cs
    public override void SendData(byte[] buffer)
    {
        Clipboard.Clear();
        Clipboard.SetText(System.Text.ASCIIEncoding.ASCII.GetString(buffer));
        SendKeys.SendWait("^v");
    }

Nor does this one
SendTrimClipboardOutput.cs
    public override void SendData(byte[] buffer)
    {
        var str = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
        str = str.Replace(System.Environment.NewLine, "");
        Clipboard.Clear();
        Clipboard.SetText(str);
        SendKeys.SendWait("^v");
        SendKeys.SendWait("{ENTER}");
    }

I dunno.. I am stumped. Any one care to tackle this problem?
EDIT
So with help I came up with this as my solution. Since SerialPortWedge is a class and not a control I was not able to call the Invoke method. I had to pass in SynchronizationContext.Current to my SerialPortWedge. So in my main form i have this after I instantiate my SerialPortWedge.
        msr.MainFormContext = SynchronizationContext.Current;

then in SerialPortWedge i changed my Input_DataAvailable to this
    void Input_DataAvailable(byte[] data)
    {
        if(MainFormContext != null)
            MainFormContext.Send(FireEventFromContext, data);
    }
    private void FireEventFromContext(object state)
    {
        Sound.Play();
        Output.SendData((byte[])state);
    }

it now works as desired. Thank you for everyones help. :)
Comment: _I got the impression that if your event takes long enough a seperate thread is generated._ - a very wrong impression.
Comment: @HenkHolterman hahaha wow I'm glad I ask questions. I learn so much. Thank you for clearing that up for me.
Answer: The problem is due to the fact that SerialPort.DataReceived is raised on a separate thread (always - it doesn't matter how long it takes).  From the documentation:

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.

Basically, you need to marshal the call back to the UI thread when you receive data, so your other code will work properly.
void Input_DataAvailable(byte[] data)
{
    this.Invoke(new Action(() =>
    {
        Sound.Play();
        Output.SendData(data);
    }));
}

Comment: @RobertSnyder Can't tell where to put this from your code, but something needs to marshal it.  You could pass SynchronizationContext.Current into one of your classes from a form, and use that to post the data.
Comment: @RobertSnyder Yes, it could do that.  You can put the invoke call (or SynchronizationContext.Send/Post) anywhere in the chain - just make sure it's happened before you call a method on Clipboard.
Comment: ... so as a for instance I could have my main form send the Context (since it instantiated the SerialportWedge)? I'll try that.
Comment: WOW i feel like a newb reading information on this. Thank you for pointing me in the right direction
Comment: Thank you so much for that!!!! I'm going to edit my post to show how I had to do it.


Eclipse plugin to view image while debugging

Question: Is there an Eclipse plugin that will let me view an image variable while I'm paused at a breakpoint?  e.g. I would like to see the image when inspecting a BufferedImage object instead of seeing it's toString value.
Answer: The extension point org.eclipse.jdt.debug.javaLogicalStructures is used to provide the structured view of variables in the "Variables" view... and unfortunately it can only give you a string based result.
In theory, you can add a new plug-in which adds a new command to the "Variables" view (the selection is of type JDILocalVariable)...


New washer overflows from the stand pipe

Question: I just got a new washer and it's overflowing from the stand pipe. My old washer was in the same stop and the standpipe never overflowed. I took a garden hose and put it in the drain and let it run for like 5 minutes and it was draining fine. I'm wondering if the new washer ( Samsung WA45K7600AW) is outputting the water too fast for my drain to handle it. Is that even possible? Just looking at the drain pipes of the old and the new washer, I can see the new one is wider. Please help!
Comment: A larger tube, could result in an increase of volume flowing out, as well as the new washer may have a more powerful pump. As an answer below suggests, try adding a section of pipe to the drain pipe, if possible.
Comment: New washing machines pump out way faster than old ones. A2" line is required to keep up with the gpm
Comment: http://www.fixya.com/support/t114258-water_overflowing_from_drain_pipe.  Here are some solutions that may help
Comment: https://diy.stackexchange.com/a/147629. This too
Answer: This situation indicates that there is a plumbing drain problem. The easiest thing to try is adding some height to the stand pipe with a coupling and a pipe section.
If you can add some detail and maybe a picture we can advise you further.
Answer: Adding Answer Incase someone runs into similar situation. i tried to snake the drain my self but it didn't go far. I thought I was doing something wrong since the water from the older washer and garden hose was making its way down. Finally got the plumber out and opened up the drywall to the p-trap and cut the pipe open. The pipe was disgustingly clogged. I'm not sure how any of the water was making it's way down the drain to begin with.


What is the most productive combination of powers to use in Quickplay+ mode?

Question: Once you've unlocked all eight warriors in Guitar Hero: Warriors of Rock, you have their second-level powers available to you during Quickplay+ mode, and you can use any two powers when playing a song (but only for the specific challenge that permits it).
Which two powers produce the most stars for a given song? If it depends on the song, the skill level of the player, the instrument, or any combination, that's good to know, and if there's one pair that trumps all the rest, I'd like to know that as well.
Powers available:

Axel, Resurrector+ (5 ankhs to resurrect you, unused ankhs become bonus stars)
Casey, Streak Guardian+ (2 shields guard your streak, long streaks earn bonus stars)
Judy, Crowd Hyper+ (Rock Meter starts maxed, overflow meter to earn bonus stars)
Johnny, Speed Freak+ (2x minimum multiplier that rises quickly, stay over 3x to earn bonus stars)
Lars, Multiplier Extender+ (max multiplier is 6x)
Pandora, Star Power Nova+ (Star Power multiplier is 6x)
Echo, Star Power Generator+ (get 10% Star Power for every 10-note streak)
Austin, Star Power Amplifier+ (Star Power earned from phrases is 4x normal amount)
Comment: Hey man. This is a good question, wondered about this for quite some time. Had to experiment rather extensively to get the best combo. Please mark my answer as correct, or comment if/how it is wrong. Thanks*
Comment: Sorry for the delay. I was wondering what other answers we would get, although I could have moved the accepted check to a better one if it showed up (obvs none did).
Answer: I have played this game far too long and far too much, and I still enjoy it.
That being said, I have experimented quite a lot with these powers. Basically, this will depend on the length and difficulty of the song, as well as the amount of notes and whether or not you can/will streak on it.
There is no pair that trumps the rest, but below are some guide lines:

If the song is short, I would suggest using Axel, Resurrector+, since it grants them regardless of length.
If the song is long, and you can streak, it could be useful to use Lars, Multiplier Extender+
If the song is long and contains lots of notes that are streak-able, use Echo, Star Power Generator+

The above STRONGLY applies to guitar. Also, always remember that the higher the skill level, the more the notes, the bigger the score! Although, this only works that way IF THE PLAYER CAN PLAY that skill level. Rather get 90% and above on Hard than getting less than 60% on Expert - Streaking is important!
My personal bests are done with 'Pandora, Star Power Nova+ (Star Power multiplier is 6x)' and 'Echo, Star Power Generator+ (get 10% Star Power for every 10-note streak)' on expert, since I streak a lot on expert, which gives a lot of notestreaks (which gives a lot of Star Power), which allows me to keep my Star Power active through almost the whole song, meaning I get a constant multiplier of 24x (4x6)!!
Using Echo and Pandora, I cannot remember ever getting less than 14 stars ever.
Hope this helps*
Comment: I can see now where this covers much of the answer I added some months ago. I recently edited it to add information to it without disrupting the original answer.
Answer: I am going to go ahead and highly recommend Star Power Generator+ and Star Power Nova+ to have the potential to get the maximum number of stars in this mode if you are highly adept at the song (on whatever difficulty with enough notes, though there is definitely the most potential on Expert, which I have been playing on for quite some years) and can take close to full advantage of the 24x multiplier to get, in this case, up to 20 "score" stars plus one more for a "full combo" (no misses or overstrums) for a total of 21 possible on "score-20-able" songs, or one more than otherwise where it is only possible to achieve 16-19 of these "score stars" no matter how you manage the star power! "Maximum starrability" does vary a fair amount in this game, especially in Quickplay+ Power Mode!
These 20 "Power Stars" from score are awarded for a 21.000x or higher average multiplier throughout the song, as available in "More Stats" for the song, and each star below that is 1 1/6x lower in average multiplier in terms of cutoff for it (so 19* is at 19.833x, 18* is at 18.667x, 17* is at 17.500x, and so on) where I have performed in this mode to date. 14* without a "full combo" is at 14.000x in this scheme, and likewise 8* would be at 7.000x... which would put 7* at 5.833x and 6* at 4.667x... this makes sense from what I've observed through my own rather long-time play on Expert in this particular Guitar Hero game!!
If you cannot pull off keeping your (usually 24x to fully pull this off) multiplier most of the way to get a "Power Star" score above 14-16 stars on whatever difficulty you play on, it would probably be better to use two powers that gain stars from things other than score that you can pull off, but if you can score "very" well on any given song "normally", then I have long observed and achieved scores above the 15-17 stars possible from other combinations of powers that don't involve score enhancement, from my own use of SP Nova+ and SP Generator+ in my own play a vast majority of the time!
Edit 8/24/2019: I can add to this answer that Star Power Amplifier+ is a viable option too most of the time I would suggest Star Power Generator+ with the Star Power Nova+, because it completely fills your star meter for every single star phrase you get. This is useful on charts with less notes for which Star Power Generator+ would be less effective, which includes on lower difficulties with less notes overall. I've been playing on Expert which has the most notes, making SP Generator+ more useful to me overall.


audio play in background issue

Question: I'm developing an application in ionic using cordova-plugin-media and cordova-plugin-mauron85-background-geolocation. When I try to play an audio in background it throws the error code 4 (MEDIA_ERR_NONE_SUPPORTED). This works perfectly in Android and iPhone 5s but fails in some iOS devices (iPhone 6 and iPhone 6s).
Any idea about how can I solve this?
Answer: I had this issue before and it was because I was using an OGG file. Android supports OGG but iOS does not. Wikipedia has a good table showing which browsers support which audio types (https://en.wikipedia.org/wiki/HTML5_Audio#Supported_audio_coding_format). Android is the same as Chrome, and iOS matches Safari.
The solution is to use MP3 or WAV files. I recommend MP3 since you get much smaller file sizes.

audio play in background issue


What theorem can I use to decide if an ODE which admits separation of variables has a unique solution?

Question: Suppose that I have the IVP : $$y' = f(x)g(y)$$
$$y(a)=b$$
It's easy to show that any solution of such an equation will satisfy the implicit formula: $$ \int \frac{1}{g(y)}dy = \int f(x) dx$$
I would like to know if there is a theorem of existence or uniqueness for an IVP like the one above.
Answer: The standard Picard-Lindelöf-Cauchy-Lipschitz existence and uniqueness theorem will apply as long as $f$ is continuous and $g$ is locally Lipschitz.
Answer: The Picard-Lindelöf theorem helps in such cases.
However, it is easy to construct solutions which do not have a unique solution, i.e. the theorem is not applicable.
Consider for example $y^\prime(x) = x^{\frac{1}{3}}$ where $y(0)=0$.
Then a solution is $y_1(x)=0$ and two others are $y_{2,3}(x) = \pm \left(\frac 23 x\right)^{\frac 32}$.


Terraria no longer starts after 1.2 update, terminates with unhandled exception

Question: I have had the game, Terraria for a while and it has always worked fine for me. Recently, a new update, 1.2, came out, and Steam updated the game to that version. After that, Terraria no longer starts up. Even if I run it as administrator, or from cmd. From cmd, there is no error. After entering the command, I am immediately allowed to type again. Nothing happens at all. I do not see any dialog telling me Steam is starting the game, but my friends are told that  I am playing it, then that I am no longer playing it, shortly after.
Here is the error I found in Event Viewer:
Application: Terraria.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.TypeInitializationException
Stack:
   at Terraria.Main..ctor()
   at Terraria.Program.Main(System.String[])

Here's what I've done to fix the problem:

Reinstall Terraria
Reinstall the XNA Framework 4.0
Did not reinstall .NET, but it works with Visual Studio (version 4.5, which is technically just an update to 4.0). Plus, I repaired it, which is, so far as I know, an equivalent to reinstallation.
Verify game cache integrity. This is the strange part. I am always told that the cache is invalid, then Steam redownloads the required file, and the cache is invalid after verifying again.
Restarting my computer
Repairing the XNA Framework in the Terraria folder
Set Terraria to compatability mode for XP SP2, which worked for the initial update, but a new bugfix makes it so that no longer works.

Here are my system specs:
OS Name Microsoft Windows 7 Home Premium
Version 6.1.7601 Service Pack 1 Build 7601
OS Manufacturer Microsoft Corporation
System Manufacturer LENOVO
System Model    IdeaCentre K430
System Type x64-based PC
Processor   Intel(R) Core(TM) i5-2320 CPU @ 3.00GHz, 3001 Mhz, 4 Core(s), 4 Logical Processor(s)
BIOS Version/Date   LENOVO E8KT24AUS, 2/16/2012
SMBIOS Version  2.7
Windows Directory   C:\Windows
System Directory    C:\Windows\system32
Boot Device \Device\HarddiskVolume1
Locale  United States
Hardware Abstraction Layer  Version = "6.1.7601.17514"
Time Zone   Eastern Daylight Time
Installed Physical Memory (RAM) 16.0 GB
Total Physical Memory   16.0 GB
Available Physical Memory   8.21 GB
Total Virtual Memory    31.9 GB
Available Virtual Memory    22.4 GB
Page File Space 16.0 GB
Page File   C:\pagefile.sys

What can I do to get the game to work? I can verify that it did work before with .NET 4.5, so that is not the problem. Can someone help me get a hint as to what's wrong? Thanks.
Comment: @Zibbobz the standard of the computer wouldn't impact on whether the game is able to start or not. Even if it was a lower end machine, it would still launch the game.
Comment: Is your PC particularly old?  If you bought Terraria when it first came out, and your PC was lower-end at the time, and it hasn't been upgraded or changed since then, the jump in required processing power or other hardware requirements may be causing it to shut down before it fully starts up.  Or you could lack some other software/hardware installation necessary, like new graphics card driver or other such things.  This is...unlikely if it's just Terraria having trouble though.
Comment: You mentioned that "this version of .NET is actually an updated version of the one Terraria typically uses." Have you tried downgrading to the version it typically uses? It's possible 1.2 has a bug only triggered by the newer .Net.
Comment: One thing to note is that installing .NET Framework 4.5 doesn't automatically mean any game that needs the framework will work; they're *all* different.  You need the one that comes with the game itself.
Comment: @Dillmo What worked before the update is obviously not relevant. It's crashing now and wasn't then, so all bets are off. Downgrading .Net, even temporarily, is something you haven't tried. Try it?
Comment: You might need to update your .NET, if you haven't installed any new games lately.  I don't know for sure though, but it's worth a try.  You could also contact Steam with these specs for help with troubleshooting.  Can't say either of these will fix it unfortunately, so only a comment, not an answer.
Comment: Terraria worked with my current .NET before the update, and this version of .NET is actually an updated version of the one Terraria typically uses.
Comment: No, my PC came out in 2012. It is a pretty high-spec machine, and is able to handle games like Civilization V at maximum graphics without lag.
Comment: Can you give some specs, such as Operating System, hardware, etc.?
Comment: Random software developer here.  `TypeInitializationException` is thrown when a static initializer throws an exception - it is a wrapper around the true exception.  Thus, the true cause of the crash will be hidden inside of that exception.  Usually when a program crashes, Windows pops up a dialog that says "Terraria.exe has crashed!" and gives you the option to view the details of the crash.  That is where you will find the relevant information.
Comment: (cont.) My first guess would be that XNA is not installed correctly, but given the steps you took, I doubt that is it.  Could you try reinstalling [this](http://www.microsoft.com/en-us/download/details.aspx?id=8328) as well?
Comment: @SevenSidedDie What I mean is, .NET 4.5 is actually the same as 4.0. Programs get 4.0 if they want it. However, it also includes the latest tools for .NET development (which I need for Visual Basic development). Also, this had worked with Terraria before the update, so I don't think it is the problem.
Comment: @BlueRaja-DannyPflughoeft Sadly, I get no dialog saying Terraria has crashed. It just terminates instantly. The only error I can find is the one in Event Viewer.
Answer: According to numerous sources (one, two) it's in fact related to .NET installation. In order to repair it, you need to uninstall both XNA Framework, and .NET Framework.
Using "Programs and Features":

Uninstall Terraria
Uninstall all XNA stuff
Uninstall all .NET Framework stuff ("extended" must be uninstalled first!)
Reboot
Reinstall Terraria and let it reinstall the .NET and XNA stuff.
Comment: @Dillmo - How about you try the suggestion before you dismiss it?
Comment: Here's some background knowledge on why I don't think this will help: When I first updated Terraria to v1.2, I had the same issue, but was able to fix it by setting it to compatibility mode for Windows XP SP2. Upon updating to a bugfix, the same issue popped up. However, the same fix did not work. I have tried reinstalling both frameworks. This is where I'm at.
Comment: Thanks. You did help me fix my problem. Apparently it was not a problem with .NET or XNA, but a missing dependency. Terraria worked before because it made not calls to .NET Extended, but now that it does, it stopped working. So, by installing .NET 4.0 Extended, I was able to fix my problem.
Comment: @Dillmo glad that helped somehow in the end. Terraria is a great game :)


Get a resource string based on javascript value

Question: Is it possible to accomplish something like this?


My app background process stops, if device booted

Question: my apps background process stops on device rebooting. What to do to make it always running also after device booted. Because my notification did not show on device boot
Comment: user broadcast receiver to listen boot complete event & start your app on boot complete
Comment: If you're not using `BroadcastReceiver` Then, simply use that. Have a look at [this](http://stackoverflow.com/a/6392009/940096)
Answer: You have to use BroadcastReceiver. and call your process inside this class. And in your manifest,
<receiver android:name=".BroadCastClass">
  <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
  </intent-filter>
</receiver>

And add uses permission.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Answer: Example code for manipulate your application onBoot of your application -
public class OnBootReceiver extends BroadcastReceiver
{
   @Override
   public void onReceive(Context context, Intent intent) {
      Log.d("OnBootReceiver", "Hi, Mom!");
   }
}

Add the below permission for onBoot service -
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

And, in your manifest file, you've to add the OnBootReceiver class for register it like below -
<receiver android:name=".OnBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

A perfect example from Commonsware available on GitHub


How is nullptr rvalue

Question: While looking at the implementation of nullptr here, what got my attention is that nullptr is rvalue which means we can do something like this
std::nullptr_t&& nullref = nullptr;

But how could nullptr be rvalue since the implementations is something like this
const class {...} nullptr = {};

Is this core feature ? What am I missing ?
Comment: _Every_ keyword is a "core feature".
Comment: It's just like `this`.
Answer: Implementation has nothing to do with it.
The keyword nullptr is defined to produce an rvalue expression, and that's the end of it.

[C++14: 2.14.7/1]: The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t. [ Note: std::nullptr_t is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value. See 4.10 and 4.11. —end note ]

I agree you couldn't yourself reimplement it to this criterion in userspace, but then that's the case for every single other keyword also.
Expressions consisting only of the keywords true and false are also rvalues, if you're curious.

[C++14: 2.14.6/1]: The Boolean literals are the keywords false and true. Such literals are prvalues and have type bool.
Answer: If Alternative #1 were the definition of nullptr, then you are right that it would be an lvalue. However, it could be forced to be an rvalue using something like this:
const class __nullptr_t {...} __nullptr = {};
#define nullptr (__nullptr_t(__nullptr));

That's not what was ultimately standardized though. In actual C++11, nullptr is a literal, the same way as 3.14 or 'x'.

How is nullptr rvalue


"Protocols cannot be used with isinstance()" - why not?

Question: The new typing module contains several objects with names like "SupportsInt" (-Float, -Bytes, etc.). The name, and the descriptions on the documentation page for the module, might be read to suggest that you can test whether an object is of a type that "supports __int__()". But if you try to use isinstance(), it gives a response that makes it clear that that isn't something you are meant to do:
>>> isinstance(5, typing.SupportsInt)
(Traceback omitted)
TypeError: Protocols cannot be used with isinstance().

On the other hand, you can use issubclass():
>>> issubclass((5).__class__, typing.SupportsInt)
True
>>> issubclass(type(5), typing.SupportsInt)
True

What is a "protocol" in this context? Why does it disallow the use of isinstance() in this way?
Comment: The purpose of the `typing` module is **not** to provide a way to perform those checks. It's meant to provide a common way to provide the types of functions etc. in their annotations. Duck-typing is still preferred, you can use those types to tell your user how the function is intended to be called.
Comment: @Bakuriu, but the typing module is provided in part to allow static type-checking, and so it is reasonable to suppose that it will provide the machinery for identifying (say) whether a particular object is of a particular type. If I invoke a function passing 5 as a parameter that is annotated as being of type typing.SupportsInt, then how will a static type checker know that this is valid?
Comment: Not to mention that runtime checking is essential if we're trying to dynamically load something from details in a configuration file, and we need to check that what we loaded does in fact conform to the expected protocol.
Answer: If you reached this question wanting to get around the error (like I did), the solution is to decorate the protocol class with @runtime_checkable:
from typing import Protocol, runtime_checkable

@runtime_checkable
class StorageProtocol(Protocol):
    ...

@typing.runtime_checkable
Mark a protocol class as a runtime protocol.
Such a protocol can be used with isinstance() and issubclass().

storage = ...  # get something that must implement StorageProtocol
if not isinstance(storage, StorageProtocol):
    raise RuntimeError(...)

Answer: This is all of the reasoning given in PEP 484, the PEP for the typing module:

Because typing.Callable does double-duty as a replacement for collections.abc.Callable , isinstance(x, typing.Callable) is implemented by deferring to `isinstance(x, collections.abc.Callable) . However, isinstance(x, typing.Callable[...]) is not supported.

A protocol is also known as a magic method. These are most of the python protocols (full list here):
>>> dir(object)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__',
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__']

I have not found any clear reason for why typing does not support isinstance. The reason that issubclass works is that isinstance uses the __class_ protocol which is not allowed in typing, while issubclass uses the __subclasshook__ protocol which is allowed. I believe the reason is that the functionality was already coded in collections.abc.Callable and they did not want to recode it in the typing module.
Answer: As the documentation says: At runtime, isinstance(x, T) will raise TypeError. In general, isinstance() and issubclass() should not be used with types. ( https://docs.python.org/3/library/typing.html?highlight=typing#typing.TypeVar )
Comment: This is a description of what happens. The question asks why this is the behaviour. You have answered a different question to the one that was asked.
Answer: Protocols are intended to be used together with static type checking, to illustrate that a method can use anything that satisfies the protocol, so that duck typing can be statically checked.
It intentionally does not add any kind of runtime behaviour. Using protocols should strictly decrease the amount of implicit branching in your code instead of increasing it. You can inherit from a protocol, but that's just to get warnings if you don't implement methods.


Errors writing a dice simulator using randomisation in python

Question: I'm making a dice simulator in python. The program throws four dices 1000 times, then calculates how many times the sum of the four dices is equal to 21 or higher. This is what I've written so far:
    import random

    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    dice3 = random.randint(1,6)
    dice4 = random.randint(1,6)

    sum = dice1 + dice2 + dice3 + dice4

    n = 0    # the amount of times the sum of the score was 21 or higher

    for i in range(1000):
        dice1 = random.randint(1,6)
        dice2 = random.randint(1,6)
        dice3 = random.randint(1,6)
        dice4 = random.randint(1,6)

        for sum >= 21:
            n = n + 1

    print("You got 21 or higher", n, "times.")

However, the program's terminal only shows "You got 21 or higher 0 times." or "You got 21 or higher 1000 times." when I attempt to run it. How do I write the code so it calculates the amount of times the sum of the score is 21 or higher out of 1000 throws of the dice, as well as print the amount of times in the terminal? Thank you in advance!
Comment: Are you quite sure you wrote `for sum >= 21:`? This is not valid python syntax. That `for` should be an `if`. The other issue is that your forgot to update variable `sum` inside the `for`-loop, so it keeps its initial value (the sum of the four dice on the very first roll).
Comment: You are not updating sum inside the for loop, by the way avoid using this name as it shadows the built-in sum
Answer: You should update variable sum inside the for-loop. Otherwise, it keeps its initial value, which is the sum of the four dice in the very first roll.
Note that their is a python builtin function called sum, and it is very bad practice to use builtin names for your variables. Below, I renamed the variable to sumOfDice.
import random

n = 0    # the amount of times the sum of the score was 21 or higher

for i in range(1000):
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    dice3 = random.randint(1,6)
    dice4 = random.randint(1,6)

    sumOfDice = dice1 + dice2 + dice3 + dice4

    if sumOfDice >= 21:
        n = n + 1

print("You got 21 or higher", n, "times.")

Other improvements
When you start to have variables with numbers in their names, you should ask yourself: do I really need four named variables for the dice? Wouldn't it be easier to use one single list to hold the four values? If dice is a list, then you can access the individual values as dice[0], dice[1], etc. But you can also use loops list comprehensions and other cool python features to manipulate the list. You can even call the python builtin sum to get the sum of the list!!
import random
n = 0
for i in range(1000):
    dice = [random.randint(1,6) for _ in range(4)]
    if sum(dice) >= 21:
        n = n + 1
print("You got 21 or higher, {} times.".format(n))

Comment: +1 for the list of N dice rolls. In this specific case, we could even write `rolls_sum = 4 * random.randint(1, 6)` because the average result will be the same.
Comment: @Guimoute That's wrong. We are not interested in the average result, we are counting the number of times the result is above 21. Imagine if I flip a coin with "0" on one side and "10" on the other, and ask you "how many times is the value greater than 7?" The average of 0 and 10 is 5, and 5 is never above 7. Yet the correct answer should be about half the number of flips.
Comment: Ah, I see! Thanks for your input and the tip on efficient python features Stef! I feel like implementing aforementioned features might be a little over-kill for me right now, as I've just begun with coding in Python, but I'll definitely keep it in mind for future endeavours when I'm a little more comfortable using the language! :-)
Comment: @quasireal Even if you're a beginner I still recommend using `dice = [random.randint(1,6) for _ in range(4)]; sumOfDice = dice[0] + dice[1] + dice[2] + dice[3]` rather than the very repetitive `dice1 = random.randint(1,6); dice2 = random.randint(1,6); dice3 = random.randint(1,6); dice4 = random.randint(1,6); sumOfDice = dice1 + dice2 + dice3 + dice4`.
Answer: You need to calculate the sum of dice within the for loop.
In your example, sum always equals to the sum of random numbers generated in first 4 calls to random.randint, but you should recalculate the sum each time.
Also, in line where you have for sum >= 21, the for should be replaced with an if. for is used for repetition, if for conditional execution.
Answer: I fixed the problem. Can you try this
import random

n = 0

for i in range(1000):
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    dice3 = random.randint(1,6)
    dice4 = random.randint(1,6)
    sum = dice1 + dice2 + dice3 + dice4
    if sum >= 21:
        n = n + 1

print("You got 21 or higher", n, "times.")

Comment: Aaah, I see the sum definition in the for-loop is what I was missing... It runs perfectly now that I've added it, thank you Cenk! :D
Answer: You dont need to define the dices, each random.randint(1,6) is a dice itself.
import random

n = 0    # the amount of times the sum of the score was 21 or higher

for i in range(1000):
    sum = random.randint(1,6) + random.randint(1,6) + random.randint(1,6) + random.randint(1,6)

    if sum >= 21:
        n = n+1

print("You got 21 or higher", str(n), "times.")

Here's a pythonic way:
dice_sum = [int((x/x)) for x in range(1,1001) if  random.randint(1,6) + random.randint(1,6) + random.randint(1,6) + random.randint(1,6) >= 21]

print("You got 21 or higher", str(sum(dice_sum)), "times.")

All I'm doing is getting the index each time the dice is >= 21, then dividing it by the same index so it returns 1 to the list, I then get the sum of list, which is just how many times 1 has been added to the list, which is how many times the dice was >= 21.


Use PySide6 in thread

Question: Qt has a promising SCXML module. Since PySCXML is obsolete, there is no other native python scxml library, which lets me run a scxml statemachine. That's why I try PySide6.
Since I don't need any Qt despite of the scxml library, I thought about running the QCoreApplication in a seperate thread, in order to have the event-loop right there.
According to the documentation QScxmlStateMachine needs one.
Unfortunately my start_statemachine() method doesn't return, but the statemachine starts working.
Any advice on how to start a QScxmlStateMachine in a thread is welcomed.
from PySide6.QtCore import QCoreApplication, QObject
from PySide6.QtScxml import QScxmlStateMachine
from PySide6.QtCore import QTimer
import threading

def start_statemachine(filename):
    app = QCoreApplication()
    mysm = MyStateMachine(filename)
    mysm.start_sm()
    app.exec()

class MyStateMachine(QObject):

    def __init__(self, filename):
        super(MyStateMachine, self).__init__()
        self.sm = QScxmlStateMachine.fromFile(filename)
        self.counter = 0
        self.timer = QTimer()
        self.timer.setInterval(2000)
        self.timer.timeout.connect(self.recurring_timer)
        self.timer.start()

    def start_sm(self):
        print('starting statemachine')
        self.sm.setRunning(True)

    def recurring_timer(self):
        print(self.sm.activeStateNames())
        self.counter += 1
        print("Counter: %d" % self.counter)
        print('statemachine running status: ' + str(self.sm.isRunning()))

if __name__ == '__main__':
    x = threading.Thread(target=start_statemachine('statemachine.scxml'))
    x.start() #won't be reached
    while True:
        pass #do something else
    x.join()

Answer: The thread target needs to be a reference to a function that will be called in the external thread, but you're not running start_statemachine() in another thread: you're actually executing it in place:
x = threading.Thread(target=start_statemachine('statemachine.scxml'))
                                              ^^^^^^^^^^^^^^^^^^^^^^

Your program is stuck there, no thread is even created because the constructor is still "waiting" for start_statemachine() to return, and since exec() is blocking, nothing else happens.
A basic solution could be to use a lambda:
x = threading.Thread(target=lambda: start_statemachine('statemachine.scxml'))

But you'll need access to the application in order to be able to quit it: x.join() won't do nothing, because the QCoreApplication event loop will keep going, so a possibility is to create a basic class that provides a reference to the application:
class StateMachineWrapper:
    app = None
    def __init__(self, filename):
        self.filename = filename

    def start(self):
        self.app = QCoreApplication([])
        mysm = MyStateMachine(self.filename)
        mysm.start_sm()
        self.app.exec()

# ...

if __name__ == '__main__':
    statemachine = StateMachineWrapper('statemachine.scxml')
    x = threading.Thread(target=statemachine.start)
    x.start()
    while True:
        pass #do something else

    if statemachine.app:
        statemachine.app.quit()

    x.join()

Use PySide6 in thread


How to execute 'for i in range' loop twice?

Question: I am trying to make Karel pick three batches of beepers each consisting of ten beepers. I want  'move_batch()' to be called twice but it is executed 3 times because of the first 'for i in range(3):' command. When Karel moves 3 times, it meets the wall and crashes. How can I call 'move_batch()' 2 times using 'for i in range()' so that Karel does not crash to the wall link?
from karel.stanfordkarel import *

def main():
   move()

   for i in range(3):
      pick_ten_beepers()
      move_batch()

def pick_ten_beepers():
   for i in range(10):
      pick_beeper()

def move_batch():
   move()
   move()

Answer: you can add if condition in for loop where i should be less than equal to 1.
def main():
   move()

   for i in range(3):
      pick_ten_beepers()
      if i <= 1:
        move_batch()

def pick_ten_beepers():
   for i in range(10):
      pick_beeper()

def move_batch():
   move()
   move()


Gimp installation failed due to depedency

Question: I want to install gimp in 13.10. I follow these procedure to install gimp.
sudo add-apt-repository ppa:otto-kesselgulasch/gimp-edge
sudo apt-get update
sudo apt-get install gimp

But after i update the system, when i go for the last command.(sudo apt-get install gimp)
It show this error
The following packages have unmet dependencies:
 gimp : Depends: libgimp2.0 (>= 18.104.22.168-build~33915~145295a~saucy0~ppa) but it is not going to be installed
        Depends: libgimp2.0 (<= 188.8.131.52-z) but it is not going to be installed
        Depends: libgegl-0.3-0 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

How can i install the gimp and resolve the error. please help me.
Answer: The procedure to install gimp is sudo apt-get install gimp
When using a third party repository you are mostly on youw own and if there is any issue with the repository you must contact with the person that maintains it.
Comment: When install gimp, the above error is shown. What i cant understand.
Comment: No, you added a third party repository and installed gimp from there.


Replace polling with clever simulation

Question: On our website, users can type in their phone number to verify it. We initiate the call and pop up a verification code on the screen. However the dialog box stays up indefinitely, until the user closes the box. This leads to a frustrating user experience as people don't think their number was verified, because the screen hasn't updated.
For technical and political reasons I cannot continually poll the server in the background to determine if the call succeeded or failed, and update the UI accordingly. I can poll the server only one time to check the status.
Is there another way I can indicate on the screen the success or failure of the call?
Comment: could you communicate the code via the phone call, and then get the user to submit the code thus closing the box?  And if the user has not answered after x seconds, assume the call failed and close the box?
Comment: So when do you actually validate if the call went through?
Comment: The user sends DTMF tones on their phone back to us with the code we show on the screen and we write to our database if the code is correct.
Comment: Could you post a screenshot of the dialog that you show. Maybe a graphical adaptation would be enough to make it clear for a user that he needs to close that dialog.
Comment: Is the dialog box showing up on their screen or their phone? If it's desktop (or even mobile) why is a simple AJAX poll not available? You *have* to check outside data unless you want to just fake "success" and close the dialog after a certain period of time
Answer: Don't express it as a close box for the popup (or not solely that). Instead, have a button labeled "I've received the call", which then causes the sole status check.
Answer: You can improve the experience described here by avoiding the popup (display what you need directly in a page). Introduce a "Re-check" button that the user can press to check the status. I've seen this kind of verification form with some other occasions and I find it easy and intuitive for the user and easy to implement also.

Replace polling with clever simulation


Start long running background process and check the status

Question: I want to start a potentially long running background process from Delphi. I want to leave the process running independently, but first I want to check that the process started OK.
If anything went wrong on startup, I want to capture any output written to standardErr and log it. If the background process starts OK, my program needs to be able to exit and leave the spawned process running.
The psuedo code would be something like this:
process:=RunProgramInBackground('someCommand.exe');
sleep(1000); // Wait a bit to see if the program started OK
if process.Finished and process.ExitCode=FAIL then
    Raise Exception.Create(process.ErrorStream);
process.Dispose; // Close any connection we may still have to the running process
Program.Exit; // Background process keeps running

I've looked at a few things (WinExec, CreateProcess, ShellExecute, JclMiscel) but can't find any examples for what I'm trying to do. What is the best way to do this?
I'm using Delphi 2010
The background process is a 3rd party program I don't have the source to.
Comment: Surely the 'RunProgramInBackground' could be implemented in a thread (assuming that you have the code to 'somecommand')?
Comment: This question likely needs clarified.  Is "someCommand.exe" something you have the source for or not?  Otherwise, what you do is start the process, then capture any exit codes, and then if there's no error, you wait until completion.  You can do this in a thread, of course, but a lot of what you are wanting to do needs made more specific.
Comment: @No'am It's a third party executable. I don't have the source code.
Comment: @Glenn1234 I don't want to wait until completion. I just want to check that the process started, then leave it to run by itself.
Answer: Check out this article. I quote: "Here is an updated and improved version of the code that allows you to choose in code whether the calling application waits until the other program closes before continuing or just carries on leaving the newly started program to its own devices".
procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
 StartInfo : TStartupInfo;
 ProcInfo : TProcessInformation;
 CreateOK : Boolean;

begin
 { fill with known state }
 FillChar(StartInfo,SizeOf(TStartupInfo),#0);
 FillChar(ProcInfo,SizeOf(TProcessInformation),#0);
 StartInfo.cb := SizeOf(TStartupInfo);
 CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil,False,
                    CREATE_NEW_PROCESS_GROUP+NORMAL_PRIORITY_CLASS,
                    nil, nil, StartInfo, ProcInfo);
 { check to see if successful }
 if CreateOK then
  begin
    //may or may not be needed. Usually wait for child processes
   if Wait then
    WaitForSingleObject(ProcInfo.hProcess, INFINITE);
  end
 else
  begin
   ShowMessage('Unable to run '+ProgramName);
  end;

 CloseHandle(ProcInfo.hProcess);
 CloseHandle(ProcInfo.hThread);
end;

Edited: after reading your comments, I suggest that you look at this previous question
Comment: @awmross I'm thinking something similar to http://www.martinstoeckli.ch/delphi/delphi.html#AppRedirectOutput  The problem I'm running into in my own example is that redirection isn't working on anything but the command prompt itself.  But it illustrates how to do it.
Comment: I had to add a line 'UniqueString(ProgramName);' before calling CreateProcess. Otherwise the program segfaulted. See http://blogs.msdn.com/b/oldnewthing/archive/2009/06/01/9673254.aspx
Comment: The process could start OK, but then exit with an error. Perhaps I still need to call WaitForSingleObject, but with a finite timeout (e.g. 1000, as in the original question). I still need a way to read any error stream...
Comment: @awmross What has been given here is good.  What you need to do is remove the "WaitForSingleObject" call and in place there read off a pipe to see what the Error stream is.
Comment: @Glenn1234 Any idea how to do that?
Comment: CreateProcess 2nd parameter is IN/OUT in unicode (but somehow, not in ansi). So the call will crash if the string ProgramName points to read-only memory. That happens if you call with a constant parameter or a string literal, for example. UniqueString is indeed the best fix for that problem.
Answer: I ended up using the example No'Am linked to, and adding code to check that the process started OK. This function only checks the exit code of the background process, it doesn't read the StdErr output.
Here is what I did:
///  Runs a new process in the background. Waits for a short period, then checks that the process started succesfully.
/// If the process has already finished, checks the exit status. Otherwise, leaves it to run.
/// <param> ProgramName The executable name, including any parameters.</param>
/// <param> TimeOut Milliseconds to wait before checking the process has executed correctly</param>
/// <param> Directory The full path of the working directory</param>
/// <exception> Exception If the process was not started correctly or if the process was started but returned
/// an error before the timeout.</exception>
procedure ExecBackgroundProcess(ProgramName : String; TimeOut: Integer; Directory:string);
var
    StartInfo : TStartupInfo;
    ProcInfo : TProcessInformation;
    CreateOK : Boolean;
    status: Cardinal;
    theExitCode: Cardinal;
begin
    FillChar(StartInfo,SizeOf(TStartupInfo),#0);
    FillChar(ProcInfo,SizeOf(TProcessInformation),#0);
    StartInfo.cb := SizeOf(TStartupInfo);
    UniqueString(ProgramName); // Required if a const string is passed in. Otherwise the program crashes.
    CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil,False,
              CREATE_NEW_PROCESS_GROUP+NORMAL_PRIORITY_CLASS+CREATE_NO_WINDOW,
              nil, PChar(Directory), StartInfo, ProcInfo);

    if CreateOK then
    begin
        status:=WaitForSingleObject(ProcInfo.hProcess, TimeOut);
        if status<> WAIT_TIMEOUT then
        begin
            // Program has exited. Get exit code.
            GetExitCodeProcess(ProcInfo.hProcess, theExitCode);
            if theExitCode<>0 then raise Exception.Create('Program '''+ProgramName+''' failed with exit code '+IntToStr(theExitCode));
        end
    end
    else
      Raise Exception.Create('Unable to run '+ProgramName+' in directory '+Directory);

    CloseHandle(ProcInfo.hProcess);
    CloseHandle(ProcInfo.hThread);
end;


Can initialization list in constructors be used in template classes?

Question: I find that most books concerning C++ templates don't tell anything about whether it's possible or not to use initialization list in constructor of a template class.
For example, I have code like this:
template <class T>
class Stack {
    T* data;
    std::size_t count;
    std::size_t capacity;
    enum {INIT = 5};
public:
    Stack() {
        count = 0;
        capacity = INIT;
        data = new T [INIT];
    }

Can I replace the constructor with
Stack(): count(0), capacity(INIT), data(new T [INIT])

Answer: Yes. Did the compiler tell you otherwise?
Answer: I've just tried and VS2008 says that it's OK, but it seems a little bit strange because some great authors don't do that (Eckel, for example, in his "Thinking in C++").


Is there a way to test if I will be able to login again?

Question: I messed up with my files... Again... Now I am concerned if I will be able to login again once I logout. Is there a way to test if the essentials files are all there?

My home was encrypted during the installation (Ubuntu 12.04).
By login I mean boot Ubuntu into lightdm, type my password and be able to use my files which are encrypted and should be decrypted after the login.
By messed up I mean I have moved all my ".xml" files under user directory. I do not care that much for the configuration of the applications, neither for my keyboard shortcuts as I have a backup for them.
I can run ecryptfs-unwrap-passphrase ~/.ecryptfs/wrapped-passphrase and it shows me the passphrase.
At ~/.ecryptfs I have auto-mount  auto-umount  Private.mnt  Private.sig  wrapped-passphrase.

One Ecryptfs manual says:
$ man ecryptfs-setup-private

FILES
   ~/.ecryptfs/auto-mount

   ~/.Private - underlying directory containing encrypted data

   ~/Private - mountpoint containing decrypted data (when mounted)

   ~/.ecryptfs/Private.sig - file containing signature of mountpoint passphrase

   ~/.ecryptfs/Private.mnt - file containing path of the private directory mountpoint

   ~/.ecryptfs/wrapped-passphrase - file containing the mount passphrase, wrapped with the login passphrase

   ~/.ecryptfs/wrapping-independent  -  this  file  exists  if  the wrapping passphrase is independent from login passphrase

May be those all are the required files?
Edit:
I rebooted the computer and although I have lost the configuration of applications and Keyboard Shortcuts I was able to login again. So I can say that no xml file is needed to login into an Ubuntu encrypted home.
But the question remains valid: is there a way to test if one will be able to login in the next boot?
Comment: What did you "mess up"? Are you asking about log in (pam, gdm, lightdm, kdm?) or encryption (ecryptfs)? Please clarify your problem and question. More likely then not the bottom line is going to be to log out an try it. If you can not log in you will have to boot to recovery mode and fix the problem, but hard to tell from what little you posted.
Comment: @bodhi.zazen Thank you Bodhi, I clarify the problem in my question now.
Comment: I am not sure how those configuration files would cause a problem with decrytping you home directory. You can not really "test" ecryptfs (encryption) without loging out because if you log in to a terminal, or ssh, while you remain previously logged in, the files will remain decrypted. You could probably manually re-encrypt yoru /home directory, but doing so while logged into X is going to be more hassle then it is worth.
Comment: @bodhi.zazen Do you know which are the "essentials" files of ecrypts?
Comment: As far as I know, the only essential files / directories in your home directory are in .Private and .ectyptfs See - http://blog.dustinkirkland.com/2009/06/migrating-to-encrypted-home-directory.html and http://askubuntu.com/questions/138950/how-to-disable-encrypted-home-directory but as you are not having a problem ...
Comment: With that edit those appear to be the required files.
Comment: One possible way to test is to copy your entire home folder into another system, or virtual system, but not a very convenient solution.
Comment: @Sparhawk A lot of disk space and time would be required. But are you sure it would reflect the actual state of the "original" system? Because as the "original" home is mounted the copied home wouldn't be identical.
Comment: @desgua To be honest, I'm not sure. However, I thought this might be equivalent to a situation where your computer crashes and you have your home folder preserved in its "mounted" state. I imagine that if it mounts after a pseudo-crash, then it should mount normally. I agree that a lot of disk space and time required, which is why I only posted this as a comment.
Comment: @Sparhawk Nevertheless this was the best solution so far.
Comment: @desgua I've added it as an answer just in case there are no better ones. I imagine it should work in theory, even if it's probably more painful than just trying to log out/in immediately.
Answer: One possibility is to copy your entire home folder into another system (or virtual system), and see if you can log into this system.
This is not ideal and suffers from a few shortcomings.

It's not very convenient, as you would need to install a parallel system, and copy across an entire home folder (although you could exclude personal documents).
Since you don't want to risk logging out, the copied home directory will be copied from its "mounted" state, which might differ from the "logged out" state. However, I imagine that this is equivalent to a situation where your computer crashes and your home folder is preserved in its "mounted" state. I imagine that if it can mount after this pseudo-crash, then it should mount under normal circumstances.
Comment: I will give you the bounty because it is the best answer so far although I think that there must be a better way to check it. Congratulations!
Comment: @desgua. This won't work because you are forgetting that the installed files are in system folders and files so you need to replicate the entire system if that is to work. There are build system's for testing in the way you seek to describe. As far as I know ubuntu don't use one, gnome do and so do opensuse
Comment: @Magpie I guess you are right.
Comment: @desgua Thanks! (Although feel free to revoke it if there's a better answer.) I didn't say it was perfect. Anyway, to solves @Magpie's probably legitimate concerns, you could also replicate the entire system too. In my case, this makes it only slightly less feasible, since `/` is so small compared to `~`.
Answer: The is no method that I know of to do what you describe. However if you struggle to graphically login to can get around this by login in via the terminal
Step One
boot and press e i the grub dialogue.
Step Two
Move the cursor down to the line which loads your kernel.
If you don't know what to look for then it should say something like either linux or linuxefi and be a long string of various letters, numbers and spaces that look like jibberish.
the line after it should say something like initrd -( you essentially need to go to the very end of the line just before the cursor reaches newline with initrd)
Step Three
type the followin before the end of the line (from step two)

rw init=/bin/bash

Step Four
press F10 to boot
Step Five
when you are in the terminal type
login yourusername

you will be prompted for your password and this should give you access.
Step Six
Type:
startx

to get to a graphical login
Step Seven
if that doesn't work the error in /var/logs/Xorg.0 should tell you why it did not work and help you fix the problem.
Comment: Thank you Magpie. The /var/logs/Xorg.0 file would be a guide in the search for a solution. But the question is if, in the future, I mess something up again, how can I test without risking loosing my files?
Comment: you won't lose your files if you are able to login via terminal
Answer: You should be able to log in.  I mean because the fact that you logged in again. I'm pretty sure those are all the needed files. I have a older version of Ubuntu and I after messing with the files was able to log in.
Comment: Yes I am able to login. But if, in the future, I mess something up again, how can I test without risking loosing my files?
Comment: You may be able to copy the log in files and test them on a vurtal machine.


Skyrim keeps freezing when it is loading an area?

Question: Whenever I fast travel, go into a cave or enter other areas, the loading takes a long time.
I am playing the game on PS3, so I try to quit the game by using the PS button to get to the menu but it does not load. I also tried turning off the console but then everything freezes.
What should I do?
Comment: How long is the loading time if you succeed to load an area? Or won't it ever load?
Comment: How old is your PS3?
Comment: This happens on console, not  just PS3.  I've played this on XBOX 360, PS3, and PC.  It has frozen on me on both consoles but not PC.  I'm pretty sure it happens when you've been playing for a while and the console gets hot.  Try moving your console somewhere with better ventilation.
Answer: Long load times CAN be a result of a save file getting too big in size.
As you might have noticed while playing, the size of the save file increases slightly as you progress through the game which results in longer loading times and in the worst case scenario, the game crashing. This is a problem, which as far as I know, exclusive to the PS3 version of the game.
Here are a few things you can do to keep the file size in check:
1) Close doors behind you so that the game does not have to save them in the "open" state.
2) Do not drop your loot on the ground because the game has to remember where you dropped it, if you are encumbered, dump it in a corpse instead as they disappear in a couple of days and so will the loot. Basically avoid interaction with things that you do not intend on using. For example: jumping on a table and dropping the plates and food on it, the game will have to save that, don't do it! Try your best not to alter things from when you started the game and you should have a much lower file size.
3) Do not take every quest you come along and fill your quest log with tons of quests, finish the older ones and then pick the new ones.
Hope this helps :D
Answer: First of all, I would like to agree with Lovejinder_LJ. His solution can help out lowering the loading times in game. My recommendation though is to "clean out" your Ps3.Start by finding your old games, apps, and other things that you don't use and delete them. They use up a lot of memory on your console and can affect the performance.The second thing you should do is unplug your Playstation. It is recommended that you have a can of compressed air and you blow out your console, and if the warranty happens to be voided/expired, then take the extra step of taking off the plastic covering to blow it out. You don't need to do anything major on the inside, just blow it out with your can of air. Also remember to clean all the dust out from where you keep your system.Finally hook it back up with all the wires and everything except for the power cord. Hold down the eject button and then plug in the power cord while still holding the eject button. After a few seconds of holding the button down, the fans will go into overdrive and will remove all the extra dust and other things inside your system. You will have to unplug the power and then plug it back in after it is done. (You will know when it has started and when it has finished by the noise of the fans.)note: If you have never used a can of compressed air before, make sure you do not hold it up-side-down. Doing so will cause the air inside to spray out freezing cold and can damage your system if you blow it out improperly.


Move object to Vector3 position with keeping gravity

Question: I have such a problem, maybe someone will help. I am making a game and I need to make a dice that goes in the direction opposite to the click. For example, clicking on the back of a cube moves it forward, etc. Gravity must act on the cube as shown in the figure below. Unfortunately, the cube does not change height, but only the position of X and Z. Please help.

<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveCube : MonoBehaviour
{
Vector3 movePosition;
public float time = 0.02f;

[HideInInspector]
public bool blockClick = false;

private void Start()
{
    movePosition = transform.position;
}

private void Update()
{
    blockClick = false;

    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit raycastHit;

        if (Physics.Raycast(ray, out raycastHit))
        {
            string hitName = raycastHit.transform.name;

            if (hitName == "MoveCube")
            {
                move(raycastHit);
                blockClick = true;
            }
        }
    }

    transform.position = Vector3.Lerp(
            transform.position,
            movePosition,
            time);
}

public void move(RaycastHit raycastHit)
{
    Vector3 incomingVec = raycastHit.normal - Vector3.up;

    // South
    if (incomingVec == new Vector3(0, -1, -1))
    {
        movePosition = movePosition + new Vector3(0, 0, 1);
        return;
    }

    // North
    if (incomingVec == new Vector3(0, -1, 1))
    {
        movePosition = movePosition + new Vector3(0, 0, -1);
        return;
    }

    // West
    if (incomingVec == new Vector3(-1, -1, 0))
    {
        movePosition = movePosition + new Vector3(1, 0, 0);
        return;
    }

    // East
    if (incomingVec == new Vector3(1, -1, 0))
    {
        movePosition = movePosition + new Vector3(-1, 0, 0);
        return;
    }
}
}
</code>
Answer: From what I know, changing the transform.position of a gameObject with a rigidbody will mess with Unity's physics, and it won't work as intended. I suggest trying to apply a force from the position of the mouse's click instead of moving the cube's position manually (if this makes sense to do for your purposes). Here is the documentation for Rigidbody.AddForce
Comment: Thanks for the hint, but I rather need a move with a click on the cube.
Comment: @olios Click is just an input, and you can keep that. Answer says, that you could change moving transform to affecting rigidbody by force (or by changing its velocity if you wish)
Comment: @olios just as in the example `AddForce` ca be used only once .. you would probably go with `ForceMode.VelocityChange` so you don't need to care about mass etc ... it will get a bit tricky if you want to pre-calculate  the needed force / velocity in order to land at a desired position => we need more details about what exactly should happen


display duplicate records in mysql

Question: I have a table(user_admin_password). I am using this query to get the records.
SELECT user_key,admin_status,count(*)
FROM user_admin_status
GROUP BY
   user_key,admin_status having count(*) > 1
ORDER BY user_key,admin_status;

The result is:
+----------+--------------+----------+
| user_key | admin_status | count(*) |
+----------+--------------+----------+
|        1 | NON-DBA      |        5 |
|        3 | DBA          |      328 |
|        5 | NON-DBA      |        8 |
|        6 | NON-DBA      |       25 |
|        7 | NON-DBA      |        4 |
|        9 | DBA          |      232 |
|       10 | NON-DBA      |        4 |
|       11 | DBA          |        4 |
|       13 | NON-DBA      |        8 |
|       15 | NON-DBA      |        2 |
|       16 | DBA          |      326 |
|       16 | NON-DBA      |        2 |
|       17 | NON-DBA      |       10 |
|       18 | NON-DBA      |        5 |
|       19 | NON-DBA      |       12 |
|       20 | NON-DBA      |        2 |
|       21 | NON-DBA      |        2 |
...
...

Now, I want all the user_keys with duplicate record...for example 16...any suggestions???
Answer: Just wrap it in another select:
select user_key, count(*)
from
(
    select user_key,admin_status,count(*)
    from user_admin_status
    group by user_key,admin_status
    having count(*) > 1
) x
group by user_key
having count(*) > 1

display duplicate records in mysql


Referencing external protos like google/rpc/status.proto

Question: I'm wondering how to properly reference external proto files. Say I've got a .proto file which references standard protobuf types such as Timestamp:
syntax = "proto3";
package api;

import "google/protobuf/timestamp.proto";

message ServerTimeResponse {
  google.protobuf.Timestamp ts = 1;
}

Easy. Timestamp is automatically available when compiling.
Now I add an external
type, say google.rpc.Status:
syntax = "proto3";
package api;

import "google/protobuf/timestamp.proto";
import "google/rpc/status.proto";

message ServerTimeResponse {
  google.protobuf.Timestamp ts = 1;
  google.rpc.Status status = 2;
}

Of course we have to tell protoc how to find this file where it is via -I/--proto_path.
My question is this: What is the best practice for actually referencing this file, in particular to make version control happy? There appears not to be a go mod equivalent for protobufs. I've seen it copied verbatim into projects (such as in grpc-gateway) or just referenced from the local filesystem.
Answer: I think you sort of answered your own question here. I've done both successfully: manually copied the necessary files in verbatim (from https://github.com/googleapis/googleapis/tree/master/google and https://github.com/protocolbuffers/protobuf/tree/master/src/google/protobuf), and referenced local copies of the files.
If you want to do this and make version control happy, you could add these two repositories as git submodules inside your repository. Just make sure to pass the right locations to protoc using -I. E.g.:
cd $PROJECT_DIR
mkdir third_party && cd third_party
git submodule add https://github.com/googleapis/googleapis/tree/master/google
cd $PROJECT_DIR
<git commit the change>
protoc -I third_party/google <the rest of your protoc command>

As for referencing local copies of the files, and making sure they're present before attempting to build, you may find that adding something like the following to your Makefile will help (this is in a Go build environment):
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
go get -u github.com/golang/protobuf/protoc-gen-go
grpc_gateway_path=$(go list -m -f '{{.Dir}}' github.com/grpc-ecosystem/grpc-gateway)
googleapis_path="$grpc_gateway_path/third_party/googleapis"
protoc -I $googleapis_path --go_out=. <list of input files>

Comment: I went the submodule route as you suggested, and it worked out well, thank you.
Comment: Glad to hear it worked out! Great minds think alike :)
Comment: I really like your `go list -m` suggestion also. In the case that I've otherwise got the same stuff coming from go modules and a submodule, it seems very clean. I'll give it a shot. Thanks again.


Implementing a static "memory" Map

Question: I am writing a small application to be used for testing purposes that accepts SOAP calls, generated UID's for each call, and returns this UID.  The UID's need to be stored on the server so I thought I'd use a simple static Map to store them.
I created a new class:
MemoryMap.java
public class MemoryMap {

    static Map<String, String> memoryMap = new ConcurrentHashMap<String, String>();

    static void printMapContents() {
        for (Entry<String, String> pair : memoryMap.entrySet()) {
            System.out.println("Key = [" + pair.getKey() + "]");
            System.out.println("Value = [" + pair.getValue() + "]");
        }
    }
}

This is then used with the calls:
MemoryMap.memoryMap.put(UID, "testString");
MemoryMap.printMapContents();

and...
MemoryMap.memoryMap.remove(parameters.getUID());
MemoryMap.printMapContents();

This works fine, but I can't think whether this is the recommended way to implement a single Map for this purpose.
Comment: What's wrong with a normal hashmap?
Comment: Do you want the size of the map to be fixed? And do you need to remove the old k-v pairs automatically by expire time or some other mechanism?
Comment: Why are you removing entries as you print them?
Comment: And generally why are you doing all that?
Comment: Another point: as you use unique (UUID) keys you don;t need Concurrent  map at all, ordinary HashMap will do the job. And - **don't** use `Iterator`, foreach loop is more than sufficient.
Comment: @Germann Arlington: Its a simple call simulator.  When the client requests a call creation, it requires a UUID returned.  Then when the request to end the call comes in, it gives the UUID for that call, which is then removed.  Thanks for the tip re: foreach.
Answer: If your application must mock a backend, e.g., a database, I recommend abstracting the map away in some datastore interface, and then provide your application with a singleton scoped instance of an implementation of this interface backed by a map. For example:
interface MyDataStore<V>{
  V retrieve(UUID id);
  void remove(UUID id);
}

public final class MockDataStore implements MyDataStore<String>{
  private final static MockDataStore instance = new MockDataStore();
  public static MockDataStore instance(){
    return instance;
  }
  private MockDataStore(){}
  private final ConcurrentHashMap<UUID,String> m =
    new ConcurrentHashMap<UUID,String>();
  @Override
  String retrieve(UUID id){
    return m.get(id);
  }
  @Override
  void remove(UUID id){
    m.remove(id);
  }
}

Then tomorrow you can swap the implementation for something that speaks to an actual database. This is a very rough approximation of an ORM system.
Even better, I would start with a database right off the bat. You could use an in memory database (like H2) so that you could replace it with an actual database (with possibly some minor migration issue) when you need to.
Finally, if your storage needs grow, e.g., you need tables and relations among them, I recommend looking at JPA and one of its implementations, e.g., Hibernate.
Answer: Your server accepts SOAP requests, most likely this is done in several threads. ConcurrentHashMap should work just fine.
Comment: OP use `ConcurrentHashMap`
Comment: Sorry, my bad. Updated answer.

Implementing a static "memory" Map


Circular references and warnings caused by forward declarations in Object C

Question: I have two classes that reference each other and therefore a forward declaration is required to avoid circular references.  Because of the forward declaration I get all kinds of warnings when trying to reference the class name or properties of the class that has the forward declaration.  Any suggestions?  The key constraint is I need to preserve the ability to have the classes reference each other
ClassA.h
#import "ClassB.h"

@interface ClassA : NSObject {
    ClassB *class_b;
}
@end

ClassB.h
@class ClassA;

@interface ClassB : NSObject {
     ClassA *class_a;

}

@end

ClassB.m
#import "ClassB.h"

@implementation ClassB

-(void)method{
}
- (id)init
{
    (self = [super init]);
    class_a = [[ClassA alloc] init];
    return self;
}

@end

The warning I get is as follows:
ClassB.m:13: warning: receiver 'ClassA' is a forward class and corresponding @interface may not exist

Answer: In ClassB.m you need to #import "ClassA.h". The @class forward declaration is just for the header file.
Answer: The headers only need to know ClassA and ClassB exist and so a forward declaration works.
However in the implementation they need to know more about the other class. Thus in the implementation files you need to #import the other class. You don't have the an issue as the implementation of one class only needs to know the interface of the other,
Answer: In headers do not use import/include but use the @class directive. It basically tells "there is a class called X defined somewhere"


Accepting a method as input parameter for another method

Question: I seen some APIs accepting method as parameter. But no idea how do they actually work. May be  using some reflection inside but no idea how.
Please tell me how should I write a method which can accept a method as input? For example;
someMethod(on(SomeClass.class).someMethod());

Alternative:
someMethod("fieldName" , SomeClass.class);

But it is not type Safe. And creating enum would be an extra burden.
Comment: Are you sure it is a method and not a field name?  Because it looks like a field name.
Comment: Do you mean something like this `someMethod(obj.getFoo())`?
Comment: yup, it is a getter method for a field. Sorry for typo. I have update the question
Comment: Please refer http://stackoverflow.com/questions/8360510/java-reflection-getmethod

And use java reflection Method class as type
Answer: In Java you would normally write an interface like this:
public interface Function{
    public void apply();
}

Then you can use your function like this:
static void main( String args[] ){
    callSomeMethod( new Function(){
        public void apply(){
            System.out.println( "hurray" );
        }
    } );
}

static void callSomeMethod( Function f ){
    f.apply();
}

In Java 8 this will be greatly simplified with the addition of lambdas.
But for the time being this is how it's done in java.
Built-in classes
Java has a few built in classes that are generic. For instance take a look at callable:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html
Reflection
You can also use reflection. The above example would look like this:
class Thing{
    public void whatever(){
        System.out.println( "hi!" );
    }
}

public static void main( String args[] ){
    Thing thing = new Thing();
    callSomeMethod( thing, "whatever" );
}

public static void callSomeMethod( Object obj, String methodName ){
    obj.getClass().getMethod( methodName ).invoke( obj );
}

However, reflection is pretty slow compared to the above method and you also lose the static type safety. All in all i suggest not doing it this way if not absolutely necessary.
Answer: In java usually this is done with a class that implements Runnable or Callable
So instead of passing in a function, you pass an object that has a function that can be called.
Comment: @kritzikratzi thanks, I only ever used java for a few courses in school, I'm lucky to remember as much as I do ;)
Comment: yes and no. runnable is a class with a concrete purpose. i prefer to use the more generic [callable](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html). in cases where you need parameters you'll have to write your own interface.
Answer: The generic way to do this is Callable, but most passing methods around in java is usually done through creating an interface.  Inside the interface you define several methods which reflect what you want to do, then you pass classes that implement the interface as the method arguments.
Answer: If the method already exists in a class, you can use java reflection.
Have a look here
java reflection tutorial


Who voiced Nuka-Girl?

Question: A quick Google search seemingly answered the question: Courtenay Taylor, right? Not quite. Clicking on the immediately listed link, the voice actress' Fandom page lists her as voicing the Sole Survivor. Investigating further, as VAs often voice multiple characters, I looked at her list of credits, but Nuka-Girl was not one of them. Naturally, I then looked at the character page for Nuka-Girl. However, Fandom did not have any listing for a voice actress. Gamepedia's Nuka-Girl's dialoge page also lacked a VA credit, citing only this for her voice: "DLC04_Announcer_NukaGalaxy_NPCFNukaGirl".
Finally, it seemed like I found a potential voice actress at IMDb's Fallout 4 credit list, but none of the ladies credited with lending their voices to the Nuka-World DLC (Anjali Bhimani, Corri English, Laura Post, and Jan Johns) were credited as voicing Nuka-Girl.
After spending more time searching than I care to admit, I still don't have an answer to my question: Who voiced Nuka-Girl?
Comment: I'm digging into this too. The Fallout Wikia for Nuka World voice acting also identifies uncredited roles (unlike Imdb), but the Nuka-Girl voice is the still not identified. I think we'd have to message one of the voice actresses to figure this out.
Comment: This is some Nick Robinson-level stuff if the voice actress's credit is not there. It could be a Vocaloid, but I doubt it.
Comment: How about getting the credits for the song in the trailer? - https://www.youtube.com/watch?v=DIneiOpuS2M
...
https://fallout.fandom.com/wiki/Nuka-World_theme_song - COPILOT Music and Sound
...
hmmm... ... And this guy helped make it... https://mgarrettsteele.wordpress.com/video-game-music/
Answer: The character page got the answer in September: Anna Graves
Comment: Huh. More than 6 years old, that tweet. Thanks!
Comment: Yup, the tweet ranks first with "vo nukagirl" in Google now. But didn't in September 2020 (at least when using the Google tools to define the time range)

Who voiced Nuka-Girl?


dropdown item does not display by background android

Question: I have a Dropdown in my android app.but when I set background for it, dropdown item does not display.
my .xml file:
 <Spinner
                android:id="@+id/spinner"
                android:layout_width="254dp"
                android:layout_height="42dp"
                android:background="@drawable/red_color"/>

red_colot.xml
  <?xml version="1.0" encoding="utf-8"?>

<item android:top="3dp" android:left="3dp" android:right="3dp" android:bottom="3dp">
    <shape>
        <solid android:color="@color/red" />
        <corners android:radius="4dp" />
    </shape>
</item>

Comment: Could you please share the full drawable code?
Comment: @Sabari I shared it.
Comment: try this: red_color.xml:
Comment: No, did not solve my problem
Comment: Oh I see, I can't reproduce your bug. In my side, drawable xml, while using your code, item tag is not resolving (the item tag should not be a direct tag.)
Answer: Hi you can resolve this with this code
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <solid android:color="#FFFFFF" />
        <stroke
            android:width="1dp"
            android:color="@color/green" />
        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <bitmap
        android:gravity="right|center"
        android:src="@drawable/ic_arrow_drop_down_gray" />
</item>