text:
Q: Detecting mobile device "notch" With the launch of the iPhone X imminent, I'm trying to get ahead of the game and prepare some of my web applications to handle any design changes - the biggest of which being the new "notch" which houses the front camera.
I was wondering whether there is, or likely to be, any way of detecting this in Javascript somehow.
Interestingly, Chris Coyier has written an article about The "Notch" and CSS which led me to discover the safe-area-inset-right constant. Is there any way this can be accessed in Javascript and is this a reliable test.
if (window.constant.safeAreaInsetRight) {
  var notch = true;
}

A: This might be a little hacky however, obtaining the screen available heights and widths and matching them to this specifications would allow us to determine if it is an iPhone X.
Please note

In portrait orientation, the width of the display on iPhone X matches
  the width of the 4.7" displays of iPhone 6, iPhone 7, and iPhone 8.
  The display on iPhone X, however, is 145pt taller than a 4.7"
  display...

So, firstly, you want to check if it is an iPhone via the userAgent, secondly you would check the area of the actual screen (excluding the orientation which defaults to portrait), lastly, once we know that it is an iPhoneX via it's screen dimensions you can determine the orientation (based on the table under the iPhone X diagram above)
if (navigator.userAgent.match(/(iPhone)/)){
  if((screen.availHeight == 812) && (screen.availWidth == 375)){

    if((window.innerHeight == "375") && (window.innerWidth == "812")){
      // iPhone X Landscape

    }else{
      // iPhone X Portrait
    }
  }
}

References:
avilHeight
avilWidth
iPhoneX Specs

As for CSS solution, I have found an interesting article about it yesterday which might be of use

Let's say you have a fixed position header bar, and your CSS for iOS
  10 currently looks like this:

header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 44px;

    padding-top: 20px; /* Status bar height */
}

To make that adjust automatically for iPhone X and other iOS 11
  devices, you would add a viewport-fit=cover option to your viewport
  meta tag, and change the CSS to reference the constant:

header {
    /* ... */

    /* Status bar height on iOS 10 */
    padding-top: 20px;

    /* Status bar height on iOS 11+ */
    padding-top: constant(safe-area-inset-top);
}

It's important to keep the fallback value there for older devices that
  won't know how to interpret the constant() syntax. You can also use
  constants in CSS calc() expressions.

Article

A: Since @youssef-makboul's answer and as commented by @hjellek, iOS has changed from constant() to env() syntax and a fallback is needed to support this approach on all current iPhone X iOS versions.
const hasNotch = function () {
    var proceed = false;
    var div = document.createElement('div');
    if (CSS.supports('padding-bottom: env(safe-area-inset-bottom)')) {
        div.style.paddingBottom = 'env(safe-area-inset-bottom)';
        proceed = true;
    } else if (CSS.supports('padding-bottom: constant(safe-area-inset-bottom)')) {
        div.style.paddingBottom = 'constant(safe-area-inset-bottom)';
        proceed = true;
    }
    if (proceed) {
        document.body.appendChild(div);
        let calculatedPadding = parseInt(window.getComputedStyle(div).paddingBottom);
        document.body.removeChild(div);
        if (calculatedPadding > 0) {
            return true;
        }
    }
    return false;
};

A: // iphone X detection

function hasNotch() {
    if (CSS.supports('padding-bottom: env(safe-area-inset-bottom)')) {
      let div = document.createElement('div');
      div.style.paddingBottom = 'env(safe-area-inset-bottom)';
      document.body.appendChild(div);
      let calculatedPadding = parseInt(window.getComputedStyle(div).paddingBottom, 10);
      document.body.removeChild(div);
      if (calculatedPadding > 0) {
        return true;
      }
    }
    return false;
  }

A: Add notch-detected-event (0.7k pure JS)
If a notch is detected, it adds HTML5 data attributes to the HTML element:
<html data-notch="true" data-orientation="portrait">
Allowing you to tweak the layout using CSS:
/* make room for the notch at the top */
html[data-notch="true"][data-orientation="portrait"] body {
  padding-top: 44px;
  height: calc(100% - 44px);
}

/* make room for the notch at the sides */
html[data-notch="true"][data-orientation="landscape"] body {
  padding-left: 44px;
  padding-right: 44px;
  width: calc(100% - 44px - 44px);
}

Or listen for notch-detected event and execute some JS:
window.addEventListener('notch-detected', function(e) {
  console.log("Notch detected, move shit around");
});

A: I hit this recently. You can set the value of a CSS environment variable (env()) to a CSS Custom Property and then read that value in via JavaScript:
CSS:
:root {
    --sat: env(safe-area-inset-top);
    --sar: env(safe-area-inset-right);
    --sab: env(safe-area-inset-bottom);
    --sal: env(safe-area-inset-left);
}

JS:
getComputedStyle(document.documentElement).getPropertyValue("--sat")

Full info here:
https://benfrain.com/how-to-get-the-value-of-phone-notches-environment-variables-env-in-javascript-from-css/

A: Couple of things to add:
Make sure you have the following in your index.html
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
Additionally:
Great article on this here: CSS Tricks Notch

A: I'm use this:
function hasNotch() {

    //iphone X 1.11
    if (document.documentElement.clientHeight == 812 && document.documentElement.clientHeight == 375 && !!window.matchMedia && window.matchMedia("only screen and (-webkit-device-pixel-ratio: 3)").matches && iOSversion()[0] == 11) {
        return true;
    }

    var proceed = false;
    var div = document.createElement('div');
    if (CSS.supports('padding-bottom: env(safe-area-inset-bottom)')) {

        div.style.paddingBottom = 'env(safe-area-inset-bottom)';
        proceed = true;
    } else if (CSS.supports('padding-bottom: constant(safe-area-inset-bottom)')) {

        div.style.paddingBottom = 'constant(safe-area-inset-bottom)';
        proceed = true;
    }
    if (proceed) {
        return true;
    }

    return false;
};

The CSS is global interface library of typescript:
interface CSS {
    escape(value: string): string;
    supports(property: string, value?: string): boolean;
}
declare var CSS: CSS;

Or in CSS:
$margin_max_constant_notch:unquote('max(-12px, constant(safe-area-inset-left))');
$margin_max_env_notch:unquote('max(-12px, env(safe-area-inset-left))');

/*** iphone X 1.11, iphone XS (quote is OR) ***/
@media only screen
and (device-width : 375px)
and (max-device-width : 812px)
and (-webkit-device-pixel-ratio : 3),
 /*** iphone XR ***/
screen and (device-width : 414px)
and (device-height : 896px)
and (-webkit-device-pixel-ratio : 2),
  /*** iphone XS Max ***/
screen and (device-width : 414px)
and (device-height : 896px)
and (-webkit-device-pixel-ratio : 3),
  /*** iphone XS Max Retina ***/
only screen and (-webkit-min-device-pixel-ratio: 3),
only screen and (   min--moz-device-pixel-ratio: 3),
only screen and (     -o-min-device-pixel-ratio: 3/1),
only screen and (        min-device-pixel-ratio: 3),
only screen and (                min-resolution: 458dpi),
only screen and (                min-resolution: 3dppx),
/** Google Pixel 3 XL  **/
screen and (device-width: 360px)
and (device-height: 740px)
and (-webkit-min-device-pixel-ratio: 4),
only screen and (   min--moz-device-pixel-ratio: 4),
only screen and (     -o-min-device-pixel-ratio: 4/1),
only screen and (        min-device-pixel-ratio: 4),
only screen and (                min-resolution: 523dpi),
only screen and (                min-resolution: 4dppx) {

    @media(orientation: portrait) {

       /* mobile - vertical */

        @media (max-width: 768px) {
         /* up to 768px */
        }

        @media (max-width: 480px) {
         /* up to 480px */
        }

       @media only screen and (max-width: 400px) {
           /* up to 400px */
        }

    }
    @media(orientation: landscape) {
        html,body {
            padding: $margin_max_constant_notch;
            padding: $margin_max_env_notch;
        }

        /* mobile - horizontal */

        @media screen and (max-width: 900px) {

          /* up to 900px */
        }

    }
}

/** iphone X 1.12 **/
@supports(padding: max(0px)) {
@media screen and (device-width : 375px)
and (device-height : 812px)
and (-webkit-device-pixel-ratio : 3) {
    @media(orientation: portrait) {

       /* mobile - vertical */

        @media (max-width: 768px) {
           //até 768px
        }

        @media (max-width: 480px) {
         /* up to 480px */
        }

        @media only screen and (max-width: 400px) {
        /* up to 400px */
        }

      }
      @media(orientation: landscape) {
        html, body {
          padding: $margin_max_constant_notch;
          padding: $margin_max_env_notch;
        }

        @media screen and (max-width: 900px) {
         /* up to 900px */
        }
      }
   }
}

/** iphone 8 **/
@media only screen
and (device-width : 375px)
and (device-height : 667px)
and (-webkit-device-pixel-ratio : 2),
  /** iphone 8 PLUS **/
screen  and (device-width : 414px)
and (device-height : 736px)
and (-webkit-device-pixel-ratio : 3) {
  @media(orientation: portrait) {

  /* mobile - vertical */

  }
  @media(orientation: landscape) {

  /* mobile - horizontal */
  }
}

@media only screen
  /** IPADS **/
and (min-device-width: 1024px)
and (max-device-width: 1366px)
and (-webkit-min-device-pixel-ratio: 2) {

 /* for ipads */

  @media(orientation: portrait) {

  /* ipad - vertical */

  }
  @media(orientation: landscape) {

  /* ipad - horizontal */
  }

}


text:
Q: Why data cannot be written on base address+1 on ASB I'm working on my project about AHB protocol.
What I'm doing is make IP blocks with AHB system and write/read data using SDK(Vitis).
The base address is assigned to 0x43C0_0000.
If I write data on base address with Xil_Out it works.
However, when I give 0x43C0_0000 +1 to Xil_Out, it does not work.
By trial and error, I found that only address on 0x43C0_0000 + 4*n works.
Why writing data not on that range does not work?

