text:
Q: Downloading a file in VBA and storing it I need to download a file that I got from a REST search. The URL is like the following:
https://abc.def/geh/servlet/rest/vault?oid=xxx&expr=files.file1
(I needed to edit it due to privacy reasons..)
The file is supposed to be a result of a Nastran computation, it can be viewed by a simple Texteditor. The Extension is .pch, it is relatively large (~21mb)
How can that be implemented in VBA?

A: First of all - the link does not work. Second of all: there can be 2 approaches depending on the output of the HTTP request.
If the output is file you can use the code below:
Sub DownloadFile(url As String, filePath As String)

    Dim WinHttpReq As Object, attempts As Integer
    attempts = 3
    On Error GoTo TryAgain
TryAgain:
    attempts = attempts - 1
    Err.Clear
    If attempts > 0 Then
        Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
        WinHttpReq.Open "GET", url, False
        WinHttpReq.send

        If WinHttpReq.Status = 200 Then
            Set oStream = CreateObject("ADODB.Stream")
            oStream.Open
            oStream.Type = 1
            oStream.Write WinHttpReq.responseBody
            oStream.SaveToFile filePath, 2 ' 1 = no overwrite, 2 = overwrite
            oStream.Close
        End If
    End If
End Sub

If the output is a simple text HTML response you can save the output to a file
Function GetXMLHTTPResult(url As String)
    Dim XMLHTTP As Object, attempts As Integer
    attempts = 3
    On Error GoTo TryAgain
TryAgain:
    attempts = attempts - 1
    Err.Clear
    If attempts > 0 Then
        Set XMLHTTP = CreateObject("MSXML2.serverXMLHTTP")
        XMLHTTP.Open "GET", url, False
        XMLHTTP.setRequestHeader "Content-Type", "text/xml"
        XMLHTTP.setRequestHeader "Cache-Control", "no-cache"
        XMLHTTP.setRequestHeader "Pragma", "no-cache"
        XMLHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0"
        XMLHTTP.send
        GetXMLHTTPResult = XMLHTTP.ResponseText
    End If
End Function
Sub SaveFile(url)
        res = GetXMLHTTPResult(url)
        Open "C:\res.txt" For Output As #1
        Write #1, res
        Close #1
End Sub

A: If the file already exists on the server and doesn't have to be built by way of a query etc, you can use an API call like so:
Option Explicit

#If VB7 Then
    Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
    (ByVal pCaller As LongPtr, ByVal szURL As String, ByVal szFileName As String, _
    ByVal dwReserved As LongPtr, ByVal lpfnCB As LongPtr) As Long
#Else
    Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
    (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
    ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#End If

Sub SO()

Dim fileURL As String, saveLocation As String

fileURL = "https://abc.def/geh/servlet/rest/vault?oid=xxx&expr=files.file1"
saveLocation = "C:\Users\bloggsj\desktop\files.file1"

MsgBox "Download completed: " & (URLDownloadToFile(0, fileURL, saveLocation, 0, 0) = 0)

End Sub


text:
Q: Getting undesired result by using while loop to find the sum of n natural numbers I am attaching the code for the same.Its working fine.But once i enter a number less than the previous one it stops giving desired output.Any help/suggestion shall be greatly appreciated.
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
   printf("Enter the number upto which you want the sum of \n \n");
   scanf("%d",&n);

   while(i<=n)
   {

      j=j+i;
      i++;

   }
   printf("%d \n",j);
   printf("Do it with another number? Y/N \n \n");
   scanf("%s",&ch);
}
return 0;

A: In your outer while loop, you're never resetting the value of the variable i back to 1, or j back to 0. That is why subsequent loops will produce an incorrect sum.

A: There are a smattering of bugs in this code, including:

*

*Comparison to uninitialized value of  of ch in the initial while expression.

*Failing to reset i and j for each outer-loop iteration

*Failing to test for data-read success in either scanf call to ensure proper input.

*The continuation scanf("%s", &ch) is simply wrong for a single character with skipped whitespace (which you must do to avoid reading the newline after your list integer input). Unless EOF or an error state is reached, what you have now is guaranteed to invoke undefined behavior, as a string-read of at least one character requires at least two for storage (the character, and a subsequent terminator).

Addressing all of those:
#include <stdio.h>

int main()
{
    char ch;
    do
    {
        int n;
        printf("Enter the number upto which you want the sum of \n \n");
        if (scanf("%d", &n) != 1) // See (3)
            break;

        int j = 0; // See (2)
        for (int i = 1; i <= n; ++i) // See (2)
            j += i;
        printf("%d \n", j);

        printf("Do it with another number? Y/N \n \n");
        if (scanf(" %c", &ch) != 1) // See (3) and (4)
            break;

    } while (ch != 'n' && ch != 'N'); // See (1)

    return 0;
}

Everything here is self-explanatory when referred to the previous bug punch list, save for maybe the format string for reading the single character. You mentioned in comments that you tried %c but it skipped to another loop iteration. That's because you didn't have the leading whitespace " %c" that tells scanf to skip white space before extracting the next argument. With that, it should work as desired.

A: You need to reset i and j for every n.
i = 1;j=0;
while(i<=n)
{

Also your format specifer is wrong. For char, it should be %c and not %s
scanf("%c",&ch);

A: The simplest solution is to set i to 0 at the outer while:
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
i = 0;
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);

while(i<n)
{

j=j+i;
i++;

}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;

Note that I have changed <= to < for your inner while, since you do not want to increment the value if the same n is inputted one after the other.

A: #include<stdio.h>
int main(){
int n;
char ch;
while(ch!='n')
{
   printf("Enter the number upto which you want the sum of \n \n");
   scanf("%d",&n);
int i=1;//it should be 1 in every loop of the number
int j=0;//the sum should also be initialized to zero to erase the previous value
   while(i<=n)
   {

      j=j+i;
      i++;

   }
   printf("%d \n",j);
   printf("Do it with another number? Y/N \n \n");
   scanf("%c",&ch);//this is a char not a string
}
return 0;
}

Due to the i is not initializing to 1 when the loop is coming for the second time there it is not going inside the loop and printing the previous value .

redpajama_set_name: RedPajamaStackExchange


text:
Q: WordPress: Do not show tags if they are a subgroup of another tag Setting
I have a huge set of posts (> 10.000) that are all equipped with varying numbers of tags per post. A typical post would have, eg, 3-4 tags like "washington, usa, travel, america", another one tags like "washington, city, architecture, usa".
With such a huge number of posts a problem arises: Very often, there is a tag ("usa") that is completely included in another tag ("america").
Completely included means that all posts belonging to "usa" also belong to "america" (but not the other way round). - This problem happens on several levels: Think of "america" being part of "world" or "washington" being part of "usa".
Problem
If you look at these tags, there is a logical cluster appearing: washington is part of usa is part of america is part of world. (washington is also part of architecture and part of city.) - so there are two hierarchies in regards to content.
Now I would like to show the user what WordPress calls a tag-archive, but with the highest level tags only. So in this case, it would be "world" and "city". When the user clicks "world", a new page is loaded presenting "america", "europe", "asia", etc. - Once we are down to a specificity that would return only, say, 100 posts at maximum (and not thousands like in the levels above), the selection/clustering-process would be stopped and I would show the user these posts.
(No, sorry, hierarchical categories, which would exactly do what I have just written, are not an option as these posts are automatically added and new clusters might pop up in the future.)
Question
How can I determine these kinds of clusters as efficient as possible?
A solution (code) is of course my preferred answer, but I am also happy, if one can point me into a direction that deals with this problem. Languages used in this project are PHP, SQL and Elastic Search.


text:
Q: Stabilizer subgroup of adjoint action Given $b \in \mathfrak{su}(n)$, how can I find the stabilizer $\text{stab}(b)$ for the adjoint action of $SU(n)$ on $\mathfrak{su}(n)$ given by $Ad_U(b) = UbU^{\dagger}$ without using coordinates? The $SU(4)$ case is particularly important in my application.

A: I have no idea what you mean "without using coordinates". The best you can hope to do without a lot of work is to determine the conjugacy class of the stabiliser.  For that, all you need to know is the spectrum.
Clearly, if $b \in \mathfrak{su}(n)$, then $ib$ is traceless and hermitian.  It can therefore be diagonalised via (special) unitary transformations.
For example, if $b \in \mathfrak{su}(4)$, let $\lambda_1\leq\lambda_2\leq\lambda_3\leq\lambda_4$, with $\sum_i \lambda_i = 0$,  be the eigenvalues of $ib$.  Up to conjugation we have five possibilities:

*

*$\lambda_1 < \lambda_2 < \lambda_3 < \lambda_4$, with stabiliser a maximal torus: $S(U(1)\times U(1) \times U(1) \times U(1))$;

*$\lambda_1 = \lambda_2 < \lambda_3 < \lambda_4$, with stabiliser $S(U(2)\times U(1)\times U(1))$;

*$\lambda_1 = \lambda_2 < \lambda_3 = \lambda_4$, with stabiliser $S(U(2) \times U(2))$;

*$\lambda_1 = \lambda_2 = \lambda_3 < \lambda_4$, with stabiliser $S(U(3) \times U(1))$; and

*$\lambda_1 = \lambda_2 = \lambda_3 = \lambda_4 = 0$, with stabiliser $SU(4)$.


text:
Q: Removed field from model, migrated, but model still shows up and causes error in Django So this is a slightly weird thing that's happening.
I had a model with a couple of attributes, and when I removed one of them and did a migration, django removed it from the database and for some reason it doesn't appear in the automatically made migrations. But when I try to print out or output a list of model objects or even just print out one of the models I get the error 1054, "Unknown column 'items.lab_id' in 'field list'")
Now when I go into python manage.py shell and type in
>>>from items.models import Item
>>>Items._meta.get_fields()

lab_id doesn't show up in the list of fields
but when I do
>>>from items.models import Item
>>>Items._meta.get_all_field_names()

lab_id does show up in the list of fields. Even though it's not in the database, it's not in my model, AND it doesn't show up in any of my past migrations. I do remember having it in there at some point, but I know I removed it. I'm just not sure how to tell django to forget about it or ignore it.


text:
Q: emulator for wp7.1 shows internal error I've just started developing for windows phone 7 but can't seem to get my emulator working. I get an pop-up "Internal Error" and as a description in the bottom view i see "Error!   Connection failed because of invalid command-line arguments".
I am running windows 8 developer preview (not in a virtual machine) on a mac mini(2gb ram, core2Duo 2,26Ghz). I've reinstalled the tools and have restarted the computer several times but nothing works. I am running VS as an administrator

A: Still there is a work around. Try installing an update WPSDK-7.1.1-KB2669191-x86.
and it all works perfectly.

