text:
Q: Finding the real difference between dates in JDK7 How can I find the difference between two dates in JDK7, such that the difference can be added back to make the two dates equal?
I tried to use the solution from a similar StackOverflow question, subtracting one date's milliseconds from the other, but this can result in an incorrect difference between dates.
In this example, I try to make a equal to b by setting a = (b-a) + a
private void makeTwoDatesEqual(GregorianCalendar a, GregorianCalendar b, DatatypeFactory datatypeFactory) {
    long b_minus_a = b.getTimeInMillis() - a.getTimeInMillis();
    Duration delta = datatypeFactory.newDuration(b_minus_a);
    delta.addTo(a);
}

But the results are unexpected:
Before
a = "2015-08-29T00:00:00.000Z"
b = "2040-01-01T00:00:00.000Z"
delta = "P24Y4M5DT0H0M0.000S" // 2 days longer than it should be.

After
a = "2040-01-03T00:00:00.000Z"
b = "2040-01-01T00:00:00.000Z"
delta = "P24Y4M5DT0H0M0.000S"
a.equals(b) = false

Joda-Time has this same issue:
private void makeTwoDatesEqual(GregorianCalendar a, GregorianCalendar b) {
    DateTime date1 = new DateTime(a);
    DateTime date2 = new DateTime(b);
    Interval interval = new Interval(a.getTimeInMillis(), b.getTimeInMillis());
    Period offsetPeriod = interval.toPeriod();
    date1 = date1.plus(offsetPeriod);
    date1.equals(date2); // false in my example
}

Before
date1 = "2015-08-29T00:00:00.000-05:00"
date2 = "2040-01-01T00:00:00.000-05:00"
offsetPeriod = "P24Y4M2DT23H"
date1.equals(date2) = false

After
date1 = "2039-12-31T23:00:00.000-05:00"
date2 = "2040-01-01T00:00:00.000-05:00"
offsetPeriod = "P24Y4M2DT23H"
date1.equals(date2) = false

Before it's asked, there should be no need to account for daylight savings or leap years because in each example I'm adding the interval back over the exact same time period from which it was derived.

A: ThreeTen Backport
There are a couple of possibilities using the modern Java date and time API known as JSR-310 or java.time. Can you use this with Java 7? Certainly! Get ThreeTen Backport and start coding.
Difference between date-times
EDIT: If you want to perceive your a and b as points in time, in other words, both dates and times of day, you may use either a suitably small time unit for the difference, or the Duration class. Both will work the same. Since Instants have nanosecond precision, calculating a difference in nanos will make sure we don't lose any precision:
Instant a = Instant.parse("2015-08-29T00:00:00.000Z");
Instant b = Instant.parse("2040-01-01T00:00:00.000Z");
long delta = ChronoUnit.NANOS.between(a, b);
a = a.plusNanos(delta);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("delta = " + delta);
System.out.println("a.equals(b) = " + a.equals(b));

This prints
a = 2040-01-01T00:00:00Z
b = 2040-01-01T00:00:00Z
delta = 768182400000000000
a.equals(b) = true

The Duration class is meant for durations in hours, minutes, seconds and fraction of second. You can use it for longer durations, but it doesn't know about weeks, months or years.
Duration delta = Duration.between(a, b);
a = a.plus(delta);

Otherwise as before. This time the output is
a = 2040-01-01T00:00:00Z
b = 2040-01-01T00:00:00Z
delta = PT213384H
a.equals(b) = true

So the difference is 213384 hours. Only because the minutes and seconds are 0 in this case, they are not printed, otherwise they would be; Duration too has nanosecond precision.
Difference between dates
Taking your title more literally and noticing that your example dates fall on midnight UTC. If you don't care about the time of day and only want to count days, months and years, you may use either the Period class or simply count days. The Period class is for periods of days, months and years and has 1 day precision (that means, cannot be used for hours and smaller units).
LocalDate a = LocalDate.of(2015, Month.AUGUST, 29);
LocalDate b = LocalDate.of(2040, Month.JANUARY, 1);
Period delta = Period.between(a, b);
a = a.plus(delta);

The printing goes as before, but now it prints
a = 2040-01-01
b = 2040-01-01
delta = P24Y4M3D
a.equals(b) = true

Counting days goes just like nanoseconds above, only with days instead:
long delta = ChronoUnit.DAYS.between(a, b);
a = a.plusDays(delta);

This time the output contains:
delta = 8891
a.equals(b) = true

Please note that because months haven't got the same length, even though 24 years 4 months 3 days seems to equal 8891 days, this will more often not be the exact case. This is explained in more detail in @Meno Hochschild's comment and Hugo's answer. So the choice between a Period and a number of days will make a difference, and you should choose based on your more exact requirements.
Combining Period and Duration
It's a bit funny that Java doesn't offer a class for a period or duration of years, months, days, hour, minutes and seconds. If you wanted, you might use a Period instance for the years, months and days, and then a Duration for the hours, minutes and seconds. It's a little bit complicated.
I am told that the ThreeTen-extra project includes a PeriodDuration class that combines the two. I haven't got any experience with it myself.

A: As @Meno explained in the comments, date arithmetic is weird, because months and years can have different lenghts. In our ISO calendar, a month can have 28, 29, 30 or 31 days, and a year can have 365 or 366 days.
So, a Period like P24Y4M5D (24 years, 4 months and 5 days) can represent a totally different number of days, depending on when you start counting it.
If I start at 2017-01-01T00:00Z, for example. If I add 24 years, I get 2041-01-01, then adding 4 months, I get 2041-05-01, then adding 5 days I get 2041-05-06. The total difference is equivalent to 8891 days.
But if I start at 2016-01-01T00:00Z and add the same period (24 years, 4 months and 5 days): adding 24 years I get 2040-01-01, then adding for 4 months I get 2040-05-01, then adding 5 days I get 2040-05-06. But if I add 8891 days, I get 2040-05-05.
That's because a month and year don't have fixed lenghts, so the equivalent total in days will always depend on the dates involved (not to mention Daylight Saving Time and leap seconds effects, which also changes the total of hours, minutes, seconds and milliseconds).
To not rely on that, you must calculate using the duration in milliseconds (and not in non-fixed-length variables such as years and months). In Joda-Time, you can use the org.joda.time.Duration class:
public void makeTwoDatesEqual(GregorianCalendar a, GregorianCalendar b) {
    DateTime date1 = new DateTime(a);
    DateTime date2 = new DateTime(b);
    System.out.println("date1=" + date1);
    System.out.println("date2=" + date2);

    Duration duration = new Duration(date1, date2);
    DateTime date3 = date1.plus(duration);
    System.out.println("date3=" + date3);
    System.out.println(date3.equals(date2));
}

Assuming that a is equivalent to 2015-08-29T00:00:00Z and b is 2040-01-01T00:00:00Z, this code will output:

date1=2015-08-29T00:00:00.000Z
  date2=2040-01-01T00:00:00.000Z
  date3=2040-01-01T00:00:00.000Z
  true

ThreeTen Backport
Joda-Time is in maintainance mode and is being replaced by the new APIs, so I don't recommend start a new project with it. Even in joda's website it says: "Note that Joda-Time is considered to be a largely "finished" project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".
If you can't (or don't want to) migrate from Joda-Time to the new API, you can ignore this section.
If you're using Java 6 or 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP (more on how to use it here).
You can use the org.threeten.bp.DateTimeUtils class to convert the GregorianCalendar to org.threeten.bp.Instant and then calculate the difference between them, resulting in a org.threeten.bp.Duration:
public void makeTwoDatesEqual(GregorianCalendar a, GregorianCalendar b) {
    Instant instantA = DateTimeUtils.toInstant(a);
    Instant instantB = DateTimeUtils.toInstant(b);
    System.out.println(instantA);
    System.out.println(instantB);

    Duration duration = Duration.between(instantA, instantB);

    Instant instantC = instantA.plus(duration);
    System.out.println(instantC);
    System.out.println(instantC.equals(instantB)); // true
}

Assuming that a is equivalent to 2015-08-29T00:00:00Z and b is 2040-01-01T00:00:00Z, this code will output:

2015-08-29T00:00:00Z
  2040-01-01T00:00:00Z
  2040-01-01T00:00:00Z
  true


text:
Q: C# show hidden window I am developing an add in for excel. At some point, I can receive async events. I need to be able to show the Excel window if hidden on these events.
I am able to store the Hwnd property, which I believe must be an immutable int/reference to identify my Excel window.
Can someone elaborate on this Hwnd ? and explain how I can show a hidden window from C# using it ?
Thanks in advance folks ;)
UPDATE : shortly, that was the piece of code that sorted my problems :
    /// Enumeration of the different ways of showing a window using
    /// ShowWindow
    private enum WindowShowStyle : uint
    {
        /// Hides the window and activates another window.
        /// <remarks>See SW_HIDE</remarks>
        Hide = 0,
        /// Activates and displays a window. If the window is minimized
        /// or maximized, the system restores it to its original size and
        /// position. An application should specify this flag when displaying
        /// the window for the first time.
        /// <remarks>See SW_SHOWNORMAL</remarks>
        ShowNormal = 1,
        /// Activates the window and displays it as a minimized window.
        /// <remarks>See SW_SHOWMINIMIZED</remarks>
        ShowMinimized = 2,
        /// Activates the window and displays it as a maximized window.
        /// <remarks>See SW_SHOWMAXIMIZED</remarks>
        ShowMaximized = 3,
        /// Maximizes the specified window.
        /// <remarks>See SW_MAXIMIZE</remarks>
        Maximize = 3,
        /// Displays a window in its most recent size and position.
        /// This value is similar to "ShowNormal", except the window is not
        /// actived.
        /// <remarks>See SW_SHOWNOACTIVATE</remarks>
        ShowNormalNoActivate = 4,
        /// Activates the window and displays it in its current size
        /// and position.
        /// <remarks>See SW_SHOW</remarks>
        Show = 5,
        /// Minimizes the specified window and activates the next
        /// top-level window in the Z order.
        /// <remarks>See SW_MINIMIZE</remarks>
        Minimize = 6,
        /// Displays the window as a minimized window. This value is
        /// similar to "ShowMinimized", except the window is not activated.
        /// <remarks>See SW_SHOWMINNOACTIVE</remarks>
        ShowMinNoActivate = 7,
        /// Displays the window in its current size and position. This
        /// value is similar to "Show", except the window is not activated.
        /// <remarks>See SW_SHOWNA</remarks>
        ShowNoActivate = 8,
        /// Activates and displays the window. If the window is
        /// minimized or maximized, the system restores it to its original size
        /// and position. An application should specify this flag when restoring
        /// a minimized window.
        /// <remarks>See SW_RESTORE</remarks>
        Restore = 9,
        /// Sets the show state based on the SW_ value specified in the
        /// STARTUPINFO structure passed to the CreateProcess function by the
        /// program that started the application.
        /// <remarks>See SW_SHOWDEFAULT</remarks>
        ShowDefault = 10,
        /// Windows 2000/XP: Minimizes a window, even if the thread
        /// that owns the window is hung. This flag should only be used when
        /// minimizing windows from a different thread.
        /// <remarks>See SW_FORCEMINIMIZE</remarks>
        ForceMinimized = 11
    }

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow);

    static void ContentClick(object obj, EventArgs ea)
    {
        Microsoft.Office.Interop.Excel.Application oExcelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
        oExcelApp.Visible = true;
        ShowWindow( (System.IntPtr) Globals.ThisWorkbook.Application.Hwnd, WindowShowStyle.ShowMaximized);
    }