A: Most computer addressing schemes state that +1 address offset means access to one byte of information. If in your design AHB bus is 32-bits write access with an address offset 1 should put your data into D[15:8] bits assuming little-endian mode of the AHB bus. In the AMBA world, that Xilinx has adopted, such access called narrow access meaning that 8 bits are less than the full 32-bits. Hence, writing of one byte should leave the remaining 24-bits in this memory location intact. This is typically accomplished by having byte selects which AHB bus does not have while its cousin AXI does have:
https://developer.arm.com/documentation/ddi0243/c/AHB-Components/Bus-matrix/Signal-descriptions
It is very likely that Xilinx design does not support narrow AHB accesses, while you can still write entire 32-bits at the address offset(s) 4*n as you have found out experimentally. However, I would rather not do experiments and just agree on one type of computer bus, but we humans rarely agree. Just look at what we do or do not do with facemasks during COVID-19 pandemic.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create a corrplot from continuous and discrete column values using R I believe the issue is in using three columns to create the correlation matrix. I attempted to follow the suggestions in this post: How can I create a correlation matrix in R? , but to no avail.
Furthermore, running the "rd_sample <- reading_data..." block gives the error "could not find function 'reading_data'". However, running "class(reading_data)" confirms it is a dataframe.
##corrplot
install.packages("corrplot")

rd_sample <- reading_data(live1 = rnorm(10),   #live1 values are discrete
                          reg = rnorm(10),     #reg values are discrete
                          books1 = rnorm(10))  #books1 values are continuous

M <- cor(rd_sample) # get correlations (returns matrix)

library(corrplot)
corrplot(M)

I would appreciate any suggestions.

A: Not being familiar with the function reading_data, I simply created a data frame and then used your code with the defaults for corrplot.
rd_sample <- data.frame(live1 = rnorm(10),   #live1 values are discrete
                          reg = rnorm(10),     #reg values are discrete
                          books1 = rnorm(10))

M <- cor(rd_sample) # get correlations (returns matrix)

library(corrplot)
corrplot(M)


text:
Q: Transient not working for custom loops I'm working at a WordPress theme. Since I need to display featured posts, related posts, some widgets with recent posts and so on, I need to use multiple custom loops. Because of this, the number of database queries have also increased.
In an attempt to optimize the theme for better performance I came across http://codex.wordpress.org/Transients_API , which seems like a good way to cache the loops that I don't need to be updated to every page reload.
So far so good, I used transient for wp_nav_menu and it worked as it should. I managed to decrease a bit the number of db queries.
The problem occured when I tried to use the transient for custom loops.
The transient is saved.
I can get the transient value.
The only problem is that the number of the database queries seems to be significantly higher than when using WP_Query without a transient.
Here is my custom loop:
if( false === ( $loop = get_transient('featured') ) ) {
    $loop = new WP_Query( array( 'posts_per_page' => 20 ) );
    set_transient('featured', $loop, 60 * MINUTE_IN_SECONDS);
}

if( $loop->have_posts() ) :

    while( $loop->have_posts() ) : $loop->the_post();

        the_title();
        the_post_thumbnail('thumb');

    endwhile;

endif;
wp_reset_postdata();

The code used to display the number of database queries and execution time is the following:
<?php echo get_num_queries(); ?> queries in <?php timer_stop(1); ?> seconds.

Using a query debug plugin, I see that update_meta_cache() generates a lot of queries.
I can't explain why the number of database queries increases instead of decreasing and why this worked for menues, but not for custom loops. Maybe I missed something. Any help is appreciated.

A: I have actually worked on a post yesterday (check it out here) and was hit by the same problem. I'm also new to the Transient API, never actually worked with it :-).
The problem here is that for a specific loop you need to use a certain value outside of your transient. You are simply storing the wrong values, and because of this, you are getting these overload of db hits.
To explain, here is part of the code from the answer I've referred to. I need to create a list of categories with post titles belonging to these categories. To accomplish this, I run my custom query and then use the value of $q to create my list
    $args = array(
        'posts_per_page' => -1
    );

    $query = new WP_Query($args);

    $q = array();

    while ( $query->have_posts() ) {

        $query->the_post();

        $a = '' . get_the_title() .'';

        $categories = get_the_category();

        foreach ( $categories as $key=>$category ) {

            $b = '' . $category->name . '';

        }

        $q[$b][] = $a; // Create an array with the category names and post titles
    }

    /* Restore original Post Data */
    wp_reset_postdata();

This gives me 6 queries in 0.06348 seconds.
OK, if you look at what the example from the codex, you should put your new WP_Query result in a transient. If I do that, the results is totally haywire
<?php
if( false === ( $query = get_transient('custom_query') ) ) {
    $args = array(
        'posts_per_page' => -1
    );

    $query = new WP_Query($args);
 set_transient('custom_query', $query, 60 * MINUTE_IN_SECONDS);
}
    $q = array();

    while ( $query->have_posts() ) {

        $query->the_post();

        $a = '' . get_the_title() .'';

        $categories = get_the_category();

        foreach ( $categories as $key=>$category ) {

            $b = '' . $category->name . '';

        }

        $q[$b][] = $a; // Create an array with the category names and post titles
    }

    /* Restore original Post Data */
    wp_reset_postdata();

?>

With the code above, my results looks like this 31 queries in 0.19141 seconds. This is 25 queries more and takes about 0.13 seconds more. The reason for this is, for each post, Wordpress needs to revisit the db to retrieve the categories the post belongs to, as this is not stored in you transient. 25 extra queries is the amount of posts in my db. So, you see, you have actually wasted a lot of resources by storing the wrong info. I do not need the info from the new WP_Query, but the result/value from $q
So, to properly make use of transients, you have to store the correct values you are after. To do this, I need to add my complete query into a transient to make sure that it is only run once, and that is when the transient is created. After that, the custom query is not needed anymore and is redundant, the only thing that needs to be stored and that I'm after now is the value $q. So, this is how the query is altered to remove the custom query after the transient is created, and to save just the value of $q
Just to note, I've changed my transient names along the way just for testing purposes to show the times and queries. Also note that when creating your transient, you need to use the value (in this case $q) you need to save
 if ( false === ( $q = get_transient( 'category_list' ) ) ) {

    $args = array(
        'posts_per_page' => -1
    );

    $query = new WP_Query($args);

    $q = array();

    while ( $query->have_posts() ) {

        $query->the_post();

        $a = '' . get_the_title() .'';

        $categories = get_the_category();

        foreach ( $categories as $key=>$category ) {

            $b = '' . $category->name . '';

        }

        $q[$b][] = $a; // Create an array with the category names and post titles
    }

    /* Restore original Post Data */
    wp_reset_postdata();

set_transient( 'category_list', $q, 12 * HOUR_IN_SECONDS );
}