A: The Windows Phone 7 SDK does not support Windows 8.
You can see the system requirements (including supported operating systems) at http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=27570


text:
Q: Serial port: Polling vs Event-Driven approach I am using Win32 API (Overlapped IO) for serial port communication. I have used PInvoke to call the Win32 API from my C# code.
In my previous implementation, the receiver thread reads data by using Polling mechanism (Infinite while loop reads RX buffer periodically). Now, I am trying to use Event-Driven approach to read the data (Using WaitCommEvent API Call). We expect the new implementation will reduce the CPU usage and Speed-Up the communication.
But, After changing to Event-Driven approach, the communication is actually slowed down, taking twice the time to read when compared to Polling mechanism.
Can anyone suggest which one of these is the best  approach improve the communication speed and reduce the CPU usage?
Below is my code snippet:
private void ReadDataForWindows()
{
    var data = new byte[255];

    // Specify a set of events to be monitored for the port.
    if (SetCommMask(this.Handle, EV_DEFAULT))
    {
        while (this.Handle != (IntPtr)INVALID_HANDLE_VALUE)
        {
            uint eventMask = 0;
            // Wait for an event to occur for the port.
            eventMask = this.WaitForEvent();

            if (eventMask == EV_RXCHAR)
            {
                this.ReadFromRXBuffer(data);
            }
            else if (eventMask == EV_ERR)
            {
                uint errors;
                ClearCommError(this.Handle, out errors, IntPtr.Zero);
            }

            // Re-specify the set of events to be monitored for the port.
            if (!SetCommMask(this.Handle, EV_DEFAULT))
            {
                break;
            }
        }
    }
}

private void ReadFromRXBuffer(byte[] data)
{
    uint dwBytesTransferred;
    // Loop for waiting for the data.
    do
    {
        // Read the data from the serial port.
        this.Read(data, 255, out dwBytesTransferred);

        // Display the data read.
        if (dwBytesTransferred > 0)
        {
            if (this.DataReceived != null)
            {
                var dataReceived = new byte[dwBytesTransferred];
                for (var i = 0; i < dwBytesTransferred; i++)
                {
                    dataReceived[i] = data[i];
                }

                this.DataReceived(this, new ByteDataReceivedEventArgs(dataReceived, Convert.ToInt32(dwBytesTransferred)));
            }
        }

    } while (dwBytesTransferred > 0);
}

private uint WaitForEvent()
{
    uint eventMask = 0;
    IntPtr evPtr = Marshal.AllocHGlobal(Marshal.SizeOf(eventMask));
    Marshal.WriteInt32(evPtr, 0);

    if (WaitCommEvent(this.Handle, evPtr, this.RxOvr.MemPtr) == false)
    {
        int error = Marshal.GetLastWin32Error();

        // Operation is executing in the background
        if (error == ERROR_IO_PENDING)
        {
            this.ReceiveSignal.WaitOne();
        }
        else
        {
            this.Fault = "WaitCommEvent() Failed. System Returned Error Code: " +
                error.ToString();
            return 0;
        }
    }

    eventMask = (uint)Marshal.ReadInt32(evPtr);
    return eventMask;
}


text:
Q: Custom Post Type Archive Pagination I've set up a template called archive-gallery.php, and I have pagination working, however, the query is ignoring my posts_per_page value and using the value that is in Settings > Reading called Blog Pages Show At Most. My gallery archive page is showing 8 posts per page, which I set, and I have 48 posts in the post type. This should give me 6 pages. Wordpress is only giving me 5 pages in the pagination using next_posts_link with $gallery_page_query->max_num_pagesincluded in the next posts link. When I go to the 6th page, which there is a link to in the pagination, I get a 404.
Here's my code:
<?php
/*
Template Name: Gallery Archive
*/
get_header(); ?>

          Check out our latest work!

          <?php
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
            $gallery_page_args = array(
              'post_type' => 'gallery',
              'posts_per_page' => 8,
              'paged' => $paged,
              'order' => 'DESC',
              'orderby' => 'date'
            );
            $gallery_page_query = new WP_Query($gallery_page_args);
            if ($gallery_page_query->have_posts()) :
              while ($gallery_page_query->have_posts()) : $gallery_page_query->the_post();
                echo 'ID);
                echo '">';
                echo 'ID));
                echo $featured_image_url;
                echo '">';
                echo '';
              endwhile;
              wp_reset_postdata();
            endif;
          ?>

          <?php previous_posts_link('<< Go back'); ?>

          <?php next_posts_link('See More >>', $gallery_page_query->max_num_pages); ?>

<?php get_footer(); ?>

The page in question is located at http://www.nickpassaro.com/clientsitedev/NJRI/gallery
If anyone could help me, I would really appreciate it.

A: Your problem is your naming convention. Look at the Template Hierarchy. The archive- prefix is reserved for date and custom post type archive pages. You are using this as prefix to a page template
This is not only confusing to humans, but to Wordpress as well. For page templates you should be using the page- prefix. Just a note, as from version 3.4 you don't need the page- prefix anymore for page templates :-)


text:
Q: Resizing width after changing position I am trying to create a sliding menu effect by changing the left value of my main element. I need it to resize to fill the remaining space created by shifting to the left however. I tried adding width: 100% but it doesn't seem to make any difference.  The position change behaves as I had hoped but I can't get the element to correctly resize also. Here's what I have so far

main {
  position: relative;
  z-index: 10;
  width: 100%;
  transition: 0.2s;
  left: 0;
}

main:hover {
  left: -5rem;
}

A: So there's a few ways of solving this, but rule no. 1 is that width: 100% is almost always a bad idea. Most of the time it will not work, while probably messing up something unintended.
On to solutions:
So solution no 1. is probably the simplest one, and looks something like this:

#main {
  position: fixed;
  min-width: 100px;
  min-height: 200px;
  right: -85px;
  top: 10px;
  padding: 10px;
  background: #50505050;
  transition: all 0.2s;
  z-index: 99;
}

#main:hover {
  right: 10px;

}

Hello world!

slide to the left

How it works is that, instead of resizing the sliding menu it has a (semi)-fixed size and starts out at a position that is partly outside of view.
hen, once you hover over it, the entire element is moved left, causing it to slide fully into view.
Great thing about this solution is that the sliding menu is completely agnostic of the rest of the page, which makes it easy to maintain. Changing something in nav won't break whatever is in main1.
For a more detailed explenation of this implementation you can take a look at this example.
The second implementation is a little trickier, and involves flexbox:

.container {
  display: flex;
  flex-direction: row;
  justify-content: right;
  flex-basis: 100px;

  /* not needed when you have content */
  min-height: 250px;
}

#nav {
  flex-grow: 1;
  justify-content: left;
}

#main {
 flex-shrink: 1;
 z-index: 99;
 background: #50505050;
 transition: all 0.2s;
 padding: 0 0 0 10px;
 overflow: hidden;
}

#main:hover {
 flex-grow: 2;

}

Hello world

Expands left

As you can see, this implementation does resize, and the menu is more of an expanding, rather than a sliding, one.
A more complete explanation of flexboxes can be found here and here but very briefly, the menu takes up space of 1/3rd of the available space by default, but when hovered on will expand to  2/3rds of the available space instead. You can manipulate this by assigning different flex-grow and flex-shrink values.
Advantages of this method are that it is size independent, flex will do all the calculating for you, so you don't have to worry about manually setting right and size values like with the first solution. I also find this looks a little more modern than ye olde slide menu, but you can make anything look good with enough work of course.
Disadvantages is that flexboxes are the black magic of CSS, and can be difficult to grasp.
Hope either of these help you create what you want, but otherwise there's also plenty other resources and tutorials you can find.
Footnotes:
1: I strongly suggest you switch the ids of #main and #nav around by the way. #main should be where your main content lives, #nav is for site navigation.


text:
Q: How to specify the area of a partial view I have an area (say User). I return a PartialView from an action method through an Ajax call as below.
return PartialView("_Users");

But at this time mvc searches the general shared folder and general user folder. It is not searching inside the area for the partial view. And thus I am getting an error. :(
How can I specify that this partial view resides under an area, at the time it returns from a view?

A: If you are not calling this action outside of the area, it won't search there. Let's say your partial view inside the following folder:

~/Areas/User/Views/Shared/_Users.cshtml

And assume that you are calling this partial view inside Bar action of Poo controller in your User area, the search order will be this one:

~/Areas/User/Views/Poo/_Users.cshtml
~/Areas/User/Views/Shared/_Users.cshtml
~/Views/Shared/_Users.cshtml

If you call this partial view out side of the Area, it will still look for the following folder and the related folder according to your controller and area (if there is one):

~/Views/Shared/_Users.cshtml

but not inside the User area.
It seems that you partial view is an application wide partial view. My advice is to move it to the following folder:

~/Views/Shared/


text:
Q: MyISAM or InnoDB, for safety of data, which should I choose? MyISAM or InnoDB, for safety of data, which should I choose?

A: InnoDB is a safer ACID compliant engine with some integrity features that MyISAM lacks.
http://dev.mysql.com/doc/refman/5.0/en/storage-engines.html
Clearly, if you are concerned with de safety of your data I would use InnoDB. Would you use an engine that does not support transactions?
MyISAM is used for performance reasons.

A: InnoDB has better respect of constraints, data integrity and reliability. It supports foreign key constraints and transactions for instance... The documentation compares transaction and nontransation engines.

A: See, developer and site lard are expecting only safety, but users are expecting fast retrieval.
Only, in InnoDB there is no fulltext support, so we manage in that situtaion.
Is there alternate constraints there, or is there any tips?
Example,
I have postcode file in my table,
I have around 100000 postcodes,
I have autocomplete for postcode, in this situtaion, if I use the MyISAM, I make the filed
as fulltext, so my user will not experience a performance issue.
So is there any idea for this creteria?
Basically I am not a database engineer, I am a developer.


text:
Q: Connect android device to wifi programmatically without user interaction I need to connect an android device to wifi programmatically without interacting with the user.  Notably, this app is being purpose built and will not be on the play store or deployed publicly  (I say this because what I need to do could have serious security concerns).
Here is how I am connecting the device programmatically
TextView textFeedback = findViewById(R.id.text);

ConnectivityManager.NetworkCallback wifiConnectionCallback = new ConnectivityManager.NetworkCallback(){
    @Override
    public void onAvailable(@NonNull Network network) {
        super.onAvailable(network);
        Log.e(logTAG, "wifi connected");
        textFeedback.setText("wifi connected");
    }

    @Override
    public void onLosing(@NonNull Network network, int maxMsToLive) {
        super.onLosing(network, maxMsToLive);
        Log.e(logTAG, "losing wifi connection");
        textFeedback.setText("losing wifi connection");
    }

    @Override
    public void onLost(@NonNull Network network) {
        super.onLost(network);
        Log.e(logTAG, "lost wifi connection");
        textFeedback.setText("lost wifi connection");
    }

    @Override
    public void onUnavailable() {
        super.onUnavailable();
        Log.e(logTAG, "user closed wifi connection");
        textFeedback.setText("user closed wifi connection");
    }
};

// instantiate connectivity manager
ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(this.CONNECTIVITY_SERVICE);

// connect to phl via wifi
Thread wifiConnectionThread = new Thread(new Runnable()
{
    @Override
    public void run()
    {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q)
        {
            NetworkSpecifier networkSpecifier  = new WifiNetworkSpecifier.Builder()
                        .setSsid(ssid)
                        .build();
            NetworkRequest networkRequest  = new NetworkRequest.Builder()
                        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                        .setNetworkSpecifier(networkSpecifier)
                        .build();
            connectivityManager.requestNetwork(networkRequest, wifiConnectionCallback);
        }
    }
});
wifiConnectionThread.start();