A: hWnd means Window Handle. It's an identifying handle for the window instance.
As for showing it, you could use the user32.ShowWindow API. Here's the P/Invoke signature, courtesy of pinvoke.net:
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, ShowWindowCommands nCmdShow);

And here's the ShowWindowCommands enum:
/// Enumeration of the different ways of showing a window using
/// ShowWindow
private enum WindowShowStyle : uint
{
    /// Hides the window and activates another window.
    /// <remarks>See SW_HIDE</remarks>
    Hide = 0,
    /// Activates and displays a window. If the window is minimized
    /// or maximized, the system restores it to its original size and
    /// position. An application should specify this flag when displaying
    /// the window for the first time.
    /// <remarks>See SW_SHOWNORMAL</remarks>
    ShowNormal = 1,
    /// Activates the window and displays it as a minimized window.
    /// <remarks>See SW_SHOWMINIMIZED</remarks>
    ShowMinimized = 2,
    /// Activates the window and displays it as a maximized window.
    /// <remarks>See SW_SHOWMAXIMIZED</remarks>
    ShowMaximized = 3,
    /// Maximizes the specified window.
    /// <remarks>See SW_MAXIMIZE</remarks>
    Maximize = 3,
    /// Displays a window in its most recent size and position.
    /// This value is similar to "ShowNormal", except the window is not
    /// actived.
    /// <remarks>See SW_SHOWNOACTIVATE</remarks>
    ShowNormalNoActivate = 4,
    /// Activates the window and displays it in its current size
    /// and position.
    /// <remarks>See SW_SHOW</remarks>
    Show = 5,
    /// Minimizes the specified window and activates the next
    /// top-level window in the Z order.
    /// <remarks>See SW_MINIMIZE</remarks>
    Minimize = 6,
      /// Displays the window as a minimized window. This value is
      /// similar to "ShowMinimized", except the window is not activated.
    /// <remarks>See SW_SHOWMINNOACTIVE</remarks>
    ShowMinNoActivate = 7,
    /// Displays the window in its current size and position. This
    /// value is similar to "Show", except the window is not activated.
    /// <remarks>See SW_SHOWNA</remarks>
    ShowNoActivate = 8,
    /// Activates and displays the window. If the window is
    /// minimized or maximized, the system restores it to its original size
    /// and position. An application should specify this flag when restoring
    /// a minimized window.
    /// <remarks>See SW_RESTORE</remarks>
    Restore = 9,
    /// Sets the show state based on the SW_ value specified in the
    /// STARTUPINFO structure passed to the CreateProcess function by the
    /// program that started the application.
    /// <remarks>See SW_SHOWDEFAULT</remarks>
    ShowDefault = 10,
    /// Windows 2000/XP: Minimizes a window, even if the thread
    /// that owns the window is hung. This flag should only be used when
    /// minimizing windows from a different thread.
    /// <remarks>See SW_FORCEMINIMIZE</remarks>
    ForceMinimized = 11
}

A: HWnd is a windows handle, in C# it is really an IntPtr type.
Try creating a wrapper class based on IWin32Window and use that when calling Show() e.g.
public class WndWrapper : IWin32Window
{
    IntPtr m_Handle;
    public WndWrapper(long pHandle)
    {
        m_Handle = (IntPtr)pHandle;
    }

    #region IWin32Window Members

    public IntPtr Handle
    {
        get { return m_Handle; }
    }

    #endregion
}

Then call it like this:
WndWrapper oWnd = new WndWrapper(pHandle);
MyForm oDlg = new MyForm();
oDlg.Show(oWnd);

Just be careful, as HWND elements are unmanaged you will be responsible for ensuring that they are disposed of when required.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you migrate Docker Desktop Kubernetes clusters to Google Kubernetes Engine I'm trying to migrate and host a Kubernetes cluster that I made locally on my machine using Docker Desktop to Google Kubernetes Engine but I'm not sure where to start or how to do it properly.
Any help is appreciated, thanks!

A: There's no migration in the sense of virtual machines. If you your deployments / services /etc defined in a CVS of some sort (github, gitlab etc), you could just change the target of kubectl and apply them in bulk using the -f switch to kubectl.
I would recommend creating namespaces first, and then using kubens to swap between namespaces as you do the separate deployments.
If you DON't have them already stored, you'll want to iterate through your namespaces and issue:
k get <object> --export -o yaml
This would be (not limited to)

*

*deployments

*secrets

*configmaps

*daemonsets

*statefulsets

*services

Once you have everything, run through re-applying them on the remote cluster, and if you missed something, just export it and reapply it remotely.
Does does NOT include your data layer. If you're running databases et all in Kubernetes, you'll need to use tools native to your data platform to export that data, and then re-import it on the other side.


text:
Q: Display custom stock message if "Manage Stock" is not enabled and exclude certain product categories in WooCommerce I'm using Display custom stock message if "Manage Stock" is not enabled in WooCommerce
The code is successfully adding a custom notice when a product is in stock but "Manage Stock" is not enabled.
However, I would like to exclude the products from "categorya", "categoryb" and "categoryc" (defined by their slugs) to be impacted by this code.
Anyone can help me exclude products from these categories to be impacted by this code?


text:
Q: Chrome on Android cannot play recorded audio from object URL I am using Recorder.js to record something with the Audio API and I want to give the user the opportunity to listen to their recording before uploading it to the server. The recording code is heavily based on the supplied example, but instead of exporting to WAV for downloading I am using a blob and setting the src attribute of an audio element for playback. The responsible code (called after stopping the recording) looks like this:
function createAudioPlayer() {
  recorder && recorder.exportWAV(function (blob) {
    var url = URL.createObjectURL(blob);
    var au = document.getElementById('recording');
    au.src = url;
  });
}

It results in something like this:
<audio id="recording" src="blob:https%3A//example.com/499ca96f-37b2-4515-bd1b-3c298f201dbd" controls="controls"></audio>
Playing back this audio works in Chrome 50 and Firefox 46 on OS X 10.11, and in Edge 13 on Windows 10. Chrome 50 on Android 6.0 records and uploads fine, but refuses playback with the following error when play() is called on the audio element:
Uncaught (in promise) DOMException: The element has no supported sources.
I've tried adding type="audio/wav" but that didn't work. If I upload the file from blob (with the File API and XHR) and use a src attribute with a 'normal' URL of the wav file on the server it also plays back fine. What should be changed so that users can listen to their recording before uploading?

A: Not yet supported.  We've got work in progress that should fix it, hopefully in Chrome 51.  (https://groups.google.com/a/chromium.org/forum/#!topic/chromium-reviews/Qi4dLcKjcCM)


text:
Q: Use a custom function to sort an asp:GridView Here's the GridView:
<asp:GridView ID="MyGridView" runat="server" AllowPaging="true" AllowSorting="true"
    OnPageIndexChanging="MyGridView_PageIndexChanging"
    OnSorting="MyGridView_Sorting">
    <Columns>
        <asp:TemplateField HeaderText="ID" SortExpression="Id">
            <ItemTemplate>
                <asp:Label ID="idLabel" runat="server" Text='<%# Bind("Id") %>' />
            </ItemTemplate>
       </asp:TemplateField>
    </Columns>
</asp:GridView>

Here, the Id column is a string consisting always of the letter "T" followed by a number, i.e. "T1" or "T597"  The other columns are fairly ordinary name and description String fields.
I need this Id column to sort as though the Id were numeric, ignoring the letter in front.  But because it is there, it is being treated as a String and sorting as such: T1, T10, T100, T2, T231, T34, ...
So what I thought would be possible is:
protected void MyGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    if (e.SortExpression.Equals("Id")
    {
         // Special sorting code
    }
    else
    {
        // Normal sorting code
    }
}

Where the "normal" sorting code follows the common pattern of converting the DataSource to DataView and setting DataView.Sort = e.SortExpression etc, for example: allow sorting by column gridview
So what do I do for the "special" sorting code?
UPDATE:  Just to be clear, I have no trouble rolling my own function to compare two strings as I need.  I do not, however, know how to apply that function to my Data Grid/ Data Source.

A: You can implement the IComparer class for the DataGridView.Sort:
http://msdn.microsoft.com/en-us/library/wstxtkxs%28v=vs.85%29.aspx
You can separate the "T" and the following number in the Compare method.

A: The GridView allows DataKeyNames, and that is the solution here.  When setting up the Data Source (in my case, a SQL query) include both the "FullId" and a "PlainId" which has stripped off the leading character and parsed the remainder as int.  Use "FullId" as the column's text value, but make "PlainId" one of the DataKeyNames and use that as the SortExpression for the column.


text:
Q: how to see elements of vectors quickly without hardcoding I have about 50 vectors named "NLTotal", "SIAuctions", "SAIC", and etc with 10 elements in each.
What I want to do is have it so I loop through all these vectors by name and look at the elements in each. I already created a 'metrics' vector which has all the names, but I don't know how to take the vector corresponding to "NLTotal" for example instead of "NLTotal".
In other words, I want a way to look at metrics[3] and not just see "NLTotal" but the vector [3, 2.3, 45, 12, 23, 98, 574, 5999, 321, 1.84].
Is this possible?

A: Probably get function would help you:
get(metrics[3])


text:
Q: Socket errors when trying to close pools and queries I am getting this exception when I close the pool very soon after closing a query:
Uncaught Error: Bad state: Cannot write to socket, it is closed
Stack Trace:
#0      BufferedSocket.writeBufferPart (package:sqljocky/src/buffered_socket.dart:114:7)
#1      BufferedSocket.writeBuffer (package:sqljocky/src/buffered_socket.dart:108:27)
#2      _Connection._sendBufferPart (package:sqljocky/src/connection.dart:261:31)
#3      _Connection._sendBuffer (package:sqljocky/src/connection.dart:249:29)
#4      _Connection.processHandler (package:sqljocky/src/connection.dart:289:16)
#5      ConnectionPool._closeQuery.<anonymous closure> (package:sqljocky/src/connection_pool.dart:220:29)
#6      _rootRunUnary (dart:async/zone.dart:730)
#7      _RootZone.runUnary (dart:async/zone.dart:864)
#8      _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:488)
#9      _Future._propagateToListeners (dart:async/future_impl.dart:571)
#10     _Future._completeWithValue (dart:async/future_impl.dart:331)
#11     _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:393)
#12     _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:23)
#13     _asyncRunCallback (dart:async/schedule_microtask.dart:32)
#14     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:128)