This give me 2 queries in 0.00195 seconds. You see how I have now effectively made use of transients. $q which is an array of many values` is now available to create my list, and it only cost me 2 db hits to accomplish my goal
I hope this all makes sense

A: Your code has 3 problems

*

*you use one DB query to save another DB query. You query a transient value instead of the post table which might or might not be faster but you don't save the penalty of communicating with the DB.

*You should not store objects in transients or options. According to the documentation values there are supposed to be scalars only which might be the reason why get_transient fails at your code.
One of the important parts of what wp_query does that you skip by that which might influence the performance of the rest of your code is cache priming by storing the returned post objects in the cache  (cache in this context is the short lived per session cache)

*the right way to cache is to cache the generated HTML. Your code attempts to save one query but you will save 40 more if you cache the HTML


text:
Q: Is there a simple way in Javascript to run a function when a specific object property changes? I am using a third party library that gives me a reference to its object when it initialises:
const flktyInit = (ref) => {
    flkty = ref.flkty;

    console.log(ref.state.flickityReady) //returns false on page load, but few seconds later returns true
  };

What I am trying to make sure of is before I run a method from flkty, ref.state.flickityReady is true first. I have achieved this in a hacky form with setInterval, but this feels too hacky and can't find an obvious answer.
FYI this app is in a React environment.
Can anyone offer up a suggestion?

A: In case you want to use vanilla javascript you'll have to use setInterval.
Since you've mentioned that you are using ReactJS, and as long as this behavior related to a component, I would recommend handling it as the component state, so when the state changes (and turning from false to true), you can execute a function call using useEffect (inside that useEffect you will have to check if the value is true or false before calling the function you want, But it will trigger useEffect each time the state of the component was updated.


text:
Q: Azure Service Bus Topic subscribe from CRM plugin I am successfully posting messages from a CRM plugin to an Azure Service Bus Queue. Ideally I need CRM to listen to a Topic (subscription) and perform an action on receive.  I do not know if this is possible with CRM and cannot find a method of implementing it.  I can read from a queue with the below;
    MessagingFactory factory = MessagingFactory.CreateFromConnectionString(QueueConnectionString);

    //Receiving a message
    MessageReceiver testQueueReceiver = factory.CreateMessageReceiver(QueueName);
    while (true)
    {
        using (BrokeredMessage retrievedMessage = testQueueReceiver.Receive())
        {
            try
            {
                var message = new StreamReader(retrievedMessage.GetBody<Stream>(), Encoding.UTF8).ReadToEnd();
                retrievedMessage.Complete();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                retrievedMessage.Abandon();
            }
        }
    }

However this gets called when a plugin is executed by a user action.  I need to be always listening. Can this be achieved with CRM?  I am using CRM 2016 on premise, with the message bus hosted in Azure.
Thanks for any pointers.

A: CRM is not an always-listening application. It is a web application triggered by an HTTP request. To bridge this gap you can use Azure Functions. Since an Azure Function can be triggered by the Service Bus and can call Dynamics CRM.
You will need to create an deploy an Azure Function that is triggered by a Service Bus queue. This is well documented at: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus
Create a package.json for your Azure Function:
{
"bindings": [
    {
    "queueName": "testqueue",
    "connection": "MyServiceBusConnection",
    "name": "myQueueItem",
    "type": "serviceBusTrigger",
    "direction": "in"
    }
],
"disabled": false
}

Basic Function code:
public static void Run(string myQueueItem, TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
}

Once you have this working you can build out your Azure Function code to connect to Dynamics CRM - same as you would any other code.
Add dependencies to project.json (must get this exactly correct as discussed here: http://crmtipoftheday.com/2016/12/12/connect-to-dynamics-365-in-azure-functions/):
{
  "frameworks": {
    "net46":{
      "dependencies": {
        "Microsoft.CrmSdk.CoreAssemblies": "8.2.0",
        "Microsoft.CrmSdk.XrmTooling.CoreAssembly": "8.2.0"
      }
    }
  }
}

A: Nick suggestion is perfect. Another way would be to use Logic App. There is a connector available for Dynamics 365 which allow you to perform crud operations in graphical interface. You cannot write code in Logic App where as in Azure functions you can implement your logic using code. Logic App is similar to workflows in Dynamics 365 and has the ability to read context from a queue or subscription.


text:
Q: How to get rid of unwanted data series in a chart? I am using vba to plot a chart with two data series. On the chart however it shows three legends. The third legend corresponds to dataserie3 which I did not add to the chart and I have no idea where it comes from. Also there is no data corresponds to this data series to plot.
So my first question is, do you have any idea why this legend is added, and how this data series are included in the chart? I was searching this issue and found out it is a common problem. Though all suggestions were to simply delete this data series, but I could not see the reason behind it.
My second question is, whether there is any command available in vba, such as clc, clear all, close all, ... to wipe out all data before running the code, so to avoid any unwanted data from being copied or transferred to the code?
Dim ws As Worksheet
Dim rng1X As Range, rng1Y As Range, rng2X As Range, rng2Y As Range
Dim objChrt As ChartObject
Dim chrt As Chart

Set ws = Sheets("Sheet2")
With ws
.Shapes.AddChart
Set objChrt = .ChartObjects(.ChartObjects.Count)
Set chrt = objChrt.Chart
With chrt
    .ChartType = xlXYScatterSmoothNoMarkers
    .SeriesCollection.NewSeries
    .SeriesCollection(1).XValues = rng1X
    .SeriesCollection(1).Values = rng1Y
    .SeriesCollection(1).Name = "Flow1"
    .SeriesCollection.NewSeries
    .SeriesCollection(2).XValues = rng2X
    .SeriesCollection(2).Values = rng2Y
    .SeriesCollection(2).Name = "Flow2"
    .HasLegend = True
    .Legend.Position = xlLegendPositionTop
    .Parent.Name = "Chart1"
End With

A: So, I've experienced this problem every time I make a clustered column chart using data that is non-contiguous.  In testing, this did not occur for me when using contiguous data.  If I step through, and inspecting the data of the chart itself, it looks like a dataseries is created when I input my XValues).
I create dataseries like:
With ActiveChart
    .ChartType = xlColumnClustered
    .SeriesCollection.NewSeries
    .SeriesCollection(1).Name = " "
    .SeriesCollection(1).Values = "=Overview!$C$29,Overview!$C$32,Overview!$C$35,Overview!$C$38,Overview!$C$41"
     .SeriesCollection(1).XValues = "={"" ""}"
End With

My solution has been to remove the dataseries by looping to one dataseries above what I have defined (in this case, >1 (i = .count to 2)).
With ActiveChart
    If .SeriesCollection.Count > 1 Then
        For i = .SeriesCollection.Count To 2 Step -1
             .SeriesCollection(i).Delete
        Next
    End If
End With

Edit1:
Will spell out a better explanation as to where more than 1 dataseries has been coming from (as I only accounted for additional +1 when I said that there was a dataseries created when I specified XValues, but 2 existed previously due to my data).
When I create a chart, i create such that:
.Shapes.AddChart.Select

This immediately creates a dataseries, using data from, typically, contiguous data starting in cell A1 of the sheet, or based on your current activecell.  This occurs before I even determine the type of Chart I want (in my case xlColumnClustered).
You could start removing dataseries at this point, though if you add a dataseries and specify .SeriesCollection(1) you will always be affecting the first dataseries only, whether or not it was the one you created with newseries...
You will get an error if the chart did not recognize an initial source dataseries and thus it would be preferable to add a .NewSeries and affect the "(1)" series, then go back and remove the excess later.
Specific to the chart i was creating, I have two dataseries the instant I .AddChartdue to how my data shows up in the spreadsheet.  I create 1 dataseries and manipulate it how I want, then remove the excess.

A: Instead of deleting undesired series you can simply select any blank cell right before creating chart
Sub test()
Dim Cell As Range
Dim UsedRng As Range
Set UsedRng = ActiveSheet.UsedRange
For Each Cell In UsedRng
If Cell.Value = Empty Then
Cell.Select
Exit For
End If
Next Cell
ActiveSheet.Shapes.AddChart.Select
End Sub


text:
Q: C++ file parse number of arguments I got a pack of c++ files with static source code (already developped, not needed to do anything to them).
There is an program/lib/way to get a list of the number of params each function withing one of those files?
I mean, getting a result like:
#File a.cpp
##a() -> 3 paramss
##foo() -> 0 params (void)

#File b.cpp
##test() -> 1 param

....

And a better question.
There is any way to also process the number of returns it has?
#File a.cpp
##a() -> 3 params, 1 return
##foo() -> 0 params (void), 2 returns

For example if "foo" has a return if condition is true and another if false
Thanks in advance.

A: You could try running Doxygen over the source files.
Since the content is (presumably) undocumented, you need to configure doxygen to extract content from undocumented files.
If you just want to browse a list of the available functions, you could use the HTML output.
You could also configure Doxygen output to be XML, and then write a parser to pull statistics that you are looking for on each function.

A: I would count the number of "," and start at 1.  This should give you an accurate count of the number of arguments to a function.  Then I would check to see if "void" exists before the function name, if not then you can bet that there is a return value.
ifstream infile;
infile.open(...);
int i, ret, args;
String s;

ret = args = 0;
s = infile.getline();
for( i=0; s[i] != '('; i++ ) {
 if( s[i] == 'v' && s[i+1] == 'o' && s[i+2] == 'i' && s[i+3] == 'd' ) {
  ret = 1;
  break;
 }
}

for( i=0; s[i] != '('; i++ ) {}

for( i; s[i] != ')'; i++ ) {
 if( args == 0 && s[i] != ' ' ) {
  args++;
 }
 if( s[i] == ',' ) {
  args++;
 }
}

A: All this is way over the top but maybe this might be your cup of tea, Elsa can parse c++ and provide you with an abstract syntax tree of the parsed file. There might be some other free tools out there that can do the same


text:
Q: Why is E(Y|X) a RANDOM VARIABLE? Is E(Y|X) a RANDOM VARIABLE ?
X is a random variable so I suppose E(Y|X) is also a random variable since its value depends on X ?
Am I right ? If yes, Then what distribution does it follow and what is its mean and variance ?
Thanks!

A: Yes, $E(Y|X)$ is a random variable, because its value is a function of the value that $X$ takes. Specifics of its distribution will depend on what $X$ and $Y$ are, and particularly the relationship between them.

A: A random variable is a function from the sample space to the real numbers, i.e. $X:\Omega\to\mathbb{R}$.
For a random variable $Y$ and an event $\{X=x\}\subseteq\Omega$ we can compute the expected value
$$
\mathbb{E}(Y|X=x)=\sum_{y}y\mathbb{P}(Y=y|X=x).
$$
Then for every $\omega\in\Omega$,
$$
\mathbb{E}(Y|X)(\omega)=u(X(ω)),
$$
where $u(x)=E(Y∣X=x)$ for every $x\in\mathbb{R}$. Therefore $\mathbb{E}(Y|X)$ is also a function from $\Omega$ to $\mathbb{R}$ and is a random variable.
In other words, the random variable $\mathbb{E}(Y|X)$ assignes probability $\mathbb{P}(X=x)$ to the value $\mathbb{E}(Y|X=x)$ for every $x\in\mathbb{R}$.
Edit: This explanation is for discrete and one-dimensional random variables, but the same idea can be applied for continuous or general settings.


text:
Q: Nunjucks Async Rendering with Keystone View In an Express-based app, I'm running an async function to fetch image source from a database and render them into a Nunjucks view engine
Nunjucks is rendering the following in the DOM

I have already enabled Nunjucks's async rendering with web: { async: true } and enabled the nunjucks async api with a callback like so
// controller.js (KeystoneJS app)
view.render('index', function (err, res) {
    console.log('err at index render', err); // undefined
    return res;
});

How can i get the resolved value of my async function?

A: As I understand it, Nunjucks doesn't support asynchronous render directly. You can use asynchronous filters to get it. Maybe I'm wrong.
Imho, use feature with Be Careful! mark is a not good idea.

// template.njk
Hello {{user_id | find | attr('name') }}!

// app.js
var nunjucks  = require('nunjucks');
var env = nunjucks.configure();

// Async filter
env.addFilter('find', function(a, cb) {
    setTimeout(function () {
        cb(null, {
            name: 'Smith'
        });
    }, 10);
}, true)

// Sync filter
env.addFilter('attr', function(obj, attr) {
    return obj && attr && obj[attr];
});

env.render('template.njk',
    {user_id: 1}, // pass sync vars
    function(err, res) {
        if (err)
           return;

        console.log(res);
        return res
    }
);

A: I don't know about nunjucks, but you can implement async functionality regardless of the view engine being used. To show the idea, I tried to reproduce your situation. I created an HTML file named index.html with an img tag without any src attribute:

        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <title>Reproduce</title>

I have a


text:
Q: One problem with imputing the missing value by the sample mean Today I read an interesting statement, which I am not sure about its correctness.
Assume we are looking at a data set with one column $H$ that is numeric. It has a bunch of missing values. Now let's say I just replace the missing value in column $H$ by the mean of this column (calculated by excluding the missing value). This method is good in the sense that it won't change the mean of column H. But it also has some problems. I was told that this will lessen the correlation with other numeric columns.
This is something I don't understand. I think the extreme case. Assume that column H only has 2 non-missing value, then I use the average of these 2 numbers to replace all the missing values in column H, then this will make the column H almost like a constant, which has variance close to 0. Then the correlation between this almost constant variable and other numeric column will be infinity? or undefined? or zero?

A: Consider the formula for computing the sample correlation between two variables, $x$ and $y$:
$$r_{x,y}=\frac{\sum_n^N(x_n-\bar x)(y_n-\bar y)}{(N-1)s_xs_y},$$
where $s_x$ and $s_y$ are non-zero corrected sample standard deviations. Now, if $x$ is the imputed variable, in all the imputed samples the term $(x_n-\bar x)$ will evaluate to 0, reducing the value of the numerator and thus of the correlation.
In your specific example, the the correlation between $H$ and some other numeric column would depend on the correlation between the values in non-imputed rows. It will always be in the range $[-1;1]$, unless one of the columns has zero sample variance, in which case it will be undefined.


text:
Q: Tesseract OCR Read Text from image I am using TesseractEngine for OCR read text for image , some time it is not working.
Problem reading bold number . Ex 666 9999 7777 . it is clear in image but OCR not able to red.
using (var img = PixConverter.ToPix(image))
using (var page = engine.Process(img))
    ocrtext = page.GetText();


text:
Q: BackboneJS / real time SPA - I don't get it? I guess this will be my first closed question, but anyways:
I'm starting to develop real time single page application (because Web 3.7) with BackboneJS, ASP.NET MVC + SignalR server side for real time. Idea is this:

*

*App loads and initiates connection with server via SignalR.

*Upon navigating to some page, page setups SignalR client function which will handle incomming data and show it to user and tells server to send updates concerning that data, etc.

Now, server side is very clear to me. But not so much with client side - I do not understand anything. Official BackboneJS documentation is very basic and all other tutorials involve static models and REST api.
Wiews - all examples show that views live in "index.html" and get rendered with static models from REST api. I'll have atleast 7 views that are quite big with a lot of HTML and scripts, so keeping them in my "index.html" is not really an option. I've found nothing in regards to loading remote views and on my own I just figured calling jQuery's load function to load the view.
So having only static footer, header and menu, and loading views into #content DIV is not really SPA? This doesn't really from 'normal' web applications, except with jQuery + load I get to keep constant SignalR connection without really navigating away from "index.html".
Basicly I'm using Backbone just for routing and instead of full page requests I load partial views into main content div - am I engineering a some sort of abomination here, doing SPA totally wrong?
Any suggestions on how to do proper real time single page application?

A: Have a look at KO + Durandal or if you want a smaller footprint library have a look at my little SPA lib for KO
https://github.com/AndersMalmgren/Knockout.Bootstrap.Demo
I have also made a Event aggregator proxy for SignalR it works very well with MVVM, once its configured it will automatically forward messages directly to the VM. Used like
TestViewModel = function () {
    signalR.eventAggregator.subscribe(MyApp.MyEvent, this.onMyEvent, this)
};

TestViewModel.prototype = {
    onMyEvent: function (message) {
        //act on my event
    }
};

wiki:
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki
install using nuget
Install-Package SignalR.EventAggregatorProxy

A: Have you looked at using Backbone.js with something like PubNub, a publisher subscriber concept? Here is a link that talks about how to make backbone,js work with it, Backbone with PubNub. I'm looking to try it out soon with an SPA I have been working on as a pet project, where the main index.html is just a bunch of lines in the head section and then a call to a single js file with all the view templates, and backbone models and router. My aim is to have a model linked to a subscribed event from data that is published elsewhere. Not sure if this helps, but if you're interested, load up my site and then look at how it is built, pull it apart, maybe it is somewhat similar to how you are wanting to do things, HydroSolar. Presently, it still pulls data via the this.myModel.fetch({async:true}); method on a periodic timed event, which works well, but like I mentioned, I'm keen to get it working with push technology like from PubNub.


text:
Q: rbind data frames with serial values in r I have a series of data short datasets (2-6rows, 9cols) (dat1,dat2,dat3...dat1000) that all have the same structure and I am trying to put them together in ascending order by name into a single data frame with rbind. Here is a small sample of what I am using and what I am trying to create.
#create sample data sets
    set.seed(1)
    dat1 = data.frame( A = (1:2),B = rnorm(2, mean = 0.03,sd = 0.01))
    dat2 = data.frame( A = (1:3),B = rnorm(3, mean = 0.05,sd = 0.01))
    dat3 = data.frame( A = (1:4),B = rnorm(4, mean = 0.05,sd = 0.01))
    dat4 = data.frame( A = (1:8),B = rnorm(8, mean = 0.05,sd = 0.01))

#put them into a single data frame, this is an example of the data frame I would like to end up with

    rbind(dat1,dat2,dat3,dat4)

my question is how can I bind the data frames together with a loop or counting device so I don't have to write out each variable in the rbind(dat1,dat2...dat1000).

A: Here's one alternative. Using the data in your example
> do.call(rbind, lapply(paste("dat", 1:4, sep=""), get))
    A          B
1  1 0.02373546
2  2 0.03183643
3  1 0.04164371
4  2 0.06595281
5  3 0.05329508
6  1 0.04179532
7  2 0.05487429
8  3 0.05738325
9  4 0.05575781
10 1 0.04694612
11 2 0.06511781
12 3 0.05389843
13 4 0.04378759
14 5 0.02785300
15 6 0.06124931
16 7 0.04955066
17 8 0.04983810

For your full case use:
do.call(rbind, lapply(paste("dat", 1:1000, sep=""), get))

A: Use data.table::rbindlist.
It needs each of your datasets to be a data.table, and an element in a list. The example below should help.
eg.
DT1 = data.table(A=1:3,B=letters[1:3])
DT2 = data.table(A=4:5,B=letters[4:5])
l = list(DT1,DT2)
rbindlist(l)


text:
Q: keras fit_generator() with hand-built image data generator: out of RAM I am writing a Jupyter notebook in Google Colab, which uses keras to fit a pre-trained model to an image classification dataset. Even though I think my handcrafted generator should not lead to memory issues, the RAM is filling up and causes the Colab session to crash.
I tried to boil down my code as much as possible (points 4, 5, and 6 are the relevant ones):
1) a few imports
import os
import tarfile
import urllib.request

import numpy as np
import pandas as pd
import skimage.io
import tensorflow as tf

2) dataset preparation
dataset = {
    'name': 'oxford-102-flowers',
    'url': 'https://s3.amazonaws.com/fast-ai-imageclas/oxford-102-flowers.tgz',
    'num_classes': 102,
}

base_dir = os.getcwd()
data_dir = os.path.join(base_dir, 'data')
dataset_dir = os.path.join(data_dir, dataset['name'])
os.makedirs(data_dir)
tgz_file = os.path.join(data_dir, dataset['name']+'.tgz')
urllib.request.urlretrieve(dataset['url'], tgz_file)
tar = tarfile.open(tgz_file, 'r:gz')
tar.extractall(data_dir)
tar.close()
os.remove(tgz_file)

train_txt = os.path.join(dataset_dir, 'train.txt')
train_df = pd.read_csv(train_txt, sep=' ', header=None, names=('file', 'label'))

3) model setup
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
base_model = tf.keras.applications.MobileNetV2(include_top=False)
pooling_dense_model = tf.keras.Sequential([
    base_model,
    tf.keras.layers.GlobalAveragePooling2D(),
    tf.keras.layers.Dense(dataset['num_classes']),
])
pooling_dense_model.compile(
    loss=loss,
    optimizer='adam',
    metrics=['acc'],
)

4) build a generator
def make_train_generator():
  while True:
    for i, record in train_df.iterrows():
      filename = os.path.join(dataset_dir, record['file'])
      image = skimage.io.imread(os.path.join(dataset_dir, filename))
      normalised_image = image/255. - 0.5
      image_batch = normalised_image[np.newaxis, ...]
      label_batch = np.array((record['label'],))
      yield image_batch, label_batch

5) check that the generator by itself does not produce memory leaks
train_generator = make_train_generator()
train_len = len(train_df)
for i in range(2*train_len):
  train_example = next(train_generator)

6) train the model
pooling_dense_model_history = pooling_dense_model.fit_generator(
    generator=train_generator,
    steps_per_epoch=train_len,
    epochs=2,
    verbose=1,
)

Now point 5) does not increase RAM consumption, while during the steps of 6) memory pressure increases, until it gets an extra boost at the end of the epoch and the Colab session crashes.
I browsed extensively for solutions related to fit_generator memory consumption, but it seems like all of them have additional complications compared to the setup above.
Any ideas of where I am going wrong?
PS I am using a python3 session with GPU acceleration and tf.__version__ is 1.15.0-rc3.


text:
Q: Two load icons simultaneously appearing in Android app This link confirms that the Android app is using two different loaders since last year, but just today I've noted that, at the questions page, it is using them simultaneously. I've never noted this, so I believe this bug was recently created.
I hope the following gif is clear enough to show the issue. Also, note that the bigger loader is "freezing".

SE Android App Version: 1.0.60
My Android OS Version: 5.0.2
Still observed in version 1.0.89


text:
Q: How to insert pie charts in Pack Layout in d3.js? Hello All instead of simple Circles, i want to add pie charts in my Pack layout.
Lets Suppose this is my pie chart data and pie layout
var data=[2,3,4,5]

var arc = d3.svg.arc()
    .outerRadius(50)
    .innerRadius(0);
var pie = d3.layout.pie()
    .sort(null)
.value(function(d) { return d; });

And this is how the packlayout draws the circle
  var circle = svg.selectAll("circle")
  .data(nodes1)
  .enter().append("circle")
  .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
  .style("fill", function(d) { return d.children ? color(d.depth) : null; })
  .on("click", function(d) { if (focus !== d) zoom(d), d3.event.stopPropagation(); });

Can anyone please explain me how instead of appending circles in pack layout i could rather append paths and make pie charts out of it?![enter image description here][1]

A: Instead of using the pack layout results directly, you can use the r value output from the pack layout to define the outerRadius of your arc generator.  Then, instead of appending svg circle elements to the chart, you can append svg g elements, and append each of the arcs inside that:
Full example: http://bl.ocks.org/jsl6906/4a1b818b64847fb05d56

Relevant code:
var bubble = d3.layout.pack()
      .value(function(d) { return d3.sum(d[1]); })
      .sort(null)
      .size([diameter, diameter])
      .padding(1.5),
    arc = d3.svg.arc().innerRadius(0),
    pie = d3.layout.pie();

var svg = d3.select("body").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
    .attr("class", "bubble");

var nodes = svg.selectAll("g.node")
    .data(bubble.nodes({children: data}).filter(function(d) { return !d.children; }));
nodes.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

var arcGs = nodes.selectAll("g.arc")
    .data(function(d) {
      return pie(d[1]).map(function(m) { m.r = d.r; return m; });
    });
var arcEnter = arcGs.enter().append("g").attr("class", "arc");

arcEnter.append("path")
    .attr("d", function(d) {
      arc.outerRadius(d.r);
      return arc(d);
    })
    .style("fill", function(d, i) { return color(i); });


text:
Q: How to obtain implicit val/def via parameterized types in scala? I'm using Playframework 2.5 and trying to make a method that all Json request/response controller method calls to avoid writing implicit val foo = Json.writes[Bar] or reads[Bar] inside of each controller method as well as handling basic validation and return the error code.
BaseController which will be inherited by each controller
class BaseController @Inject()(implicit exec: ExecutionContext) extends Controller {
  def handleJson[T <: RequestModel,U <: ResponseModel](request: Request[JsValue])(cb: (T) => Future[U]):Future[Result] = {
    implicit val convertReq = Json.reads[T]
    implicit val convertRes = Json.writes[U]
    val reqOpt = request.body.asOpt[T]
    reqOpt match {
      case Some(data) =>
        cb(data).map{x => Ok(Json.toJson(x))}
      case None =>
        Future.successful(Ok(Json.obj("foo" -> "bar")))
    }
  }
}

controller
  def send = Action.async(parse.json) { req =>
    handleJson[RequestCaseClass,ResponseCaseClass](req)( (x)  =>
      injectedClass.foo(x.bar).map{ case (success: Boolean,mes: String) =>
        if(success) SendRes(SomethingForSuccess)
        else SendRes(SomethingForError)
      }
    )
  }

Codes above can't be compiled because handleJson's implicit val convertReq = Json.reads[T] and implicit val convertRes = Json.writes[U] says

No Json deserializer found for type T. Try to implement an implicit
  Reads or Format for this type.

I've already tried making case class's companion object and put the implicit in it though this does not solve anything.
My question is, How can I use implicit value of parameterized types?
Thanks in advance.

A: You can initialize implicit variable before invoke handleJson and set convertReq with convertRes to implicit method parameters for handleJson:
def send = Action.async(parse.json) { req =>
    implicit val convertReq = Json.reads[RequestCaseClass]
    implicit val convertRes = Json.writes[ResponseCaseClass]
    handleJson[RequestCaseClass,ResponseCaseClass](req)( (x)  =>
      injectedClass.foo(x.bar).map{ case (success: Boolean,mes: String) =>
        if(success) SendRes(SomethingForSuccess)
        else SendRes(SomethingForError)
      }
    )
}

def handleJson[T <: RequestModel,U <: ResponseModel](request: Request[JsValue])(cb: (T) => Future[U])(implicit convertReq: Reads, convertRes: Writes):Future[Result] = {
    val reqOpt = request.body.asOpt[T]
    reqOpt match {
      case Some(data) =>
        cb(data).map{x => Ok(Json.toJson(x))}
      case None =>
        Future(Ok(Json.obj("foo" -> "bar")))
    }
  }

A: I would suggest doing it like this
class Application @Inject()(implicit exec: ExecutionContext) extends Controller {
  def handleJson[A : Reads, B : Writes](request: Request[JsValue])(cb: A => Future[B]): Future[Result] = {
    val reqOpt = request.body.asOpt[A]
    reqOpt match {
      case Some(data) =>
        cb(data).map { x => Ok(Json.toJson(x)) }
      case None =>
        Future.successful(Ok(Json.obj("foo" -> "bar")))
    }
  }

  def index = Action.async(parse.json) { req =>
    handleJson[MyReq, MyResp](req)(x => Future.successful(MyResp((x.i to x.i + 4).toList)))
  }
}

You don't have to constrain your model with any trait, just enough that implicit Reads and Writes exists.
To ensure that, it is nice to have your Reads and Writes defined in companion object of your class. You will bring them to implicit scope when you import your model classes.
object MyReq {
  implicit val myReqReads: Reads[MyReq] = Json.reads[MyReq]
}
case class MyReq(i: Int)

object MyResp {
  implicit val myRespWrites: Writes[MyResp] = Json.writes[MyResp]
}
case class MyResp(l: List[Int])


text:
Q: functional analysis complementary subspace Let $Y$ and $Z$ be closed subspaces in a Banach space $X$. Show that each $x \in X$ has a unique decomposition $x = y + z$, $y\in Y$, $z\in Z$ iff $Y + Z = X$ and $Y\cap Z = \{0\}$. Show in this case that there is a constant $\alpha>0$ such that $ǁyǁ + ǁzǁ \leq\alphaǁxǁ$ for every $x \in X$

A: Hint: Assume that $Y\cap Z=\{0\}$. If $z+y=x=z'+y'$ s.t. $z,z'\in Z$, $y,y'\in Y$ then $z-z'=y'-y$.
For the other direction, if $y\in Y\cap Z$ then $0+0=y+(-y)$.

A: I think that the constant part requires the Open Mapping Theorem.
Consider the space $Y\oplus Z$ with the norm $\|y\oplus z\|_1=\|y\|+\|z\|$. It is easy to see that it is a Banach space. Then we define the map $T:Y\oplus Z\to X$ given by $T(y\oplus z)=y+z$. This map is clearly linear and bijective. Moreover,
$$
\|T(y\oplus z)\|=\|y+z\|\leq\|y\|+\|z\|=\|y\oplus z\|_1,
$$
so $T$ is bounded. By the Open Mapping Theorem $T$ is open, which means that $T^{-1}$ is bounded. So, given $x\in X$ with $x=y+z$, $y\in Y$, $z\in Z$, there exists $\alpha=\|T^{-1}\|>0$ such that
$$
\|y\|+\|z\|=\|y\oplus z\|_1=\|T^{-1}(x)\|_1\leq\alpha\|x\|.
$$
For the sake of completeness, here is a proof for the first part of the question. Note that both sides of the implication have the assertion $X=Y+Z$, so what we have to prove is
$$
\mbox{unique decomposition }\iff\ Y\cap Z=\{0\}.
$$
So assume first that $X=Y+Z$ with unique decomposition, and let $w\in Y\cap Z$. By the decomposition, $w=y+z$, $y\in Y$, $z\in Z$. But as $w\in Y$, we get $z=w-y\in Y$. So $w=(y+z)+0$ is another decomposition of $w$; by the uniqueness, $z=0$. A similar argument shows that $y=0$, and thus $w=0+0=0$. This shows that $Y\cap Z=\{0\}$.
Conversely, suppose that $Y\cap Z=\{0\}$. If $x=y_1+z_1=y_2+z_2$ with $y_1,y_2\in Y$, $z_1,z_2\in Z$, then we have $y_1-y_2=z_2-z_1\in Z$, so $y_1-y_2\in Y\cap Z$ and $y_1=y_2$. A similar argument shows that $z_1=z_2$. So the decomposition is unique.


text:
Q: Vase and marginal probability Suppose we have a vase with different balls as follows:

*

*$15$ blue (B)

*$12$ red (R)

*$10$ green (G)

*$5$ white (W)

The probability to see a blue ball in the 1st pick and a green ball in the 3rd pick would be the marginal (without replacement: once one color is picked, all balls of that color are out of the vase):
$
P(B*G*) = P(BRGW)+P(BWGR)=
\big ( \dfrac{15}{42} \times \dfrac{12}{27} \times \dfrac{10}{15} \times \dfrac{5}{5} \big )
+
\big ( \dfrac{15}{42} \times \dfrac{5}{27} \times \dfrac{10}{22} \times \dfrac{12}{12} \big )
$
I have two questions:

*

*Is there any other way to compute $P(B*G*)$ (I mean without computing the marginals)?

*Can we claim that $\dfrac{P(B*G*)}{P(G*B*)} > \dfrac{P(R*G*)}{P(G*R*)}?$ The intuition behind is that the number of blue balls compared to green balls is higher than that of red and green balls.

Thanks for any help or hint.

A: The problem is about the colors picked in the first and in the third draw, so you don't have to bother about the fourth one. You need, however, to consider the case with the second ball being green and the case of second ball being non-green.
First, from all possible triplets we can separate those starting with blue.
The probability of picking a blue ball in the first attempt is
$$P(B) = \frac{15}{15+12+10+5}=\frac{15}{42}$$
In the second attempt we pick from $41$ remaining balls with $10$ green among them, so we can either pick a green ball with conditional probability
$$P(*G|B) = \frac{10}{41}$$
or a non-green ball with probability
$$P(*\overline G|B) = \frac{41-10}{41}=\frac{31}{41}$$
If the second ball picked was green, we're left with $9$ green balls in the vase, so the probability of picking a green ball as a third one from remaining $40$ is
$$P(**G|BG)=\frac 9{40}$$
and in the opposite case
$$P(**G|B\overline G)=\frac{10}{40}$$
Finally the probability of drawing a three-ball sequence with the first ball blue and the third one green is
$$P(B*G) = P(BGG)+P(B\overline GG)\\
= P(B)\cdot P(*G|B) \cdot P(**G|BG) + P(B)\cdot P(*\overline G|B) \cdot P(**G|B\overline G) \\
= \frac{15}{42} \cdot \frac{10}{41} \cdot \frac 9{40} + \frac{15}{42} \cdot \frac{31}{41} \cdot \frac{10}{40} \\
= \frac{6000}{68880} \\
= \frac 1{11.48} \approx 0.087108$$


text:
Q: How to add "+91" and remove "+91" in edit text in android? I have an activity in which I have mobile edit text what I want when user enter mobile number I want to add "+91" before number and when user delete full number I want to delete "+91" also .How can I do that
TextWatcher m_MobileWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!s.toString().contains("+91")) {
            m_InputMobie.setText("+91" + s.toString());
            Selection.setSelection(m_InputMobie.getText(), m_InputMobie.getText().length());
        }
    }
};

A: Try below code this is working fine, I have checked.
TextWatcher m_MobileWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String text_value = m_InputMobie.getText().toString().trim();
            if(text_value.equalsIgnoreCase("+91"))
            {
                m_InputMobie.setText("");
            }else
            {
                if(!text_value.startsWith("+91") && text_value.length()>0) {
                    m_InputMobie.setText("+91" + s.toString());
                    Selection.setSelection(m_InputMobie.getText(), m_InputMobie.getText().length());
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


text:
Q: How to find last index of shortest run in an Array? I have worked out following logic.  Shortest Run: a subarray of original array having same elements.
// "A" is Array, p is length of a current run, q is global variable that stores lowest run length
procedure(){
    while( i < sizeOfArray){
     if(A[i]==A[i+1]){
     //1.Increment a variable "p" to capture the length of run
      //2. compare p and q and which ever is smaller , is saved into q
      }else{
     //3. What to do here ?
     }
    }
return q;
}

A: I'm assuming that "Shortest run" based on your code means the shortest sequence in the array where all the numbers are the same. The algorithm below will find the last index of the shortest row. Note that it finds the first shortest run, given that there are multiple runs of the same size.
int A[10] = {1,1,1,1,2,2,2,3,3,3};
int q = INT_MAX, i = 0, p = 1, lastIndex = 0;
while( i != 9 ){ //10 is the size of the array
        if(A[i]==A[i+1]){
                ++p;
        }else{
                if(p < q) {
                        q = p;
                        lastIndex = i;
                }
                p = 1; //reset p, the size of the run should be 1
        }
        i++;
}
return lastIndex;

Note that to find the shortest run, you compare p and q after the run is over, so you compare them in the else statement. The above example returns 6, where A[6] is 2, the last index of the smallest run, which is of size 3.


text:
Q: problems updating ubuntu kernel I've installed Ubuntu 16.04.4 LTS on Virtual Box. I've some problems with the updating of my kernel and I don't know how to fix them! Reading others answer I tried with
sudo apt-get update

and
sudo apt-get upgrade

and this is the report
Lettura elenco dei pacchetti... Fatto
Generazione albero delle dipendenze
Lettura informazioni sullo stato... Fatto
Calcolo dell'aggiornamento... Fatto
I seguenti pacchetti saranno RIMOSSI:
linux-image-extra-4.10.0-28-generic
0 aggiornati, 0 installati, 1 da rimuovere e 0 non aggiornati.
5 non completamente installati o rimossi.
Dopo quest'operazione, verranno liberati 156 MB di spazio su disco.
Continuare? [S/n] S
(Lettura del database... 232826 file e directory attualmente installati.)
Rimozione di linux-image-extra-4.10.0-28-generic (4.10.0-28.32~16.04.2)...
depmod: ERROR: failed to load symbols from /lib/modules/4.10.0-28-generic/misc/vboxvideo.ko: Invalid argument
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.10.0-28-generic /boot/vmlinuz-4.10.0-28-generic
run-parts: executing /etc/kernel/postinst.d/dkms 4.10.0-28-generic /boot/vmlinuz-4.10.0-28-generic
Error! Your kernel headers for kernel 4.10.0-28-generic cannot be found.
Please install the linux-headers-4.10.0-28-generic package,
or use the --kernelsourcedir option to tell DKMS where it's located
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.10.0-28-generic /boot/vmlinuz-4.10.0-28-generic
update-initramfs: Generating /boot/initrd.img-4.10.0-28-generic
run-parts: executing /etc/kernel/postinst.d/pm-utils 4.10.0-28-generic /boot/vmlinuz-4.10.0-28-generic
run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.10.0-28-generic /boot/vmlinuz-4.10.0-28-generic
run-parts: executing /etc/kernel/postinst.d/update-notifier 4.10.0-28-generic /boot/vmlinuz-4.10.0-28-generic
run-parts: executing /etc/kernel/postinst.d/vboxadd 4.10.0-28-generic /boot/vmlinuz-4.10.0-28-generic
run-parts: failed to exec /etc/kernel/postinst.d/vboxadd: Exec format error
run-parts: /etc/kernel/postinst.d/vboxadd exited with return code 1
dpkg: errore nell'elaborare il pacchetto linux-image-extra-4.10.0-28-generic (--remove):
il sottoprocesso installato script di post-removal ha restituito lo stato di errore 1
Si sono verificati degli errori nell'elaborazione:
linux-image-extra-4.10.0-28-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

Thanks everyone for help!

A: Solved! I managed to fix my kernel problem following the instructions in this site (I've to delete the references of the broken packages in var/lib/dpkg/status).
Here the site with the answer
https://askubuntu.com/questions/1014322/how-to-fix-configuration-issues-of-an-old-kernel-in-order-to-make-upgrade-possib


text:
Q: Generate specific data from database? I have been working a some code that contains a form which asks you to enter the ID of a customer and once the form is submitted the PHP behind the form will access the database and display a table of information on the ID that was entered.
However my PHP doesn't seem to be working, when i enter an ID and hit submit i get this error message "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '987451'' at line 1"
Here is my HTML :

Task 8

<form id="customerform" action="task8.php" method="get">

please fill in the following form

Customer ID:  <input type="text" name="custID" />

<input type="submit"  value="Submit">
<input type="reset" value="Reset">

</form>

Here is my PHP :

<?php
$conn = mysql_connect("localhost", "twa312", "dam6av9a");
mysql_select_db("warehouse312", $conn)
or die ('Database not found ' . mysql_error() );

$cust = $_GET["custID"];
$sql = "select * from orders";
$sql = $sql . "where customerID = '$cust'";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
?>

information for customer ID <?php echo $cust ?> :

<?php if (mysql_num_rows($rs)>0){ ?>

Order Number
Order Date
Shipping Date

<?php while ($row = mysql_fetch_array($rs)) { ?>

<?php echo $row["orderNumber"]?>
<?php echo $row["orderDate"]?>
<?php echo $row["shippingDate"]?>

<?php } mysql_close($conn); ?>

<?php }
else {?>
No customer with ID <?php echo $cust ?> in the database

<?php } ?>

If you need any more information just ask and any help would be really appreciated!

A: You're missing a space between your tablename name and WHERE:
$sql = "select * from orders";
$sql = $sql . "where customerID = '$cust'";

should be
$sql = "select * from orders";
$sql = $sql . " where customerID = '$cust'";

or just
$sql = "select * from orders where customerID = '$cust'";

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Also, you're wide open to SQL injections


text:
Q: ¿Como traer campos de tablas relacionadas con Eloquent PHP laravel? estoy creando un api en PHP Laravel, yo ya vengo de C# y Entity Framework pero hay cosas que aun no entiendo como funcionan en laravel.
tengo esta consulta:
People::with('user','rol','state','tower','apartament')->get()

y me trae esta información:
[
        {
            "id": 1,
            "name": "User1",
            "last_name": "lnUser1",
            "phone": 3132835875,
            "img_profile": null,
            "floor": 4,
            "user": {
                "id": 1,
                "email": "user1@dev.com",
                "email_verified_at": null,
                "created_at": null,
                "updated_at": "2022-04-26T03:12:03.000000Z"
            },
            "rol": {
                "id": 1,
                "name": "Administrador"
            },
            "state": {
                "id": 1,
                "name": "Activo"
            },
            "tower": {
                "id": 1,
                "name": "A"
            },
            "apartament": {
                "id": 116,
                "name": "1206"
            }
        },
        {
            "id": 2,
            "name": "User2",
            "last_name": "lnUser2",
            "phone": 3132835875,
            "img_profile": null,
            "floor": 2,
            "user": {
                "id": 2,
                "email": "user2@dev.com",
                "email_verified_at": null,
                "created_at": null,
                "updated_at": null
            },
            "rol": {
                "id": 2,
                "name": "Moderador"
            },
            "state": {
                "id": 2,
                "name": "Inactivo"
            },
            "tower": {
                "id": 1,
                "name": "A"
            },
            "apartament": {
                "id": 116,
                "name": "1206"
            }
        }
]

una lista de usuarios. pero yo necesito mostrar solo un par de datos no todo. asi que arme esta consulta asi:
People::with('user','rol','state','tower','apartament')->select(DB::raw('CONCAT(name, " ", last_name) as name, phone, img_profile, floor'))->get()

y me trae esta respuesta:
[
{
            "name": "User1 lnUser1",
            "phone": 3132835875,
            "img_profile": null,
            "floor": 4,
            "user": null,
            "rol": null,
            "state": null,
            "tower": null,
            "apartament": null
        },
        {
            "name": "User2 lnUser2",
            "phone": 3132835875,
            "img_profile": null,
            "floor": 2,
            "user": null,
            "rol": null,
            "state": null,
            "tower": null,
            "apartament": null
        }
]

He buscado y averiguado pero en todas las ocasiones me genera error o problemas con el query.
Asi que no se como seleccionar solamente el/los campos específicos de las tablas relacionadas (user, rol,state, tower y apartament). necesito una respuesta que me venga así:
[
    {
        "name": "User1 lnUser1",
        "phone": 3132835875,
        "img_profile": null,
        "floor": 4,
        "user_email": "user1@dev.com",
        "rol_name": "Administrador",
        "state_name": "Activo",
        "tower_name": "A",
        "apartament_number": "1206"
    },
    {
        "name": "User2 lnUser2",
        "phone": 3132835875,
        "img_profile": null,
        "floor": 2,
        "user_email": "user2@dev.com",
        "rol_name": "Moderador",
        "state_name": "Inactivo",
        "tower_name": "A",
        "apartament_number": "1206"
    }
]

A: Buen día,
Para obtener únicamente ciertas columnas puedes utilizar el método pluck()
Ejemplo:
People::pluck('user','rol','state','tower','apartament')->get()

A: Si requieres  algo mas  complejo y deseas utlizar una consulta mas  simple puedes usar querybuilder de laravel  un ejemplo aqui con un join
          DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();

A: Puedes utilizar accesors para crear campos del modelo Eloquent, por ejemplo:
public function getRolNameAttribute {
    return $this->rol->name;
}

Esto hace que puedas acceder al campo name de rol desde una instancia de People: $somePeople->rol_name. Aquí puedes leer mas sobre los accesors.
Luego de definir tus accesors para los campos que quieres añadir a la respuesta, los añades a la propiedad $appends de la clase modelo, esto hace que esos campos sean añadidos a las respuestas del modelo:
 protected $appends = ['rol_name', 'state_name', 'tower_name'];


text:
Q: Error trying to attach an image to an Azure DevOps wiki page I have successfully used the Azure DevOps API to create multiple wiki pages, via a standalone C# desktop app. Now I'm trying to attach an image (currently stored locally) to the wiki (as per https://learn.microsoft.com/en-us/rest/api/azure/devops/wiki/attachments/create?view=azure-devops-rest-6.0), but get an error

The wiki attachment creation failed with message : The input is not a
valid Base-64 string as it contains a non-base 64 character, more than
two padding characters, or an illegal character among the padding
characters.

This is the code that I use to read the image file and convert it to a Base64 string - is this correct?
string base64String = null;
string img = File.ReadAllText(att.Value);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(img);
base64String= Convert.ToBase64String(byteCredentials);

Then I create the "content" for the API call as
string data = @"{""content"": """ + base64String + @"""}";

and run the API call
string url = "https://dev.azure.com/{organization}/{project}/_apis/wiki/wikis/{wikiIdentifier}/attachments?name=Image.png&api-version=6.0";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/octet-stream";
request.Method = "PUT";
request.Proxy.Credentials = CredentialCache.DefaultCredentials;

request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", "AzurePAT"))));

if (data != null)
{
     using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
     {
           writer.Write(data);
     }
}

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
     result = reader.ReadToEnd();
}

Can anyone see anything wrong with any of this? The concept of setting up a "content" JSON with an encoded Base64 string doesn't seem to be documented, so have I done it correctly?
Any help or advice gladly appreciated, thanks

A: An image file does not contain text, it is a binary file, calling File.ReadAllText probably messes up the encoding. Try:
var img = File.ReadAllBytes(att.Value);
var base64String = Convert.ToBase64String(img);

In addition, the request expects the body to just be a string. You are passing JSON. Your code should look like this:
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write(base64String);
}


text:
Q: A way to keep the current iteration of a "for" variable in a closure
Possible Duplicate:
Javascript closure inside loops - simple practical example

for (i=0; i<N; i++) {
   $.get("script"+ i +".jsp", function() {
       //I want to use i here
       //but by the time the ajax request comes back i==N, but I want the old i
   })
}

So I got this code and I was wondering if there is a better way to do it than the one from my response.
This is not about jquery ajax calls, I'm aware there are ways to pass "i" through the event object, I want a general solution better than the one I came up with.

A: Making a self-executing function to hold i works, but is very ugly:
for (i=0; i<N; i++) {
   (function(i) {
      $.get("script"+ i +".jsp", function() {
          //I want to use i here
          //but by the time the ajax request comes back i==N, but I want the old i
      })
   } (i) );
}


text:
Q: How to prove the Milner-Rado Paradox?
For every ordinal $\alpha<\kappa^+$ there are sets $X_n\subset\alpha$ $(n\in\Bbb{N})$ such that $\alpha=\bigcup_n X_n$ and for each $n$ the order-type of $X_n$ is $\le\kappa^n$.
[By induction on $\alpha$, choosing a sequence cofinal in $\alpha$.]

I tried to prove this problem by using transfinite induction.

For $\alpha=0$, this statement is trivial.
If $\alpha$ has sets $X_n\subset \alpha$ satisfies $\alpha=\bigcup_n X_n$, $\text{order-type of }X_n\le\kappa^n$, we define
  $X'_0=\{\alpha\}$, $X_{n+1}'=X_n$. Then $\{X_n'\}$ satisfies $\bigcup_n X_n'=\alpha+1$, $\text{order-type of }X'_n \le \kappa^n$.

But I don't know how to proceed the proof. Thanks for any help.

A: Let $\alpha$ be a limit ordinal, and for each $\beta < \alpha$, let $(X^\beta _n)_n$ be the obvious thing.  Fix an increasing sequence $(\beta_\gamma)_{\gamma < \mathrm{cf}(\alpha)}$ cofinal in $\alpha$ with $\beta_0 = 1$.  Note $\mathrm{cf}(\alpha) \leq \kappa$.  Define:
$$X^\alpha _0 = \{0\};\ \ X^\alpha_{n+1} = \bigcup_\gamma X^{\beta_{\gamma+1}}_n\setminus \beta_\gamma$$
and that's it!

To see that it works, observe that:
$$\bigcup_{n>0}X^\alpha_n = \bigcup _n \bigcup _\gamma X^{\beta_{\gamma+1}}_n\setminus \beta_\gamma = \bigcup_\gamma \bigcup_n X^{\beta_{\gamma+1}}_n\setminus \beta_\gamma = \bigcup_\gamma \beta_{\gamma+1}\setminus \beta_\gamma = \alpha \setminus \beta_0$$
and so $\bigcup_nX^\alpha_n = \alpha$.
As for the order types, clearly $\mathrm{ot}(X^\alpha_0) = 1 = \kappa^0$.  Noting that the sets $\beta_{\gamma+1}\setminus\beta_\gamma$ form a consecutive sequence of ordinal intervals, and that each $X^{\beta_{\gamma+1}}_n\setminus\beta_\gamma$ is a tail segment of $X^{\beta_{\gamma+1}}_n$ we get that:
$$\mathrm{ot}(X^\alpha_{n+1}) = \sum_\gamma \mathrm{ot}(X^{\beta_{\gamma+1}}_n\setminus\beta_\gamma) \leq \sum_\gamma \kappa^n = \kappa^n \cdot \mathrm{cf}(\alpha) \leq \kappa^n\cdot\kappa = \kappa^{n+1}$$

A: $\newcommand{\cf}{\operatorname{cf}}$There's no problem if $\alpha\le\kappa$, so suppose that $\alpha$ is a limit ordinal such that $\kappa<\alpha<\kappa^+$. Let $\lambda=\cf\alpha$, and let $\langle\alpha_\xi:\xi<\lambda\rangle$ be an increasing sequence cofinal in $\alpha$. For each $\xi<\lambda$ let $\{X_n^\xi:n\in\omega\}$ be a Milnor-Rado decomposition of $\alpha_\xi$, and let $\{X_n^\lambda:n\in\omega\}$ be a decomposition of $\lambda$.
For $n\in\omega$ let
$$X_{2n}=\bigcup_{\eta\in X_n^\lambda}\left(X_n^\eta\cap\alpha_\eta\setminus\bigcup_{\xi<\eta}\alpha_\xi\right)\;;$$
the order type of each set
$$X_n^\eta\cap\alpha_\eta\setminus\bigcup_{\xi<\eta}\alpha_\xi$$
is clearly at most that of $X_n^\eta$, which by hypothesis is at most $\kappa^n$. Moreover, if $\eta<\theta$,
$$\beta\in X_n^\eta\cap\alpha_\eta\setminus\bigcup_{\xi<\eta}\alpha_\xi\;,\quad\text{and}\quad\gamma\in X_n^\theta\cap\alpha_\eta\setminus\bigcup_{\xi<\theta}\alpha_\xi\;,$$
then $\beta<\delta$. Or in brief,
$$X_n^\eta\cap\alpha_\eta\setminus\bigcup_{\xi<\eta}\alpha_\xi<X_n^\theta\cap\alpha_\eta\setminus\bigcup_{\xi<\theta}\alpha_\xi\;.$$
Since the order type of $X_n^\lambda$ is at most $\kappa^n$, that of $X_{2n}$ is at most $\kappa^n\cdot\kappa^n=\kappa^{2n}$. Let $X_{2n+1}=\varnothing$, whose order type is certainly no more than $\kappa^{2n+1}$. It only remains to show that $\alpha=\bigcup_{n\in\omega}X_n$.
If $\beta<\alpha$, let $\eta<\lambda$ be minimal such that $\beta<\alpha_\eta$. Then $\beta\in\alpha_\eta\setminus\bigcup_{\xi<\eta}\alpha_xi$, and $\alpha_\eta=\bigcup_{n\in\omega}X_n^\eta$, so
$$\beta\in X_n^\eta\cap\alpha_\eta\setminus\bigcup_{\xi<\eta}\alpha_\xi\subseteq X_{2n}$$
for some $n\in\omega$.

A: The Milner-Rado paradox is only a paradox in the traditional sense of the word: there are no inconsistencies here, but rather the result is (perhaps naively) seen as counter-intuitive. There are two reasons here: First, if $\alpha=\bigcup_{n<\omega}A_n$, and the $A_n$ are intervals, $A_n=[\alpha_n,\alpha_{n+1})$, where the $\alpha_i$ are increasing, and the order type of $A_n$ is at most $\kappa^n$ for all $n$, then $\alpha\le\kappa^\omega$. This means the obvious attempt to decompose an ordinal as requested has to fail as soon as the ordinal is sufficiently large.
It follows that the decomposition ought to be somewhat messy, for example, we may see  $i< j$, such that the ordinals in $A_j$ are smaller than the ordinals in $A_i$, or we may see $i\ne j$ such that there are points in $A_i$ between points in $A_j$, and vice versa. But then we reach the second reason why the result may seem counter-intuitive: In

G.H. Toulmin. Shuffling ordinals and transfinite dimension, Proc. London Math. Soc. (3), 4, (1954), 177–195. MR0065907 (16,502a),

it is shown that if $A,B$ are sets of ordinals of order types $\alpha$ and $\beta$, then there is an upper bound on the order type of $A\cup B$ that depends only on $\alpha,\beta$.
(Namely, write $\alpha$ and $\beta$ as a decreasing sum of indecomposable ordinals, $\alpha=\sum_{i<k} \gamma_i n_i$ and $\beta=\sum_{i<k} \gamma_i m_i$, where the $\gamma_i$ are indecomposable, $\gamma_0>\dots>\gamma_{k-1}$, and the $n_i,m_i$ are natural numbers. Then $A\cup B$ has type at most $\sum_{i<k}\gamma_i(n_i+m_i)$, the natural or Hessenberg sum of $\alpha$ and $\beta$. In fact, Toulmin proved that there are only finitely many possible order types for $A\cup B$, all expressible in terms of the $\gamma_i,n_i,m_i$.)
This means that the fact that we may write ordinals much larger than $\kappa^\omega$ as the union of sets $A_n$ ($n<\omega$) with each $A_n$ of type at most $\kappa^n$, cannot be "seen" or anticipated by considering only finitely many of the $A_n$ and thus may appear surprising. (Of course, this is but one example of the many ways in which our intuitions about the finite prove insufficient when dealing with the infinite.)

Now we proceed to the proof.
This comes from a set of notes I'm working on. A draft version of the argument below can be found here. A proof close to this one can be found in the paper by Hajnal and Larson in the Handbook of set theory. The result itself comes from

Eric C. Milner, and Richard Rado. The pigeon-hole principle for ordinal numbers, Proceedings of the London Mathematical Society (3), 15, (1968), 750–768, 1965.

First notice that the result is clear if $\kappa=\omega$, since we can write any $\alpha<\omega_1$ as a
countable union of singletons (and an empty set). So we may assume that $\kappa$ is uncountable. All
powers in what follows are in the sense of ordinal exponentiation.
Notice that $|\kappa^{\rho}|=\kappa$ for any $\rho<\kappa^+$,  as one can easily check by induction.
Notice also that the function $\alpha\mapsto\omega^{ \alpha}$ is normal (i.e., strictly increasing and
continuous). By the above, it follows that $\omega^{\lambda}=\lambda$ for all uncountable cardinals
$\lambda$. In particular, it suffices to prove the result for ordinals $\alpha$ that are an ordinal power of
$\kappa$, since these ordinals are cofinal in $\kappa^+$, and a representation as desired for an ordinal
gives (by restriction) such a representation for any smaller ordinal.
By the above, $\kappa^{\rho}=\omega^{\kappa\cdot\rho}$ for any $\rho$. Since $\omega^\delta$ is
indecomposable, if $\alpha<\omega^{\delta}$, then the interval $[\alpha,\omega^{\delta})$ is order
isomorphic to $\omega^{\delta}.$
For any $\alpha<\kappa^+$, we can write $\kappa^{\alpha+1}=\bigcup_{\nu<\kappa}A_\nu$, where $A_
\nu=[\kappa^{ \alpha}\cdot\nu,\kappa^{\alpha}\cdot(\nu+1))$ so it has order type $\kappa^{\alpha}$.
Also, if $\alpha$ is a limit ordinal below $\kappa^+$, then we can write $\alpha=\sup_{\nu<\mathrm{cf}(\alpha)}\beta_\nu$ for some strictly increasing continuous sequence $(\beta_\nu\mid\nu<\mbox{cf}
(\alpha))$ cofinal in $\alpha$. Let $A_0=\kappa^{\beta_1}$ and $A_\nu=[\kappa^{\beta_\nu},
\kappa^{\beta_{\nu+1}})$ for $0<\nu<\mbox{cf}(\alpha)$. Then $\kappa^{\alpha}=\bigcup_\nu A_\nu$
and each $A_\nu$ has order type $\kappa^{\beta_{\nu+1}}$.
That the sequence $\beta_\nu$ is continuous (at limits) ensures that the $A_\nu$ cover
$\kappa^{ \alpha}$. That they have the claimed order type follows from indecomposability.
So we have written each $\kappa^{\rho}$ as an increasing union of $\sigma$ many intervals whose
order types are ordinal powers of $\kappa$ (smaller than $\kappa^\rho$), and $\sigma$ is either
$\kappa$ or $\mbox{cf}(\rho)$. Now proceed by induction. We may assume that each ordinal below
$\kappa^{\rho}$ can be written as claimed in the paradox. In particular, each $A_\nu$, having order type
an ordinal smaller than $\kappa^{\rho}$, can be written that way, say $A_\nu=\bigcup_n A_{\nu,n}$
where $\mbox{ot}(A_{\nu,n})<\kappa^{ n}$.
If $\sigma=\omega$, this immediately gives the result for $\kappa^{\rho}$: Take $X_0=\emptyset$ and
$X_{2^m(2n+1)}=A_{m,n}$. Clearly their union is $\kappa^{\rho}$ and they have small order type as
required.
If $\sigma>\omega$, take $X_0=X_1=\emptyset$ and $X_{n+2}=\bigcup_\nu A_{\nu,n}$. Again, their
union is $\kappa^{\rho}$, and $\mbox{ot}(X_{n+2})$ is at most the order type of concatenating $\kappa$
many copies of $\kappa^{ n}$ (it is here that we use that $A_\nu<A_\mu$ for $\nu<\mu$), so $\mbox{ot}
(X_{n+2})\le\kappa^{ n+1}$.

Edit, November 1, 2016: Toulmin's result actually appeared significantly earlier, and Toulmin rediscovered it independently. See

MR0005878 (3,225a). Philip W. Carruth. Arithmetic of ordinals with applications to the theory of ordered Abelian groups. Bull. Amer. Math. Soc. 48, (1942). 262–271.


text:
Q: Find A Cell Value in Sheet 1 and see if value exists in Column of Sheet 2 I am working on a doc to confirm if specific values exist, in a specific order of text documents.
Essentially what I am trying to determine, is if a String Value from Cell B2 on Sheet 1(Campaign) exists inside of a column of String values on Sheet 2(Master List).
If the String Value Does exist then the Cell should highlight Green, IF it doesn't then Highlight Red, Then move down to the next Column value on Sheet 1 (i.e. B3) if any
I know I have to use for loops, but not 100% sure of the specific functions to employ within the loop
Any assistance you could provide would be greatly appreciated. Thanks all.
The Closest I have come up with
Dim WS As Worksheet
Set WS = Sheets("Master List")
Dim WS1 As Worksheet
Set WS1 = Sheets("Campaign")

For i = 2 To 100
  For j = 2 to 100
' Loop through the Master sheet
      If WS1.Cells(i, 2) = WS.Cells(i, 2) Then
         ' If a match is found update color:
               Selection.Interior
               .Pattern = xlSolid
               .PatternColorIndex = xlAutomatic
               .Color = 5287936
               .TintAndShade = 0
               .PatternTintAndShade = 0
      Else If WS1.Cells(i, 2) <> WS.Cells(i, 2) Then
         ' If cell doesn't match is found update color:
               Selection.Interior
               .Pattern = xlSolid
               .PatternColorIndex = xlAutomatic
               .Color = 5287936
               .TintAndShade = 0
               .PatternTintAndShade = 0
     End if
  Next j
Next i

A: If this has to be VBA, then something like this should work for you:
Sub FindValues()

    Dim wb As Workbook:         Set wb = ThisWorkbook
    Dim wsCmpn As Worksheet:    Set wsCmpn = wb.Worksheets("Campaign")
    Dim wsMstr As Worksheet:    Set wsMstr = wb.Worksheets("Master List")
    Dim rFindValues As Range:   Set rFindValues = wsCmpn.Range("B2", wsCmpn.Cells(wsCmpn.Rows.Count, "B").End(xlUp))
    If rFindValues.Row < 2 Then Exit Sub    'No values to find

    Dim rCell As Range
    Dim rFound As Range
    Dim rGreen As Range
    Dim rRed As Range

    'xlWhole for exact match
    'xlPart for partial match
    Dim lMatchType As Long: lMatchType = xlWhole

    For Each rCell In rFindValues.Cells
        If Len(rCell.Value) > 0 Then 'Ignore blanks
            Set rFound = wsMstr.Columns("B").Find(rCell.Value, , xlValues, lMatchType, MatchCase:=False)
            If rFound Is Nothing Then
                Select Case (rRed Is Nothing)
                    Case True:  Set rRed = rCell
                    Case Else:  Set rRed = Union(rRed, rCell)
                End Select
            Else
                Select Case (rGreen Is Nothing)
                    Case True:  Set rGreen = rCell
                    Case Else:  Set rGreen = Union(rGreen, rCell)
                End Select
                Set rFound = Nothing
            End If
        End If
    Next rCell

    rFindValues.EntireColumn.Interior.ColorIndex = xlNone
    If Not rRed Is Nothing Then rRed.Interior.Color = vbRed
    If Not rGreen Is Nothing Then rGreen.Interior.Color = vbGreen

End Sub

A: Highlight Matching Cells

Option Explicit

Sub HighlightCampaign()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    Dim sws As Worksheet: Set sws = wb.Sheets("Master List")
    Dim srg As Range
    Set srg = sws.Range("B2", sws.Cells(sws.Rows.Count, "B").End(xlUp))

    Dim dws As Worksheet: Set dws = wb.Sheets("Campaign")
    Dim drg As Range
    Set drg = dws.Range("B2", dws.Cells(dws.Rows.Count, "B").End(xlUp))

    Dim dCell As Range

    For Each dCell In drg.Cells
        If IsNumeric(Application.Match(dCell.Value, srg, 0)) Then
            dCell.Interior.Color = 14348258 ' Green
        Else
            dCell.Interior.Color = 14083324 ' Red
        End If
    Next dCell

    MsgBox "Campaign values highlighted.", vbInformation

End Sub


text:
Q: Trying to decrypt a FormsAuthentication ticket always unable to validate data I am using the new webapi.
Now I don't know if I am doing this correctly but I am trying to setup my api to return an authentication cookie within the HttpResponseMessages header to use on another an mvc application.
I am using the FormsAuthenticationTicket as I think its what I need to use like
  public HttpResponseMessage Get(LoginModel model)
    {
        if (model.UserName == "bob")
        {
            //  if (Membership.ValidateUser(model.UserName, model.Password))
            // {
            var msg = new HttpResponseMessage(HttpStatusCode.OK);
            var expires = DateTime.Now.AddMinutes(30);
            var auth = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, expires,
                                                     model.RememberMe,"password",
                                                     FormsAuthentication.FormsCookiePath);
            var cookie = new HttpCookie("user");
            cookie.Value = FormsAuthentication.Encrypt(auth);
            cookie.Domain = "localhost";
            cookie.Expires = expires;
            msg.Headers.Add("result",cookie.Value);
            return msg;
            //   }
        }
        return new HttpResponseMessage(HttpStatusCode.Forbidden);
        //else
        //{
        //    return "The user name or password provided is incorrect.";
        //}
    }

now within my login controller on my mvc application I call the service and get the data value from the header I set in the api controller.
   string data = response.Headers["result"].ToString();
   FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(data);

Everytime I try running the FormsAuthentication.Decrypt I keep getting an error

Unable to validate data.

I assume its due to when the api encrypts the data it uses some kind of key that the website doesn't know about. Am I right?
Can someone help out?
Thank you

A:
I assume its due to when the api encrypts the data it uses some kind
  of key that the website doesn't know about. Am I right?

FormsAuthentication.Encrypt and Decrypt methods use the machine key. So make sure you have configured the same key for both your Web API web application and the consuming ASP.NET MVC application.
You could also take a look at the following article which illustrates how you could use OAuth 2.0 with the Web API.


text:
Q: How to do a one-to-one relationship in GORM? I have a series of categories of a type of Product. There are only 3 of them so I can create a table for each. Lets call them SubProductA, SubProductB and SubProductC. They are distinct enough that storing them in the parent Product table would make a mess.
So naturally, I just allow the primary key to be the foreign key linking back to product for each of these. However, GORM seems to not be able to preload any field like this. Here is what I have (as an example) for one of these:
type SubProductA struct {
  ProductID uint64 `gorm:"primary_key;ForeignKey:ProductID"`
  Product Product
  CreatedAt           time.Time
  UpdatedAt           time.Time
  DeletedAt           *time.Time
}

However, when I run a query like
db.Where("product_id=?", p.ID).Preload("Product").First(&subProduct).Error

The result is:
Can't preload field Product for models.SubProductA.
I suspect this is because I'm not properly identifying the primary key as the foreign key as well. However, I have tried a bunch of different things and I get the same error.
Is there a way to make this work?

A: To answer my own question for people passing through...
It seems that GORM has problems with multiple-level one-to-one relationships. For a single level, the example I gave, it works without needing anything more. However, to do a preload on a field that is also a one-to-one with the same key farther up the tree, I needed to do the following:
type SubSubProductA struct {
  SubProductID uint64 `gorm:"primary_key"`
  SubProductA SubProductA `gorm:"ForeignKey:SubProductID`"
  CreatedAt           time.Time
  UpdatedAt           time.Time
  DeletedAt           *time.Time
}