This works just fine with one exception.  It prompts the user to ask them if they would like to connect to the network.  This is problematic because I need the device to connect even if there isn't a user (hence the need to do this programmatically, there often will not be a user around).  Is there a way to do this (preferably without rooting the device)?  For example, is it possible to set this up so that a user is only prompted once and from that point on it is automatic?

A: Some years ago I encountered that exact same problem while developing a small gateway to collect data from our BLE sensors and push it to our backend over Wi-Fi.
At that time I used a small library publicly available in GitHub which is called WifiUtils. You can find that library following this link.
It was pretty simple to use and you can get a lot of information from the README.md at GitHub.
Enabling Wi-Fi:
WifiUtils.withContext(getApplicationContext()).enableWifi();

Scanning for Wi-Fi networks:
WifiUtils.withContext(getApplicationContext()).scanWifi(this::getScanResults).start();

private void getScanResults(@NonNull final List<ScanResult> results)
{
    if (results.isEmpty())
    {
        Log.i(TAG, "SCAN RESULTS IT'S EMPTY");
        return;
    }
    Log.i(TAG, "GOT SCAN RESULTS " + results);
}

And finally connecting to them:
WifiUtils.withContext(getApplicationContext())
    .connectWith("JohnDoeWiFi", "JohnDoePassword")
    .setTimeout(40000)
    .onConnectionResult(new ConnectionSuccessListener() {
        @Override
        public void success() {
            Toast.makeText(MainActivity.this, "SUCCESS!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void failed(@NonNull ConnectionErrorCode errorCode) {
            Toast.makeText(MainActivity.this, "EPIC FAIL!" + errorCode.toString(), Toast.LENGTH_SHORT).show();
        }
    })
    .start();

As the library has all its code in GitHub, you might find much more information there.

A: Sorry you can't do this...
The best solution for actual Android device connection is launch intent to open WiFi settings and observe the current WiFi network.
To enable WiFi YOU MUST need to ask to the user!!!


text:
Q: Get the latest directory (not the latest file) My folder parent has the following content:
A.Folder B.Folder C.File

It has both folders and files inside. B.Folder is newer. Now I just want to get B.Folder, how could I achieve this? I tried this,
ls -ltr ./parent | grep '^d' | tail -1

but it gives me drwxrwxr-x 2 user user   4096 Jun 13 10:53 B.Folder, but I just need the name B.Folder.

A: ls -td -- ./parent/*/ | head -n1 | cut -d'/' -f2

Difference to Herson's solution is the slash after *, which makes the shell ignore all non-dir files.
Difference to Gnouc, it'll work if you are in another folder.
Cut needs to know the number of parent directories (2) in order to delete trailing '/'. If you don't have that, use
VAR=$(ls -dt -- parent/*/ | head -n1); echo "${VAR::-1}"

A: Try this:
$ ls -td -- */ | head -n 1

-t options make ls sort by modification time, newest first.
If you want remove /:
$ ls -td -- */ | head -n 1 | cut -d'/' -f1

A: Obligatory zsh answer:
latest_directory=(parent/*(/om[1]))

The characters in parentheses are glob qualifiers: / to match only directories, om to sort matches by increasing age, and [1] to retain only the first (i.e. newest) match. Add N if you want to get an empty array (normally you get a 1-elementy array) if there is no subdirectory of parent.
Alternatively, assuming that parent doesn't contain any shell globbing character:
latest_directory='parent/*(/om[1])'; latest_directory=$~latest_directory

If you don't have zsh but you have recent GNU tools (i.e. non-embedded Linux or Cygwin), you can use find, but it's cumbersome. Here's one way:
latest_directory_inode=$(find parent -mindepth 1 -maxdepth 1 -type d -printf '%Ts %i\n' | sort -n | sed -n '1 s/.* //p')
latest_directory=$(find parent -maxdepth 1 -inum "$latest_directory_inode")

There's a simple solution with ls, which works as long as no directory name contains newlines or (on some systems) non-printable characters:
latest_directory=$(ls -td parent/*/ | head -n1)
latest_directory=${latest_directory%/}