Unhandled exception:
Bad state: Cannot write to socket, it is closed
#0      _rootHandleUncaughtError.<anonymous closure>.<anonymous closure> (dart:async/zone.dart:713)
#1      _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:23)
#2      _asyncRunCallback (dart:async/schedule_microtask.dart:32)
#3      _asyncRunCallback (dart:async/schedule_microtask.dart:36)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:128)

the issue seems to be that the query close fires of a Future internally, so the close() function returns before the close is actually finished:
void _closeQuery(Query q, bool retain) {
  _log.finest("Closing query: ${q.sql}");
  for (var cnx in _pool) {
    var preparedQuery = cnx.removePreparedQueryFromCache(q.sql);
    if (preparedQuery != null) {
      _waitUntilReady(cnx).then((_) {
        _log.finest("Connection ready - closing query: ${q.sql}");
        var handler = new _CloseStatementHandler(preparedQuery.statementHandlerId);
        cnx.autoRelease = !retain;
        cnx.processHandler(handler, noResponse: true);
      });
    }
  }
}

The pool close happens immediately, it closes the socket right away. This means the query close (which is delayed till after the pool close due to the Future) fails, unable to send whatever information it needs to through the socket. I've opened a ticket to sqljocky at https://github.com/jamesots/sqljocky/issues/44 but I've received no replies, and I need a workaround if it's going to take a while to get a response.
This code has allowed me to replicate the issue 100% of the time:
Future _putMethod(RestRequest request) {
  return new Future.sync(() {
  mysql.ConnectionPool pool = getConnectionPool();
    return pool.prepare("SELECT * FROM files").then((mysql.Query query) {
      return query.execute().then((result) {
        // Do something?
      }).then((_) {
        this._log.info("Closing");
        query.close();
      });
    }).then((_) {
      pool.close();
    });
  });
}

A: This is yet more a question than an answer but I can't put this code in a comment in a usable way.
You should ensure that you return the Future returned from every async invocation.
I don't know if the lines where I added the comment // added return are async invocations.
Can you please try and give feedback if this changes anything.
Future _putMethod(RestRequest request) {
  return new Future.sync(() {
  mysql.ConnectionPool pool = getConnectionPool();
    return pool.prepare("SELECT * FROM files").then((mysql.Query query) {
      return query.execute().then((result) {
        // Do something? // also ensure that a Future of an async invocation is returned
      }).then((_) {
        this._log.info("Closing");
        return query.close(); // added return
      });
    }).then((_) {
      return pool.close(); // added return
    });
  });
}


text:
Q: Rails not loading mountable engine's js I have a mountable rails engine included in Gemfile as
gem 'my_engine', :path => 'engines/my_engine'

and mounting in main app as
Rails.application.routes.draw do
  mount MyEngine::Engine => "/blog", as: 'blog_engine'
end

In app/engines/my_engine/app/assets/javascripts/my_engine/application.js I have
alert('hello');

In app/engines/my_engine/lib/my_engine/engine.rb I added
module MyEngine
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine

    # Append engine's migrations to root app's migrations
    initializer :append_migrations do |app|
      unless app.root.to_s.match root.to_s
        config.paths["db/migrate"].expanded.each do |expanded_path|
          app.config.paths["db/migrate"] << expanded_path
        end
      end
    end

    config.autoload_paths += Dir["#{config.root}/spec/support"]

    initializer "my_engine.precompile" do |app|
      app.config.assets.paths << Rails.root.join('/engines/my_engine/app/assets/javascripts')
      app.config.assets.precompile << "my_engine/application.js"
    end

  end
end

But when I reload http://localhost:3000/blog alert message is not showing up? What am I missing ?

A: You also need to actually insert the JavaScript into your page. Do you have a javascript_include_tag pulling in the application.js file in your blog code? It often gets put into one of the layouts:
<%= javascript_include_tag 'my_engine/application' %>


text:
Q: Graphing in R - combining factors This is  a slightly odd request, I don't know if a function is necessarily likely to exist, but I was hoping there might be. Basically, I have a number of variables that I'm looking at to give an outcome and so my typical data would look like below
Sample   Daylength  Expt   Line    Protein

1            LD      L      K        100
2            SD      S      R        150
3            LD      L      R        200
4            SD      S      K        120
5            LD      L      K        95
6            SD      S      R        160
7            LD      L      R        195
8            SD      S      K        130

So I have 3 dependant variables (daylength, expt, line) and 1 outcome variable of protein. However, what I'd like to be looking at in a graph is comparing the protein levels showing bars for L and S experiments
An example of the code I would use to draw a bar graph with ggplot2 is:
ggplot(data=results, aes(x=daylength, y=protein, fill=line)) + geom_bar(stat="identity", position=position_dodge())

and this would give me a graph showing the results for LD and SD experiments with the lines offering the separate series. However, this does not account for my third factor, the expt.
Ordinarily in Excel I would be able to manipulate the table to give results for LD/L, LD/S, SD/L and SD/S as being separate headings and create a graph using them as the X factors, however this can be arduous, especially if I'm going to rewrite the table, save it and run it in R each time. I was looking to see if there was a simple enough method to either manipulate the table in R to group everything as below with a few commands or combine the two factors to draw a graph directly each time, especially because in some cases I may be interested in combining different factors.
Sample   Daylength/Expt   Line    Protein

1            LD/L          K        100
2            SD/S          R        150
3            LD/L          R        200
4            SD/S          K        120
5            LD/L          K        95
6            SD/S          R        160
7            LD/L          R        195
8            SD/S          K        130

A: You can use the interaction operator : on factors:
library(ggplot2)
head(CO2) # using builtin data
#  Plant   Type  Treatment conc uptake
#1   Qn1 Quebec nonchilled   95   16.0
#2   Qn1 Quebec nonchilled  175   30.4
#3   Qn1 Quebec nonchilled  250   34.8
#4   Qn1 Quebec nonchilled  350   37.2
#5   Qn1 Quebec nonchilled  500   35.3
#6   Qn1 Quebec nonchilled  675   39.2
qplot(conc, uptake, color=Type:Treatment, data=CO2)

A: You can create the Daylength/Expt column using paste:
dl_ex <- paste(results$Daylength, results$Expt, sep='/')

(Use as.character on the columns if R complains about factors or gives you weird numeric results)
and then add it to a dataset
results2 <- results[, -c("Daylength", "Expt")]
results2$DE <- dl_ex

However if you'd like to group your data by some attributes you should look into R's package plyr or sqldf if you're familiar with SQL syntax.


text:
Q: How to Modify a String in Arm Assembly I'm having trouble figuring out how to add spaces to an infix expression so that something like 3+5 would turn into 3 +5. I keep on getting a segmentation fault and I can't even pinpoint which line the error is coming from because for some reason, I can't print out anything also. Here's my code for reference:
.data

.balign 4
return: .word 0

.balign 4
operations: .asciz "+-*/^"

.balign 4
    output: .space 100

.balign 4
    spa: .asciz " "
.text
.global printf
.global main

