text:
Q: How do I setup and use a persistent framebuffer object for doing unique color selection? This question changed a lot since it was first asked because I didn't understand how little I knew about what I was asking. And one issue, regarding resizing, was clouding my ability to understand the larger issue of creating and using the framebuffer. If you just need a framebuffer jump to the answer... for history I've left the original question intact.

Newbie question. I've got a GL project I'm working on and am trying to develop a selection strategy using unique colors. Most discussion/tutorials revolve around drawing the selectable entities in the back buffer and calculating the selection when a user clicks somewhere. I want the selection buffer to be persistent so I can quickly calculate hits on any mouse movement and will not redraw the selection buffer unless display or object geometry changes.
It would seem that the best choice would be a dedicated framebuffer object. Here's my issue. On top of being completely new to framebuffer objects, I am curious. Am I better off deleting and recreating the frambuffer object on window size events or creating it once at the maximum screen resolution and then using what may be just a small portion of it. I've got my events working properly to only call the framebuffer routine once for what could be a stream of many resize events, yet I'm concerned about GPU memory fragmentation, or other issues, recreating the buffer, possibly many times.
Also, will a framebuffer object (texture & depth) even behave coherently when using just a portion of it.
Ideas? Am I completely offbase?
EDIT:
I've got my framebuffer object setup and working now at the windows dimensions, and I resize it with the window. I think my issue was classic "overthink". While it is certainly true that deleting/recreating objects on the GPU should be avoided when possible. As long as it is handled correctly the resizes are relatively few.
What I found works is to set a flag and mark the buffer as dirty on window resize, then wait for a normal mouse event before resizing the buffer. A normal mouse enter or move signals you're done dragging the window to size and are ready to get back to work. The buffers recreated once. Also, since the main framebuffer is generally resized for every window size event in the pipeline, it would stand to reason that resizing a framebuffer isn't going to burn a hole in your laptop.
Crisis averted, carry on!

A: I mentioned in the question that I was overthinking the problem. The main reason for that is because the problem was bigger than the question. The problem was, not only did I not know how to control the framebuffer, I didn't know how to create one. There are so many options and none of the web resources seemed to specifically address what I was trying do, so I struggled with it. If you're also struggling with how to move your selection routine to a unique color scheme with a persistent buffer, or are just at a complete loss as to framebuffers and offscreen rendering, read on.
I've got my OpenGL canvas defined as a class, and I needed a "Selection Buffer Object." I added this to the private members of the class.
unsigned int sbo;
unsigned int sbo_pixels;
unsigned int sbo_depth;
bool sbo_dirty;
void setSelectionBuffer();

In both my resize handler and OpenGL initialization I set the dirty flag for the selection buffer.
sbo_dirty = true;

At the begining of my mouse handler I check for the dirty bit and setSelectionBuffer(); if appropriate.
if(sbo_dirty) setSelectionBuffer();

This tackles my initial concerns about multiple delete/recreates of the buffer. The selection buffer isn't resized until the mouse pointer reenters the client area, after resizing the window. Now I just had to figure out the buffer...
void BFX_Canvas::setSelectionBuffer()
{
    if(sbo != 0) // delete current selection buffer if it exists
    {
        glDeleteFramebuffersEXT(1, &sbo);
        glDeleteRenderbuffersEXT(1, &sbo_depth);
        glDeleteRenderbuffersEXT(1, &sbo_pixels);
        sbo = 0;
    }

    // create depth renderbuffer
    glGenRenderbuffersEXT(1, &sbo_depth);
    // bind to new renderbuffer
    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, sbo_depth);
    // Set storage for depth component, with width and height of the canvas
    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, canvas_width, canvas_height);
    // Set it up for framebuffer attachment
    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, sbo_depth);
    // rebind to default renderbuffer
    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

    // create pixel renderbuffer
    glGenRenderbuffersEXT(1, &sbo_pixels);
    // bind to new renderbuffer
    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, sbo_pixels);
    // Create RGB storage space(you might want RGBA), with width and height of the canvas
    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGB, canvas_width, canvas_height);
    // Set it up for framebuffer attachment
    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, sbo_pixels);
    // rebind to default renderbuffer
    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

    // create framebuffer object
    glGenFramebuffersEXT(1, &sbo);
    // Bind our new framebuffer
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, sbo);
    // Attach our pixel renderbuffer
    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, sbo_pixels);
    // Attach our depth renderbuffer
    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, sbo_depth);

    // Check that the wheels haven't come off
    GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
    if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
    {
        // something went wrong
        // Output an error to the console
        cout << "Selection buffer creation failed" << endl;
        // restablish a coherent state and return
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
        sbo_dirty = false;
        sbo = 0;
        return;
    }

    // rebind back to default framebuffer
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
    // cleanup and go home
    sbo_dirty = false;
    Refresh(); // force a screen draw
}

Then at the end of my render function I test for the sbo, and draw to it if it seems to be ready.
if((sbo) && (!sbo_dirty)) // test that sbo exists and is ready
{
    // disable anything that's going to affect color such as...
    glDisable(GL_LIGHTING);
    glDisable(GL_LINE_SMOOTH);
    glDisable(GL_POINT_SMOOTH);
    glDisable(GL_POLYGON_SMOOTH);

    // bind to our selection buffer
    // it inherits current transforms/rotations
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, sbo);
    // clear it
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // draw selectables
    // for now i'm just drawing my object
    if (object) object->draw();

    // reenable that stuff from before
    glEnable(GL_POLYGON_SMOOTH);
    glEnable(GL_POINT_SMOOTH);
    glEnable(GL_LINE_SMOOTH);
    glEnable(GL_LIGHTING);

    // blit to default framebuffer just to see what's going on
    // delete this bit once selection is setup and working properly.
    glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, sbo);
    glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
    glBlitFramebufferEXT(0, 0, canvas_width, canvas_height,
                         0, 0, canvas_width/3, canvas_height/3,
                         GL_COLOR_BUFFER_BIT, GL_LINEAR);

    // We're done here, bind back to default buffer.
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

That gives me this...

At this point I believe everything is in place to actually draw selectable items to the buffer, and use mouse move events to test for hits. And I've got an onscreen thumbnail to show how bad things are blowing up.
I hope this was as big a help to you, as it would have been to me a week ago. :)