A: You can do:
ls -td -- ../parent/* | head -n 1

A: Following command will do the job even in case of directory name containing space :
cp `find . -mindepth 1 -maxdepth 1 -type d  -exec stat --printf="%Y\t%n\n" {} \;  |sort -n -r |head -1 |cut -f2'`/* /target-directory/.

The updated explanation of the stuff in the backticks is:

*

*. - the current directory (you may want to specify an absolute path here)

*-mindepth/-maxdepth - restrict the find command only to the immediate children of the current directory

*-type d - only directories

*-exec stat .. - outputs the modified time and the  name of the directory from find separated with a tab (and not a space)

*sort -n -r |head -1 | cut -f2 - date orders the directory and outputs the entire name of the most recently modified (even if containing some space as cut default delimiter tab)


text:
Q: How to aggregate based on various conditions lets say I have a table which stores itemID, Date and total_shipped over a period of time:
ItemID | Date      | Total_shipped
__________________________________
  1    | 1/20/2000 |   2
  2    | 1/20/2000 |   3
  1    | 1/21/2000 |   5
  2    | 1/21/2000 |   4
  1    | 1/22/2000 |   1
  2    | 1/22/2000 |   7
  1    | 1/23/2000 |   5
  2    | 1/23/2000 |   6

Now I want to aggregate based on several periods of time. For example, I Want to know how many of each item was shipped every two days and in total. So the desired output should look something like:
ItemID | Jan20-Jan21 | Jan22-Jan23 | Jan20-Jan23
_____________________________________________
  1    |  7          |  6          |  13
  2    |  7          |  13         |  20

How do I do that in the most efficient way
I know I can make three different subqueries but I think there should be a better way. My real data is large and there are several different time periods to be considered i. e. in my real problem I want the shipped items for current_week, last_week, two_weeks_ago, three_weeks_ago, last_month, two_months_ago, three_months_ago so I do not think writing 7 different subqueries would be a good idea.
Here is the general idea of what I can already run but is very expensive for the database
WITH
sq1 as (
SELECT ItemID, sum(Total_shipped) sum1
FROM table
WHERE Date BETWEEN '1/20/2000' and '1/21/2000'
GROUP BY ItemID),
sq2 as (
SELECT ItemID, sum(Total_Shipped) sum2
FROM table
WHERE Date BETWEEN '1/22/2000' and '1/23/2000'
GROUP BY ItemID),
sq3 as(
SELECT ItemID, sum(Total_Shipped) sum3
FROM Table
GROUP BY ItemID)
SELECT ItemID, sq1.sum1, sq2.sum2, sq3.sum3
FROM Table
JOIN sq1 on Table.ItemID = sq1.ItemID
JOIN sq2 on Table.ItemID = sq2.ItemID
JOIN sq3 on Table.ItemID = sq3.ItemID

A: I dont know why you have tagged this question with multiple database.
Anyway, you can use  conditional aggregation as following in oracle:
select
    item_id,
    sum(case when "date" between date'2000-01-20' and date'2000-01-21' then total_shipped end) as "Jan20-Jan21",
    sum(case when "date" between date'2000-01-22' and date'2000-01-23' then total_shipped end) as "Jan22-Jan23",
    sum(case when "date" between date'2000-01-20' and date'2000-01-23' then total_shipped end) as "Jan20-Jan23"
from my_table
group by item_id

Cheers!!

A: Use FILTER:
select
    item_id,
    sum(total_shipped) filter (where date between '2000-01-20' and '2000-01-21') as "Jan20-Jan21",
    sum(total_shipped) filter (where date between '2000-01-22' and '2000-01-23') as "Jan22-Jan23",
    sum(total_shipped) filter (where date between '2000-01-20' and '2000-01-23') as "Jan20-Jan23"
from my_table
group by 1

 item_id | Jan20-Jan21 | Jan22-Jan23 | Jan20-Jan23
---------+-------------+-------------+-------------
       1 |           7 |           6 |          13
       2 |           7 |          13 |          20
(2 rows)

Db<>fiddle.


text:
Q: What is a "step"? Certain things in the game occur when you have taken x steps. Happiness, egg production/hatching, etc are all determined by the number of steps you have taken.
In previous Pokemon games, it is immediately obvious when you take a step. You press up, your character moves one step. There are only four directions to move in, and each step is locked to a grid.
In X/Y, however, movement is more fluid. I can take what seems to be a "partial step" by bumping the analog stick quickly, or move at an angle that wasn't possible before. In addition, there's no built-in step counter (like the Poketch app for DPPT), so it seems I have no way of knowing at all what a step is.
Is there a specific distance that counts as one step? If so, what is it? When moving at an angle, is the distance Euclidean (e.g. ~√2 steps if I'm moving at 45 degrees for one unit in both x/y directions)?

A: You can move in 'steps' on the underlying grid in Pokemon X/Y by using the D-Pad for movement instead of the Circle Pad.
While I can't necessarily verify this, I have a hunch that the step counter when using the Circle Pad is indeed based on trigonometric principles - if only because if this wasn't the case, we'd see in guides everywhere to avoid diagonal movement to conserve Repels, or to move diagonally to expedite egg hatching.


text:
Q: I need a straight forward simple how to for nautilus clutter I have followed many how-to videos, but those just wont work. Could someone tell me or link me to a straightforward working video? I currently do not have nautilus-elementary installed, in the past I've installed it but the function still didn't work.

A: Install Nautilus elementary with clutter view from ppa using the link below
How to install nautilus elementary on ubuntu 10.10 with clutter view from ppa
and if you see only a blank screen when you try to enable clutter view it's a bug try this link for a work around.
How to fix the blank screen on clutterview problem on ubuntu 10.10 maverick meerkat
Hope this answers all your queries


text:
Q: jQuery: Shows an error while adding name attribute to elements - setAttribute is not a function I have a dynamic table where a button on click adds a new row. I want to add a name attribute each time new row created.
Here's my code:
$(function() {
  const $tb = $('#service-table tbody');
  $("tr",$tb).eq(0).hide();
  $("#serviceAdd").on("click",function() {
    const $row = $tb.find("tr").eq(0).clone();
    $row.show();
    $row.find("select").val("").attr("name", "service_id[]"); // reset the select
    $row.find(".s_qty").val().attr("name", "s_qty[]"); // reset the numbers
    $row.find(".s_total").val().attr("name", "s_total[]"); // reset the numbers
    $tb.append($row);

  });
});

It shows error Uncaught TypeError: $row.find(...).val(...).attr is not a function
I have tried with many changes but it shows the same error.
How can I add attribute to new rows?


text:
Q: Alternative to `unwrap()` when `T` does not implement `Debug` I am aware that x.unwrap() when x: Result<T, E> does not work when E does not implement Debug: unwrap() would need to print out the Err variant in case x.is_err() but it cannot. Sometimes, however, especially in tests, I do need to get my hands on the Ok value. I assumed x.expect() would do the trick, as I am the one that specifies the message upon failure. And yet, for some reason I don't completely understand, expect(), too, requires E: Debug. This means that I always end up taking the verbose, repetitive way:
   let x_ok = match x {
      Ok(x_ok) => x_ok,
      Err(_) => panic!("Something went horribly wrong!"),
   }

I cannot imagine there wouldn't be a more standardised solution to this problem, and yet I struggle to find one. How does one quickly get_ok_or_panic if the Err type of a Result does not implement Debug?

A: Idiomatic code would just forward the error:
fn do_it() -> Result<(), E> {
   let x_ok = x_ok?;
   // work with x_ok
   Ok(())
}

or handle the error gracefully where possible:
let x_ok = x_ok.unwrap_or(sane_default);

If neither is an option and you absolutely have to panic you can use let … else:
let Ok(x_ok) = x_ok else { panic!("Something went horribly wrong") };

A: The typical workaround is to use unwrap_or_else():
let x_ok = x.unwrap_or_else(|_| panic!("Something went horribly wrong!"));


text:
Q: Get category of a discussion from discussion folder using /jquery/spservices/ below is the code for the same which shows an error of status 500, at alert status it shows error. let me know how to do that

var _query = ""+discussionTitle+"";
             alert(_query);

$().SPServices({
    operation: 'GetListItems',
    async: false,
    listName: '',
    CAMLQueryOptions: "",
    CAMLViewFields: "",
    CAMLQuery: _query,
      completefunc: function (xData, Status) {
                   **alert(Status);**
                    $(xData.responseXML).SPFilterNode("z:row").each(function() {
            alert("Hi");
          var NewCategory=$(this).attr('Category');
          alert(NewCategory);

                        });
                    }

        });


text:
Q: Downloading the data from LAADS using Python wget code equal to the wget command I'm trying to download data from LAADS using Python Script
and using the order link Data page. But I couldn't download the data.
Now I want to create the script on python using wget /or other packages. I have used this line of codes and the output is given:
wget code, I couldn't understand the error message. I also dont know how and where to use the App Key.
So, finally, I want the necessary suggestion to create the python script which gives the output as wget command in the command-line window.

A: From your link, it seems that you didn't escape the backslash characters in you wget.download statement, therefore python thinks that '...\Nov18' should be a \N{name} unicode literal, which is malformed - hence the complaint. Try
wget.download(url2, out='D:\\Data\\AOD\\S18M19\\Nov18')


text:
Q: More efficient way to view changes on a mobile device without pushing rails app to heroku? Probably a dumb question:
Right now, to see changes made in development, I run rails s and see the changes on the local version of my site.  To see how changes look on my phone, I currently commit to Git (no matter how small the changes) and then push to heroku.  This takes some time and results in lots of commits and deployments for minor changes (i.e. CSS stuff).
What is a more efficient way to test changes for rails web apps on mobile?
NOTE: I am aware I can shrink my browser but it never fails I get different outcomes on my phone.
Any help is appreciated.
RELATED: how do i run a development rails app / website on an ipod

A: You can also use Nitrous.io which is a cloud development environment. I like it because not only can I view my work on mobile, but since it's a hosted URL, I can share it with others while my server is running.

A: 1) connect your phone to the same network that your local server is running on and point it to http://[your server's ip]:3000
2) use the XCode iOS Simulator and/or the Android Emulator

A: you can also use ngrok
https://ngrok.com/
which gives you a way to make an external tunnel to the outside world (for free) so you can use it outside of your local network


text:
Q: C# and Data Execution Prevention (Vista) I was writing a small program and have some problems with DEP, what I want to do is to open files stored on another windows-share, my code looks like this:
foreach (string file in files)
{
    Process.Start(file);
}

files is a simple string array with file locations (for example "\myshare\dir\picture.jpg"). This code works without any problems on XP but trying to run in with windows vista throws exceptions and a message pops up that Data Execution Prevention stopped my prog. How can I fix that? I red about NXCOMPAT already but maybe there is a right way how to open files in C#?
Greetings
J

A: This is most likely not a problem with your code. Microsoft wouldn't leave serious bugs like attempting to execute NX pages in the .NET Framework. The problem may be caused by anything from anti-virus/security software to actual viruses.


text:
Q: Is it possible to create a new RSpec matcher by composing existing ones? In one of my specs, I find myself repeating lines like these often:
expect(result.status).to be(:success)
expect(result.offers).not_to be_empty
expect(result.comments).to be_empty

To make my tests more succinct and readable, I want to compose these into a line like this:
expect(result).to be_successful

I can do this by creating a custom matcher:
matcher :be_successful do
  match { |result|
    result.status == :success &&
    result.offers.length > 0 &&
    result.comments.empty?
  }
end

But I now have a failing test, and the failure message is completely useless. All it says now is Expected #<Result ...> to be successful.
I know I can override the failure message, but now this solution is getting more complicated than it's worth for saving 2 lines for every spec example. The original 3 lines generated useful failure messages, all I wanted to do was combine them into 1 line.
I could move the 3 lines into a separate function (e.g. assert_successful) and call that from each spec example, but I'd like to keep the matcher syntax.
Can this be done?

A: According to this
You could do something like this:
RSpec::Matchers.define :be_successful do

  match do |result|
    result.status == :success &&
    result.offers.length > 0 &&
    result.comments.empty?
  end

  failure_message do |result|
    "Should have #{result} equal to be successful"
  end

  failure_message_when_negated do |result|
    "Should not have #{result} to be successful"
  end
end

If you reuse this test elsewhere more than 3 times, then it makes sense to create a new matcher and override the failure messages(It's not an overhead). If you use this test only one time then it makes sense to keep it without overly abstract it.

A: One way of organizing this is: Put the real testing code into
a method _check_ok(expected, actual) of its own,
which returns either [true] or [false, message].
This is called as follows:
  RSpec::Matchers.defined :check_ok do |expected|
    match do |actual|
      return _check_ok(expected, actual)[0]
    end
    failure_message do |actual|
      return _check_ok(expected, actual)[1]
    end
  end

This repeats the _check_ok call in the failure case,
which normally isn't a problem.


text:
Q: Raise Application Error when user enters duplicate primary key in PHP app from Oracle I'm not sure where to start to raise an error in my php app from oracle. I need to raise an error whenever the user (which would be us here) enters a duplicate primary key, foreign key violation or even not null values. The thing is, i'm not sure where to start, do i need to use a trigger here ?
Look at the code below, i think i'm almost there but i'm not sure what to do from now on. This is just the code for my primary key error. Of course, i assume that if i can make this one work, the others error should not be too hard to code after that
create or replace trigger TRG_PRIMARY_KEY_TYPE_ENCAN
    before insert or update on TP2_TYPE_ENCAN

declare

    cursor PRIM_KEY is
    select CODE_TYPE_ENC FROM TP2_TYPE_ENCAN;
    V_CODE_TYPE_ENCAN char(2);

begin
    select CODE_TYPE_ENCAN into V_CODE_TYPE_ENCAN from TP2_TYPE_ENCAN;
    for V_CODE in PR_KEY
    loop
    if V_CODE = V_CODE_TYPE_ENCAN then
    raise_application_error(-20050, 'Key duplicate');
    end if;

    end loop;

end TRG_PRIMARY_KEY_TYPE_ENCAN;

I am excepting my raise_application_error message to show in my php app to show that there's a 'Key duplicate'.

A: At the SQL level you can add constraints when you create the table.  You probably won't need the PL/SQL trigger.  Search for 'check constraint' e.g. at https://asktom.oracle.com/
Then in PHP, check the error return codes that the DB will return.  See https://www.php.net/manual/en/function.oci-error.php e.g.
<?php
$stid = oci_parse($conn, "your SQL statement goes here");
$r = oci_execute($stid);
if (!$r) {
    $e = oci_error($stid);  // For oci_execute errors pass the statement handle
    print htmlentities($e['message']);
    print "\n<pre>\n";
    print htmlentities($e['sqltext']);
    printf("\n%".($e['offset']+1)."s", "^");
    print  "\n</pre>\n";
}
?>


text:
Q: Why the magnetic flux is not zero? If $\vec{\mathbf B}=B\vec{\mathbf a}_z$, compute the magnetic flux passing through a hemisphere of radius $R$ centered at the origin and bounded by the plane $z=0$.

Solution
The hemisphere and the circular disc of radius $R$ form a closed surface, as illustrated in the figure; therefore, the flux passing through the hemisphere  must be exactly equal to the flux passing through the disc.
The flux passing through the disc is
$$\Phi=\int_S\vec{\mathbf B}\cdot\mathrm d\vec{\mathbf s}=
\int\limits_0^R\int\limits_0^{2\pi}B\rho\,\mathrm d\rho\,\mathrm d\phi
=\pi R^2B$$
The reader is encouraged to verify this result by integrating over the surface of the hemisphere.

According to Maxwell's equations the magnetic flux over a closed surface must be zero, why in this case does not happen?

A: According to Maxwell's equations the magnetic flux over a closed surface must be zero.
In this case the hemispherical surface in question is not a closed surface, it is an open surface.
If we consider the closed surface (the hemispherical section And the circular base)
the total flux passing through will be zero.
Using this information it is clear that the flux leaving thought the hemisphere will be equal in magnitude and opposite in sign to the flux entering through the circular base.

A: The flux through the closed hemisphere is zero,
$$\Phi_{\mathrm{hemi}}+\Phi_{\mathrm{disk}} = 0.$$
This allows us to find the flux through the hemisphere knowing the (more easily calculable) flux through the disk,
$$\Phi_{\mathrm{hemi}} = -\Phi_{\mathrm{disk}}.$$

A: the net flux is always zero , and it's satisfies the Maxwell equation , in the answer firstly the flux through disc has been calculated next using the fact that the net flux must be zero we can conclude the flux of hemisphere must be equal to the flux though the disc but with opposite sign namely : flux through hemisphere + flux through disc = 0


text:
Q: Best preposition choice
The playlist was played with the songs sung by the popular singers.

The playlist was played in the songs sung by the popular singers.

Which preposition would be better in these sentences in or with?

A: The first example feels a bit convoluted, but is generally correct. The second example is plainly wrong ;)
Let's start with the second example:

The playlist was played in the songs sung by popular singers.

would mean that the playlist was played in the songs, like for example a band is playing in the concert hall. That just doesn't work ;)
On the other hand

The playlist was played with the songs sung by the popular singers.

would technically mean that the playlist was played by using the songs of popular singers, like using a tool. While the sentence is grammatically correct, you would probably just say something like

They played a list of songs by popular singers.

Some side notes:

*

*It's often considered good style not to repeat words or similar words in short order. So if you're already use "to play" in the sentence, maybe don't use "playlist", but just "list". If you're already using "songs", don't use "to sing", but maybe "to perform" (or no verb at all, like in the example above). Same for "singers", which could be replaced with "artists" or "performers", and so forth. Of course, if you specifically mean "singers" and not the more general "performers", for example, you sometimes can't help it.

*You don't have to use the definite article all the time. If you don't want to refer to some specific "the songs by popular artists", just "songs by popular artists" is completely fine. That would refer to some songs that are from popular artists, but not to any specific group of songs. Of course, if you want to refer to specific songs, specific artists and so forth, you use the definite article.

*It's also considered good style to use the passive voice only when there's a reason to use it. So, instead of "the playlist was played", maybe just use "They played the playlist".

A:
The playlist was played with the songs sung by the popular singers.

This preposition is correct since with is a kind of a word accompanied by another term. While in is usually used for words referring to either things inside something, or a date( for example, 1952 and 2012), movements made, etc.
Also, if you read both sentences the 1st example sounds more natural and is grammatically correct rather than the 2nd one.


text:
Q: Abdera SSLHandshakeException I have a litte problem with the SSL Handshake, with I try to launch a GET request, the server return me  java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException.
I'm using Abdera for the connection with the Connections Server, and on Websphare I did install the SSL of the Connections Site, but this din't work, my code it's:
public static void send(HttpServletRequest req, HttpServletResponse respo) throws Exception {
    String back = "";

    String connectionsUser = req.getHeader("user");
    String connectionsPassword = req.getHeader("password");

    Abdera abdera = new Abdera();
    AbderaClient abderaClient = new AbderaClient(abdera);

    AbderaClient.registerTrustManager();

    System.out.println(connectionsUser + "    " + connectionsPassword);
    abderaClient.addCredentials(Utils.configJson.getString("connectionsServer"), null, null, new UsernamePasswordCredentials(connectionsUser, connectionsPassword));

    ClientResponse resp = abderaClient.get(Utils.configJson.getString("connectionsServerURL") + Utils.configJson.getString("profileService"));

and the log it's:
[8/27/15 17:14:56:663 CDT] 0000007c SystemErr     R java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
[8/27/15 17:14:56:664 CDT] 0000007c SystemErr     R     at org.apache.abdera.protocol.client.AbderaClient.execute(AbderaClient.java:701)
[8/27/15 17:14:56:664 CDT] 0000007c SystemErr     R     at org.apache.abdera.protocol.client.AbderaClient.get(AbderaClient.java:216)
[8/27/15 17:14:56:664 CDT] 0000007c SystemErr     R     at org.apache.abdera.protocol.client.AbderaClient.get(AbderaClient.java:404)
[8/27/15 17:14:56:664 CDT] 0000007c SystemErr     R     at com.cemex.services.ProfileServiceDo.send(ProfileServiceDo.java:71)
[8/27/15 17:14:56:664 CDT] 0000007c SystemErr     R     at com.cemex.services.ProfileServiceDo.doGet(ProfileServiceDo.java:38)
[8/27/15 17:14:56:664 CDT] 0000007c SystemErr     R     at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
[8/27/15 17:14:56:664 CDT] 0000007c SystemErr     R     at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
[8/27/15 17:14:56:664 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1230)
[8/27/15 17:14:56:664 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1071)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3774)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:981)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:453)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:515)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:306)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:277)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
[8/27/15 17:14:56:665 CDT] 0000007c SystemErr     R     at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R     at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R     at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R     at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R     at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R     at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R     at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R     at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R     at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1702)
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
[8/27/15 17:14:56:666 CDT] 0000007c SystemErr     R     at com.ibm.jsse2.o.a(o.java:36)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at com.ibm.jsse2.o.a(o.java:43)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at com.ibm.jsse2.SSLSocketImpl.b(SSLSocketImpl.java:32)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at com.ibm.jsse2.SSLSocketImpl.a(SSLSocketImpl.java:626)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at com.ibm.jsse2.SSLSocketImpl.h(SSLSocketImpl.java:39)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at com.ibm.jsse2.SSLSocketImpl.a(SSLSocketImpl.java:696)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at com.ibm.jsse2.k.write(k.java:26)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:76)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:134)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at org.apache.commons.httpclient.HttpConnection.flushRequestOutputStream(HttpConnection.java:827)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.flushRequestOutputStream(MultiThreadedHttpConnectionManager.java:1525)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:1975)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:993)
[8/27/15 17:14:56:668 CDT] 0000007c SystemErr     R     at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:397)
[8/27/15 17:14:56:669 CDT] 0000007c SystemErr     R     at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)
[8/27/15 17:14:56:669 CDT] 0000007c SystemErr     R     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
[8/27/15 17:14:56:669 CDT] 0000007c SystemErr     R     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)
[8/27/15 17:14:56:669 CDT] 0000007c SystemErr     R     at org.apache.abdera.protocol.client.AbderaClient.execute(AbderaClient.java:688)
[8/27/15 17:14:56:669 CDT] 0000007c SystemErr     R     ... 30 more

you have idea that happen with the SSL or how resolve?
thaks.

A: You should import the Connections Server into the CellDefaultTrustSTore if you are running the application on a WebSphere Application Server.
You can refer to security certificates to https://www-01.ibm.com/support/knowledgecenter/SSYGQH_5.0.0/admin/install/t_exchange_keys_network.dita
Log into the IBM WebSphere Application Server Integrated Solutions Console and select Security > SSL Certificate and key management > Key stores and certificates.
Click CellDefaultTrustStore.
Click Signer Certificates.
Click Retrieve from port.
Enter the Host name, SSL Port, and Alias of the web server. The Alias is typically an arbitrary string that will become the name of the credentials.
Click Retrieve Signer Information and then click OK. The root certificate is added to the list of signer certificates.

You have to sync the node afterwards


text:
Q: Rails wrong number of arguments (1 for 0) when passing no arguments to custom action I promise i've looked through all the similar answers, but I'm new to Rails and just have no idea what I'm doing.  Anyway...
I have a UsersController with a method customer.  I don't know if this method works or not, I haven't made it far enough to see what errors pop up.
64     def customer
65        begin
66          customer = Stripe::Customer.retrieve("hardcodedidfornow")
67        rescue Stripe::StripeError => e
68          status 402
69          return "Error retrieving customer: #{e.message}"
70        end
71      status 200
72      content_type :json
73      customer.to_json
74    end

I defined that method in my routes as such
namespace :api do
    namespace :v1 do
      resources :users, only: [:index, :create, :show, :update, :destroy] do
        member do
          get :customer
        end
      end
    end
end

Then I call it from my iOS app with GET at this route and no extra parameters
http://baseurl.com/api/v1/users/theuserid/customer

And I always get internal server error 500 and when I check the logs it says wrong number of arguments (1 for 0).
Processing by Api::V1::UsersController#customer as JSON
2016-10-07T05:04:59.087546+00:00 app[web.1]: Started GET "/api/v1/users/5/customer" for 162.237.102.13 at 2016-10-07 05:04:59 +0000
2016-10-07T05:04:59.135976+00:00 app[web.1]:   Parameters: {"id"=>"5", "user"=>{}}
2016-10-07T05:04:59.568989+00:00 heroku[router]: at=info method=GET path="/api/v1/users/5/customer" host=someapp.herokuapp.com request_id=7f0f76bd-4577-40b0-9eb6-265787cf3d5c fwd="162.237.102.13" dyno=web.1 connect=0ms service=496ms status=500 bytes=259
2016-10-07T05:04:59.578541+00:00 app[web.1]:
2016-10-07T05:04:59.577583+00:00 app[web.1]: Completed 500 Internal Server Error in 441ms (ActiveRecord: 3.7ms)
2016-10-07T05:04:59.578543+00:00 app[web.1]: ArgumentError (wrong number of arguments (1 for 0)):
2016-10-07T05:04:59.578544+00:00 app[web.1]:   app/controllers/api/v1/users_controller.rb:71:in `customer'

So I guess I'm looking for a solution but also an understanding of where i've gone wrong so I can handle this better in the future.
Thanks!


text:
Q: LTSpice, can I have separate plot panes? I have LTSpice for mac.
I can add more than one plot pane in the same window.
Can I have plot panes in separate windows? (In order to have diagrams with different dimensions on my desktop)

A: Unfortunately, that's not possible. But you can run multiple instances of LTspice and you can load the .raw file and select whatever traces you have. The downside is that after each run, the .raw file will need reloading for each of the external instances of LTspice.
One thing that could help is to save the plot settings (make the waveform window active, click save). Then, when loading the .raw file externally, the waveform window will show the saved traces.
Or you could use the .step command to get all the desired traces inside one plot, in the same window.


text:
Q: Every ridge in the convex polytope is an intersection of exactly two facets This statement is used without proof in various sources (incl. Ziegler's "Lectures on polytopes" and Gruber's "Convex and discrete geometry"), yet I don't have any idea how to prove it, or have intuition about it in $n>3$ dimensions. Someone suggested me to use a concept of dual polytope to prove it, I have not explored it thoroughly and maybe someone can help with understanding how duality is convenient here.

A: You do not need to know what the dual poltype is in detail, but it is helpful to known about the face-lattice.
All you need is that the dual polytope has the same face-lattice as the original polytope, but turned up-side-down, in particular, every $\delta$-dimensional face of the original polytope becomes a $(d-\delta-1)$-dimensional face of the dual.
The facets are the faces of dimension $d-1$, and the ridges are the faces of dimension $d-2$.
In the dual polytope, every facet becomes a vertex (face of dimension $0$), and every ridge becomes an edge (face of dimension $1$).
Obviously, every edge of the dual contains exactly two vertices.
Since the face-lattice of the dual and the face-lattice of the original are so similar, this statement translates to "every ridge $R$ of the original polytope is contained in exactly two facets, say $F_1$ and $F_2$".
You known that the intersection of faces of a polytope is again a face of that polytope.
So what could the intersection $F_1\cap F_2$ be?
This intersection is a face that contains the ridge $R$ since both facets contain this ridge.
Since the ridge is of dimension $d-2$, the only faces that can contain $R$ are $R$, $F_1$, $F_2$ and maybe another facet (and the polytope itself).
But we have discussed previously that $F_1$ and $F_2$ are the only facets that contain $R$.
Hence $F_1\cap F_2=R$.

A: Your quest on proving that statement is just like proving that there is just a single parallel line to a given line. The latter seems obviously true within euclidean spaces, so one might be tempted to prove it, but it is neither true in spherical (less than 1) nor in hyperbolical ones (more than 1). In fact, in history right that trial to prove it by means of a contradictional attempt directly lead to the discovery of those other space types.
And in fact quite similarily, there are polytopes, which have 2 facets per ridge (the usual real space polytopes), but there are realizations of according abstract polytopal structures with 3 or more facets per ridge. This then is the realm of so called complex polytopes.
Cf. to https://en.wikipedia.org/wiki/Complex_polytope


text:
Q: FTS3 searches in ORMLite? I know nothing about FTS3, except that http://developer.android.com/guide/topics/search/search-dialog.html says

performing a full-text search (using FTS3, rather than a LIKE query)
  can provide a more robust search across text data and can produce
  results significantly faster

I don't see any mention of FTS3 in the ORMLite documentation, though. Is there a way to do this?

A: Sorry but there is no direct support for this in ORMLite.  If the underlying database supports this then you can use ORMLite's raw query interface to process a raw query to the database.  See the documentation here:

http://ormlite.com/docs/raw-queries


text:
Q: Is there a way to make executionTimeout take effect while debugging? I would like to debug a website, but also cause the httpRuntime executionTimeout setting to take effect. However, the documentation says:

This time-out applies only if the
  debug attribute in the compilation
  element is False.

Is there any way to enable executionTimeout when debug="True"?

A: After more than a week of searching and trying various hacks, I'm confident in saying that, as of now, there is no reasonable way to have the httpRuntime executionTimeout setting take effect while the compilation debug flag is set to true.
One possible terrible hack workaround is to somehow trick the system into thinking that more than 30,000,000 seconds (just over 347 days) have elapsed, which is what executionTimeout is overridden to when debug is true.

A: If you use ASP.NET MVC then this may help.
ASP.NET MVC (version < 4) doesn't support this timeout.

A: That's interesting, because I have debugging sessions timeout on me all the time when I'm just sitting there looking at the code.  Is there another timeout value that is handled by IIS rather than ASP.NET?


text:
Q: How to avoid insert empty record in mongodb using mongoose In my script i can create a new collection in mongodb but default one empty record is inserting so how to avoid that.
model.js:
 /* model.js */
 'use strict';

 var mongoose = require('mongoose'),
 Schema = mongoose.Schema;

 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String
    }

   });
   return mongoose.model(suffix, addressSchema);
  }
  module.exports = dynamicModel;