main:
    ldr r0, [r1, #4] //load address of first character in expression
    ldr r1, =return
    str lr, [r1] //store lr in return variable
    ldr r2,=output //load address of output on r2
    ldr r3, =spa //load address of space variable
    ldr r3, [r3] //load character ' ' onto r3

loop:
    cmp r0, #0 //check if reached end of input
    beq end //if so go to end
    ldr r1, =operations //load the address of  operations string in r1

loop2:;
    cmp r1, #0 //check if reached end of operation string
    beq loop3 //means the current character in output isn't an operator
    ldr r5, [r1] //else load value of r1 in r5, the current operator
    ldr r6, [r0] //load current value in input string to r6
    cmp r5, r6 //compare the two values
    beq loop3 //if equal go to loop3
    add r1, r1, #1 //if not increment address of r1
    b loop2 //start next iteration of loop2

loop3:
    str r3, [r2] //since current character is an operator, store space first
    add r2, r2, #1
    b loop4 //on output string. Then go to loop4

loop4:
    str r6, [r2] //store the current character, stored in r6, in r2
    add r0, r0, #1 //increment address of r0 by 1 to get to next character
    add r2, r2, #1 //increment address of r2 by one to get to next slot in array
    b loop //start next iteration of loop

end:
    ldr r0, =output //load address of output onto r0
    bl printf //print out string
    ldr lr, =return //restore link register
    ldr lr, [lr]
    bx lr


text:
Q: Jquery issues effecting all element instead of just one I'm currently working on a little project in which I have several div elements with an img, h1 tag, and a p tag.  They each have the same class name, and what I'm trying to do is place some css effects to it so that the h1 tag and p tag slide into frame and become visible when I hover over the div element that they are contained in.
The problem here is that the code I am using makes the effects to all div elements when I only want the div element that is currently being hovered over to have this effect.
Here is my code:
The css


text:
Q: Working on a website, mozilla firefox inspector showing overflow in , due to this my navbar setion got topmargin with showing (").need fix here you can see top left corner " .enter image description here
enter image description here


text:
Q: Elementary functions with zeros only at the positive integers Does there exist a (meromorphic) elementary function $f(z)$ that is zero at all the positive integers $z = 1, 2, 3, \ldots$ and only at those points?
Edit: an elementary function can be written as a finite composition of constants, rational functions, exponentials and logarithms.
Obviously a function with those zeros can be constructed using the gamma function or a Weierstrass product, but the question is whether there is an elementary function.

A: $1/\Gamma(1-z)$.

A: I don´t completely understand what you mean by elementary, but you can look at http://en.wikipedia.org/wiki/Weierstrass_factorization_theorem. Sorry if the question had not to do with this.


text:
Q: Evaulate $\lim_{n \to \infty} \int_0^\infty ne^{-nx} \sin(1/x)dx$ Now, I know that the question was answered here: $\int_0^\infty ne^{-nx}\sin\left(\frac1{x}\right)\;dx\to ?$ as $n\to\infty$
But I'm looking for more of a measure theoretical approach, so if someone can point me in the right direction, I would be grateful. (i.e. use of Dominated Convergence Theorem or Monotone Convergence Theorem)
My rough idea has been the following:
We can't use MCT because the functions are not pointwise increasing.
We can't use DCT since there there is no function to bound $ne^{-nx} sin(1/x)$.
But, it seems that on $[\ln 2, \infty)$, $e^{-x} \geq ne^{-nx}$, and on $[\ln (\frac{n+1}{n}, \ln \frac{n}{n-1}]$, $ne^{-nx} \geq me^{-mx}$ for all $n, m \in \mathbb{N}$ (I don't have proof of this, and it seems hard to prove).
So we can use DCT on integral restricted such intervals. That is, we can use DCT on the integral $$\int_{\mathbb{R}} ne^{-nx} \sin(\frac{1}{x}) \chi_{[\ln(n+1/n), \ln (n/n-1)]}dx$$ And on these intervals, the integrals are all 0.
Since these intervals partitions $[0, \infty)$, it follows our integral is 0.
I don't know if the idea is correct, and even if it was, it wouldn't be an elegant solution. So I'm hoping someone could point me in the right direction for a clean solution.
Thanks!
EDIT:
If we let $u = nx$, we get the integral
$$\int^\infty_0 e^{-u} \sin(\frac{n}{u}) du$$.
We could apply DCT to this to get 0?
Another EDIT:
But $\sin(\frac{n}{u})$ is not convergent, so we cannot apply DCT.


text:
Q: show one li, hide rest on click | save option for first list after clicking on other option in second list Here is my code and i have two questions about it:
1. For example I'm clicking on List 1 and then on Show info 2. How can i make options unique to show unique information AND "save" active class in Show info 2 so after i will click on List 2 and choose for example Show info 8 and then go back to List 1, Show info 2 will still be active and won't be changed by clicking on Show info 8 to Show info 3?
Should be like this: I click on List 1 -> Show info 2-> Info 2 pops option in List 1 is choosen, background color for Show info 2 is yellow Then I click on List 2(List 1 and Info 2 are hiding) -> Show info 8 -> Info 8 pops option in List 2 is choosen, background color for Show info 8 is yellow. I click again on List 1 (List 2 and Info 8 hides) and there should be popped already info 2 and Show info 2 should have yellow background-color.
I have tried with ID's instead of classes, but then only one list will be able to be clicked..
2.How can i refactor my JS code to make above rule? At first i was like "well its working.. but then i wrote second list and i don't want to write 2nd time that much code to just show and hide elements on
 elements when they are all the same de facto.

var displayNone = 'displayNone';
var active = 'active'; //from bootstrap nav-tabs to style active
 elements

var showList1 = $('.showList1');
var showList2 = $('.showList2');

var hiddenList1 = $('#list1');
var hiddenList2 = $('#list2');

hiddenList1.addClass(displayNone);
hiddenList2.addClass(displayNone);

showList1.on('click', function () {
 $(hiddenList2).addClass(displayNone);
  $(hiddenList1).removeClass(displayNone);

});
showList2.on('click', function () {
 $(hiddenList1).addClass(displayNone);
  $(hiddenList2).removeClass(displayNone);
});

var info1_Id = $('.info1');
var info2_Id = $('.info2');
var info3_Id = $('.info3');
var info4_Id = $('.info4');
var info5_Id = $('.info5');

var info1_Display = $('.info1-display');
var info2_Display = $('.info2-display');
var info3_Display = $('.info3-display');
var info4_Display = $('.info4-display');
var info5_Display = $('.info5-display');

info1_Display.addClass(displayNone);
info2_Display.addClass(displayNone);
info2_Display.addClass(displayNone);
info3_Display.addClass(displayNone);
info4_Display.addClass(displayNone);
info5_Display.addClass(displayNone);

info1_Id.on('click', function () {
  $(this).addClass(active);
  info2_Id.removeClass(active);
  info3_Id.removeClass(active);
  info4_Id.removeClass(active);
  info5_Id.removeClass(active);

  info2_Display.addClass(displayNone);
  info3_Display.addClass(displayNone);
  info4_Display.addClass(displayNone);
  info5_Display.addClass(displayNone);
  info1_Display.removeClass(displayNone);
});

info2_Id.on('click', function () {
  $(this).addClass(active);
  info1_Id.removeClass(active);
  info3_Id.removeClass(active);
  info4_Id.removeClass(active);
  info5_Id.removeClass(active);

  info1_Display.addClass(displayNone);
  info3_Display.addClass(displayNone);
  info4_Display.addClass(displayNone);
  info5_Display.addClass(displayNone);
  info2_Display.removeClass(displayNone);
});

info3_Id.on('click', function () {
  $(this).addClass(active);
  info1_Id.removeClass(active);
  info2_Id.removeClass(active);
  info4_Id.removeClass(active);
  info5_Id.removeClass(active);

  info1_Display.addClass(displayNone);
  info2_Display.addClass(displayNone);
  info4_Display.addClass(displayNone);
  info5_Display.addClass(displayNone);
  info3_Display.removeClass(displayNone);
});

info4_Id.on('click', function () {
  $(this).addClass(active);
  info1_Id.removeClass(active);
  info2_Id.removeClass(active);
  info3_Id.removeClass(active);
  info5_Id.removeClass(active);

  info1_Display.addClass(displayNone);
  info2_Display.addClass(displayNone);
  info3_Display.addClass(displayNone);
  info5_Display.addClass(displayNone);
  info4_Display.removeClass(displayNone);
});

info5_Id.on('click', function () {
  $(this).addClass(active);
  info1_Id.removeClass(active);
  info2_Id.removeClass(active);
  info3_Id.removeClass(active);
  info4_Id.removeClass(active);

  info1_Display.addClass(displayNone);
  info2_Display.addClass(displayNone);
  info3_Display.addClass(displayNone);
  info4_Display.addClass(displayNone);
  info5_Display.removeClass(displayNone);
});
.displayNone{
  display: none;
}

ul > li{
  list-style-type: none;
  width: 100px;
  height: 20px;
  margin-bottom: 5px;
  background-color: lightblue;
}

.active{
  background-color: yellow;
}

ul>li:hover, div{
  cursor: pointer;
}

List 1

Show info 1

Show info 2

Show info 3

Show info 4

Show info 5

Info 1

Info 2

Info 3

Info 4

Info 5

List 2

Show info 6

Show info 7

Show info 8

Show info 9

Show info 10

Info 6

Info 7

Info 8

Info 9

Info 10

A: I hope I got close to the answer you were looking for. jsfiddle
I tried to keep as much of your structure as possible in this fiddle.
I made a group of : list header, action list (show info 1, show info 2), info list.
when you click a list header, it will show that groups action list and selected info if there is one and hide all other groups actions lists/info.
the showing/hiding of elements in this example is done with css and the applying of an "active" class. if a group has the active class, it will show its action list and info (otherwise its hidden). if an action li has the active class, it will have the background color of yellow. if an info li has the active class, it will show (otherwise its hidden)
    //Clicking on the header will add active class to its group and remove from all sibling groups (this assumes that all groups are on the same DOM level
$('a.list-header').click(function(){
        $(this).closest('div.list-group').addClass('active').siblings('div.list-group').removeClass('active');
    });
//clicking an action list item will toggle the active class and then find the appropriate info li and toggle the active class there as well
    $('div.list-group').on('click', 'li.list-item', function(e){
        var $li = $(this),
          info=$(this).data('toggle'),
            $listGroup = $(e.delegateTarget);

          $li.addClass('active').siblings().removeClass('active');
      $listGroup.find('ul.info-list li[data-info="'+info+'"]').addClass('active').siblings().removeClass('active');
    });

A:

$(".listOpener").click( function () {
    $("li").hide();
    $(this).next("ul").children(".show").show();
});

$(".show").click( function () {
    $(this).addClass("active").siblings('.show').removeClass('active');
    $(".info").hide()
    $(this).next(".info").show();
});
.active {
  background-color: yellow;
}

.show {
  display: none;
}

.info {
  display: none;
}
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="main.css" type="text/css" media="screen" charset="utf-8">

        <title>title</title>

            List 1

show 1

                    info 1

show 2

                    info 2

show 3

                    info 3

            List 2

show 4

                    info 4

show 5

                    info 5

show 6

                    info 6

If you want you can use .toggle() instead of show() and hide(), but you wll have to change something.


text:
Q: How can C# allow interface's to have member variables with getters/setters? -For as long as I can remember, I always thought that interfaces in Java and C# would only allow the following in an interface
--constants
--method signatures
1) How can C# allow interface's to have member variables with getters/setters?
public interface IEntityBase
{
    ObjectId _id { get; set; }
}

2) Would Java allow for something similar to the aforementioned C# code?

A: A property is not a member variable. Think of it as a replacement for the old technique of a private variable with GetVarA() and SetVarA(int varA) methods exposing it.
All a property really is, is that with neater syntax. That's why it can exist in an interface, as technically it's not defining a variable at all - your implementation of string MyName {get;} could have a private 'myName' member variable backing it up, whereas someone elses could grab the name from a database each time the property's Get was called.


text:
Q: jquery delay between html and group of calls Trying to figure this out and haven't had much success.  First and foremost I want to make sure that the html call has completed before the fadein and two functions are called below it.
Secondly, I want to add in a delay, say 200, after the html loading and before the fadein and two functions.
I can add .delay(200) to the end of the html call, but it only delays the fadein... the other two functions run earlier... I all three to run at the same time. I am trying to mimic the same result if I were using load and wrapping these three in a function call.
if (response.success) {

    $myElem = $('#show-edit'); //performance
    $myElem.fadeOut('fast', function(){
        $myElem.html('someText');

        //once html added do these
        $myElem.fadeIn('fast');

        showSelect();

        // show success toast
        toastr.info('User \''+response.username+'\' has been deleted.', 'Success');

    });
}

A: Use a timeOut, or you could use delay() with a queue(), but it's not really any easier :
if (response.success) {
    $('#show-edit').fadeOut('fast', function(){
        var self = $(this);
        self.html('someText');
        setTimeout(function() {
           self.fadeIn('fast');
           showSelect();
           toastr.info('User \''+response.username+'\' has been deleted.', 'Success');
        },200)
    });
}


text:
Q: Setting fitsSystemWindows="true" for Cordova WebView I want to configure Cordova WebView with fitsSystemWindows="true" in order to avoid navbar soft keys overlapping webview content. Ho can I do it?

A: Try adding this to your config.xml


text:
Q: Keytool command in Java? I have spent multiple hours trying to figure out the keytool CLI command for Java (in order to zipalign my Android app).
After a long search, I saw on another Stack Overflow Question that I should verify that I have the filepath, and after confirming the path to the binary was correct, I tried to check for the keytool; this is what happened:
 C:\Users\ealeo_000>dir "C:/Program Files (x86)/Java/jre1.8.0_73/bin/keytool.exe"

 Volume in drive C has no label.
 Volume Serial Number is 70C4-072A

 Directory of C:\Program Files (x86)\Java\jre1.8.0_73\bin

 File Not Found

According to what I've looked up, this should be the correct path; yet nothing is showing up. This leads me to believe that for some reason that keytool is not being installed along with the JDK...
Am I correct in assuming this? If so, how do I fix this?

A: You're showing a path to a JRE, the Java runtime environment, not a path to a JDK, the Java development kit. You need to download & install the JDK and then make sure it is used before the JRE.
Note that there are two Program Files and Program Files (x86) on 64 bit Windows machines where the Java installations may reside.


text:
Q: select ids for which 2 mandatory values are present I've a table -
id1 type people
id1 type actor
id2 type people
id3 type people
id2 type politician
id3 type magician
id4 type ps: i love you
id4 type movie
id2 type poet
id3 type singer

How can I get all ids which are people and politician? In our example id2 should be in final output table. I what thinking of making list over last column over the grouping of column 1 & 2 together as -
id1 type {people, actor}
id2 type {people, politician, poet}
id3 type {people, magician, singer}
...

and now i can check i column #3 for people and politician.
Is there a better way in Sequel with some C# supported methods in queries?

A: This can be done in sql using intersect.
select id from table where type = 'people'
intersect
select id from table where type = 'politician'


text:
Q: xcodebuild -exportArchive options plist values for thinning The xcodebuild help says:

thinning : String
For non-App Store exports, should Xcode thin the package for one or
  more device variants? Available options: <none> (Xcode produces a
  non-thinned universal app), <thin-for-all-variants> (Xcode produces a
  universal app and all available thinned variants), or a model
  identifier for a specific device (e.g. "iPhone7,1"). Defaults to
  <none>.

It's not clear if this is meant to be literal:
<key>thinning</key>
<string><none></string>

But then in my enterprise build I'm still seeing this phase occur:
2017-03-08 13:39:32.486 xcodebuild[43633:2535491] [MT] IDEDistribution: Step failed: <IDEDistributionThinningStep: 0x7fd756bef4e0>: Error Domain=IDEDistributionErrorDomain Code=14 "No applicable devices found." UserInfo={NSLocalizedDescription=No applicable devices found.}

There isn't great documentation nor information online about this setting. Does anyone know definitively what values to use?

A: It is absolutely literally <string><none></string>
In Xcode 7, here is a list of all options:
{<none>, <thin-for-all-variants>, iPad3,1, iPad3,2, iPad3,3, iPad3,4, iPad3,5, iPad3,6, iPad2,3, iPad2,1, iPad2,4, iPad2,2, iPad4,1, iPad4,2, iPad4,3, iPad5,3, iPad5,4, iPad6,7, iPad6,8, iPad6,3, iPad6,4, iPad2,5, iPad2,6, iPad2,7, iPad4,4, iPad4,5, iPad4,6, iPad4,7, iPad4,8, iPad4,9, iPad5,1, iPad5,2, iPhone4,1, iPhone5,1, iPhone5,2, iPhone5,3, iPhone5,4, iPhone6,1, iPhone6,2, iPhone7,2, iPhone7,1, iPhone8,1, iPhone8,2, iPhone8,4, iPod5,1, iPod7,1}


text:
Q: Crystal reports keep sections together on same row Is it possible to show two groups and details in the same row? My crystal report has two groups that I keep together.
The current output is:
LocName   Date  un1     un2
-------------------------------
LocNAme
        Date
              compl     compl
              compl     compl

LocName and Date are grouped.
I would like the output to be:
LocName   Date  un1     un2
-------------------------------
 LocNAme  Date  compl     compl
                compl     compl

A: Your Grouping is on LOCNAME and DATE. To get your required output try below steps,
1] Bring LOCNAME and DATE column in details field. (Grouping should not be removed)
2] Right click on LOCNAME column and click Format Field.
3] Under Common tab check the checkbox which has label Suppress If Duplicated.
4] Follow similar steps for DATE column too.
5] Hide your two groups if you do not want to show group name in group headers.
I hope this helps!