In other words, the ForeignKey part goes on the object itself. This fixed the preloading for me. Hope this helps someone. The GORM documentation is very sparse for anything but the common cases.

A: GORM now supports nested preloading. You can check out the docs here.


text:
Q: Why does the id type in Objective-C omit the asterisk? My understanding of the Objective-C id type is that it's a pointer to an object of unknown type. In my eyes it's like a void* for Objective-C classes with some compiler sugar on top for stuff like type checking. My question is why is it not id* instead of id then since it is a pointer type? If this were Java or C# where object references aren't declared using an * then I wouldn't be so surprised. But in Objective-C, every class is referenced by C-style pointers, so why hide the * for the unknown object type?

A: The id typedef is already a pointer:
typedef struct objc_object {
    Class isa;
} *id;

From the Objective-C Programming Language:

In Objective-C, object identifiers are of a distinct data type: id.
  This type is the general type for any kind of object regardless of
  class and can be used for instances of a class and for class objects
  themselves.
id anObject;

For the object-oriented constructs of Objective-C, such
  as method return values, id replaces int as the default data type.
  (For strictly C constructs, such as function return values, int
  remains the default type.)
The keyword nil is defined as a null object, an id with a value of 0.
  id, nil, and the other basic types of Objective-C are defined in the
  header file objc/objc.h.
id is defined as pointer to an object data structure:

typedef struct objc_object {
    Class isa;
} *id;

Every object thus has an isa variable that tells it of what class it is an instance. Since the Class type is itself
  defined as a pointer:
typedef struct objc_class *Class;

the isa variable is frequently
  referred to as the "isa pointer."