data.controller.js:
      var NewModel = require(path.resolve('./models/model.js'))(collectionName);
      NewModel.create({ category: 1, title: 'Minion' }, function(err, doc) {

      });

after created new collection I am seeing like this:
  _id:ObjectId("5eceb362d538901accc0fefe");
  __v:0

A: You must define these attributes in your model.
 /* model.js */
 'use strict';

 var mongoose = require('mongoose'),
 Schema = mongoose.Schema;

 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String,
    },
    category: {
       type: Number,
    },
    title: {
       type: String,
    }

   });
   return mongoose.model(suffix, addressSchema);
  }
  module.exports = dynamicModel;


text:
Q: What are these extra processes? In my Electron app, I have my main process and two renderer windows open.  Why does Task Manager show 8 "electron.exe" processes?  I would expect it to be 3.
Thanks.

A: Extra processes are electron listeners.
A new process will spawn every time you add a listener to ipcMain or ipcRenderer.
Example:
ipcRenderer.on("data", (e, data) => {
  console.log("this will spawn a process")
})

More:

*

*If you start your app:

*

*

*If you add a listener:

*

*

*If a window is visible, Windows joins them all in a group:

*

*
Just wondering if there's any way to specify a process id or something to join them together...


text:
Q: What is the recommended way to work with multiple (nested) SQL Server queries using C#? I have a scenario where I query my SQL Server DB, obtain the results, and based on the results, make subsequent queries to the DB again. Following is how I've structured my code for the same:
What I'm interested in knowing is, that is this the correct way to deal with such scenarios?
Should I be doing something else alternatively? Like, make the first call to the DB, load all the results in a dictionary, then make the next calls and use the result stored in the dictionary to make these next calls
(If you feel you need context on what my code does - I want to add a uniqueness constraint and index over columns ColA, ColB, and ColC on MyTable, but I can't directly apply the uniqueness constraint. There are some existing violations over these columns. So I first resolve these violations by changing the value of ColC for the entries that cause the violation, and after fixing all violations, I add the constraint)
void Main() {

    using(SqlConnection connection = new SqlConnection(@"Data Source=localhost; Initial Catalog=mydatabase; Integrated Security=True; MultipleActiveResultSets=true"))
    {
        connection.Open();

        //Check if the index exists over Columns ColA_ColB_ColC without the uniqueness constraint
        SqlCommand myCommand = new SqlCommand(@"SELECT 1 FROM sys.indexes
                                WHERE name = 'UQ_ColA_ColB_ColC'
                                AND object_id = OBJECT_ID('MyTable')
                                AND is_unique = 0");
        SqlDataReader myReader = myCommand.ExecuteReader();
        if(myReader.HasRows)
        {
            try {

                //Get the unique values that exist (ColA,ColB,ColC) tuple
                myCommand = new SqlCommand(@"select count(*) as count,
                                                        ColA,ColB,ColC
                                                        from [apimanagement.local].[dbo].[MyTable]
                                                        group by ColA,ColB,ColC ", connection);

                SqlDataReader myReader = myCommand.ExecuteReader();
                while (myReader.Read()) {

                    //For each of the unique values, get all the rows that have that value
                    SqlCommand myCommand2 = new SqlCommand(@"select Id,ColA,ColB,ColC from MyTable
                    where ColA=@ColA and ColB=@ColB and ColC=@ColC", connection);
                    myCommand2.Parameters.AddWithValue("@ColA", myReader["ColA"].ToString());
                    myCommand2.Parameters.AddWithValue("@ColB", myReader["ColB"].ToString());
                    myCommand2.Parameters.AddWithValue("@ColC", myReader["ColC"].ToString());

                    int index = 2;
                    SqlDataReader myReader2 = myCommand2.ExecuteReader();
                    myReader2.Read(); //Read the first row off the results

                    //If more rows exist, then we have violations for the uniqueness constraint over (ColA,ColB,ColC)
                    //fix these violations by appending indices to the ColC value
                    while (myReader2.Read()) {
                        SqlCommand myCommand3 = new SqlCommand(@"UPDATE MyTable
                                                                SET ColC=@NewColC
                                                                WHERE Id=@Id", connection);

                        myCommand3.Parameters.AddWithValue("@Id", myReader2["Id"].ToString());
                        myCommand3.Parameters.AddWithValue("@NewColC", myReader2["ColC"].ToString()+index);

                        bool changedSuccessfully = false;
                        while(!changedSuccessfully)
                        {
                            try
                            {
                                myCommand3.ExecuteNonQuery();
                                index++;
                                break;
                            }
                            catch(SqlException e)
                            {
                                if((uint)e.HResult == 0x80131904)
                                {
                                    index++;
                                }
                                else
                                {
                                    throw e;
                                }

                            }
                        }
                    }
                }

                //After all the violations are fixed, we create an index over (ColA,ColB,ColC) with the uniqueness constraint
                myCommand = new SqlCommand(@"DROP INDEX UQ_ColA_ColB_ColC on [MyTable];
                CREATE UNIQUE NONCLUSTERED INDEX [UQ_ColA_ColB_ColC] ON [MyTable]([ColA] ASC, [ColC] ASC, [ColB] ASC) WHERE [ColB] != 3");

                myCommand.ExecuteNonQuery();

            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }

    }
}

A: Well - I'd say your SqlDataReader handling is wrong.
Wrap them in a usingto avoid connection leaks:
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
//do stuff with myReader here.
} //using clause will ensure dispose

//do remainder stuff outside here.

Also only have the connection open as short a time as possible. Connection pooling will limit most all of the overhead with opening/closing connections while leaving you free to not worry about. Keeping connections open too long can hinder performance.
Outside those tips - the "recommended" way to structure is extremely subjective and logic dependant.
Basically - it comes down to how much data needs to be moved around between the server and your application. Also letting the database do the work it is optimized for and letting your code do the work .NET is optimized for - meaning how much of it can/should be kept in the database and how much data should be moved to your code layer.
A lot of that comes from experience and basically trying it out and then performance tuning it to see what it does best.
Edit: Saw your comment that this is a one time thing you'll not run again. Then I wouldn't worry at all and just do it the easiest way for you now and then move on.
Because then it's rarely cost effective to fiddle about too much and time is better spend on actual problems :)


text:
Q: How to evaluate the following integral? $\int\frac1{1+\sqrt{\tan x}}\mathrm dx.$
Evaluate the following integral:
  $$\int\dfrac1{1+\sqrt{\tan x}}\mathrm dx.$$

I know this question has a solution, but I haven't the slightest idea
how to do it.

A: $t=\sqrt{\tan(x)}$ then we get $x=\arctan(t^2)$ and $dx=\frac{2tdt}{1+t^4}dt$ and we get the integral
$\int\frac{2tdt}{(1+t)(1+t^4)}$


text:
Q: Weak and weak* convergence on Banach spaces I'm trying to understand weak and weak* convergence. These two statements are used in a proof of a theorem.
Let $(X, \vert \vert \cdot \vert \vert_X )$ and $(Y, \vert \vert \cdot \vert \vert_Y )$ be Banach spaces.
(1) $(x_n)_n$ converges in $X$ to $x \in X$. If
$ \ x^*_n \overset{w^*}{\underset{n \rightarrow \infty}{\rightarrow}} x^* \in X^*$,
then $lim_{n \rightarrow \infty} \langle x_n, x_n^* \rangle =  \langle x, x^* \rangle.$ Why does this equotion hold? And why it does not if $x_n \overset{w}{\underset{n \rightarrow \infty}{\rightarrow}} x$?
(2) $(x_n)_n$ converges weakly in $X$ to $x \in X$. If $(x_n^*) \in X^*$ converges to $x^*$, then $lim_{n \rightarrow \infty} \langle x_n, x_n^* \rangle =  \langle x, x^* \rangle.$ Same here: Why does it  hold? And why it does not if $x^*_n \overset{w^*}{\underset{n \rightarrow \infty}{\rightarrow}} x^*$?

A: If $x_n^{*} \to x^{*}$ in weak* topology and $x_n \to x$ in the norm then $$|x_n^{*}(x_n) - x^{*}(x)| \leq |x_n^{*}(x_n) - x_n^{*}(x)|+|x_n^{*}(x) - x^{*}(x)|$$ $$ \leq \|x_n^{*}\| ||x_n-x\|+|x_n^{*}(x) - x_n^{*}(x)|.$$ The second term tends to $0$ by weak* convergence of $(x_n^{*})$ and the first term tends to $0$ because $\|x_n^{*}\|$ is bounded.
For a counter-example when we only have weak convergence of $(x_n)$ consider a Hilbert  space with orthonormal basis $(e_n)$. Take $x_n=x_n^{*}=e_n$ and $x=x^{*}=0$.
2) is proved similarly.


text:
Q: How to pass phone number to phone application from scope I'd like to be able to pass a phone number to the phone application from within a preview of a scope.

*

*Is that possible?

*Is it done with action widgets?

*Is there an example
of this somewhere in JavaScript?

A: You are able to do it by specifying a tel: URI in a actions preview widget's url, e.g.:
var actions_widget = new scopes.lib.PreviewWidget("actionsId", "actions");
actions_widget.add_attribute_value(
  "actions",
  [
    {
      "id": "call",
      "label": "Call",
      "uri": "tel:+555555555"
    }
  ]
);

in the run() callback as you create a PreviewQuery


text:
Q: 301 redirect for old urls with language parameter I need a hand with some 301 redirects for my apache htaccess file. The old urls contain variables at the end and have structures like the following:
/furniture-248/category/570-shelves.html?lang=en
/all-products/furniture-248/shelves.html?page=2&lang=en
/store/product/asearch.html?path=7_632&lang=en&Itemid=284

The new urls don't contain parameters of this nature and would be simply of the form:
main-cat/subcat/sale.html

I tried a regular 301 redirect in the htaccess file which works for urls without parameters but those urls containing the ?lang=en simply don't work.
This is what I was trying:
Redirect 301 /furniture-248/category/570-shelves.html?lang=en http://www.domain.com/shelves.html

I'd be very grateful for any help and advice.
Many thanks in advance

A: You can't use the query string as part of a redirect like that. You have two options.
Option 1
Take the "?lang=en" part off and just redirect all instances of that URL, whatever the query string is.
Redirect 301 /furniture-248/category/570-shelves.html http://www.domain.com/shelves.html

This will leave the query string intact, so the new URL will include "?lang=en" if it is present, or any other query string.
But of course, you might need to only redirect it when it has the "?lang=en" part, or leaving the query string intact when redirecting might not be acceptable. In that case, it will need to be...
Option 2
Use mod_rewrite:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^lang=en$
RewriteRule ^furniture-248/category/570-shelves\.html$ http://www.domain.com/shelves.html? [R=301,L]

This does exactly what you asked for, redirecting /furniture-248/category/570-shelves.html?lang=en to http://www.domain.com/shelves.html and only that.
Note that..

*

*The query string is matched separately.

*The opening forward slash on the matching part is not used (because the fact you're in a website root level .htaccess file implies that opening slash).

*The closing question mark on the redirect URL is important, as it tells the engine to drop the existing query string, which is what you want.

*[R=301,L] means do a 301 redirect and don't process any more URL rewriting on this URL.

*For the matching part in RewriteRule, the dot before "html" is escaped with "\" because dot has a special meaning in a regex.

*Also for the matching parts, in both RewriteCond and RewriteRule, the ^ means the start of the string and the $ means the end of it, so that we are matching exactly that rather than it being possible for it to be part of a longer string.
And finally, if you're adding a number of these, you only need the "RewriteEngine On" part once, at the top. The other two parts are needed for each one.
Please be sure to test all redirects you add with this method as there is more to mod_rewrite than I have mentioned in this simple explanation.


text:
Q: Cloud Functions Firestore import doesn't work I'm trying to use Firestore from Cloud functions package like this:
export async function deleteDocRecursively(docRef) {
    await Firestore.recursiveDelete(docRef);
}

This works:
const {Firestore} = require('@google-cloud/firestore');

This doesn't work:
import {Firestore} from '@google-cloud/firestore';

I get this error:

TS2339: Property 'recursiveDelete' does not exist on type 'typeof Firestore'.

https://www.npmjs.com/package/@google-cloud/firestore

A: You are using client firestore inside firebase functions instead you should use the one which comes with admin one.
As you are using client firestore
const {Firestore} = require('@google-cloud/firestore');

Above one is working and
import {Firestore} from '@google-cloud/firestore';

Is being failed and getting below error
Property 'recursiveDelete' does not exist on type 'typeof Firestore'.

To get it work you have to use the admin one as this will run on the server.
As Firebase client SDK is meant to run in a client-side environment hence we use Client SDK using firebaseConfiguration listed in the firebase console.
While in firebase functions by initializing the Firebase Admin SDK with admin.initializeApp(), we can perform actions on behalf of your users and take advantage of the security and management features provided by Firebase.
When using firebase function it is advisable to use admin services as stated in the docs
If you have configured your firebase functions with typescript then follow this:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();

const firestore = admin.firestore();

exports.deleteDocRecursively = functions.https.onRequest(async (req, res) => {
  // Delete Recursively
  const documentRef = firestore.collection("users").doc("<doc_id of doc to be deleted>");
  await firestore.recursiveDelete(documentRef);
});

If you have configured your firebase functions with javascript follow this:
const =  functions require("firebase-functions");
const = admin require("firebase-admin");
admin.initializeApp();
const firestore = admin.firestore();

exports.deleteDocRecursively = functions.https.onRequest(async (req, res) => {
  // Delete Recursively
  const documentRef = firestore.collection("users").doc("<doc_id of doc to be deleted>");
  await firestore.recursiveDelete(documentRef);
});

For more information go through these links:
Thread using recursiveDelete

A: As mentioned in the documentation, recursiveDelete is a method on an instance of Firestore class and not a static method on the class itself. Try:
import { Firestore } from '@google-cloud/firestore';
// const { Firestore } = require('@google-cloud/firestore');

const db = new Firestore();

export async function deleteDocRecursively(docRef) {
    await db.recursiveDelete(docRef); // <-- not 'Firestore'
}


text:
Q: It is not calling NSObject Class I created simple NSObject class to take some values. My application has not come any error when I run and build the application. I tried it lot of time to run program. I am beginner of the objective c.
Code ::
#import "FibonachiNo.h"

@implementation FibonachiNo

- (NSArray *) fibonacci:(NSInteger) n {

    NSMutableArray *fib = [NSMutableArray array];

    int a = 0;
    int b = 1;
    int sum;
    int i;

    for (i=0; i<=n; i++)
    {
        [fib addObject:[NSNumber numberWithInt:a]];
        sum = a + b;
        a = b;
        b = sum;
    }

    return (NSArray *) fib;
}

- (NSInteger) factorial:(NSInteger) n {
    if ( n <= 1 )
        return 1;
    else
        return n * [self factorial:( n-1 )];
}

@end

My application header class
#import <UIKit/UIKit.h>
#import "FibonachiNo.h"
@interface ViewController : UIViewController
@property FibonachiNo *myFibonachi;
@end

Calling Method to NSObject Class ::
  NSLog(@"fibonacci for 10 = %@", [myFibonachi fibonacci:10]);
  NSLog(@"10! = %d",[myFibonachi factorial:10]);

Is it any wrong in this calling method ?

A: first alloc init your Array
#import "FibonachiNo.h"

@implementation FibonachiNo

- (NSArray *) fibonacci:(NSInteger) n {

    NSMutableArray *fib = [NSMutableArray alloc]init];

    int a = 0;
    int b = 1;
    int sum;
    int i;

    for (i=0; i<=n; i++)
    {
        [fib addObject:[NSNumber numberWithInt:a]];
        sum = a + b;
        a = b;
        b = sum;
    }

    return fib;
}

- (NSInteger) factorial:(NSInteger) n {
    if ( n <= 1 )
        return 1;
    else
        return n * [self factorial:( n-1 )];
}

@end

Calling Method to NSObject Class ::
in ViewDidLoad use following.
FibonachiNo *myFibonachi=[[FibonachiNo alloc]init];
  NSLog(@"fibonacci for 10 = %@", [myFibonachi fibonacci:10]);
  NSLog(@"10! = %d",[myFibonachi factorial:10]);

if still you facing any issue , then show your NSLog output here.

A: try using
@synthesize *myFibonachi;
in your ViewController.m file below @implementation


text:
Q: Today Stock Price is 15. Find value of Call Option Stock price is $15$ today. In a year, it has $50-50$ chances of going up or down. If it goes up, then $0.8$ probability of the price being $25$. If it goes down, then $0.4$ probability of price being $5$ and $0.6$ probability of it being $0$. Find the price of $call$ $option$ at strike $25$.

My approach:
I think I should, first of all, find the value of the stock on the up branch of the tree that happens with a probability of 0.2. I don't know though how to find such value.
I thought to include in the reasoning the formulas of $p,u,d$ of the tree, but it doesn't seem to help.

This is the tree I am talking about. Nevertheless, in this problem, the tree should have only one node so $n=1$,  and since the maturity is 1 year, t should also be 1, $t=1$


text:
Q: addEventListener Executing Before Being Clicked I'm Developing a basic Chrome extension centred around a video game. In order to create the menu I have used HTML and come up with:
    <head>
        <title>Inheritance Popup</title>
        <script src="popup.js"></script>
    </head>

    <body style="background-color:#4d2b88">

        <img
        src= "start_screen.png"
        id='startScreenImage'
        style="z-index: -1;">
        <img
        src= "start_button.png"
        id='startButtonImage'
        style="position:absolute; left:65px; top:145px;">
        <img
        src= "info_button.png"
        id='infoButtonImage'
        style="position:absolute; left:65px; top:295px;">

    </body>
</html>

In order to receive input upon the buttons being clicked I am using this:
function startGame(){
  console.log("start works")
}
// Add event listeners once the DOM has fully loaded by listening for the
// `DOMContentLoaded` event on the document, and adding your listeners to
// specific elements when it triggers.
  document.addEventListener('DOMContentLoaded', function () {
  document.querySelector("#startButtonImage").addEventListener('click', startGame());
  document.querySelector("#infoButtonImage").addEventListener('click', openInfo());
});

function openInfo(){
  console.log("info works")

(The above is Javascript)
The only issue is that the functions startGame() and  openInfo() are executing before the corresponding buttons are clicked. This code was taken from chromes page about content security policy (https://developer.chrome.com/extensions/contentSecurityPolicy) which states that this should work. I also attempted the solution on this post addEventListener('click') is executing on its own but was unsuccessful in adjusting it to my own code.

A: Don't call the startGame and openInfo functions as you do here:
document.querySelector("#startButtonImage").addEventListener('click', startGame());
document.querySelector("#infoButtonImage").addEventListener('click', openInfo());

Instead do:
 document.querySelector("#startButtonImage").addEventListener('click', startGame);
 document.querySelector("#infoButtonImage").addEventListener('click', openInfo);

This passes the function itself as a parameter to the addEventHandler function, rather than the return value of the function.

A: You only need to pass the reference, as second parameter is a callback
document.querySelector("#startButtonImage").addEventListener('click', startGame);
document.querySelector("#infoButtonImage").addEventListener('click', openInfo);


text:
Q: how to bind key code to submit button in IE mobile I am developing application for IE mobile and i want to bind function to some keys on the keyboard.
for example:
I would like to have this button clicked when i press for example ENTER key (keycode == 13)
Is there any way to do it? I tried with keyup and keydown but id doesn't work
EDIT:
 document.onkeydown = function(e){
         var n = (window.Event) ? e.which : e.keyCode;
            if(n==9) document.getElementById("submit_button").click(); //alert("tab");
        }

this code works on other browsers, but i need it to work on IE mobile
PS: i need it to keycode 9 (Tab button)

A: I found the solution
<head>
<script>
  function check(){
            if(event.keyCode == 9){
              document.getElementById("submit_button").click();
            }
        }
</script>
</head>
<body onkeydown="check();"></body>


text:
Q: Dynamically creating a 2 dimensional array of pointers in c I want to create 2 dimensional array of pointers in c
some code
typedef void* element;
..
..
..
//reading n,m from user
//creating the element matrix
element** newMat = (element**)malloc(sizeof(element)*n*m)

and hoping to get something that will work in
newMat[5][3];

i know this syntax wont work, any idea what can work?
the best thing i got working is an array for each row, but im looking for something cleaner


text:
Q: Having just one selected item in javascript by add & remove classlist I have prepared code below but i have some UI problems with it i want it to have one selected item at first and display the service content belongs to it then change the content & selected box by user click it is working fine with changing the content but it will not remove the orange border from the old box.
it will be great if someone can help me with it.

function changeContent(service) {
    document.getElementById(service).classList.remove("selected-service");
    switch(service) {
        default:
        document.getElementById("services-content").innerHTML = service
        document.getElementById(service).classList.add("selected-service");
    }
}
.our-services div {
        box-shadow: 0px 0px 4px rgba(0, 0, 0, 0.15);
border-radius: 20px;
        padding: 30px;
    display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.our-services div h4 {
    margin-bottom:0!important
}

.selected-service {
        border: 2px dashed #ff7200;
}

.our-services {
    direction: ltr;
    text-align: center;
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-column-gap: 25px;
grid-row-gap: 25px;
}

.data-center { grid-area: 1 / 1 / 2 / 2; }
.VDSL { grid-area: 1 / 2 / 2 / 3; }
.ADSL2+ { grid-area: 1 / 3 / 2 / 4; }
.TD-LTE { grid-area: 1 / 4 / 2 / 5; }
.dedicatd-bandwidth { grid-area: 1 / 5 / 2 / 6; }
.VOIP { grid-area: 2 / 5 / 3 / 6; }
.SIP-TRUNK { grid-area: 3 / 5 / 4 / 6; }
.content { grid-area: 2 / 1 / 4 / 5; }

        ADSL2+

      VDSL

        تلفن ثابت

        TD-LTE

      bandwidth

      دیتاسنتر

        SIP  /

      پهنای باند اختصاصی

     description

    hhhhhhhh

    <button style="border:1px solid #FF7200;color:#FF7200;padding:14px 32px;background:#fff;border-radius:50px">
        مشاهده و خرید
    </button>

A: After clicking,you need to remove class selected-service for all elements and assign it to the current element
let eles = document.querySelectorAll('.selected-service')
for(let i=0;i<eles.length;i++){
  eles[i].classList.remove('selected-service');
}

Or we can use a variable to store the previous cliked element and the next time just remove style from the previous one
Note:  document.getElementById(service).classList.remove("selected-service"); will just remove class from the current element.

function changeContent(service) {
    let eles = document.querySelectorAll('.selected-service')
    for(let i=0;i<eles.length;i++){
      eles[i].classList.remove('selected-service');
    }
    switch(service) {
        default:
        document.getElementById("services-content").innerHTML = service
        document.getElementById(service).classList.add("selected-service");
    }
}
.our-services div {
        box-shadow: 0px 0px 4px rgba(0, 0, 0, 0.15);
border-radius: 20px;
        padding: 30px;
    display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.our-services div h4 {
    margin-bottom:0!important
}

.selected-service {
        border: 2px dashed #ff7200;
}

.our-services {
    direction: ltr;
    text-align: center;
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-column-gap: 25px;
grid-row-gap: 25px;
}

.data-center { grid-area: 1 / 1 / 2 / 2; }
.VDSL { grid-area: 1 / 2 / 2 / 3; }
.ADSL2+ { grid-area: 1 / 3 / 2 / 4; }
.TD-LTE { grid-area: 1 / 4 / 2 / 5; }
.dedicatd-bandwidth { grid-area: 1 / 5 / 2 / 6; }
.VOIP { grid-area: 2 / 5 / 3 / 6; }
.SIP-TRUNK { grid-area: 3 / 5 / 4 / 6; }
.content { grid-area: 2 / 1 / 4 / 5; }

        ADSL2+

      VDSL

        تلفن ثابت

        TD-LTE

      bandwidth

      دیتاسنتر

        SIP  /

      پهنای باند اختصاصی

     description

    hhhhhhhh

    <button style="border:1px solid #FF7200;color:#FF7200;padding:14px 32px;background:#fff;border-radius:50px">
        مشاهده و خرید
    </button>

A:

const elements = ['adsl', 'vdsl', 'voip', 'tdlte', 'bandwidth', 'datacenter', 'siptrunk' ];

elements.forEach((el, i) => document.querySelector(`#${el}`).onclick = () => changeContent(el));
function changeContent(service) {
    document.querySelector('.selected-service').classList.remove("selected-service");
        document.getElementById("services-content").innerHTML = service
        document.getElementById(service).classList.add("selected-service");

}
/*add this line below so that the elements don't look "jumping" when they get selected*/
.our-services div[id] {
  border: 2px solid rgba(0, 0, 0, 0);
}
.our-services div {
        box-shadow: 0px 0px 4px rgba(0, 0, 0, 0.15);
border-radius: 20px;
        padding: 30px;
    display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.our-services div h4 {
    margin-bottom:0!important
}

.selected-service {
        border: 2px dashed #ff7200!important;
}

.our-services {
    direction: ltr;
    text-align: center;
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-column-gap: 25px;
grid-row-gap: 25px;
}

.data-center { grid-area: 1 / 1 / 2 / 2; }
.VDSL { grid-area: 1 / 2 / 2 / 3; }
.ADSL2+ { grid-area: 1 / 3 / 2 / 4; }
.TD-LTE { grid-area: 1 / 4 / 2 / 5; }
.dedicatd-bandwidth { grid-area: 1 / 5 / 2 / 6; }
.VOIP { grid-area: 2 / 5 / 3 / 6; }
.SIP-TRUNK { grid-area: 3 / 5 / 4 / 6; }
.content { grid-area: 2 / 1 / 4 / 5; }

        ADSL2+

      VDSL

        تلفن ثابت

        TD-LTE

      bandwidth

      دیتاسنتر

        SIP  /

      پهنای باند اختصاصی

     description

    hhhhhhhh

    <button style="border:1px solid #FF7200;color:#FF7200;padding:14px 32px;background:#fff;border-radius:50px">
        مشاهده و خرید
    </button>

Also, your images are not showing up as http://31.184.128.92 is a local address and is not available to anyone besides your computer until you deploy your Wordpress website on hosting


text:
Q: Best practices for SQL Server exception handling in ServiceStack.OrmLite? I am using ServiceStack.OrmLite with the SQL Server provider.
Given the code fragment below:

*

*Is there a best practice for retrieving SQL Server exceptions?

*What is the best way to know if a record is in the result of the db.Single call ? It seems I get an exception when db.Single is called with an invalid message ID (ie. a message ID that is not in the data set). The call returns without exceptions if  messages IDs exist in the database. Is there a way to do this without the try catch block?
Exception if call is made without try/catch block:

ArgumentNullException  Value cannot be null.
  Parameter name: ENSMessageEntry: 'ID = 25' does not exist

And here is my code:
public ENSStatusResponse GetMessageStatus(int messageID)
{
    var statusResponse = new ENSStatusResponse();

    using (var db = DBConnectionFactory.OpenDbConnection())
    {
        try
        {
            ENSMessageEntry mes = db.Single<ENSMessageEntry>("ID = " + messageID);
            statusResponse.ENSMessageStatus = mes.Id;
        }
        catch
        {
            statusResponse.ENSMessageStatus = 0;
        }
    }

    return statusResponse;
}

A: *

*I don't think this query would generate a SQL Server exception, the exception is coming from .Single which is assuming there will be result and throwing if there is not.

*Use Db.GetByIdOrDefault<ENSMessageEntry>(messageID) and check for null


text:
Q: Getting compilation error while converting number to words in jaspersoft studio In Jasperstudio I have added ConvertToWord plugin jar in classpath for converting number to word and created the scriplet, included fully qualified class name in scriplet properties after referring Jasperstudio tutorials.
num.jrxml file
<?xml version="1.0" encoding="UTF-8"?>

<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="num" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="7a5c9b49-9dc5-422a-ac69-e92cf61ef530">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="Sample1"/>


text:
Q: iPhone GPS (location) API link required I am new to iPhone Application... I want to use GPS API in my iPhone Application, for getting current location of iPhone.. Can any one plz post some links for GPS API for iPhone ? Thanks..

A: The link from ttvd is not valid anymore. They the current link to the documentation of CoreLocation instead

A: Look at Core Location framework: Apple link here
Link is not valid anymore, please see Heiko Behrens's post.