A: At first right click of the report and go to "Report-->Selection expert". Go to the common tab. select your group heading name "LocName" from right side then check the "Underlay following section" option from common tab. then select "Date" group heading and also check the "Underlay following section". Now you will get your desire output.
Sorry for my bad English :)

A: You can move the group header from group 2 up next to your group header 1 and then suppress group 2. I don't think there is a way to display the details in the same line though. And since I don't know your data make sure after you do that that you still display the correct data.
Hope that helps,
Chris
EDIT:
Here is a screenshot of a report with both groups and the detail section on the same line.
The way I did this is by suppressing group 1, putting the field that group 1 is grouped by in group header 2 and then creating a subreport that shows the detail section. The subreport is linked by the fields for group 1 and group 2.

A: You can move your Group Header 2 from the Date Group up to Group Header 1 (LocName) to get them displayed in the same row. To get the Details also in the same row you will need to insert a subreport that shows the Compl data. Link that subreport to the LocName and you should be good to go.
EDIT: Since you can't put a subreport in a subreport, I guess the closest solution is to have both Group Headers on the same level and the Details below. Use Group 1 in your Main Report and then create a subreport with Group 2 and the Details. See added screenshot. The subreport has the border around it.


text:
Q: Amazon Linux LAMP with php 5.5 I installed PHP 5.5 on my Amazon Linux VPS via the instructions here.  The CLI is working fine.
I also had apache already installed and running via the httpd package.  It was running without any issue.
I see that there is no mod_php in the list of available modules.  Now when I try to restart httpd I get the error:

httpd: Syntax error on line 222 of /etc/httpd/conf/httpd.conf: Syntax error on line 6 of /etc/httpd/conf.d/php.conf: Cannot load /etc/httpd/modules/libphp5.so into server: /etc/httpd/modules/libphp5.so: symbol SSLeay_version, version OPENSSL_1.0.1 not defined in file libcrypto.so.10 with link time reference

I've looked up parts of this error, and the general advice seems to be to run
yum update openssl

However, when I run this I just get:

No packages marked for update

When I run install instead of update, I get:

Package 1:openssl-1.0.1e-4.55.amzn1.x86_64 already installed and latest version
  Nothing to do

I'm not sure what else to do at this point.

A: The php55 package in Amazon's repositories depends on httpd24, not httpd (which is 2.2). Using the more recent version of Apache should resolve your issues.
$ repoquery --requires php55
/bin/sh
httpd-mmn = 20120211-x86-64
httpd24
...


text:
Q: disable css style for certain elements I used css to create a style for a menu which has links but now that style applies to all the links on the page. how can i disable that css style for some links? Here is the css code:
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}

li {
font-size: 35px;
display: inline-block;
}

a:link, a:visited {
display: block;
width: 250px;
font-weight: bold;
color: #FFFFFF;
background-color: #0080FF;
text-align: center;
padding: 4px;
text-decoration: none;
text-transform: uppercase;
}

a:hover, a:active {
background-color: #66B2FF;
}