text:
Q: IdentityServer 3 signing certificate expiry What happens when the signing certificate (used for signing jwt tokens) expires when using IdentityServer 3?
It's unclear to me and I can't find any documentation, other than that it's possible to get a warning that it has expired. (Ref. https://identityserver.github.io/Documentation/docsv2/configuration/events.html)
Is there any mechanism that stops the use of expired signing certs?
And what happens on the client side (client being the Web API that uses IdentityServer for authentication) when validating a token signed by an expired certificate? (For example if  https://github.com/IdentityServer/IdentityServer3.AccessTokenValidation is used as a middleware.)

A: Well I've just tested this (on IdentityServer4) and it seems to continue to work happily with an expired signing certificate, here's my test cert's validity:

I'm able to login, get an ID token and an access token and then access an API with the access token. What IdentityServer does do however is to log a warning:
2017-07-13 12:15:54.871 +02:00 [Warning]
    Certificate "CN=test_expired_signing_certificate" has expired on "13/07/2016 14:14:37"

This matches what the IdentityServer (3) docs say here:

IdentityServer raises a number of events at runtime, e.g:
snip...

*

*Expired/invalid/no signing certificate

  By default these events are forwarded to the configured log provider - a custom event service can process or forward them in any way suitable for the environment.

So this would be your way of detecting it when it's already too late. A better option is to rollover signing keys periodically and within the validity of the keys, this is the common approach which also allows for a compromised key to be revoked if necessary. See this issue where the process is discussed, basically IdentityServer can handle two keys:

[Middleware refreshes] the metadata document ... once a day.
The metadata doc can hold 2 keys - primary and secondary and the middleware will load and use both when present (JWTs have a key identifier that allows picking the right one).
When you start to rollover - set both keys and at some point swap primary and secondary.

A: Disclaimer: I never worked with IdentityServer3
The outside world doesn't know your certificate and therefore doesn't know it's expired. The outside world merely sees your public key at:
YourIdentityServer.com/.well-known/openid-configuration

or more accurately:
YourIdentityServer.com/.well-known/openid-configuration/jwks

You can play around with this: Create a new cert on startup (see https://gist.github.com/mykeels/408a26fb9411aff8fb7506f53c77c57a). Even if you set the TimeSpan to one minute, it will keep working.
But once you wait 1 minute and restart your IdentityServer your token from last sign in will be considered invalid, because it was created with the now outdated signing key. It is checked against the new public key and fails.
It seems to be recommended to periodically replace your cert with a new one, while also keeping the previous key around, see "signing key rollover":
https://docs.identityserver.io/en/dev/topics/crypto.html#signing-key-rollover

redpajama_set_name: RedPajamaStackExchange


text:
Q: ServicePoint Configuration - Application starving http connections? I have two C# asp.net applications running on IIS:
The main application creates up to 80 threads where each of them will
establish an http connection to a certrain endpoint (all the same endpoint (LAN)) at a frequency of roughly 3 seconds.
That endpoint is beeing hosted on localhost (e.g localhost:4510).
This endpoint is the second application which represents the "driver" that will ultimately establish a connection to a device within LAN.
So it's totally possible to have 80 threads trying to make a request to driver/device at the same time.
Over time the app seems to have issues with anything involving httpclients. RavenDB, Elasticsearch and also the 80 threads.
I read a few things about ServicePointManager class; especially DefaultConnectionLimit and
MaxServicePoints and how the influence http througput.
I only have basic understanding of the underlying mechanism so I'd like to ask if I should focus on a specific subject or what I would want to check to may improve on http throughput.
Update:
With current configuration CPU load is low and memory consumption also.
Following code shows how the 80 httpclients which connect to the driver on localhost:4510:
var driverBaseAddressSp= ServicePointManager.FindServicePoint(driverBaseAddress);                               Debug.WriteLine(driverBaseAddressSp.ConnectionLimit);
Debug.WriteLine(driverBaseAddressSp.MaxIdleTime);
var connectionUriSp = ServicePointManager.FindServicePoint(connectionUri);
Debug.WriteLine(connectionUriSp.ConnectionLimit);
Debug.WriteLine(connectionUriSp.MaxIdleTime);
return new HttpClient { BaseAddress = driverBaseAddress };

ConnectionLimit shows Int.Max when debugging but
I cannot find any configuration in the solution?


text:
Q: MSB6003 clang.exe could not be run I have a small C++ project in Visual Studio based on the cross platform OpenGLES2 template. I didn't have any problems until I suddenly started to get this compilation error:
MSB6003 The specified task executable "clang.exe" could not be run. The file or directory is corrupted and unreadable.

There are no changes in the code before and after I started to get the error. I've tried to clean the solution and rebuild, restart VS and restart the computer.
I've googled the problem, but I can't seem to find anything that works or understandable solution. Though it seem to be related to some environment variables? But do they change for no reason?
What is "clang.exe" and where should it be located?

A: I found a solution to my problem.
As the error stated "The file or directory is corrupted and unreadable.", some files were actually corrupted. By trying to delete some files in the project folder, I got an error from Windows stating the files were corrupt. (Why? I don't know how it happened.)
I created a new project based on the same template, and copied over my source code. Luckily none of my source code was corrupt!


text:
Q: Exponential recurrence relation I am currently struggling to find a closed form solution for a recurrence relation and don't know where to start. I have worked with linear homogenous first and second-order relations before but this is unlike anything I have seen. Suggestions would be greatly appreciated.
$$k_{t+1}=A(1-\alpha)(1-\beta)g^tk_t^\beta$$
where $\alpha$ and $\beta$ are strictly between $0$ and $1$, $t>0$, $k_1>0$, $g$ is a growth rate and $A$ is a positive real constant.


text:
Q: Mail is sending text attachments rather than including the text inline In My Mac Mail, the messages are going as text attachment, rather than just appearing inline as the mail contents.  How can I make sure that the contents of my mails are not being sent as attachments?

A: I was facing the same problem and figured out what was going wrong.
In mail, when you copy or drag the attachment, all text below attachment is treated as attachment hence it converts it to attachment and no text goes to the recipient.
All you need to do is in menu bar Edit > Attachment > Always insert attachment at end of message.
This will now always copy your attachments to the end and your text will remain safe in email.


text:
Q: Calculate weighted mean point from array of 3D points I am writing the program in Cocoa but I think that the solution must be quite universal.
I have a set of points represented by 3D vectors. Each point has a weight assigned to it. The weight is in the range from 0 to 1. The sum of all weights isn't equal to 1.
How should the weighted mean point be calculated from such set?
Either programmatic or pure mathematical solution will be helpful.
Of course if Cocoa has some specific tools for solving this task, I would very appreciate this information.

A: Simply sum all vectors scaled by their weight. Finally, divide by the sum of all weights. This  has the same effect as first normalizing all weights to sum to 1.
Pseudo-code:
sum = [0, 0, 0]
totalWeights = 0
for each point p with associated weight w:
    sum += p * w
    totalWeights += w
mean = sum / totalWeights


text:
Q: How to maintain the cache when I return to the previous page using node / express? I would like to know how I can implement a cache for a route, that keeps the data even when I go to another page.
I have the problem that when I'm on a particular route and I refresh the page, the data disappears and the content does not load because it is not in memory.
import * as scraper from './scraper';
import * as express from 'express';
const router = express.Router();

router.get('/anime/:id/:chapter', (req: express.Request, res: express.Response) => {
  const id: string = req.params.id;
  const chapter: number = req.params.chapter;
  scraper.getAnimeVideo(id, chapter)
    .then(video => {
      res.status(200).json({
        video
      });
    }).catch((err) =>{
      console.log(err)
    });
});

export default router;


text:
Q: How to make `visible on` keyword compatible with -+ overlays in forest I'm trying to use visible on style defined by Qrrbrbirlbel with an automatic increment overlay <-+>. However, when I do so the nodes and the edges are incremented separately. I blame the lines
/tikz/visible on={#1},
edge={/tikz/visible on={#1}}

that apply the passed range to the edge and nodes separately. However, I don't know how to send the same auto-increment to both of them simultaneously. Another way may be to decrement the counter, but I'm not familiar with beamer overlays to know which parts to tweak.
How can I achieve such endeavor?
I took this code to show the behavior I described. I'm trying to make the tree appear a node (and its corresponding edge) at a time.
\documentclass{beamer}
\usepackage{forest}

\setbeamertemplate{navigation symbols}{} %Remove navigation bar
\tikzset{
    invisible/.style={opacity=0,text opacity=0},
    visible on/.style={alt=#1{}{invisible}},
    alt/.code args={<#1>#2#3}{%
      \alt<#1>{\pgfkeysalso{#2}}{\pgfkeysalso{#3}} % \pgfkeysalso doesn't change the path
    },
}
\forestset{
  visible on/.style={
    for children={
      /tikz/visible on={#1},
      edge={/tikz/visible on={#1}}}}}

\begin{document}
\begin{frame}[plain]{Same with forest}
  \begin{forest}
    [VP, calign=last, visible on=<+->
      [{[ajout]}\\\textit{rapidement},
      align=center,
      base=top, visible on=<+->, ]
      [VP, calign=first, visible on=<3->,
        [VP, calign=first, visible on=<2->,
          [V\\\textit{mange}, align=center,base=top, visible on=<1->, ]
          [{[compl]}\\\textit{une orange}, align=center,base=top, visible on=<1->, ]
        ]
        [{[ajout]}\\\textit{dans la cuisine}, align=center, visible on=<2->,]
      ]
    ]
  \end{forest}

\end{frame}
\end{document}

See the result using descendants (children produces the same result). Notice how the nodes appear first, and then edges start appearing.

A: I'm not sure what exactly you want to achive, but I understand the problem behind synchronous appearance of a node and its edge. As promised in the documentation of draw tree key (section 3.3.7), the nodes are drawn first, then edges and finally extra tikz code. The idea behind such order is that edges and tikz code should be able to refer to any node, but obviously this creates problem when using beamer's incremental overlay specification <+->.
Solution. The idea is to reset the value of counter beamerpauses before we start drawing the edges. Now, as forest offers no hook there (hmm ... an idea:)  we must get creative.

*

*We put the code to save the beamerpauses counter inside the node options of the root node. (In this particular case, simply saving it during option processing would work, too, but the node options variant is more robust, it works also if the tree is drawn multiple times).

*We squeeze the code restoring the beamerpauses counter inside the first edge that will be drawn. One detail is straightforward: as the root node has no edge, we increase the counter by one. The other detail is not resolved automatically: forest has no idea which edge is the first one that will be drawn, so for first was specified manually.
Here's the code, hope it helps.
\documentclass{beamer}
\usepackage{forest}

\setbeamertemplate{navigation symbols}{} %Remove navigation bar
\tikzset{
    invisible/.style={opacity=0,text opacity=0},
    visible on/.style={alt=#1{}{invisible}},
    alt/.code args={<#1>#2#3}{%
      \alt<#1>{\pgfkeysalso{#2}}{\pgfkeysalso{#3}} % \pgfkeysalso doesn't change the path
    },
}
\forestset{
  visible on/.style={
    %for children={
      /tikz/visible on={#1},
      edge={/tikz/visible on={#1}}
   % }
  }
}

\begin{document}
\begin{frame}[plain]{Same with forest}
  \begin{forest}
    node options={/utils/exec={\xdef\mybeamerpauses{\thebeamerpauses}}},
    for first={edge={/utils/exec={\setcounter{beamerpauses}{\numexpr1+\mybeamerpauses}}}},
    [VP, calign=last, visible on=<+->
      [{[ajout]}\\\textit{rapidement},
      align=center,
      base=top, visible on=<+->, ]
      [VP, calign=first, visible on=<+->,
        [VP, calign=first, visible on=<+->,
          [V\\\textit{mange}, align=center,base=top, visible on=<+->, ]
          [{[compl]}\\\textit{une orange}, align=center,base=top, visible on=<+->, ]
        ]
        [{[ajout]}\\\textit{dans la cuisine}, align=center, visible on=<+->,]
      ]
    ]
  \end{forest}

\end{frame}
\end{document}

Actually, as it makes no difference when the visible on=<+-> is given, here's also a shorter version using for tree.
\documentclass{beamer}
\usepackage{forest}

\setbeamertemplate{navigation symbols}{} %Remove navigation bar
\tikzset{
    invisible/.style={opacity=0,text opacity=0},
    visible on/.style={alt=#1{}{invisible}},
    alt/.code args={<#1>#2#3}{%
      \alt<#1>{\pgfkeysalso{#2}}{\pgfkeysalso{#3}} % \pgfkeysalso doesn't change the path
    },
}
\forestset{
  visible on/.style={
    %for children={
      /tikz/visible on={#1},
      edge={/tikz/visible on={#1}}
   % }
  }
}

\begin{document}
\begin{frame}[plain]{Same with forest}
  \begin{forest}
    node options={/utils/exec={\xdef\mybeamerpauses{\thebeamerpauses}}},
    for first={edge={/utils/exec={\setcounter{beamerpauses}{\numexpr1+\mybeamerpauses}}}},
    for tree={visible on=<+->},
    [VP, calign=last
      [{[ajout]}\\\textit{rapidement},
      align=center,
      base=top ]
      [VP, calign=first
        [VP, calign=first
          [V\\\textit{mange}, align=center,base=top ]
          [{[compl]}\\\textit{une orange}, align=center,base=top ]
        ]
        [{[ajout]}\\\textit{dans la cuisine}, align=center]
      ]
    ]
  \end{forest}

\end{frame}
\end{document}


text:
Q: menubutton not working anymore after upgrade to cordova 5+cordova android 4.0.0 I've recently upgraded to cordova 5 and removed/recreated android platform in version 4.0.0 and uninstalled/reinstalled all plugins.
I also had to upgrade android sdk to sdk 22 instead of 21.
Since the update, I'm no more able to catch the menubutton event as described in the cordova documentation.
As it's still referenced in the edge docs, I assume it should still be working and I've seen nothing about this in the release notes.
back button is still working.
I tried to set the target-sdk to 19, it did not solve anything about the issue.
Edit:
I've dug into cordova source code and found in CordovaWebViewImpl.java I found a suspicious TODO comment :
   public void setButtonPlumbedToJs(int keyCode, boolean override) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_VOLUME_UP:
            case KeyEvent.KEYCODE_BACK:
                // TODO: Why are search and menu buttons handled separately?
                if (override) {
                    boundKeyCodes.add(keyCode);
                } else {
                    boundKeyCodes.remove(keyCode);
                }
                return;
            default:
                throw new IllegalArgumentException("Unsupported keycode: " + keyCode);
        }
    }

Well my answer would be "IT SHOULDN'T!!!!"
Cordova makes a list of keycode to handle but does not add the menu button and later on the keycode is compared to KeyEvent.KEYCODE_MENU only after the keycode has been skipped because it's not in the list.
I've tried to add a case for the menu button, but it turns out the function is only called with the code of the back button.
So now I know why it doesn't work but still not how to fix it.
Edit 02/2016:
As per latest Jira, the support of the menubutton is now fixed in java part in Cordova Android 5.1.0 but still not initialized from the javascript.
For the moment, as indicated by Jira user Keith Wong, you need to add a javascript call before you add your event listener :
document.addEventListener("deviceready", function() {
    ...
    navigator.app.overrideButton("menubutton", true);  // <-- Add this line
    document.addEventListener("menubutton", yourCallbackFunction, false);
    ...
}, false);

A: clarent's answer didn't do it for me, the menu button still didn't respond.
I tried several patches, one other suggestion to disable the boundKeyCodes check completely didn't do it either, because then the backbutton behaviour would be compromised.
The clean way to get the old behaviour back should be as follows.
The boundKeyCodes check ensures, that custom behaviour is only executed when there actually is a custom event handler bound to the event. But binding an event handler to "menubutton" in your app's JS code no longer triggers the menubutton key code to be added to the boundKeyCodes list.
This is because the setButtonPlumbedToJs method is never executed for the "menubutton" handler in the first place AND even if it would, the switch statement in this method doesn't handle KEYCODE_MENU.
You can get that behaviour back quite easily, first you will have to apply the change suggested by clarent:

*

*Handle KEYCODE_MENU
in CordovaLib/src/org/apache/cordova/CoreAndroid.java (around line 357, setButtonPlumbedToJs) add a case statement after the KEYCODE_BACK entry like this:
public void setButtonPlumbedToJs(int keyCode, boolean override) {
  switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_DOWN:
    case KeyEvent.KEYCODE_VOLUME_UP:
    case KeyEvent.KEYCODE_BACK:
    case KeyEvent.KEYCODE_MENU:
    // TODO: Why are search and menu buttons handled separately?
      if (override) {
        boundKeyCodes.add(keyCode);
      } else {
        boundKeyCodes.remove(keyCode);
      }
      return;
    default:
      throw new IllegalArgumentException("Unsupported keycode: " + keyCode);
  }
}

Then ensure that setButtonPlumbedToJs actually gets executed. You need two more changes for that.

*Add framework handler
In CordovaLib/src/org/apache/cordova/CoreAndroid.java (around line 243, overrideButton) make the method look like this (add the last else-if clause):
public void overrideButton(String button, boolean override) {

  if (button.equals("volumeup")) {
    webView.setButtonPlumbedToJs(KeyEvent.KEYCODE_VOLUME_UP, override);
  }
  else if (button.equals("volumedown")) {
    webView.setButtonPlumbedToJs(KeyEvent.KEYCODE_VOLUME_DOWN, override);
  }
  else if (button.equals("menubutton")) {
    webView.setButtonPlumbedToJs(KeyEvent.KEYCODE_MENU, override);
  }
}

*

*Add javascript handler call
In platform_www/cordova.js (around line 1532, bootstrap) change this line:
cordova.addDocumentEventHandler('menubutton');

to this:
var menuButtonChannel = cordova.addDocumentEventHandler('menubutton');
menuButtonChannel.onHasSubscribersChange = function() {
  exec(null, null, APP_PLUGIN_NAME, "overrideButton", ['menubutton', this.numHandlers == 1]);
};

This will trigger the frameworks overrideButton method as soon as an event handler is added to "menubutton".
That should do it. I also added this solution as a comment to
https://issues.apache.org/jira/browse/CB-8921
and might be filing a pull request shortly.

A: Just add to function setButtonPlumbedToJs one line : case KeyEvent.KEYCODE_MENU:
public void setButtonPlumbedToJs(int keyCode, boolean override) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_DOWN:
        case KeyEvent.KEYCODE_VOLUME_UP:
        case KeyEvent.KEYCODE_BACK:
        case KeyEvent.KEYCODE_MENU:

So in onDispatchKeyEvent switch will work:
      } else if (boundKeyCodes.contains(keyCode)) {
                String eventName = null;
                switch (keyCode) {
                    case KeyEvent.KEYCODE_VOLUME_DOWN:
                        eventName = "volumedownbutton";
                        break;
                    case KeyEvent.KEYCODE_VOLUME_UP:
                        eventName = "volumeupbutton";
                        break;
                    case KeyEvent.KEYCODE_SEARCH:
                        eventName = "searchbutton";
                        break;
                    case KeyEvent.KEYCODE_MENU:
                        eventName = "menubutton";
                        break;
                    case KeyEvent.KEYCODE_BACK:
                        eventName = "backbutton";
                        break;
                }

A: Now with cordova-android 5.1, the code has changed and my patch didn't work any-more (and sadly, with no patch the menu button is still not working in this version).
As I wanted to be able to upgrade the platform without having to review the code each time, I searched for a new way to get the menu button working again.
In cordova android 5.1 it turns out that everything is here in the java code for the button to be working, except that the menu button key is never added to the boundKeyCoded array.
It turns out that this array needs to be filled by a call from javascript (which is done for the back button and volume button, but neither for the search button or the menu button).
The code that is missing is something like that :
exec(null, null, APP_PLUGIN_NAME, 'overrideButton', ['menubutton' , true]);

(a js call to the java function overrideButton from CoreAndroid.java to tell to add the menu button key to the boundKeyCodes array.
I think this call should be added to platform.js, but since platform.js is used to build cordova.js during the platform add, I decided to make a after_platform_add hook that patchs the cordova.js file.
The advantage of this hook is that there's no java change and it should work even if you use a different webview like crosswalk.
So, first, in config.xml, in the android section add the hook :
<platform name="android">
    ....
    ....
    <hook type="after_platform_add" src="scripts/android/patch_menubutton.js" />
    ....
    ....
</platform>

Then, in the scripts folder add the hook file patch_menubutton.js :
#!/usr/bin/env node
module.exports = function(ctx) {
    var fs = ctx.requireCordovaModule('fs'),
        path = ctx.requireCordovaModule('path');
    var CordovaJSPath = path.join(ctx.opts.projectRoot, 'platforms/android/platform_www/cordova.js');
    var data = fs.readFileSync(CordovaJSPath, 'utf8');
    var result = data.replace(new RegExp("cordova\\.addDocumentEventHandler\\('menubutton'\\);", "g"), "cordova.addDocumentEventHandler('menubutton'); exec(null, null, APP_PLUGIN_NAME, 'overrideButton', ['menubutton' , true]);");
    fs.writeFileSync(CordovaJSPath, result, 'utf8');
}

(it looks for the initialisation of the event handler for the menu button and appends the call to the overrideButton function, like described in the last part of FewKinG's answer)


text:
Q: Отображение картинки на Canvas Надо отобразить иконку на Canvas. Использую метод:
drawImage(image, x1, y1, w1, h1, x1, y1, w1, h1);

Картинка задается как ресурс:
public interface Bundle extends ClientBundle {
  public static final Bundle ourInstance = GWT.create(Bundle.class);

  @ClientBundle.Source(value = {"icon.png"})
  public ImageResource icon();
}

В момент отрисовки каринка 100% загружена (был вызван onLoad). Но всё равно картинка не рисуется, падает исключение:

com.google.gwt.core.client.JavaScriptException:
(INDEX_SIZE_ERR): INDEX_SIZE_ERR: DOM
Exception 1   at
com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:237)
  at
com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:132)
  at
com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
  at
com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:289)
  at
com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:107)
  at
MyClassCanvas.drawImage(MyClassCanvas.java)

A: Измените
Image img = new Image(Bundle.ourInstance.icon())

на
Image img = new Image(Bundle.ourInstance.icon().getURL)


text:
Q: How can I show the wget progress bar only? For example:
wget http://somesite.com/TheFile.jpeg

    downloading: TheFile.tar.gz ...
    --09:30:42--  http://somesite.com/TheFile.jpeg
               => `/home/me/Downloads/TheFile.jpeg'
    Resolving somesite.co... xxx.xxx.xxx.xxx.
    Connecting to somesite.co|xxx.xxx.xxx.xxx|:80... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 1,614,820 (1.5M) [image/jpeg]

    25% [======>                              ] 614,424      173.62K/s    ETA 00:14

How can I get it to look like the following?

    downloading: TheFile.jpeg ...
    25% [======>                              ] 614,424      173.62K/s    ETA 00:14

I know curl can do that. However, I need to get wget to do that job.

A: You can use standard options:
wget --progress=bar http://somesite.com/TheFile.jpeg

A: You can use the following filter:
progressfilt ()
{
    local flag=false c count cr=$'\r' nl=$'\n'
    while IFS='' read -d '' -rn 1 c
    do
        if $flag
        then
            printf '%s' "$c"
        else
            if [[ $c != $cr && $c != $nl ]]
            then
                count=0
            else
                ((count++))
                if ((count > 1))
                then
                    flag=true
                fi
            fi
        fi
    done
}

Usage:
$ wget --progress=bar:force http://somesite.com/TheFile.jpeg 2>&1 | progressfilt
100%[======================================>] 15,790      48.8K/s   in 0.3s

2011-01-13 22:09:59 (48.8 KB/s) - 'TheFile.jpeg' saved [15790/15790]

This function depends on a sequence of 0x0d0x0a0x0d0x0a0x0d being sent right before the progress bar is started. This behavior may be implementation dependent.

A: Run using these flags:
wget -q --show-progress --progress=bar:force 2>&1

A: Use:
wget http://somesite.com/TheFile.jpeg -q --show-progress

*

*-q: Turn off wget's output

*--show-progress: Force wget to display the progress bar no matter what its verbosity level is set to

A: This is another example:
download() {
    local url=$1
    echo -n "    "
    wget --progress=dot $url 2>&1 | grep --line-buffered "%" | sed -u -e "s,\.,,g" | awk '{printf("\b\b\b\b%4s", $2)}'
    echo -ne "\b\b\b\b"
    echo " DONE"
}

A: You can use the follow option of tail:
wget somesite.com/TheFile.jpeg --progress=bar:force 2>&1 | tail -f -n +6

The +6 is to delete the first 6 lines. It may be different on your version of wget or your language.
You need to use --progress=bar:force otherwise wget switches to the dot type.
The downside is that the refreshing is less frequent than with wget (looks like every 2 seconds). The --sleep-interval option of tail seems to be meant just for that, but it didn't change anything for me.

A: The option --show-progress, as pointed out by others, is the best option, but it is available only since GNU wget 1.16, see Noteworthy changes in wget 1.16.
To be safe, we can first check if --show-progress is supported:
# set progress option accordingly
wget --help | grep -q '\--show-progress' && \
  _PROGRESS_OPT="-q --show-progress" || _PROGRESS_OPT=""

wget $_PROGRESS_OPT ...

Maybe it's time to consider just using curl.

A: Here is a solution that will show you a dot for each file (or line, for that matter). It is particularly useful if you are downloading with --recursive. This won't catch errors and may be slightly off if there are extra lines, but for general progress on a lot of files it is helpful:
wget -r -nv https://example.com/files/ | \
    awk -v "ORS=" '{ print "."; fflush(); } END { print "\n" }'

A: This is not literally an answer but this snippet might also be helpful to some coming here for e.g. "zenity wget GUI":
LANG=C wget -O /dev/null --progress=bar:force:noscroll --limit-rate 5k http://nightly.altlinux.org/sisyphus/ChangeLog 2>&1 | stdbuf -i0 -o0 -e0 tr '>' '\n' | stdbuf -i0 -o0 -e0 sed -rn 's/^.*\<([0-9]+)%\[.*$/\1/p' | zenity --progress --auto-close
What was crucial for me is stdbuf(1).


text:
Q: AngularJs get filtered input from ng-repeat to a Javascript variable? I'm currently working with AngularJs and am filtering an input array with a number of select boxes. On the filtered result, I'm running an ng-repeat to display each element in my now filtered array. Now my question. I want to save the filtered input array as an javascript variable, to later display or print the whole result. I actually only want either the filtered input array saved to a javascript variable or even better, the results of each ng-repeat saved altogether in a variable but updating itself after applying a new filter or a filter again. I'm stuck here. Is there a smooth way to do this. Or do you have a even better idea what would work here? Thank's already.
Let's say we have a filter for languages and name:
<select class="form-control"
              ng-options="l.language for l in languages"
              ng-model="languageModel"
              ></select>
<select class="form-control"
              ng-options="n.name for n in names"
              ng-model="nameModel"
              ></select>

Language: {{sq['Language']}}

Name: {{sq['Name']}}

Now I want something like :
$scope.var = ... // The filtered result.

A: You can directly store the array in your ng-repeat

Now you can access $scope.filteredInput to get the filtered array

A: You can call the filter directly from javascript:
$scope.filteredInput = $filter('languageModel')($scope.input);

Where languageModel is the name of your filter.
Make sure to inject $filter in your controller.
By the way, it is weird to have the ng-repeat on the
 element. Something more appropriate would be to put it on the
:

        Language: {{sq['Language']}}
        Name: {{sq['Name']}}

A: You can write your own filter function in your code behind, something like this
$scope.filterlanguage=function(item){

//add your condition if satisfies return or null
if(condition)
{
return item;
}
return null;

}


text:
Q: Prawn pdf 2 and Rmagick i've got trouble for croping a picture with Rmagick and then display with Prawn
Here is the code :
First a method to instantiate the image with RMagick :
def build_magick_image(path)
    if path.instance_of?(StringIO)
      Magick::Image.from_blob(path.read)
    else
      Magick::Image.read(path)
    end.first
end

In my case i have an instance of StringIO.
Then i crop the picture :
img = build_magick_image(picture_path)
cropped_img = img.resize_to_fill(1735, 1560)

But now i can't find how to display it in my Prawn pdf.
My last try is :
pdf.image cropped_img, at: [image_x, image_y], height: image_height.mm , width: inner_page_width.mm

But obviously it doesn't work.
Can someone help me?
Thanks :)

A: I found your question when I was trying to figure out the same thing  Here's the solution I came up with:
Wrap your image blob in a StringIO object, which will give Prawn the interface it needs. In your specific case:
cropped_img_sio = StringIO.open(cropped_img.to_blob)
pdf.image cropped_img_sio, at: [image_x, image_y], height: image_height.mm, width: inner_page_width.mm


text:
Q: Yii2 Swift_SmtpTransport gmail not working I'm trying to send an email using yii2 mailer component.
config web.php
'mailer' => [
    'class' => 'yii\swiftmailer\Mailer',
    // send all mails to a file by default. You have to set
    // 'useFileTransport' to false and configure a transport
    // for the mailer to send real emails.
    // 'useFileTransport' => true,
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'smtp.gmail.com',
        'username' => 'myEmail2131@gmail.com',
        'password' => 'password1234',
        'port' => '587',
        'encryption' => 'tls',
    ]
],

And my code.
Yii::$app->mailer->compose()
        ->setFrom('myEmail07@gmail.com')
        ->setTo('toSomeone@gmail.com')
        ->setSubject('Some Subject here')
        ->setTextBody('Plain text content')
        ->setHtmlBody("<p> This is the body of email</p>")
        ->send()

I'm getting this error.

Swift_TransportException Expected response code 250 but got code
  "535", with message "535-5.7.8 Username and Password not accepted.
  Learn more at 535 5.7.8
  https://support.google.com/mail/?p=BadCredentials
  a13-v6sm4133042wrc.19 - gsmtp "

I already configure my Gmail account as said here enter link description here
less secure app on on your gmail account
And I also try to use ssl instead tls.
'mailer' => [
    'class' => 'yii\swiftmailer\Mailer',
    // send all mails to a file by default. You have to set
    // 'useFileTransport' to false and configure a transport
    // for the mailer to send real emails.
    // 'useFileTransport' => true,
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'smtp.gmail.com',
        'username' => 'myEmail2131@gmail.com',
        'password' => 'password1234',
        'port' => '465',
        'encryption' => 'ssl',
    ]
],

Any idea? Thanks!

A: I've found a solution.
Note: I use this method just for testing. soon on production, I will use an actual email of our company.
My mail config
'mailer' => [
    'class' => 'yii\swiftmailer\Mailer',
    // send all mails to a file by default. You have to set
    // 'useFileTransport' to false and configure a transport
    // for the mailer to send real emails.
    // 'useFileTransport' => true,
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'smtp.gmail.com',
        'username' => 'myEmail2131@gmail.com',
        'password' => 'password1234',
        'port' => '587',
        'encryption' => 'tls',
    ]
],

Then do this:
https://www.google.com/settings/security/lesssecureapps and active it.
https://accounts.google.com/b/0/DisplayUnlockCaptcha and active it.
As answer from Ankit Tyagi here


text:
Q: Crash on `reloadRowsAtIndexPath` I have a paging tableView that loads a new page every time the user over scrolls, sort of like the instagram feed. The reloading of the tableView happens in a callback after the new page was fetched. The code looks something like this:
func fetchNewPage() {
    ws.fetchNewPage(completion: { () -> Void in {
        updateDataSource()
        self.tableView.reloadData()
    })
}

At the same time, the cells in the tableView should be updated when the user taps on them (they change their background color). This happens after a call to the WS. The code looks something like this:
func markAsSeen(indexPath: NSIndexPath) {
     ws.markAsSeen(completion: { () -> Void in {
         self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
     })
}

My problem is that the dataSource can change the number of elements while the markAsSeen completion block is executing. Then the app crashes with this exception:
Fatal Exception: NSInternalInconsistencyException
Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (50) must be equal to the number of rows contained in that section before the update (25), plus or minus the number of rows inserted or deleted from that section (1 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

So, my question is if you have any idea how to synchronize these two blocks so that the app does not crash anymore but also the row gets updated.
Thanks a lot

A: Your idea about synchronization is correct. As an option you can perform updates of data source on main queue. In such case data source and UI updates will be queued and executed serially, as result change of data will be predictable and consistent.
Also it worth to mention that all UI calls is mandatory should be executed on main thread. From your code it is not really clear that it is true.


text:
Q: Not able to print { codec => rubydebug } in the separate file output {
  elasticsearch {
     hosts => "localhost:8812"
     index =>"test_span_qry_one"
     document_id =>"%{cotid}"
     #document_type="_doc"

  }
  file {
     path => C:/Soft/ES3/ELK_stack_7.4.2/logstash-7.4.2/logstash-7.4.2/temp.txt
     codec => rubydebug
  }
}

This is my code in the config file of logstash.

[ERROR][logstash.agent           ] Failed to execute action {:action=>LogStash::PipelineAction::Create/pipeline_id:main, :exception=>"LogStash::ConfigurationError", :message=>"Expected one of #, { at line 58, column 15 (byte 2760) after output {\r\n  elasticsearch {..........

A:  file {
     path => "C:/Soft/ES3/ELK_stack_7.4.2/logstash-7.4.2/logstash-7.4.2/temp.txt"
     codec => rubydebug
 }

This is the correct syntax ..path should be in double qoutes.


text:
Q: iOS News App like Animation How can I achieve the following animation?
https://ibb.co/mZgAGF
Consider the list of cells in UITableView/UICollectionView.When the user taps on an UITableViewCell/UICollectionViewCell, the detail page animates/opens from the selected cell and when we go back, the detail view goes inside the selected cell.
Please let me even if we've any existing libraries.
Thanks in advance.


text:
Q: Тип возвращаемого значения Есть метод, который возвращает значение конкретного типа, исходя из указанного параметра (dbObjectType). Если изначально тип возвращаемого значения в методе является object, то когда компилятор дойдет, например до условия c "int", что он вернет, object или int ?
Как можно компактнее переписать этот метод ? т.к предусматривается что типов будет больше.
public static object ReturnDBObjectValue(DatabaseObject databaseObject, string dbObjectKey, string dbObjectType)
{
    var dbObjectTypes = new[] {"int", "string", "float", "double"};
    for (var i = 0; i < dbObjectTypes.Length; i++)
    {
        if(dbObjectType != dbObjectTypes[i])
            _errorLog.WriteError("write error type to log");
    }
    if (dbObjectType == null)
        return databaseObject.GetObject(dbObjectKey);

    if (dbObjectType == "int")
        return databaseObject.GetInt(dbObjectKey);
    if (dbObjectType == "string")
        return databaseObject.GetString(dbObjectKey);
    if (dbObjectType == "float")
        return databaseObject.GetFloat(dbObjectKey);
    if (dbObjectType == "double")
        return databaseObject.GetDouble(dbObjectKey);

    return databaseObject.GetObject(dbObjectKey);
}

A: В данном случае - конечно генерик.
Но когда вам необходимо передать одно значение из ограниченного множества, лучше использовать enum (вместо string dbObjectType в вашем случае)
enum ObjectType { eInt, eString, eFloat, eDouble }

// В реализации метода:
switch(dbObjectType)
{
...
case ObjectType.eInt:
    return databaseObject.GetInt(dbObjectKey);
...
}
// При вызове:
ClassName.ReturnDBObjectValue(databaseObject, dbObjectKey, ObjectType.eInt);

Таким образом, вам не придется создавать массив, проверять ввод =)


text:
Q: one handler for many instance I have 2 instances from one class.
Rectangle first = new Rectangle();
OnErrorHandler handler = new OnErrorHandler(Rectangle_OnError);
first.OnError += handler;
second.OnError += handler;

first.Width = 10;
first.Height = -5;

second.Width = -4;
second.Height = 2;

first.OnError -= handler;
first.Width = -1;
Rectangle second = new Rectangle();

and I want to know which instance creates event?
namespace EventSample
{
    public delegate void OnErrorHandler(string message);
}

public class Rectangle
{
    public event OnErrorHandler OnError;

    private int _Width;
    private int _Height;

    public int Width
    {
        get
        {
            return _Width;
        }
        set
        {
            if (value < 0)
            {
                if (OnError != null)
                    OnError("Width can not be less than zero!");

                return;
            }

            _Width = value;
        }
    }

thanks for your help.

A: As ChaosPandion said above, you should use exceptions to inform about error conditions.
Assuming that you still want to use events, you should use the proper convention for event handlers in C#.  This involves using the predefined EventHandler<TEventArgs> delegate rather than creating your own delegate.  The signature is this:
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

The important part in this case is the sender, which by convention is the instance which raised the event.  The typical way to raise the event is like this:
EventHandler<MyEventArgs> myEvent = this.MyEvent;
if (myEvent != null)
{
    // pass 'this' as sender to tell who is raising the event
    myEvent(this, new MyEventArgs(/* ... */));
}

A: You should be using exceptions for this (as Chaos mentions).
if (value < 0)
{
  throw new ArgumentException("Width can not be less than zero!");
}

see MSDN


text:
Q: What algorithm or software can I use to calculate tiles placement? My father is currently working on his new house and he is now ready to get to the floor tiles. He asked me what he called a "computer sciences" question but I guess it is more mathematics and algorithmics.
The problem is the following : let's imagine a given space of work (for instance 10x5 meters) and tiles from different sizes :

*

*50cm x 50cm

*30cm x 50cm

*30cm x 50cm

There's a suggested pattern which is built around these 3 types of tiles which form kind of an "L" and I want to repeat this pattern as much as possible in the room for aesthetic.
My question is : How can I optimize tiles placement to fit the maximum number of full tiles without cutting too much of them on the edge? Is there a software or a given data-structure for this kind of problem?
I don't have a given language (even if Python is welcomed) but my goal is to be able to draw the room with all tiles placed to fit the maximum number of uncut tiles! Hope I made it clear
Sorry if it's duplicate but I can't seem to find decent keywords

A: We can't give you a strict solution, because you haven't completely specified the problem.  You haven't given us the trade-off evaluation between maintaining the desired "L" shape and cutting a tile.  You also haven't specified the "L"; there are several possibilities.  For instance:
 +-----+
 | 3x5 |
 |     +---+
 |         |
 | 5x5  5x3|
 +---------+

 +---+
 |5x3|
 |   +-----+
 |         |
 | 5x5  5x3|
 +---------+

I recommend that you look up the field of tesselations; the most comprehensive references (IMHO) are from Darrah Chavey.
The simplest beginning is to simply "spoon" your "l" shapes on their natural diagonal:
       +-----+  ... and upward to the wall
       |     |
       |     +---+
 +-----+         |
 | 3x5 |         |
 |     +---+-----+
 |         |
 | 5x5  5x3|
 +---------+

Another is that you can form two of your "L" shapes, rotate one a half-turn, and join them into a hexagon with two concave corners.  This hexagon will tile the plane similarly:
   +---------+
   |         |
   |         |
 +-+---+     |
 | 3x5 |     |
 |     +---+-+
 |         |
 | 5x5  5x3|
 +---------+

For such a large space, you will probably want to choose a repeating pattern the works well for your specific space dimensions, and then either

*

*Start in one corner and propagate across the room, dealing with the opposite edges as you see fit;

*Start in the center, adjust a little to hit the walls nicely, but handle the edges more equitably;

*Align with the edges and work toward the middle, cutting a few tiles to produce a differentiated center feature.


text:
Q: PowerBuilder 12.1 production performance issues causing asynchrony? We have a legacy PowerBuilder 12.1 Classic application with an Oracle 11g back end, and are experiencing performance issues in production that we cannot reproduce in our test environments.
The window in question has shared grid/freeform DataWindows and buttons to open other response windows, which when closed cause the grid to re-retrieve.
The grid has a very expensive query behind it, several columns receive their values from function calls with some very intense SQL within, however it still runs within a couple seconds, even in production.
The only consistency in when the errors occur is that it seems to be more likely if they attempt to navigate to the other windows quickly.  The buttons that open said windows are assuming that a certain instance variable is set with the appropriate value from the row in focus in the grid.  However, in this scenario, the instance variable has not yet been set, even though it looks like the row focus change has occurred.  This is causing null reference exceptions that shouldn't be possible.
The end users' network connectivity is often sluggish, and their hardware isn't any less capable than ours.  I want to blame the network, but I attempted to reproduce this myself in development by intentionally slowing down the SQL so that I could attempt to click a button, however everything happened as I expected:  clicking the button didn't happen until after retrieve and all the other events finished.
My gut tells me that for some reason things aren't running synchronously when they should, and the only factor I can imagine is the speed of the SQL, whether from the query being slow, or the network being slow, but when I tried reproducing that effect things still happened in the proper sequence.  The only suspect code is that the datawindow ancestor posts a user event called ue_post_rfc from rowfocuschanged, and this event does a Yield().  ue_post_rfc is where code goes instead of rowfocuschanged.
Is there any way Yield() would cause these problems, without manifesting itself in test environments, even when SQL is artificially slowed?

A: While your message may not give enough information to give you a recipe to solve your problem, it does give me a hint towards a common point of hard-to-diagnose failures that I see often in PowerBuilder systems.
The sequence of development events goes something like this

*

*Developer develops code where there is a dependence on one event firing before another event, often a dependence through instance or global variables

*

*This event sequence has been something the developer has observed, but isn't documented as a guaranteed sequence (like the AcceptText() sequence or the Update() sequence are documented)

*I find this a lot with posted events, and I'm not talking about event and post-event where post-event is posted from event, but more like between post-ItemChanged and post-GetFocus

*Something changes the sequence of events, breaking the code. Things that I've seen change non-guaranteed sequences of events include:

*

*PowerBuilder version change

*Operating system change

*Hardware change

*The application running with other applications taxing the system resources

*Whoever is now in charge of solving this, has no clue what is going on or how to deal with it, so they start peppering the code with Yield() statements (I've literally seen comments beside a Yield() that said "I don't know why this works, but it solves problem X")

*

*Note that Yield() allows any and all events in the message queue to be processed, while this developer really wants only one particular event to get through

*Also note that the commonly-seen-in-my-career DO ... LOOP UNTIL (NOT Yield()) could loop infinitely on a heavily loaded system

*Something happens to change the event sequence again

*Now when the Yield() occurs, there is a different sequence of messages in the queue to be processed, and not the message the developer had wanted to be processed

*Things start failing again

My advice to get rid of this problem (if this is your problem) is to either:

*

*Get rid of the cross-event dependence

*Get rid of event sequence assumptions

*Manage the event sequence yourself

Good luck,
Terry

P.S. Here's a couple of quotes from your question that make me think of Yield() (not that I don't love the opportunity to jump all over Yield() grin)

The only consistency in when the errors occur is that it seems to be
  more likely if they attempt to navigate to the other windows quickly.

Seen this when the user tries to initiate (let's say for example) two actions very quickly. If the script from the first action contains a Yield(), the script from the second action will both start and finish before the first action finishes. This can be true of any combination of user actions (e.g. button clicks, menu clicks, tabs, window closings... you coded with the possibility that the window isn't there anymore after the Yield() was done, right? If not, join the 99% of those that code Yield(), don't, and live dangerously) and system events (e.g. GetFocus, Deactivate, Timer)

My gut tells me that for some reason things aren't running
  synchronously when they should

You're right. PowerBuilder (unless you force it) runs synchronously. However, if one event is starting before another finishes (see above), then you're going to get behaviours that look like asynchronous behaviours.
There's nothing definitive in what you've said, but you did ask about Yield(). The really kicker to nail this down is if you could reproduce this with a PBDEBUG trace; you'd see which event(s) is(are) surprising you. However, the amount that PBDEBUG slows things down affects event sequences and queuing, which may or may not be helpful.


text:
Q: git bash how to enable quick edit mode? (my OS is win 10) I can't find option to enable QuickEdit mode?

when I select block with left click, git bash copy(extend from win 10 command line) by execute Ctrl + C automatically. So it terminate process as the following picture.
How can I do?

PS: Ctrl-C is not my action,but by terminal automatically when I release left mouse clicking for selecting text

A: You're not using the Windows Console; you're using a terminal built for cygwin, a unix emulation environment. The usual default behaviour for unix terminals is to place text in the clipboard as soon as you select it. You don't need to press Ctrl-C or any other key.
(I don't have your terminal, so I can't verify that this will help, but there's a very good chance that this will address your issue.)

A: You can just select/highlight the text and it will automatically be placed on clipboard. then you can Past it using mouse Right Click and  Clicking Past or pressing Shift+Insert from keyboard on Windows machines.

A: QuickEdit Mode was available in Git 1.x, but your screenshot is from Git 2.x
You can use Ctrl+Shift+c for copy as shown here.
You can also use your mouse as shown here.
Also, note that starting from Windows 10 the Ctrl+c, Ctrl+v can be used for copy/paste as mentioned here.


text:
Q: Ensure execution order of two Apache Filters I need to ensure my custom filter always executes before the mod_rewrite. As per Apache Tutor, filters do not run in a deterministic order:

The request processing axis is straightforward: the phases happen strictly in order. But confusion arises in the data axis. For maximum efficiency, this is pipelined, so the content generator and filters do not run in a deterministic order. So, for example, you cannot in general set something in an input filter and expect it to apply in the generator or output filters.

How to ensure execution sequence of two filters, or is it possible?

Update:
Someone has indicated to mod_info to display detailed information about modules and their order.

A: The best way to understand this is to look into the apache source code. The mod_proxy and mod_rewrite usage of the ap_hook_fixups is a perfect example of how to insert a hook before or after particular module.
Let say you want to insert a hook before mod_rewrite, you can do something like this:
static int my_fixup(request_rec *r)
{
    /* do something with request headers before it goes to the mod_rewrite */
    return OK;
}

static void register_hooks(apr_pool_t *p) {
    static const char * const aszSucc[] = {"mod_rewrite.c", NULL};
    ap_hook_fixups(my_fixup, NULL, aszSucc, APR_HOOK_FIRST);
}

Also, you can check the http://httpd.apache.org/docs/2.2/developer/hooks.html page for other kinds of hooks, or to better understand how to control hook calling order.


text:
Q: How to fix TextView move far left and right when rotated? I want to make TextView align to  left and right edges of window screen. The expect result will look like this

but the actual result look like this

Here is my XML...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cameraContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/cameraPreview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@color/grey_700"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/white"
        android:textSize="35sp" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@color/grey_700"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/white"
        android:textSize="35sp"
        />

    <TextView
        android:id="@+id/text3"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/grey_700"
        android:rotation="270"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/white"
        android:textSize="35sp"
        android:layout_alignBottom="@+id/text4"
        android:layout_alignParentStart="true"
        />

    <TextView
        android:id="@+id/text4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/grey_700"
        android:rotation="90"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/white"
        android:textSize="35sp"
        android:layout_centerVertical="true"
        android:layout_alignParentEnd="true"
        />
</RelativeLayout>

It seem like that when I rotate the textview, only the textview I rotated will move far left and far right.
Do you have any ideas how to make 2 text view on the left and right align as expect result?
Thank you!

A: I found a custom vertical TextView in this answer that you can use and keep the backgrounds:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/cameraContainer"
             android:layout_width="match_parent"
             android:layout_height="match_parent">
    <FrameLayout
        android:id="@+id/cameraPreview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:background="@color/grey_700"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/white"
        android:textSize="35sp"/>
    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="bottom"
        android:background="@color/grey_700"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/white"
        android:textSize="35sp"/>
    <com.app.views.VerticalTextView
        android:id="@+id/text3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|left"
        android:gravity="bottom|center_horizontal"
        android:text="TEST TEXT TEST TEXT"
        android:background="@color/grey_700"
        android:textColor="@color/white"
        android:textSize="35sp"/>
    <com.app.views.VerticalTextView
        android:id="@+id/text4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|right"
        android:gravity="top|center_horizontal"
        android:text="TEST TEXT TEST TEXT"
        android:background="@color/grey_700"
        android:textColor="@color/white"
        android:textSize="35sp"/>
</FrameLayout>

/*VerticalTextView.java*/
package com.app.views;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

public class VerticalTextView extends TextView {
    final boolean topDown;

    public VerticalTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        final int gravity = getGravity();
        if (Gravity.isVertical(gravity) && (gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
            setGravity((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
            topDown = false;
        } else
            topDown = true;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    @Override
    protected boolean setFrame(int l, int t, int r, int b) {
        return super.setFrame(l, t, l + (b - t), t + (r - l));
    }

    @Override
    public void draw(Canvas canvas) {
        if (topDown) {
            canvas.translate(getHeight(), 0);
            canvas.rotate(90);
        } else {
            canvas.translate(0, getWidth());
            canvas.rotate(-90);
        }
        canvas.clipRect(0, 0, getWidth(), getHeight(), android.graphics.Region.Op.REPLACE);
        super.draw(canvas);
    }
}

A: You could trick the layout by using a square TextView, but you need to get rid of the backgrounds...
Try out this:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/cameraContainer"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    <FrameLayout
        android:id="@+id/cameraPreview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:background="@color/grey_700"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/white"
        android:textSize="35sp"/>
    <TextView
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="bottom"
        android:background="@color/grey_700"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/white"
        android:textSize="35sp"/>
    <com.app.views.TextViewSquareW
        android:id="@+id/text3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="center_horizontal"
        android:rotation="270"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/grey_700"
        android:textSize="35sp"/>
    <com.app.views.TextViewSquareW
        android:id="@+id/text4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="center_horizontal"
        android:rotation="90"
        android:text="TEST TEXT TEST TEXT"
        android:textColor="@color/grey_700"
        android:textSize="35sp"/>
</FrameLayout>

/*TextViewSquareW.java*/
package com.app.views;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.TextView;

public class TextViewSquareW extends TextView {
    public TextViewSquareW(Context context) {
        super(context);
    }

    public TextViewSquareW(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TextViewSquareW(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public TextViewSquareW(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}


text:
Q: Implementing a TLabel with TabStop and FocusRect? I'm using Delphi7 and I'm trying to implement a LinkLabel like the ones you can find under the Control Panel on Windows Vista and above.
Changing the cursor/color on hover is really simple, the only thing I need to do is to make the TLabel receive tab stops and to draw a focus rectangle around it.
Any ideas on how to do this? I understand that the TLabel doesn't receive tabs because of its nature. There is also TStaticText which does receive tabs, but it also doesn't have a focus rectangle.

A: Here's a derived static that draws a focus rectangle when focused. 'TabStop' should be set, or code that checks should be added. Doesn't look quite nice (the control doesn't actually have room for lines at all edges), but anyway:
type
  TStaticText = class(stdctrls.TStaticText)
  private
    FFocused: Boolean;
  protected
    procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
    procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
    procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
  end;

...

procedure TStaticText.WMSetFocus(var Message: TWMSetFocus);
begin
  FFocused := True;
  Invalidate;
  inherited;
end;

procedure TStaticText.WMKillFocus(var Message: TWMKillFocus);
begin
  FFocused := False;
  Invalidate;
  inherited;
end;
procedure TStaticText.WMPaint(var Message: TWMPaint);
var
  DC: HDC;
  R: TRect;
begin
  inherited;
  if FFocused then begin
    DC := GetDC(Handle);
    GetClipBox(DC, R);
    DrawFocusRect(DC, R);
    ReleaseDC(Handle, DC);
  end;
end;


text:
Q: A script on this page may be busy, or it may have stopped responding. Asp.net I have a page which gives me this error in Firefox:

A script on this page may be busy, or it may have stopped responding.
  You can stop the script now, or you can continue to see if the script
  will complete.

This is my jquery code:
 function uploadComplete(sender, args) {
             var imgDisplay = $get("imageEmployeeTemp");
             var img = new Image();
             img.onload = function () {
             imgDisplay.style.cssText = "height:100px;width:100px";
             imgDisplay.src = img.src;
             };
             img.src = "/Resources/Images/Employee/" + args.get_fileName();
         }

         $(document).ready(function () {
             $('#TxBx_BasicSalary').focusout(function () {

                var EmployeeId = $('#Hid_EmpID').val();
                if (EmployeeId == 0) {
                    return;
                }
                $.ajax({
                    type: "POST",
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    url: '/WebService/IncDedWebService.asmx/GetInceDed',
                    data: '{ "id": "' + EmployeeId + '" }',
                    dataType: 'json',
                    success: function (data) {
                  var data = $.parseJSON(data.d)
                  var TotalIncentives = data["TotalIncentives"];
                  var TotalDeduction = data["TotalDeduction"];
                  var BasicSalary = $("#TxBx_BasicSalary").val();
                  var GrossSalary = parseInt(BasicSalary) + parseInt(TotalIncentives)
                   $('#Ltrl_GSalary').html(GrossSalary);
                   $('#Hid_GSalary').val(GrossSalary);
                  $('#Ltrl_NetSalary').html(GrossSalary - parseInt(TotalDeduction));
                   $('#Hid_NetSalary').val(GrossSalary - parseInt(TotalDeduction));
                 },
                     error: function () { alert("error"); }
                 });
            });
             var id = "#<%= Rtb_PayMode.ClientID %>";
             var bool = false;
             $(id).click(function () {
                HideShowRows();
                 bool = true;
             });

             if (!bool) {
                 HideShowRows();
             }
             function HideShowRows() {
                var BankInfo = $('#BankInfo');
                 var BankAccount = $('#BankAccount');
                 if ($('#<%= Rtb_PayMode.ClientID %> input:checked').val() == '1') {
                     BankInfo.hide();
                     BankAccount.hide();
                }
                else {
                     BankInfo.show();
                     BankAccount.show();
                 }
             }
         });

Please help me what to do.

A: You could try setting a flag to stop multiple simultaneous ajax requests:
     $(document).ready(function () {
         var inProgress = false;
       $('#TxBx_BasicSalary').focusout(function () {

          if(!inProgress){
            inProgress = true;
            var EmployeeId = $('#Hid_EmpID').val();
            if (EmployeeId == 0) {
                return;
            }
            $.ajax({
                type: "POST",
                cache: false,
                contentType: "application/json; charset=utf-8",
                url: '/WebService/IncDedWebService.asmx/GetInceDed',
                data: '{ "id": "' + EmployeeId + '" }',
                dataType: 'json',
                success: function (data) {
                  inProgress = false;
                  var data = $.parseJSON(data.d)
                  var TotalIncentives = data["TotalIncentives"];
                  var TotalDeduction = data["TotalDeduction"];
                  var BasicSalary = $("#TxBx_BasicSalary").val();
                  var GrossSalary = parseInt(BasicSalary) + parseInt(TotalIncentives)
                  $('#Ltrl_GSalary').html(GrossSalary);
                  $('#Hid_GSalary').val(GrossSalary);
                  $('#Ltrl_NetSalary').html(GrossSalary - parseInt(TotalDeduction));
                  $('#Hid_NetSalary').val(GrossSalary - parseInt(TotalDeduction));
             },
                 error: function () { alert("error"); }
             });
           }
      });

A: i had the same problem using ajaxToolkit:AsyncFileUpload.
there is a workaround with css;
-apply CssClass="asyncupload" in your AsyncFileUpload,
-add class .asyncupload input { width:100%!important; } to your css file.


text:
Q: dojo display property I am trying to assign the anything value to the display property as shown below.
dojo.query(".item").style('display', 'anything');

But it is not effecting. Please provide me any suggestion.

A: My guess is that you have to give the .item a display setting in CSS before you can change the setting in the script.
So, if you do .item { display:none; } in CSS,
query('.item').style('display', 'block'); in the script will work.
This is how Dojo works for me.
On a side note, consider looking at Dojo 1.7 where you don't use the dojo.method way of coding.


text:
Q: Picturing Riemannian geometry on a surface as a flow This question asks pictures or intuitions of Riemannian geometry on a compact surface.
Pull the connection 1 form on the tangent circle bundle down to the tangent bundle with a vector field with isolated singularities. Take its dual vector field under the Riemannian metric. Now there is a vector field that is dual to the connection. In fact there are many such forms, one for each vector field with isolated singularities.
My question is: What picture of the connection does this vector field or its flow give us?
Is there a particularly clear picture if the vector field is dual to a meromorphic 1 form?

A: Most of your question is about local Riemannian geometry on a surface $(M,g)$, and that part can be answered without too much trouble, so I'll do that.  Whether you can get anything global out of it is another matter, and I'm somewhat doubtful, but maybe the following will be of some use.
First, let's avoid the singular points for a moment and work on the part of the surface where the vector field isn't zero.  Let's start with a unit vector field $\mathbf{e}_1$ on an open set $U\subset M$.  Let $\mathbf{e}_2$ be such that $(\mathbf{e}_1,\mathbf{e}_2)$ is an oriented $g$-orthonormal frame field on $U$.
Direct computation shows that the vector field your process associates to $\mathbf{e}_1$ is the vector field $[\mathbf{e}_1,\mathbf{e}_2]$, i.e., the Lie bracket of the two unit vector fields.
Let $\mathbf{v}$ be another vector field on $U$. One can write $\mathbf{v} = r\cos\theta\ \mathbf{e}_1+r\sin\theta\ \mathbf{e}_2$ and, on the open set where $r>0$ (so that $\theta$ is well-defined), and your process associates to $\mathbf{v}$ the vector field
$$
\bigl[\cos\theta\ \mathbf{e}_1+\sin\theta\ \mathbf{e}_2,
\ -\sin\theta\ \mathbf{e}_1+\cos\theta\ \mathbf{e}_2\bigr]
= [\mathbf{e}_1,\mathbf{e}_2] - \nabla^g\theta,
$$
where $\nabla^g\theta$ is the gradient of $\theta$ with respect to the metric $g$.
It is not clear to me that you can get much local geometric information from this formula, and I'm not sure what you are hoping to see globally, but maybe you have something in mind.  Locally, what you see is that the vector fields you get this way all differ by gradient vector fields.  If you think of this as a first-order differential operator from vector fields to vector fields, it's nonlinear, but if you think of the map from $C^\infty(M)$ to vector fields given by $\theta\mapsto [\mathbf{e}_1,\mathbf{e}_2] - \nabla^g\theta$, then this is obviously an affine operator, so, you can almost think of it as a linear operator.
Note that, if $\mathbf{v}$ has isolated zeros of nonzero index, then $\nabla^g\theta$ blows up at those points, so your process yields vector fields with unbounded lengths.
As for the case of a meromorphic $1$-form, I guess you mean a vector field $\mathbf{v}$ that is $g$-dual to the real part of a meromorphic $1$-form $\omega$. Otherwise, I'm not sure what you mean.  In this case, you can see, without too much trouble, that, away from the poles and zeros (where it isn't defined) the flow of the resulting vector field, say $\mathbf{w}$, is $g$-area preserving.  The converse is true also (at least locally); i.e., if the flow of the resulting vector field is $g$-area preserving, then, up to a (real, nonzero) multiple, it is dual to a $g$-harmonic $1$-form (i.e., one that is closed and co-closed), so that (again, locally) it is dual to the real part of a holomorphic $1$-form.
Locally, at least, there is not anything more to say.


text:
Q: make string starting with $ a non variable
Possible Duplicate:
Difference between single quote and double quote string in php

I have some strings which which are made up of random characters including $ sign, this becomes a problem if the string happens to begin with $ as it is treated as a variable, is there some way around this problem?
<?php
$variable="$&%51a-notaVariable";
?>

A: Use single quotes:
<?php
   $variable='$&%51a-notaVariable';
?>

A: Answer 1: Use single quotes instead of double quotes.
$variable = '$&%51a-notaVariable';

Answer 2: If you definitely need to use double quotes for whatever reason, you can escape the dollar sign with a backslash.
$variable = "\$&%51a-notaVariable";

A: Short answer - yes. Use ' instead of " as it won't try to parse the characters in the string. :)
Long answer - yes. Note that you'll have to concat strings instead of putting variables "$inline" (or use sprintf() & co)... however, all in all, it's a beneficial tradeoff.


text:
Q: SSE2 extract float from packed data in golang I'm writing an assembly function in Golang. To simplify let's suppose that I want to do the following function:
func sseSumOfMinimums (d1, d2 [2]float64) float64

It will compute the minimum of d1[0], d2[0] and the minimum of d1[1] and d2[1] and compute the sum
In assembly I do:
TEXT ·sseSum(SB), $0-40
MOVUPD d1+0(FP), X0 // loading d1 to X0
MOVUPD d2+16(FP), X1 // loading d1 to X1
MINPD X0, X1 // compute pair minimums and store to X1
MOVSD X1, X2 // move first min to X2
// How do I move second float of X1 to X3?
ADDSD X2, X3
MOVSD X3, ret+32(FP)

The part that I'm missing is how to extract the second scalar from X1 to X3

A: Does Go not guarantee stack alignment so you could use a memory source operand for minpd?
Also, I'm not familiar with Go; is its float really IEEE binary64, which most languages (including x86 asm) call double?  It's weird to see float in the source and pd (packed double) instructions used in the asm.

The overhead of calling a standalone hand-written-asm function for this is going to be higher than letting a compiler do it with scalar minsd, for a single pair.  Especially with Go's crappy calling convention, passing args in memory and storing the return value to memory.
An optimizing Go compiler with an LLVM or gcc back-end should get the job done with inline code with lower latency and fewer uops of throughput cost than calling this function, even with the optimization given below.  Or if you're lucky, the compiler will use minpd for you.

But for the actual problem, after minpd   x0, x1, what you need is a horizontal sum of xmm1.  Fastest way to do horizontal float vector sum on x86.
You should use movaps to copy xmm registers, even if you only care about the low 64 bits.  movsd x1, x2 merges into the low 64 bits of xmm2, creating a false dependency on the old value and costing a shuffle uop.
minpd   x0, x1
movhps  x1, x0        // high 64 bits of xmm1  => low 64 of xmm0
addsd   x1, x0

You could movaps x1, x2 and unpckhpd x2,x2, but that would cost an extra movapd or movaps which you can avoid by using movhps.
(movaps / movups is shorter than movapd, smaller code-size, and otherwise exactly equivalent to movapd / movupd on all CPUs for loads, stores, and reg-reg copies.)


text:
Q: GPA regex in Perl I'm attempting to make a GPA validation regex in Perl, and I seem to have something wrong with my logic. You should be able to end a number 0-3 followed by a . with 1 more digit in the range of 0-9. or if the first digit is a 4 it must be followed with a .0 Here's my code:
$get_gpa_input =~ m/[0-3]\.\d[0-9]|[4].[0]/

A: m/(?: [0-3] [.] [0-9] ) | 4[.]0 /x

A: Remove the [0-9]. You've also got some extra brackets and you should escape the decimal in '4.0'.
$get_gpa_input =~ m/[0-3]\.\d|4\.0/

A: If you are doing validation, you don't want to search within a string but rather to force the entire string to match your regex; you do this by adding anchors to the beginning and ending:
/\A (?: [0-3]\.[0-9] | 4\.0 ) \z/x

\A matches only before the first character of the string, \z matches only after the last character of the string.
Avoid using \d in most code since it can match any number of Unicode "digits" that aren't 0 through 9 (though in newer perls, the /a flag reverts it to its old ASCII meaning).

A: You have \d[0-9] which would require two digits following 0-3.  You also don't escape the decimal in the 4 alternate, which may make a difference.
[0-3]\.\d|4\.0


text:
Q: awk printing field in the wrong column When I run the below command, it outputs a list of columns as follows:
# rancher clusters
CURRENT   ID        STATE     NAME                           PROVIDER
*         abcd      active    test-cluster                   Imported
          efgh      active    prod-cluster                   Imported
          xyzd      active    dev-cluster                    Imported

When I try to print the NAME column, test-cluster is not returned in the results
# rancher clusters | awk '{print $3}'
STATE
active
prod-cluster
dev-cluster

You can see that parts of the STATE column show in the printed NAME column.
When I print the fourth column, test-cluster is returned along with NAME
# rancher clusters | awk '{print $4}'
NAME
test-cluster
Imported
Imported

Why isn't awk returning values from the exact column that is printed?  What could cause values from one column to be returned in another column?  My expectation is when I print $3, I will get all of the results in the fourth column (NAME).

A: You are getting $3 - however, by default, awk ignores leading and trailing whitespace when breaking a record up into fields.
You should be able to force it to treat the leading whitespace as an empty field by setting the field separator explicitly ex.
$ cat clusters | awk -F'[ \t]+' '{print $3}'
STATE
active
active
active

whereas
$ cat clusters | awk '{print $3}'
STATE
active
prod-cluster
dev-cluster

A: awk splits the strings based on a separator (default is one or several whitespaces, i.e. tabs or spaces). To make it clearer, here is your data with the data delimited by |
CURRENT|ID|STATE|NAME|PROVIDER
*|abcd|active|test-cluster|Imported
efgh|active|prod-cluster|Imported
xyzd|active|dev-cluster|Imported

As you can see above, on the first line, $1 is CURRENT, $2 is ID, and so on. On the second line, $1 is *, $2 is abcd, etc. However, on the third line, $1 is efgh, which corresponds to the ID column. Since there is nothing except whitespace in the CURRENT column, it is ignored by awk, and therefore $3 shows the NAME for lines 3 and 4.
What you need to do is to strip off the first column before you send it to awk. The following command should do that for you.
rancher clusters | cut -b 8- | awk '{ print $3 }'
The cut command in the pipeline above will delete the first 7 bytes in every line, and print the rest to STDOUT. That will result in awk not getting confused by different number of columns on every line.

A: awk by default separates records into fields based on contiguous sequences of white space and ignores any leading trailing white space. Since your first "field" is sometimes empty to awk it doesn't exist. Given that, there's a few ways to print the NAME column, the simplest being to count fields from the end of the record rather than the start of it:
$ awk '{print $NF}' file
PROVIDER
Imported
Imported
Imported
$
$ awk '{print $(NF-1)}' file
NAME
test-cluster
prod-cluster
dev-cluster
$
$ awk '{print $(NF-2)}' file
STATE
active
active
active
$
$ awk '{print $(NF-3)}' file
ID
abcd
efgh
xyzd
$
$ awk '{print (NF>4 ? $(NF-4) : "")}' file
CURRENT
*

$

You need to do some math on that last one so $(NF-4) doesn't cause $0 to be printed when NF is 4. You can calculate the intended number of fields rather than hard-coding 4 by counting how many fields are in the header line:
$ awk 'NR==1{max=NF-1} {print (NF>max ? $(NF-max) : "")}' file
CURRENT
*

$

A: The problem is that sometimes the output of your rancher command has 5 fields per line, and sometimes it has 4.
The following awk one-liner will print the correct field depending on how many fields (using awk's built-in variable NF) any given input line has:
$ awk 'NF==5 {print $4}; NF==4 {print $3}' clusters.txt
NAME
test-cluster
prod-cluster
dev-cluster

Alternatively, if you can be certain that there will be no blank lines, you could use:
$ awk '{print $(NF-1)}' clusters.txt
NAME
test-cluster
prod-cluster
dev-cluster

If there is a blank line, you'll get an error message like this:
awk: cmd. line:1: (FILENAME=clusters.txt FNR=5) fatal: attempt to access field -1

That can be avoided with:
awk 'NF>=1 {print $(NF-1)}' clusters.txt


text: Q: how to upload a laravel project in free server I need upload My Laravel project with free web server like https://www.000webhost.com/ this is My first time. I need some tutorials. I do not have database in the movement. can you help me?


text:
Q: Extend JTextField to InputStream and action from Button I have some problems with my code and i would need some help if you can please(and explain it a bit so i can understand in the future:)), so this is my code and what i need is that my JButton to action a shutdown command and the shutdown command to be delayed from the seconds i input in my JTextfield.
So my code so far  is :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Shutdown extends JFrame{
    InputStream text1;
    JButton start;
    String shutdownCmd;

        public Shutdown() {

        this.setTitle("Shutdown When you want");
        setSize(300, 150);
        setResizable(false);
        setLocation(370, 150);
        setLayout(null);

        JLabel desc1 = new JLabel("Time until shutdown : ");
        desc1.setBounds(95, 25, 125, 25);
        add(desc1);

        JTextField text1 = new JTextField();
        text1.setBounds(95, 45, 120, 25);
        text1.setForeground(Color.BLACK);
        text1.setToolTipText("Introdu textu aici");
        add(text1);

        JButton start = new JButton("Start Shudown");
        start.setBounds(95, 75, 120, 25);
        add(start);

        ActionListener eventstart = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO auto- generated method
                String actionstart = arg0.getActionCommand();
                if(actionstart.equals("Start Shudown")){
                    try {
                        ShutdownCmd();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                }

        };
        start.addActionListener(eventstart);
}
        public void ShutdownCmd() throws IOException{
     Runtime runtime = Runtime.getRuntime();
     BufferedReader br=new BufferedReader(new InputStreamReader(text1));
     long a=Long.parseLong(br.readLine());
     Process proc = runtime.exec("shutdown -s -t "+a);
     System.exit(0);
}
}

Thank you or the help in advanced !!! :D

A: Lots of things jump out at me here, but...
Redeclare text1 as JTextField instead of an InputStream...
//InputStream text1;
private JTextField text1;

This will allow you to access the field and it's value from anywhere in the class.
Make sure you aren't shadowing the variables when you create the text field...
//JTextField text1 = new JTextField();
text1 = new JTextField(10);

Make use of ProcessBuilder instead of Runtime.getRuntime().  It will make your life easier to deals with parameters much better
ProcessBuilder pb = new ProcessBuilder("shutdown", "-s", "-t", text1.getText());
pb.redirectError();
Process p = pb.start();

The action command will always be null as you never set, so the following will cause you a NullPointerException
String actionstart = arg0.getActionCommand();
if(actionstart.equals("Start Shudown")){

When you create your button, you need to set the action command...
JButton start = new JButton("Start Shudown");
start.setActionCommand("Start Shudown");

Additional suggestions...

*

*Make use of appropriate layout managers.  Even across the same OS, it's possible your application will need to deal with different screen resolutions, DPI, fonts etc...

*Avoid extending directly from top level containers like JFrame.  Instead, base you application on something like JPanel.  It makes your application for flexible and re-usable.

A: All you need to do is make the JTextField a field:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Shutdown extends JFrame{
    JTextField text1;
    JButton start;
    String shutdownCmd;

        public Shutdown() {

        this.setTitle("Shutdown When you want");
        setSize(300, 150);
        setResizable(false);
        setLocation(370, 150);
        setLayout(null);

        JLabel desc1 = new JLabel("Time until shutdown : ");
        desc1.setBounds(95, 25, 125, 25);
        add(desc1);

        text1 = new JTextField();
        text1.setBounds(95, 45, 120, 25);
        text1.setForeground(Color.BLACK);
        text1.setToolTipText("Introdu textu aici");
        add(text1);

        JButton start = new JButton("Start Shudown");
        start.setBounds(95, 75, 120, 25);
        add(start);

        ActionListener eventstart = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO auto- generated method
                String actionstart = arg0.getActionCommand();
                if(actionstart.equals("Start Shudown")){
                    try {
                        ShutdownCmd();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                }

        };
        start.addActionListener(eventstart);
}
        public void ShutdownCmd() throws IOException{
            Runtime runtime = Runtime.getRuntime();

            long a=Long.parseLong(text1.getText());
            Process proc = runtime.exec("shutdown -s -t "+a);
            System.exit(0);
        }
}

If it's global, you can use it in any of this object's functions, so you can get the Text from the textField from anywhere you want inside your JFrame Object.
I hope this is what you want to do. If its not explained well enough, please tell me. ;)


text:
Q: Is there a pre-defined built-in function to convert a number to its binary format in C++? Integer.toString(n,8) // decimal to octal

Integer.toString(n,2) // decimal to binary

Integer.toString(n,16) //decimal to Hex

We have these functions in java ... do we have such built-in functions in c++

A: There is one function available itoa present in the stdlib.h by which we can convert integer to string. It is not exactly defined in C or C++ but supported by many compilers.
char *  itoa ( int value, char * str, int base );

itoa example
#include <iostream>
#include <stdlib.h>

int main ()
{
    int i;
    char buffer [33];
    printf ("Enter a number: ");
    scanf ("%d",&i);
    itoa (i,buffer,10);
    printf ("decimal: %s\n",buffer);
    itoa (i,buffer,16);
    printf ("hexadecimal: %s\n",buffer);
    itoa (i,buffer,2);
    printf ("binary: %s\n",buffer);
    return 0;
}

OUTPUT
Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110

For more details you can refer itoa

A: If you need a cross platform way to do this cplusplus.com suggests: sprintf is a good option for hex and oct:
int Integer = 13;
char toOct[sizeof(int) * (unsigned int)(8.0f / 3.0f) + 2];
char toHex[sizeof(int) * 8 / 4 + 1];
bitset<sizeof(int)> toBin(Integer);

sprintf(toOct, "%o", Integer);
sprintf(toHex, "%x", Integer);

cout << "Binary: " << toBin << "\nOctal: " << toOct << "\nDecimal: " << Integer << "\nHexadecimal: " << toHex << endl;

Note that toOct and toHex are char arrays sized to hold the largest integer in Octal and Hexadecimal strings respectively, so there is no need for dynamic resizing.

A: You can use  std::bitset  to convert a number to its binary format.
Use the following code snippet:
  std::string binary = std::bitset<8>(n).to_string();

A: int n = 64;
string binary = bitset<64>(n).to_string();
binary.erase(0, binary.find_first_not_of('0'));
cout << binary << endl;

A:  int main() {
    int n;
    cin >> n;
    string binary = bitset<32>(n).to_string();
    cout << binary << endl;
    return 0;
}

Expected output: 00000000000000000000000000010000


text:
Q: How to run logcat on multiple devices? How can I run logcat on multiple devices at the same time? "adb logcat" command gives an error:
error: more than one device and emulator

A: Use the -s option of adb:
adb -s <serialnumber>

Example
C:\Users\lel>adb devices
List of devices attached
192.168.198.101:5555    device
0123456789ABCDEF        device

adb -s 0123456789ABCDEF logcat
adb -s 192.168.198.101:5555 logcat

You can combine grep whit this, to get all lines that contain it.
an example is with System.out
Example:
 adb -s 192.168.198.101:5555 logcat | grep "System.out"

A: I thought it might be useful. I have this script that helps me a lot. It logcats each device to a different file. To stop logging just press CTRL+C.
#! /bin/bash

devices=`adb devices | grep 'device$' | cut -f1`
pids=""

for device in $devices
do
    log_file="$device-`date +%d-%m-%H:%M:%S`.log"
    echo "Logging device $device to \"$log_file\""
    adb -s $device logcat -v threadtime > $log_file &
    pids="$pids $!"
done

echo "Children PIDs: $pids"

killemall()
{
    echo "Killing children (what a shame...)"

    for pid in $pids
    do
        echo "Killing $pid"
        kill -TERM $pid
    done
}

trap killemall INT

wait

A: Use your device ip:
adb -s device_ip:5555