And here is the html code (It's a gallery):

        <title>GALLERY</title>
        <link rel="stylesheet" type="text/css" href="styles.css">

GALLERY

home

about

gallery

contact

So all the links in the table use the style from the css. How do I stop that? Thanks in advance.

A: Use CSS specific selectors:
ul{
    //CSS for ul
}

ul li{
   //CSS for li
}

ul li a{
    //add CSS for nav links
}

A: You got to understand what css does. The purpose of applying css in not to remove it from some elements. If you want to "disable" or "exempt" some elements from having a particular css style, well the answer is you don't apply the css to those elements at first place.
Coming back to your code, I would suggest you do not generalize css rules the way you have done it for the  anchor tags you have. Rather you seperate them with classes using class="menuItems" or class="galleryImages". In short, don't do this,
ul li a{
    // some css
}

Do this,
.menuItems{
    // some css that is specific to menu items
}

.galleryImages{
    // some css that is specific to images
}

And in your html do this,

home

about

gallery

contact

A: create another class, or use style=""
example:
page

A: If you know you're targeting only CSS3 capable browsers, you can use the :not() selector for CSS. Give your links that you don't want styled a class and then apply to your link css definitions:
a:link:not(.no-style), a:visited:not(.no-style){
...
}

a:hover:not(.no-style), a:active:not(.no-style) {
...
}

JSFiddle: http://jsfiddle.net/L60ktyb3/

A: You need to understand that css property defined on page can be overridden by adding css property inline. Refer : http://www.expression-web-tutorial.com/Types_CSS_Styles.html#.VYVxElIoRoc

A: Inline style-attributes should only be, if at all, only be used when it's a single item or maybe in limited cases for dynamic generated style. Otherwise you have redundant CSS, which will result in a bad maintainability. Also the size of your HTML increases. This can result in larger load times and higher traffic-costs, especially when people using your site on mobile devices with limited traffic. So its a good idea not to use them at all.
Using css classes or ids from the beginning has the advantage that you're very flexible:

Now you can style all gallery-links by using their class in css:

In some cases the not-selector http://www.w3schools.com/cssref/sel_not.asp can be usefull. He will style ALL elements EXPECT the ones in the selector:
a:not(.gallery-link) {
    color: orange;
}

So this is can be seen as the opposite of the css above: It will colorize all links orange which don't has the class .gallery-link - But mostly you would be better to set a general rule for all links like
a {
  color: blue;
}

or maybe you already have such a rule defined by a css-framework you're using. For your gallery-links and other element which should look differend you can define classes and ids, which you can style as you cant. They will have no influence on other a-elements whithout the specified class(es).


text:
Q: IBM SBT: com.ibm.sbt.services.client.connections.files.model.FileEntry no longer present in latest SDK? Getting Started Tutorial: http://www-10.lotus.com/ldd/appdevwiki.nsf/xpDocViewer.xsp?lookupName=IBM+Social+Business+Toolkit+SDK+documentation#action=openDocument&res_title=Creating_your_first_J2EE_application_SDK1.0&content=pdcontent&sa=true
I was looking through the getting started tutorial and i did step 1 but it just so happens that Step 1.I's FileEntry datatype couldn't be resolved. Is there a new tutorial up somewhere that I can use? I'm using the latest version of the IBM SBT SDK, BTW.
Here's a snippet of the code on step 1.I:
            <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
            <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
            <%@page import="com.ibm.sbt.services.client.connections.files.model.FileRequestParams"%>
            <%@page import="java.util.HashMap"%>
            <%@page import="com.ibm.sbt.services.client.connections.files.FileService"%>
            <%@page import="com.ibm.sbt.services.client.connections.files.model.FileEntry"%>
            <%@page import="java.util.List"%>
            <%@page import="java.util.Map"%>
            <%@page import="com.ibm.commons.runtime.Application"%>
            <%@page import="com.ibm.commons.runtime.Context"%>

                        <title>My Files</title>

                            <%
                            try {
                                FileService fileService = new FileService();
                                List<FileEntry> files = fileService.getPublicFiles(null);
                                if(files != null && ! files.isEmpty()) {
                                    for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                                    FileEntry file = (FileEntry)iterator.next();
                                    out.println(" " + file.getLabel() + "
" );
                                }
                                } else {
                                    out.println("No Results");
                                }
                            } catch (Throwable e) {}
                            %>

A: You should use...
com.ibm.sbt.services.client.connections.files.FileList  i think it inherits from collection
https://github.com/OpenNTF/SocialSDK/blob/master/sdk/com.ibm.sbt.core/src/main/java/com/ibm/sbt/services/client/connections/files/FileList.java
com.ibm.sbt.services.client.connections.files.File instead of FileEntry
https://github.com/OpenNTF/SocialSDK/blob/master/sdk/com.ibm.sbt.core/src/main/java/com/ibm/sbt/services/client/connections/files/File.java
Based on this snippet...
https://greenhouse.lotus.com/sbt/SBTPlayground.nsf/JavaSnippets.xsp#snippet=Social_Files_Get_File_Comments
try {
    FileService fileService = new FileService();
   FileList files = fileService.getPublicFiles(null);
    if(files != null && ! files.isEmpty()) {
        for (File file : files) {
            out.println(" " + file.getLabel() + "
" );
        }
    } else {
    out.println("No Results");
    }
} catch (Throwable e) {}

I'm also reporting the documentation error


text:
Q: How do I display name instated of Id I have two table  Test1 and Test2.
Test1
p_id|imp_id | Name    |  Member_type
1   |001    | A       |  1
2   |002    | B       |  2
3   |003    | C       |  1
4   |004    | D       |  2

Test2
r_id|p_id |secondary_type
1   |1    |2
2   |3    |4

I am using join to get my design output.
Query
SELECT * FROM `test1` JOIN `test2` ON `test2`.`secondary_type` = `test1`.`p_id`

My output is
p_id    imp_id  Name    Member_type     r_id    p_id    secondary_type
2       002     B       2               1       1       2
4       004     D       2               2       3       4

So I am getting p_id value. I have to display name instated of the Id value.
For example B is connected to A. So I am getting the ID of A but I need Name instated of ID.
So my output will
p_id    imp_id  Name    Member_type     r_id |  p_id|   secondary_type
2       002     B       2               1    |   A  |   2
4       004     D       2               2    |   C  |   4

I tried using CodeIgniter.
$this->db->select('*');
$this->db->from('test1');
$this->db->join('test2', 'test2.secondary_type = test1.p_id');

A: Try using alias in select statement like
SELECT
test1.p_id,test1.imp_id,test2.name,test1.member_type,test2.r_id,test1.name as
p_id,test2.secondary_type
FROM `test1` JOIN `test2`
ON `test2`.`secondary_type` = `test1`.`p_id`

Result will come as per your requirement.


text:
Q: amcharts need to parseFloat the values from ajax response I am trying to create amcharts bar charts. I have the following json which is getting from json:
[
        { "option": "Czech Republic", "percentage": 156.90,"color":"#2175d9"},
        { "option": "Ireland", "percentage": 131.10,"color":"#ff9900"},
        { "option": "Germany", "percentage": 115.80,"color":"#448800"},
        { "option": "Australia", "percentage": 109.90,"color":"#2175d9"},
        { "option": "Austria", "percentage": 108.30,"color":"#2175d9"},
        { "option": "UK", "percentage": 99.00,"color":"#2175d9"}
    ]

I am calling ajax as follows:
$("#viewResult").click(function(){

       $("#chart").show();

       var qstnId = $("div[name='pollqstn']").attr("id");
       //Ajax to load all poll results
       $.post("fetchpollresult.php", {qstnid: qstnId}, function (data) {
           drawStuff(data);
       });

   });

My fetchpollresult.php page looks like this:
$questionid = $_REQUEST['qstnid'];

 $arranstext = array();
 $arranscount = array();

 $arranscolours = array("#2175d9","#448800","#448800","#ff9900");

//find qstn text
$pollqstndetails = $DB->get_records('epoll_questions', array('id' => $questionid));

$optiondetails = $DB->get_records('epoll_answers', array('questionid' => $questionid));

foreach($optiondetails as $optval){

 $optionresponseCount = $DB->get_records('epoll_responses', array('answerid' => $optval->id,'questionid'=>$questionid));

 $countOptresponse =  count($optionresponseCount);

 array_push($arranstext ,$optval->answertext);
 array_push($arranscount ,count($optionresponseCount));

}

 $data =array();

for($i=0;$i<count($arranstext);$i++){

$data[]  = array('option' =>$arranstext[$i],'percentage'=>$arranscount[$i],'color'=>$arranscolours[$i]) ;
}

$optionnoresponseCount = $DB->get_records('epoll_responses', array('answerid' => 0,'questionid'=>$questionid));

$data[]  = array('option' =>"NA",'percentage'=>count($optionnoresponseCount),'color'=>"#ff9900") ;

echo json_encode($data);

I am getting response as:
        [
            { "option": "Czech Republic", "percentage": 156.90,"color":"#2175d9"},
            { "option": "Ireland", "percentage": 131.10,"color":"#ff9900"},
            { "option": "Germany", "percentage": 115.80,"color":"#448800"},
            { "option": "Australia", "percentage": 109.90,"color":"#2175d9"},
            { "option": "Austria", "percentage": 108.30,"color":"#2175d9"},
            { "option": "UK", "percentage": 99.00,"color":"#2175d9"}
        ]

Than I have a function calling in ajax response:

   function drawStuff(val){

    // RADAR CHART
    chart = new AmCharts.AmSerialChart();
chartData =val; //assigning ajax response
    chart.dataProvider = chartData;
    chart.categoryField = "option";
    chart.startDuration = 3;
    chart.sequencedAnimation = false;

    // VALUE AXIS
    var valueAxis = new AmCharts.ValueAxis();
    valueAxis.axisAlpha = 0.15;
    valueAxis.minimum = 0;
    valueAxis.dashLength = 3;
    chart.addValueAxis(valueAxis);

    // GRAPH
    var graph = new AmCharts.AmGraph();
    graph.type = "column";
    graph.colorField = "color"
    graph.valueField = "percentage";
    graph.fillAlphas = 0.6;
    graph.balloonText = "[[value]] litres of beer per year";
    chart.addGraph(graph);

    // WRITE
    chart.write("chart");
}

But in this case it is not working. When I hard code it on the same page it works fine.
What I understand is this:
var chartData =
        [
            { "option": "Czech Republic", "percentage": 156.90,"color":"#2175d9"},
            { "option": "Ireland", "percentage": 131.10,"color":"#ff9900"},
            { "option": "Germany", "percentage": 115.80,"color":"#448800"},
            { "option": "Australia", "percentage": 109.90,"color":"#2175d9"},
            { "option": "Austria", "percentage": 108.30,"color":"#2175d9"},
            { "option": "UK", "percentage": 99.00,"color":"#2175d9"}
        ]

I need to parseFloat the json percentage values.
How can I parseFloat only percentage pair such as 156.90,131.10.... from that json and pass as chartData??
I am getting am chart as follows:

A: There are a few reasons why the chart does not show up.
1) You're not specifying content type for jQuery's AJAX call. This way you get a plain text response which is not converted to array. It's the fourth's parameter in $.post() function.:
$.post("fetchpollresult.php", {qstnid: qstnId}, function (data) {
           drawStuff(data);
       }, "json");

2) Simple typo. You have "options" for categoryField in chart code, while "option" (singular) in data.
Just change the categoryField accordingly:
chart.categoryField = "option";

3) You are assigning chart object in an unitianalized variable. This might confuse some older browsers. Simply add var before assignation to initialize chart variable:
var chart = new AmCharts.AmSerialChart();

Here's the full code:
$( "#viewResult" ).click( function() {

  $( "#chart" ).show();

  var qstnId = $( "div[name='pollqstn']" ).attr( "id" );
  //Ajax to load all poll results
  $.post( "fetchpollresult.php", {
    qstnid: qstnId
  }, function( data ) {
    drawStuff( data );
  }, "json" );

} );

function drawStuff( chartData ) {
  var chart = new AmCharts.AmSerialChart();
  chart.dataProvider = chartData;
  chart.categoryField = "option";
  chart.startDuration = 3;
  chart.sequencedAnimation = false;

  // VALUE AXIS
  var valueAxis = new AmCharts.ValueAxis();
  valueAxis.axisAlpha = 0.15;
  valueAxis.minimum = 0;
  valueAxis.dashLength = 3;
  chart.addValueAxis( valueAxis );

  // GRAPH
  var graph = new AmCharts.AmGraph();
  graph.type = "column";
  graph.colorField = "color"
  graph.valueField = "percentage";
  graph.fillAlphas = 0.6;
  graph.balloonText = "[[value]] litres of beer per year";
  chart.addGraph( graph );

  // WRITE
  chart.write( "chart" );
}


text:
Q: How to change the current trace file of the oracle database process Is it possible to change the current trace file of the Oracle Database process?
Actually one of the Oracle process trace file is growing continuously and we need change the current trace file of the Oracle Database process to another so that we can remove the trace file and freeup the space.
If we remove the current trace file using os commands, the new trace file will  get generated automatically for the Oracle process ??
Should we need to restart the corresponding Oracle DB process to change the trace file??

Operating system = Linux
Database version = 12cR1

Kindly share your commands ...
Thanks,
Sasikumar

A: I usually solve this problem with:
 cat /dev/null > [trace_file_path]

Make sure to copy your file first


text:
Q: How to use the AngularJS ngShow directive to show only if an element is in an array? My goal is to, rapidly, have a  tag displaying all the authors associated with a given publication.
Everything works when $scope.publications.authors is set to a single value. They do not work when multiple values are stored in an array, as shown below.
I know that the conditional statement for the AngularJS ngShow directive isn't the proper one to use for arrays, but I can't seem to figure out what I actually should use.
HTML:

{{person.firstName}}

JS:
$scope.publications = [
{"title": "Research Paper",
 "authors": ["Bill", "George"]};

$scope.persons = [
{"firstName": "Bill",
 "lastName": "Smith"},
{"firstName": "George",
 "lastName": "Jones"},
{"firstName": "Mike",
 "lastName": "Thomas"};

A: Make function inside your controller that could check if element exists in persons and call it within your ng-show. Check fiddle below:
http://jsfiddle.net/HB7LU/323/

A: According to the data structure of publications, you need a nested repeater. And you can use a function with current person and publication passed in to drive the display.

{{publication.title}}

{{person.firstName}}

function ctrl($scope) {
    $scope.publications = [{
        "title": "Research Paper",
            "authors": ["Bill", "George"]
    }];

    $scope.people = [{
        "firstName": "Bill",
            "lastName": "Smith"
    }, {
        "firstName": "George",
            "lastName": "Jones"
    }, {
        "firstName": "Mike",
            "lastName": "Thomas"
    }];

    $scope.show = function (person, publication) {
        return publication.authors.indexOf(person.firstName) >= 0;
    }
}

A: I think the best way to do this would be to use a method in your controller instead of trying to iterate all the data in the DOM.
There are multiple way to do it using a method. If you just want all the name of the authors on 1 line, you could have a method that take the authors and return a string with all the names and refer to this method for the content of your div with this
{{getAuthors(publication.authors}}
You could also have a method that return an array of the names and iterate on it using an ng-repeat with something like this


text:
Q: Event handling with kivy Checkboxes I'm able to launch an event upon checking a checkbox on kivy, but how to do the same with uncheking?

A: from kivy.uix.checkbox import CheckBox
def on_checkbox_active(checkbox, value):
  if value:
    print('The checkbox', checkbox, 'is active')
    # your active Function call
  else:
    print('The checkbox', checkbox, 'is inactive')
    # your unactive function call

checkbox = CheckBox()
checkbox.bind(active=on_checkbox_active)


text:
Q: Pandas DataFrame.to_csv() OSError: [Errno 22] Invalid argument and PermissionError: [Errno 13] Permission denied I am writing a large number of financial time series datas to individual CSV files. In one instance I have found that the to_csv method repeatably fails but I cannot for the life of me figure out why. During the call to method to_csv everything just hangs for upwards of 10-15 minutes. Before crashing with the the error:

Traceback (most recent call last):   File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 172, in save
      self._save()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 274, in _save
      self._save_header()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 242, in _save_header
      writer.writerow(encoded_labels) OSError: [Errno 22] Invalid argument
During handling of the above exception, another exception occurred:
OSError: [Errno 22] Invalid argument
During handling of the above exception, another exception occurred:
Traceback (most recent call last):   File "securitiesArchives.py",
  line 1072, in
      out_df.to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None)     File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py",
  line 3020, in to_csv
      formatter.save()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 187, in save
      f.close() OSError: [Errno 22] Invalid argument

It seems to be hanging up while writing the header row of the csv file. I wrote the same frame to hdf, then loaded from hdf, and using the hdf loaded frame, reproduced the same (or very close to the same) failure:

Traceback (most recent call last):   File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 172, in save
      self._save()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 274, in _save
      self._save_header()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 242, in _save_header
      writer.writerow(encoded_labels) PermissionError: [Errno 13] Permission denied
During handling of the above exception, another exception occurred:
PermissionError: [Errno 13] Permission denied
During handling of the above exception, another exception occurred:
Traceback (most recent call last):   File "bad_archive.py", line 12,
  in
      #out_df.to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None)   File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py",
  line 3020, in to_csv
      formatter.save()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 187, in save
      f.close() PermissionError: [Errno 13] Permission denied

Not sure why it changed from "OSError: [Errno 22] Invalid argument" to "PermissionError: [Errno 13] Permission denied" when moving from a larger code body to a small sample problem. I have searched for these errors in relation to the method to_csv and have seen that previous version of pandas may have had similar issues but this was supposed to be resolved in a later version. My pandas is:

INSTALLED VERSIONS
  ------------------ commit: None python: 3.7.3.final.0 python-bits: 64 OS: Windows OS-release: 10 machine: AMD64 processor: Intel64 Family 6
  Model 94 Stepping 3, GenuineIntel byteorder: little LC_ALL: None LANG:
  None LOCALE: None.None
pandas: 0.24.2 pytest: 5.0.1 pip: 19.1.1 setuptools: 41.0.1 Cython:
  0.29.12 numpy: 1.16.4 scipy: 1.2.1 pyarrow: None xarray: None IPython: 7.6.1 sphinx: 2.1.2 patsy: 0.5.1 dateutil: 2.8.0 pytz: 2019.1 blosc: None bottleneck: 1.2.1 tables: 3.5.2 numexpr: 2.6.9 feather: None
  matplotlib: 3.1.0 openpyxl: 2.6.2 xlrd: 1.2.0 xlwt: 1.3.0 xlsxwriter:
  1.1.8 lxml.etree: 4.3.4 bs4: 4.7.1 html5lib: 1.0.1 sqlalchemy: 1.3.5 pymysql: None psycopg2: None jinja2: 2.10.1 s3fs: None fastparquet:
  None pandas_gbq: None pandas_datareader: 0.8.1 gcsfs: None

I am on a win-10 64 bit machine using Anaconda Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
I have tried:

*

*convert index to str to astype(str) prior to calling to_csv, same issue

*dropna on index (rows) as there were a large number of NaN entries (originally this frame was part of a much larger multi index frame) problem persists

*keyword arguments headers=False and index=False, neither changed the behavior.

*Using .loc[] to slice first row only and perform to_csv on this

out_df.loc[out_df.index.values[0]].to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None)
which also failed. Even though this is now a series and no longer a frame as the following warning was produced

FutureWarning: The signature of Series.to_csv was aligned to that of
  DataFrame.to_csv, and argument 'header' will change its default
  value from False to True: please pass an explicit value to suppress this warning.

*

*Tried again same method as above instead slicing the first two row to ensure it remained a frame and not converted to series

The entire two row DataFrame which refuses cooperation with to_csv
out_df.loc[out_df.index.values[0]:out_df.index.values[1]].to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None,index=False,header=False)
But this also failed as before. I was however, able to write the sequence of each column independently to its own CSV file without issue.
for col_name in out_df.columns:
   print('Writing '+col_name+' as CSV')
    out_df[col_name].to_csv(col_name.replace(' ','_')+"_PRN.csv",mode='w',encoding='UTF-8' ,compression=None)
    print('Done.')

Combined, the above success, and failure of the two row write attempt, makes me think this is not an issue related to specific columns values. Further, the tracebacks make me think this issues is related to writing the column headers. But the thing is I have 3000+ other DataFrames withe the exact same column labels and they write to csv using to_csv without issue. At this point I am out of my depth.
Failure occurs on this same set of data repeatedly whether I am using the data I wrote to hdf or using a fresh pull from yahoo using yfinance. The following code reliably recreates the issue on my system:
import pandas as pd
import yfinance as yf

good_df = yf.download(tickers='AAPL',interval='1m',period='7d')
bad_df = yf.download(tickers='PRN',interval='1m',period='7d')
print('Writing test case AAPL as CSV')
good_df.to_csv("AAPL.csv",mode='w',encoding='UTF-8' ,compression=None)
print('Writing test case PRN as CSV')
bad_df.to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None)

Anyone have any ideas?
PS - While re-reading I decided to check the column labels for equivalence and as far as a Boolean comparison is concerned those of the 'good' DataFrame and those of the 'bad' DataFrame as identical.
>>>print(good_df.columns)
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'], dtype='object')
>>>print(bad_df.columns)
Index(['Open', 'High', 'Low', 'Close', 'Adj Close','Volume'], dtype='object')
>>>print(good_df.columns == bad_df.columns)
[ True  True  True  True  True  True]

PPS - I also have tried removing all flags from to_csv though they should have been the default values. It was a carry-over from as used in other code and I was going through different values to see if it would work. The most basic to_csv call fails as before
import pandas as pd
import yfinance as yf

good_df = yf.download(tickers='AAPL',interval='1m',period='7d')
bad_df = yf.download(tickers='PRN',interval='1m',period='7d')
print('Writing test case AAPL as CSV')
good_df.to_csv("AAPL.csv")
print('Writing test case PRN as CSV')
bad_df.to_csv("PRN.csv")

Update In response to reply from Cheng
I can see no file in explorer or via dir in console. But to test this I used a new file name that was not the symbol "PRN" and lo'n'behold it works.
I did not think this was the issue as I already tried writing to a different destination folder, both in the larger parent code, and then in the toy problem. Neither worked.
It would seem that windows has an old reference to any old file named "PRN.csv" or something....how frustrating. Lets hope a simple restart fixes it.
Thanks!

A: I literally had this same problem earlier today, but since I was working with much smaller data, the solution was easier to spot.
When a file is opened in another program, you cannot write or append to it. Check for places where you might have forgotten to close() or if it's open for viewing in Microsoft Excel.
Also generally it's better to use open('file', 'a') to write in case there's any previous data you stored there. If not, it will do the same as open('file','w') and create a new file.


text:
Q: How to rewrite if directory OR sub-directory requested I want to rewrite
mydir/xxx to mydir/fileA.php?param=xxx
and
mydir/xxx/yyy to mydir/fileB.php?param=yyy
xxx and yyy are wildcards.
I've tried
RewriteRule ^mydir/(.*)/(.*)$       mydir/fileA.php?param=$2
RewriteRule ^mydir/(.*)$            mydir/fileB.php?param=$1

but I get a 500 misconfiguration error.

A: You can use these rules for this in your root .htaccess:
RewriteEngine On
RewriteBase /

# skip real files and directories from more rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^mydir/[^/]+/([^/]+)/?$ mydir/fileA.php?param=$1 [L,QSA]
RewriteRule ^mydir/([^/]+)/?$       mydir/fileB.php?param=$1 [L,QSA]


text:
Q: Prevent streaming play stop when screen goes off Kitkat We are streaming to play sound in App but due to Kill/Draining battery feature in Android Kitkat 4 currently playing is stopped when screen goes off. How to overcome this or handle this and keep playing in screen off mode also.
Thanks

A: Your streaming playback should be managed by a foreground Service, one that is maintaining a partial WakeLock (to keep the CPU going normally) and, if needed, a WifiLock (to keep the WiFi radio on).


text:
Q: How to display custom view in ActionBar? I want to display custom search in actionbar (I'm using ActionBarSherlock for that).
I got that:

But I want make custom layout (edittext field) to occupy the entire available width.
I've implemented custom layout as suggested here.
There is my custom layout search.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="?attr/actionButtonStyle"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_gravity="fill_horizontal"
    android:focusable="true" >

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|fill_horizontal" >

        <EditText
            android:id="@+id/search_query"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center"
            android:background="@drawable/bg_search_edit_text"
            android:imeOptions="actionSearch"
            android:inputType="text" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right|center_vertical"
            android:src="@drawable/ic_search_arrow" />

    </FrameLayout>

</LinearLayout>

And in MyActivity:
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setIcon(R.drawable.ic_action_search);

LayoutInflater inflator = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.search, null);

actionBar.setCustomView(v);

How can I make custom layout to occupy all the available width of actionBar?
Help, please.

A: The answers from Tomik and Peterdk work when you want your custom view to occupy the entire action bar, even hiding the native title.
But if you want your custom view to live side-by-side with the title (and fill all remaining space after the title is displayed), then may I refer you to the excellent answer from user Android-Developer here:
https://stackoverflow.com/a/16517395/614880
His code at bottom worked perfectly for me.

A: I struggled with this myself, and tried Tomik's answer.
However, this didn't made the layout to full available width on start, only when you add something to the view.
You'll need to set the LayoutParams.FILL_PARENT when adding the view:
//I'm using actionbarsherlock, but it's the same.
LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(overlay, layout);

This way it completely fills the available space. (You may need to use Tomik's solution too).

A: For example, you can define a layout file which contains a EditText element.
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/searchfield"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inputType="textFilter" >

</EditText>

you can do
public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar actionBar = getActionBar();
    // add the custom view to the action bar
    actionBar.setCustomView(R.layout.actionbar_view);
    EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
    search.setOnEditorActionListener(new OnEditorActionListener() {

      @Override
      public boolean onEditorAction(TextView v, int actionId,
          KeyEvent event) {
        Toast.makeText(MainActivity.this, "Search triggered",
            Toast.LENGTH_LONG).show();
        return false;
      }
    });
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
        | ActionBar.DISPLAY_SHOW_HOME);

    }

A: There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .
The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.
Here're the themes:
styles.xml
 <style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowShowWallpaper">true</item>
  </style>

  <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
  </style>

  <style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
    <item name="android:displayOptions">showCustom</item>
    <item name="android:background">#88000000</item>
  </style>

value-v19/styles.xml
 <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

  <style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:
getSupportActionBar().setDisplayShowCustomEnabled(true);

A: This is how it worked for me (from above answers it was showing both default title and my custom view also).
ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// actionBar.setCustomView(view); //last view item must set to android:layout_alignParentRight="true" if few views are there
actionBar.setCustomView(view, layout); // layout param width=fill/match parent
actionBar.setDisplayShowCustomEnabled(true);//must other wise its not showing custom view.

What I noticed is that both setCustomView(view) and setCustomView(view,params) the view width=match/fill parent. setDisplayShowCustomEnabled (boolean showCustom)

A: There is a trick for this. All you have to do is to use RelativeLayout instead of LinearLayout as the main container. It's important to have android:layout_gravity="fill_horizontal" set for it. That should do it.


text:
Q: Не отображаются записи из SQL таблицы в WPF DataGrid Никаких ошибок, к базе данных подключается исправно. Просто не выводит записи из таблицы. Если есть идеи, буду благодарен.
DataGrid:
<DataGrid Name="DataGridEmployee" Height="260">

        <DataGrid.Columns>
            <DataGridTextColumn Header="ID"/>
            <DataGridTextColumn Header="Фамилия"/>
            <DataGridTextColumn Header="Имя"/>
            <DataGridTextColumn Header="Отчество"/>
            <DataGridTemplateColumn Header="Дата рождения"
                    CellTemplate="{StaticResource DateTemplate}"
                    CellEditingTemplate="{StaticResource EditingDateTemplate}" />
            <DataGridTextColumn Header="Телефон"/>
            <DataGridTextColumn Header="Электронная почта"/>
            <DataGridTextColumn Header="Должность"/>
        </DataGrid.Columns> </DataGrid>

.cs страницы:
string connectionString; SqlDataAdapter adapter;
    DataTable employeeTable;

    public PageEmployee()
    {
        InitializeComponent();
        // получаем строку подключения из app.config
        connectionString = ConfigurationManager.ConnectionStrings["WpfApp1.Properties.Settings.TitlePersonEntities"].ConnectionString;
    }

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        string sql = "SELECT * FROM Employee";
        employeeTable = new DataTable();
        SqlConnection connection = null;
        try
        {
            connection = new SqlConnection(connectionString);
            SqlCommand command = new SqlCommand(sql, connection);
            adapter = new SqlDataAdapter(command);
            connection.Open();
            adapter.Fill(employeeTable);
            DataGridEmployee.ItemsSource = employeeTable.DefaultView;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            if (connection != null) connection.Close();
        }
    }


text:
Q: Ruby ARGV array search I am having some issues searching for what options have been passed in the ARGV. I have,
if ARGV.include? '-v' == true
    puts "Do junk"
else
    puts "Nope"
end

This seems like a shockingly simple thing but I always get "Nope" either when I place "-v" or when I do not. Am I missing something simple here?

A: I don know if it's your problem, but you don't need the == true.
if ARGV.include? '-v'
  puts "Do junk"
else
  puts "Nope"
end

The include? method returns true or false.

A: Why are you searching ARGV for options? Use the standard library's OptionParser class, which is made for this.
require 'optparse'
require 'pp'

options = {}
OptionParser.new { |opt|
  opt.on('-v', '--verbose', 'Be verbose') { |o| options[:verbose] = o }
}.parse!

pp options

Save that, and run it with something like: ruby test.rb -v or ruby test.rb --verbose and you'll see:
{:verbose=>true}

Run it with ruby test.rb -h or ruby test.rb --help and you'll see:
Usage: test [options]
    -v, --verbose                    Be verbose

OptionParser has all sorts of nice (and intelligent) tricks for setting booleans, required parameters, coercing values so you can get multiple values for a parameter returned as an array, etc. And, notice that it created the help for me, including using -h or --help for the flag.
Look at the examples in the documentation for additional ideas of what it can do.

A: This is a precedence problem. Write as'
if ARGV.include?('-v') == true
  puts "Do junk"
else
  puts "Nope"
end

In your case if ARGV.include? '-v' == true has been interpreted as if ARGV.include?
('-v' == true). Now '-v' == true returns false, and false is not included in your ARGV array, so if evaluates as false, and else part is getting executed.
Better to write as
if ARGV.include? '-v'
  puts "Do junk"
else
  puts "Nope"
end

Because ARGV is an array, and Array#include?(ob) returns true, if the ob found inside the array.

A: All of the other answers so far are right in that it's a precedence problem.
Here are a couple helpful notes, the first of which has already been touched on:

*

*You don't need == true, since the include? method already returns true or false.

*For parsing command-line arguments, you might find it more intuitive to use a library like Trollop. Using Trollop, your example could be done like this:
require 'trollop'
opts = Trollop::options do
  opt :verbose, "Run verbosely"  # (-v is created automatically from this)
end

if opts[:v]
  puts "yes"
else
  puts "no"
end

(EDIT: See also the Tin Man's answer re: optparse)


text:
Q: jquery hide/show function Hi! I'm just a newbie for jquery functions, I was able to finish the hide/show       function of certain divs but I want to make in centered way while executing the show   div.. Now these div has a content but when I click the show it appears from left to   right.. Can somebody do these trick to be centered?
window.onload = function(){
    $('#show').click(function()
    {
        $('#nav').show('blind');
        $('#show').hide();
        $('#hide').show();
    });

    $('#hide').click(function()
    {
        $('#nav').hide('blind');
        $('#hide').hide();
        $('#show').show();
    });
}

A: use .toggle()  for doing both hide and show in  a same time.u no need to write show and hide function separately
http://api.jquery.com/toggle/
<!DOCTYPE html>

<button>Toggle 'em</button>

Hiya

Such interesting text, eh?


text:
Q: Continuity at a given point. I have found the left-hand limit. For right-hand limit, I have used squeeze theorem, but from there I am unable to proceed further.

A: Regarding the right-hand limit: For $1<x<\sqrt{2}$, we have $[x^2]=1$. That means for $x$ values in that range, the function is $f(x)=\frac{1-1}{x^2-1}=0$, and so the right-hand limit is $0$.


text:
Q: Restrict value of a parameter in a constructor AT DESIGN TIME I'd like to restrict the value of a number parameter in a constructor to within a certain range.
I know the conventional way is to do something like the following:
public class Foo
{
    public int MaxAmount { get; }
    public int Amount { get; set; }

    public Foo(int amount)
    {
        if (amount > MaxAmount) { Amount = MaxAmount; }
        else if (amount < 1) { Amount = 1; }
        else { Amount = amount; }
    }
}

But what I don't like about this is that the caller doesn't know when the property gets set to something other than what was specified. I could return an exception instead of silently clamping the value, but that's not very friendly.
What I'd like is something akin to this:
public Foo(int(1, this.MaxAmount) amount) // Where int(minimumValue, maximumValue)
{
   Amount = amount;
}
in which one wouldn't even be able to instantiate Foo with an unacceptable value - the framework would prevent it.
Is anything like this possible?
EDIT FOR CLARITY:
What I'm after is a means by which the parameter itself can carry and communicate the information about its constraints - in a 'baked in' fashion which might, for example, surface in Intellisense when you wrote the call. So, I'd avoid the work of even attempting to instantiate the class if the values for the parameters were not valid.
If, for example, the program is running and the user types a number (N) and presses a button which creates a new Foo with an illegal quantity of N, I now have an exception to handle and something to debug and fix. Why even allow it in the first place? If Foo has been explicitly defined as having an upper boundary of 4 for its Amount property, what's the point of allowing the developer to write Foo(5) when I could have informed him that the value he's passing is not valid at the time that he wrote it?
If there's some syntactic sugar, like ParameterConstraint or something, that is handled by the Framework for me so that I don't have to roll my own into every class I write, I think that would be very useful.

A:
I could return an exception instead of silently clamping the value, but that's not very friendly.

Say what? What do you mean, "friendly"? The caller isn't your friend, it's another piece of code that is trying to set an out of range value. The developer who wrote the code should be told immediately that he's doing something wrong.
Throw an exception!

A: You can do this using static-contract checking with Code Contracts (Premium only - The standard edition only offers runtime contract checking).
The syntax is simply
public Foo(int amount) {
    Contract.Requires(amount < MaxAmount);
    ...
 }

(Requires) contracts are evaluated by checking that the arguments is constrained when calling the method. In your instance, it will be difficult to evaluate the constructor argument with against the instance field MaxAmount, because you cannot check that value beforehand. (Make MaxValue static to solve this).
Example of such call.
int val = _getFromSomewhere();
var foo = new Foo(val);
//This May produce compile time error
// because the contract checker cannot prove you contract is met.

The fix would be to make sure you put the constraint where you call is made.
int val = _getFromSomewhere();
if (val < Foo.MaxAmount)
    var foo = new Foo(val);
    //Will always compile fine, because contract is met.

When you install Contracts, the static checker isn't turned on by default. Your project properties will have an extra tab where you can configure the contract options and enable static checking.

A: You will need to wrap the parameter up in a new type then.  ints know what their max amount is, and it is int.MaxValue.  If it is truly the case that the parameter itself knows its own max amount, and that it isn't something specific to class Foo, then you will need to create another type that checks the amount passed in to it.  As it stands, the signature of Foo's constructor accepts any int data structure.

A: Either throw the exception or provide a static property to validate the amount
public static bool ValidateAmount(int amount)
{
    if(amount > MaxAmount)
        return false;
    return true;
}

A: Not for sure if this works for properties types in C#, but you might be able to define an enumeration contain all of the acceptable values and then set the data type of the property to that enumeration. That would force the caller to use the enumeration and thus know what values are acceptable. Of course, if you have a lot of values in the acceptable range, the enumeration would be unwieldy.